Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 92 additions & 12 deletions packages/google-cloud-spanner/samples/samples/pg_snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,36 @@ def create_instance(instance_id):


# [START spanner_postgresql_create_database]
def create_database(instance_id, database_id):
"""Creates a PostgreSql database and tables for sample data."""
def create_database(instance_id: str, database_id: str) -> None:
"""Creates a PostgreSql database and tables for sample data.

This takes two operations. The first creates an empty database. The
second, in create_table_using_ddl, creates the Singers and Albums tables.
If the second operation fails, the database from the first one remains.
Each operation is given up to OPERATION_TIMEOUT_SECONDS (240 seconds, set
at the top of this file) to finish.

Args:
instance_id: ID of an existing Spanner instance.
database_id: ID for the new database. It must be 2 to 30 characters
long, start with a lowercase letter, contain only lowercase
letters, digits, underscores, and hyphens, and not end with an
underscore or a hyphen.

Raises:
google.api_core.exceptions.AlreadyExists: The instance already has a
database with this ID. Recovery: if that database has no tables,
call create_table_using_ddl with its full name. Otherwise use
it, or pass a different database_id.
google.api_core.exceptions.InvalidArgument: database_id does not
follow the rules above. Recovery: pass an ID that follows them.
google.api_core.exceptions.NotFound: The instance does not exist.
Recovery: check instance_id.
concurrent.futures.TimeoutError: An operation was still running
after the wait. The client stops waiting and does not cancel it.
Recovery: check whether the database and its tables exist before
you run this sample again.
"""

from google.cloud.spanner_admin_database_v1.types import spanner_database_admin

Expand All @@ -78,19 +106,40 @@ def create_database(instance_id, database_id):
request = spanner_database_admin.CreateDatabaseRequest(
parent=database_admin_api.instance_path(spanner_client.project, instance_id),
create_statement=f'CREATE DATABASE "{database_id}"',
# DatabaseDialect is imported at the top of this file, from
# google.cloud.spanner_admin_database_v1.types.common.
database_dialect=DatabaseDialect.POSTGRESQL,
)

operation = database_admin_api.create_database(request=request)

print("Waiting for operation to complete...")
database = operation.result(OPERATION_TIMEOUT_SECONDS)
database = operation.result(timeout=OPERATION_TIMEOUT_SECONDS)

create_table_using_ddl(database.name)
print("Created database {} on instance {}".format(database_id, instance_id))


def create_table_using_ddl(database_name):
def create_table_using_ddl(database_name: str) -> None:
"""Creates the Singers and Albums tables in a PostgreSQL-dialect database.

The call waits up to OPERATION_TIMEOUT_SECONDS (240 seconds, set at the
top of this file) for the operation to finish.

Args:
database_name: Full name of the database, in the form
projects/<project>/instances/<instance>/databases/<database>.

Raises:
google.api_core.exceptions.FailedPrecondition: The tables already
exist. Recovery: continue with the next step.
google.api_core.exceptions.NotFound: The database does not exist.
Recovery: check database_name.
concurrent.futures.TimeoutError: The operation was still running
after the wait. The client stops waiting and does not cancel it.
Recovery: check whether the tables exist before you call this
function again.
"""
from google.cloud.spanner_admin_database_v1.types import spanner_database_admin

spanner_client = spanner.Client()
Expand All @@ -114,8 +163,8 @@ def create_table_using_ddl(database_name):
) INTERLEAVE IN PARENT Singers ON DELETE CASCADE""",
],
)
operation = spanner_client.database_admin_api.update_database_ddl(request)
operation.result(OPERATION_TIMEOUT_SECONDS)
operation = spanner_client.database_admin_api.update_database_ddl(request=request)
operation.result(timeout=OPERATION_TIMEOUT_SECONDS)


# [END spanner_postgresql_create_database]
Expand Down Expand Up @@ -236,8 +285,28 @@ def read_data(instance_id, database_id):


# [START spanner_postgresql_add_column]
def add_column(instance_id, database_id):
"""Adds a new column to the Albums table in the example database."""
def add_column(instance_id: str, database_id: str) -> None:
"""Adds a new column to the Albums table in the example database.

The column, MarketingBudget, has the type bigint. The call waits up to
OPERATION_TIMEOUT_SECONDS (240 seconds, set at the top of this file) for
the operation to finish.

Args:
instance_id: ID of the Spanner instance.
database_id: ID of a database created by the create_database sample.

Raises:
google.api_core.exceptions.FailedPrecondition: The column already
exists. Recovery: continue with the next step.
google.api_core.exceptions.NotFound: The instance, the database, or
the Albums table does not exist. Recovery: check instance_id and
database_id, and use a database created by create_database.
concurrent.futures.TimeoutError: The operation was still running
after the wait. The client stops waiting and does not cancel it.
Recovery: check whether the column exists before you run this
sample again.
"""

from google.cloud.spanner_admin_database_v1.types import spanner_database_admin

Expand All @@ -250,10 +319,10 @@ def add_column(instance_id, database_id):
),
statements=["ALTER TABLE Albums ADD COLUMN MarketingBudget BIGINT"],
)
operation = database_admin_api.update_database_ddl(request)
operation = database_admin_api.update_database_ddl(request=request)

print("Waiting for operation to complete...")
operation.result(OPERATION_TIMEOUT_SECONDS)
operation.result(timeout=OPERATION_TIMEOUT_SECONDS)

print("Added the MarketingBudget column.")

Expand Down Expand Up @@ -595,6 +664,15 @@ def query_data_with_parameter(instance_id, database_id):
# [START spanner_postgresql_query_with_parameter]
# instance_id = "your-spanner-instance"
# database_id = "your-spanner-db-id"
#
# Prints every singer whose LastName is "Garcia", or nothing if no singer
# matches. The insert_with_dml sample inserts one such singer. The query
# parameter $1 takes its value from the "p1" key of params.
#
# Raises google.api_core.exceptions.InvalidArgument if the Singers table
# does not exist. Recovery: use a database created by create_database.
# Raises google.api_core.exceptions.NotFound if the instance or the
# database does not exist. Recovery: check instance_id and database_id.
spanner_client = spanner.Client()
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
Expand All @@ -606,8 +684,10 @@ def query_data_with_parameter(instance_id, database_id):
param_types={"p1": spanner.param_types.STRING},
)

for row in results:
print("SingerId: {}, FirstName: {}, LastName: {}".format(*row))
for singer_id, first_name, last_name in results:
print(
f"SingerId: {singer_id}, FirstName: {first_name}, LastName: {last_name}"
)
# [END spanner_postgresql_query_with_parameter]


Expand Down
4 changes: 3 additions & 1 deletion packages/google-cloud-spanner/samples/samples/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ def run_quickstart(instance_id, database_id):
# Get a Cloud Spanner database by ID.
database = instance.database(database_id)

# Execute a simple SQL statement.
# Execute a simple SQL statement. This prints "[1]".
# Raises google.api_core.exceptions.NotFound if the instance or the
# database does not exist. Recovery: check instance_id and database_id.
with database.snapshot() as snapshot:
results = snapshot.execute_sql("SELECT 1")

Expand Down
Loading
Loading