Skip to content

Commit

Permalink
feat: add database dialect (#671)
Browse files Browse the repository at this point in the history
- [ ] Regenerate this pull request now.

PiperOrigin-RevId: 423930262

Source-Link: googleapis/googleapis@b0c104f

Source-Link: googleapis/googleapis-gen@4289d82
Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDI4OWQ4MjAwMGQ1NTQ1NjM1N2YwNWJlMDFiNzc2MzA4MmJiNzdiNiJ9

feat: add api key support
  • Loading branch information
gcf-owl-bot[bot] committed Jan 25, 2022
1 parent 979442c commit 819be92
Show file tree
Hide file tree
Showing 22 changed files with 929 additions and 234 deletions.
2 changes: 2 additions & 0 deletions google/cloud/spanner_admin_database_v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from .types.common import EncryptionConfig
from .types.common import EncryptionInfo
from .types.common import OperationProgress
from .types.common import DatabaseDialect
from .types.spanner_database_admin import CreateDatabaseMetadata
from .types.spanner_database_admin import CreateDatabaseRequest
from .types.spanner_database_admin import Database
Expand Down Expand Up @@ -63,6 +64,7 @@
"CreateDatabaseRequest",
"Database",
"DatabaseAdminClient",
"DatabaseDialect",
"DeleteBackupRequest",
"DropDatabaseRequest",
"EncryptionConfig",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from collections import OrderedDict
import functools
import re
from typing import Dict, Sequence, Tuple, Type, Union
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources

from google.api_core.client_options import ClientOptions
Expand Down Expand Up @@ -51,11 +51,13 @@

class DatabaseAdminAsyncClient:
"""Cloud Spanner Database Admin API
The Cloud Spanner Database Admin API can be used to create,
drop, and list databases. It also enables updating the schema of
pre-existing databases. It can be also used to create, delete
and list backups for a database and to restore from an existing
backup.
The Cloud Spanner Database Admin API can be used to:
- create, drop, and list databases
- update the schema of pre-existing databases
- create, delete and list backups for a database
- restore a database from an existing backup
"""

_client: DatabaseAdminClient
Expand Down Expand Up @@ -133,6 +135,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):

from_service_account_json = from_service_account_file

@classmethod
def get_mtls_endpoint_and_cert_source(
cls, client_options: Optional[ClientOptions] = None
):
"""Return the API endpoint and client cert source for mutual TLS.
The client cert source is determined in the following order:
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
client cert source is None.
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
default client cert source exists, use the default one; otherwise the client cert
source is None.
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
default mTLS endpoint; if the environment variabel is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
More details can be found at https://google.aip.dev/auth/4114.
Args:
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. Only the `api_endpoint` and `client_cert_source` properties may be used
in this method.
Returns:
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
client cert source to use.
Raises:
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
"""
return DatabaseAdminClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore

@property
def transport(self) -> DatabaseAdminTransport:
"""Returns the transport used by the client instance.
Expand Down Expand Up @@ -617,7 +655,8 @@ async def drop_database(
) -> None:
r"""Drops (aka deletes) a Cloud Spanner database. Completed backups
for the database will be retained according to their
``expire_time``.
``expire_time``. Note: Cloud Spanner might continue to accept
requests for a few seconds after the database has been deleted.
Args:
request (Union[google.cloud.spanner_admin_database_v1.types.DropDatabaseRequest, dict]):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,13 @@ def get_transport_class(cls, label: str = None,) -> Type[DatabaseAdminTransport]

class DatabaseAdminClient(metaclass=DatabaseAdminClientMeta):
"""Cloud Spanner Database Admin API
The Cloud Spanner Database Admin API can be used to create,
drop, and list databases. It also enables updating the schema of
pre-existing databases. It can be also used to create, delete
and list backups for a database and to restore from an existing
backup.
The Cloud Spanner Database Admin API can be used to:
- create, drop, and list databases
- update the schema of pre-existing databases
- create, delete and list backups for a database
- restore a database from an existing backup
"""

@staticmethod
Expand Down Expand Up @@ -325,6 +327,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
return m.groupdict() if m else {}

@classmethod
def get_mtls_endpoint_and_cert_source(
cls, client_options: Optional[client_options_lib.ClientOptions] = None
):
"""Return the API endpoint and client cert source for mutual TLS.
The client cert source is determined in the following order:
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
client cert source is None.
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
default client cert source exists, use the default one; otherwise the client cert
source is None.
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
default mTLS endpoint; if the environment variabel is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
More details can be found at https://google.aip.dev/auth/4114.
Args:
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. Only the `api_endpoint` and `client_cert_source` properties may be used
in this method.
Returns:
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
client cert source to use.
Raises:
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
"""
if client_options is None:
client_options = client_options_lib.ClientOptions()
use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_client_cert not in ("true", "false"):
raise ValueError(
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
)
if use_mtls_endpoint not in ("auto", "never", "always"):
raise MutualTLSChannelError(
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
)

# Figure out the client cert source to use.
client_cert_source = None
if use_client_cert == "true":
if client_options.client_cert_source:
client_cert_source = client_options.client_cert_source
elif mtls.has_default_client_cert_source():
client_cert_source = mtls.default_client_cert_source()

# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
elif use_mtls_endpoint == "always" or (
use_mtls_endpoint == "auto" and client_cert_source
):
api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
else:
api_endpoint = cls.DEFAULT_ENDPOINT

return api_endpoint, client_cert_source

def __init__(
self,
*,
Expand Down Expand Up @@ -375,57 +444,22 @@ def __init__(
if client_options is None:
client_options = client_options_lib.ClientOptions()

# Create SSL credentials for mutual TLS if needed.
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
"true",
"false",
):
raise ValueError(
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
)
use_client_cert = (
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
client_options
)

client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
is_mtls = True
client_cert_source_func = client_options.client_cert_source
else:
is_mtls = mtls.has_default_client_cert_source()
if is_mtls:
client_cert_source_func = mtls.default_client_cert_source()
else:
client_cert_source_func = None

# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
else:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_mtls_env == "never":
api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
if is_mtls:
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
else:
api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
"values: never, auto, always"
)
api_key_value = getattr(client_options, "api_key", None)
if api_key_value and credentials:
raise ValueError(
"client_options.api_key and credentials are mutually exclusive"
)

# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, DatabaseAdminTransport):
# transport is a DatabaseAdminTransport instance.
if credentials or client_options.credentials_file:
if credentials or client_options.credentials_file or api_key_value:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
Expand All @@ -437,6 +471,15 @@ def __init__(
)
self._transport = transport
else:
import google.auth._default # type: ignore

if api_key_value and hasattr(
google.auth._default, "get_api_key_credentials"
):
credentials = google.auth._default.get_api_key_credentials(
api_key_value
)

Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
Expand Down Expand Up @@ -843,7 +886,8 @@ def drop_database(
) -> None:
r"""Drops (aka deletes) a Cloud Spanner database. Completed backups
for the database will be retained according to their
``expire_time``.
``expire_time``. Note: Cloud Spanner might continue to accept
requests for a few seconds after the database has been deleted.
Args:
request (Union[google.cloud.spanner_admin_database_v1.types.DropDatabaseRequest, dict]):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ class DatabaseAdminGrpcTransport(DatabaseAdminTransport):
"""gRPC backend transport for DatabaseAdmin.
Cloud Spanner Database Admin API
The Cloud Spanner Database Admin API can be used to create,
drop, and list databases. It also enables updating the schema of
pre-existing databases. It can be also used to create, delete
and list backups for a database and to restore from an existing
backup.
The Cloud Spanner Database Admin API can be used to:
- create, drop, and list databases
- update the schema of pre-existing databases
- create, delete and list backups for a database
- restore a database from an existing backup
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
Expand Down Expand Up @@ -390,7 +392,8 @@ def drop_database(
Drops (aka deletes) a Cloud Spanner database. Completed backups
for the database will be retained according to their
``expire_time``.
``expire_time``. Note: Cloud Spanner might continue to accept
requests for a few seconds after the database has been deleted.
Returns:
Callable[[~.DropDatabaseRequest],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,13 @@ class DatabaseAdminGrpcAsyncIOTransport(DatabaseAdminTransport):
"""gRPC AsyncIO backend transport for DatabaseAdmin.
Cloud Spanner Database Admin API
The Cloud Spanner Database Admin API can be used to create,
drop, and list databases. It also enables updating the schema of
pre-existing databases. It can be also used to create, delete
and list backups for a database and to restore from an existing
backup.
The Cloud Spanner Database Admin API can be used to:
- create, drop, and list databases
- update the schema of pre-existing databases
- create, delete and list backups for a database
- restore a database from an existing backup
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
Expand Down Expand Up @@ -399,7 +401,8 @@ def drop_database(
Drops (aka deletes) a Cloud Spanner database. Completed backups
for the database will be retained according to their
``expire_time``.
``expire_time``. Note: Cloud Spanner might continue to accept
requests for a few seconds after the database has been deleted.
Returns:
Callable[[~.DropDatabaseRequest],
Expand Down
2 changes: 2 additions & 0 deletions google/cloud/spanner_admin_database_v1/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
EncryptionConfig,
EncryptionInfo,
OperationProgress,
DatabaseDialect,
)
from .spanner_database_admin import (
CreateDatabaseMetadata,
Expand Down Expand Up @@ -70,6 +71,7 @@
"EncryptionConfig",
"EncryptionInfo",
"OperationProgress",
"DatabaseDialect",
"CreateDatabaseMetadata",
"CreateDatabaseRequest",
"Database",
Expand Down
4 changes: 4 additions & 0 deletions google/cloud/spanner_admin_database_v1/types/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ class Backup(proto.Message):
encryption_info (google.cloud.spanner_admin_database_v1.types.EncryptionInfo):
Output only. The encryption information for
the backup.
database_dialect (google.cloud.spanner_admin_database_v1.types.DatabaseDialect):
Output only. The database dialect information
for the backup.
"""

class State(proto.Enum):
Expand All @@ -125,6 +128,7 @@ class State(proto.Enum):
encryption_info = proto.Field(
proto.MESSAGE, number=8, message=common.EncryptionInfo,
)
database_dialect = proto.Field(proto.ENUM, number=10, enum=common.DatabaseDialect,)


class CreateBackupRequest(proto.Message):
Expand Down
14 changes: 13 additions & 1 deletion google/cloud/spanner_admin_database_v1/types/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,22 @@

__protobuf__ = proto.module(
package="google.spanner.admin.database.v1",
manifest={"OperationProgress", "EncryptionConfig", "EncryptionInfo",},
manifest={
"DatabaseDialect",
"OperationProgress",
"EncryptionConfig",
"EncryptionInfo",
},
)


class DatabaseDialect(proto.Enum):
r"""Indicates the dialect type of a database."""
DATABASE_DIALECT_UNSPECIFIED = 0
GOOGLE_STANDARD_SQL = 1
POSTGRESQL = 2


class OperationProgress(proto.Message):
r"""Encapsulates progress related information for a Cloud Spanner
long running operation.
Expand Down
Loading

0 comments on commit 819be92

Please sign in to comment.