diff --git a/packages/google-cloud-spanner/samples/samples/pg_snippets.py b/packages/google-cloud-spanner/samples/samples/pg_snippets.py index cd77d7aefc28..90d75edb47bf 100644 --- a/packages/google-cloud-spanner/samples/samples/pg_snippets.py +++ b/packages/google-cloud-spanner/samples/samples/pg_snippets.py @@ -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 @@ -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//instances//databases/. + + 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() @@ -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] @@ -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 @@ -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.") @@ -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) @@ -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] diff --git a/packages/google-cloud-spanner/samples/samples/quickstart.py b/packages/google-cloud-spanner/samples/samples/quickstart.py index f2d355d931c7..df93672d72ca 100644 --- a/packages/google-cloud-spanner/samples/samples/quickstart.py +++ b/packages/google-cloud-spanner/samples/samples/quickstart.py @@ -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") diff --git a/packages/google-cloud-spanner/samples/samples/snippets.py b/packages/google-cloud-spanner/samples/samples/snippets.py index a40b701f547c..74578db3a9b1 100644 --- a/packages/google-cloud-spanner/samples/samples/snippets.py +++ b/packages/google-cloud-spanner/samples/samples/snippets.py @@ -241,8 +241,34 @@ def list_databases(instance_id): # [START spanner_create_database] -def create_database(instance_id, database_id): - """Creates a database and tables for sample data.""" +def create_database(instance_id: str, database_id: str) -> None: + """Creates a database and tables for sample data. + + One operation creates the GoogleSQL database and its Singers and Albums + tables. If a table statement fails, no database is created. 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 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: use that database, 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: The operation was still running + after the wait. The client stops waiting and does not cancel it. + Recovery: check whether the database exists before you run this + sample again. + """ from google.cloud.spanner_admin_database_v1.types import spanner_database_admin spanner_client = spanner.Client() @@ -273,7 +299,7 @@ def create_database(instance_id, database_id): 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) print( "Created database {} on instance {}".format( @@ -523,11 +549,27 @@ def query_information_schema_database_options(instance_id, database_id): # [START spanner_insert_data] -def insert_data(instance_id, database_id): +def insert_data(instance_id: str, database_id: str) -> None: """Inserts sample data into the given database. The database and table must already exist and can be created using `create_database`. + + The rows are sent in one commit when the `with` block ends. The commit is + atomic: either every row is inserted or none is. The Singers rows come + first because each Albums row needs its Singers row to exist. + + 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.AlreadyExists: At least one of the rows + already exists. Recovery: if this sample already ran, continue + with the next step. + google.api_core.exceptions.NotFound: The instance, the database, or + one of the tables does not exist. Recovery: check instance_id + and database_id, and use a database created by create_database. """ spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) @@ -657,8 +699,22 @@ def delete_data(instance_id, database_id): # [START spanner_query_data] -def query_data(instance_id, database_id): - """Queries sample data from the database using SQL.""" +def query_data(instance_id: str, database_id: str) -> None: + """Queries sample data from the database using SQL. + + Prints one line for each row of the Albums table. The query has no + ORDER BY clause, so the rows can print in any order. + + 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.InvalidArgument: The Albums table does not + exist. Recovery: use a database created by create_database. + google.api_core.exceptions.NotFound: 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) @@ -668,16 +724,31 @@ def query_data(instance_id, database_id): "SELECT SingerId, AlbumId, AlbumTitle FROM Albums" ) - for row in results: - print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*row)) + for singer_id, album_id, album_title in results: + print( + f"SingerId: {singer_id}, AlbumId: {album_id}, AlbumTitle: {album_title}" + ) # [END spanner_query_data] # [START spanner_read_data] -def read_data(instance_id, database_id): - """Reads sample data from the database.""" +def read_data(instance_id: str, database_id: str) -> None: + """Reads sample data from the database. + + Prints one line for each row of the Albums table. This is a key read, + which returns rows in primary-key order: by SingerId, then by AlbumId. + + 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.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. + """ spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) database = instance.database(database_id) @@ -688,8 +759,10 @@ def read_data(instance_id, database_id): table="Albums", columns=("SingerId", "AlbumId", "AlbumTitle"), keyset=keyset ) - for row in results: - print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*row)) + for singer_id, album_id, album_title in results: + print( + f"SingerId: {singer_id}, AlbumId: {album_id}, AlbumTitle: {album_title}" + ) # [END spanner_read_data] @@ -722,7 +795,7 @@ def read_stale_data(instance_id, database_id): # [START spanner_query_data_with_new_column] -def query_data_with_new_column(instance_id, database_id): +def query_data_with_new_column(instance_id: str, database_id: str) -> None: """Queries sample data from the database using SQL. This sample uses the `MarketingBudget` column. You can add the column @@ -730,6 +803,20 @@ def query_data_with_new_column(instance_id, database_id): your database: ALTER TABLE Albums ADD COLUMN MarketingBudget INT64 + + A row whose MarketingBudget is NULL prints "MarketingBudget: None". The + query has no ORDER BY clause, so the rows can print in any order. + + Args: + instance_id: ID of the Spanner instance. + database_id: ID of a database where the add_column sample has run. + + Raises: + google.api_core.exceptions.InvalidArgument: The Albums table or its + MarketingBudget column does not exist. Recovery: use a database + created by create_database, and run add_column on it. + google.api_core.exceptions.NotFound: 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) @@ -740,16 +827,39 @@ def query_data_with_new_column(instance_id, database_id): "SELECT SingerId, AlbumId, MarketingBudget FROM Albums" ) - for row in results: - print("SingerId: {}, AlbumId: {}, MarketingBudget: {}".format(*row)) + for singer_id, album_id, marketing_budget in results: + print( + f"SingerId: {singer_id}, AlbumId: {album_id}, " + f"MarketingBudget: {marketing_budget}" + ) # [END spanner_query_data_with_new_column] # [START spanner_create_index] -def add_index(instance_id, database_id): - """Adds a simple index to the example database.""" +def add_index(instance_id: str, database_id: str) -> None: + """Adds a simple index to the example database. + + The index, AlbumsByAlbumTitle, is on the AlbumTitle column of the Albums + table. 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 index 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 index exists before you run this + sample again. + """ from google.cloud.spanner_admin_database_v1.types import spanner_database_admin @@ -763,10 +873,10 @@ def add_index(instance_id, database_id): statements=["CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)"], ) - 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 AlbumsByAlbumTitle index.") @@ -820,7 +930,7 @@ def query_data_with_index( # [START spanner_read_data_with_index] -def read_data_with_index(instance_id, database_id): +def read_data_with_index(instance_id: str, database_id: str) -> None: """Reads sample data from the database using an index. The index must exist before running this sample. You can add the index @@ -829,6 +939,16 @@ def read_data_with_index(instance_id, database_id): CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle) + Rows print in the order of the index: by AlbumTitle. + + Args: + instance_id: ID of the Spanner instance. + database_id: ID of a database where the add_index sample has run. + + Raises: + google.api_core.exceptions.NotFound: The instance, the database, the + Albums table, or the AlbumsByAlbumTitle index does not exist. + Recovery: check instance_id and database_id, then run add_index. """ spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) @@ -843,16 +963,39 @@ def read_data_with_index(instance_id, database_id): index="AlbumsByAlbumTitle", ) - for row in results: - print("AlbumId: {}, AlbumTitle: {}".format(*row)) + for album_id, album_title in results: + print(f"AlbumId: {album_id}, AlbumTitle: {album_title}") # [END spanner_read_data_with_index] # [START spanner_create_storing_index] -def add_storing_index(instance_id, database_id): - """Adds an storing index to the example database.""" +def add_storing_index(instance_id: str, database_id: str) -> None: + """Adds a storing index to the example database. + + The index, AlbumsByAlbumTitle2, is on the AlbumTitle column and stores a + copy of MarketingBudget, so a read that uses the index can return that + column. 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 where the add_column sample has run. + + Raises: + google.api_core.exceptions.FailedPrecondition: The index already + exists. Recovery: continue with the next step. + google.api_core.exceptions.InvalidArgument: The Albums table has no + MarketingBudget column. Recovery: run the add_column sample. + 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 index exists before you run this + sample again. + """ from google.cloud.spanner_admin_database_v1.types import spanner_database_admin @@ -869,10 +1012,10 @@ def add_storing_index(instance_id, database_id): ], ) - 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 AlbumsByAlbumTitle2 index.") @@ -881,17 +1024,29 @@ def add_storing_index(instance_id, database_id): # [START spanner_read_data_with_storing_index] -def read_data_with_storing_index(instance_id, database_id): +def read_data_with_storing_index(instance_id: str, database_id: str) -> None: """Reads sample data from the database using an index with a storing clause. The index must exist before running this sample. You can add the index - by running the `add_scoring_index` sample or by running this DDL statement + by running the `add_storing_index` sample or by running this DDL statement against your database: CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget) + Rows print in the order of the index: by AlbumTitle. + + Args: + instance_id: ID of the Spanner instance. + database_id: ID of a database where the add_storing_index sample has + run. + + Raises: + google.api_core.exceptions.NotFound: The instance, the database, the + Albums table, or the AlbumsByAlbumTitle2 index does not exist. + Recovery: check instance_id and database_id, then run + add_storing_index. """ spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) @@ -906,16 +1061,39 @@ def read_data_with_storing_index(instance_id, database_id): index="AlbumsByAlbumTitle2", ) - for row in results: - print("AlbumId: {}, AlbumTitle: {}, MarketingBudget: {}".format(*row)) + for album_id, album_title, marketing_budget in results: + print( + f"AlbumId: {album_id}, AlbumTitle: {album_title}, " + f"MarketingBudget: {marketing_budget}" + ) # [END spanner_read_data_with_storing_index] # [START spanner_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 INT64 and is NULL in every + existing row. 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 @@ -931,10 +1109,10 @@ def add_column(instance_id, database_id): ], ) - 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.") @@ -942,7 +1120,7 @@ def add_column(instance_id, database_id): # [START spanner_update_data] -def update_data(instance_id, database_id): +def update_data(instance_id: str, database_id: str) -> None: """Updates sample data in the database. This updates the `MarketingBudget` column which must be created before @@ -951,6 +1129,20 @@ def update_data(instance_id, database_id): ALTER TABLE Albums ADD COLUMN MarketingBudget INT64 + The update sets MarketingBudget to 100000 for the album with SingerId 1 + and AlbumId 1, and to 500000 for the album with SingerId 2 and AlbumId 2. + It is atomic: if either row is missing, neither row is updated. + + Args: + instance_id: ID of the Spanner instance. + database_id: ID of a database where the insert_data and add_column + samples have run. + + Raises: + google.api_core.exceptions.NotFound: The instance, the database, the + Albums table, the MarketingBudget column, or one of the two rows + does not exist. Recovery: check instance_id and database_id, + then run insert_data and add_column. """ spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) @@ -1039,11 +1231,26 @@ def update_albums(transaction): # [START spanner_read_only_transaction] -def read_only_transaction(instance_id, database_id): +def read_only_transaction(instance_id: str, database_id: str) -> None: """Reads data inside of a read-only transaction. Within the read-only transaction, or "snapshot", the application sees consistent view of the database at a particular timestamp. + + Both reads return the same rows, even if another transaction changes the + table between them. The first read is a SQL query without ORDER BY, so + its rows can print in any order. The second is a key read, which returns + rows in primary-key order. + + 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.InvalidArgument: The Albums table does not + exist. Recovery: use a database created by create_database. + google.api_core.exceptions.NotFound: 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) @@ -1055,9 +1262,13 @@ def read_only_transaction(instance_id, database_id): "SELECT SingerId, AlbumId, AlbumTitle FROM Albums" ) + # Finish this loop before the next read. A read that is sent before + # this result is read raises ValueError. print("Results from first read:") - for row in results: - print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*row)) + for singer_id, album_id, album_title in results: + print( + f"SingerId: {singer_id}, AlbumId: {album_id}, AlbumTitle: {album_title}" + ) # Perform another read using the `read` method. Even if the data # is updated in-between the reads, the snapshot ensures that both @@ -1068,8 +1279,10 @@ def read_only_transaction(instance_id, database_id): ) print("Results from second read:") - for row in results: - print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*row)) + for singer_id, album_id, album_title in results: + print( + f"SingerId: {singer_id}, AlbumId: {album_id}, AlbumTitle: {album_title}" + ) # [END spanner_read_only_transaction] @@ -1838,13 +2051,30 @@ def write_with_struct(transaction): def insert_with_dml(instance_id, database_id): """Inserts data with a DML statement into the database.""" # [START spanner_dml_getting_started_insert] + from google.cloud.spanner_v1.transaction import Transaction + # instance_id = "your-spanner-instance" # database_id = "your-spanner-db-id" spanner_client = spanner.Client() instance = spanner_client.instance(instance_id) database = instance.database(database_id) - def insert_singers(transaction): + def insert_singers(transaction: Transaction) -> None: + """Inserts four singers with one DML statement. + + The client library commits the transaction after this function + returns. It calls this function again if Spanner aborts the + transaction, so the print statement can run more than once. + + Raises: + google.api_core.exceptions.AlreadyExists: A singer with one of + these IDs already exists. The statement inserts none of the + four rows. Recovery: if this sample already ran, continue + with the next step. + google.api_core.exceptions.InvalidArgument: The Singers table + does not exist. Recovery: use a database created by the + create_database sample. + """ row_ct = transaction.execute_update( "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES " "(12, 'Melissa', 'Garcia'), " @@ -1854,6 +2084,8 @@ def insert_singers(transaction): ) print("{} record(s) inserted.".format(row_ct)) + # Raises google.api_core.exceptions.NotFound if the instance or the + # database does not exist. Recovery: check instance_id and database_id. database.run_in_transaction(insert_singers) # [END spanner_dml_getting_started_insert] @@ -1895,6 +2127,14 @@ def query_data_with_parameter(instance_id, database_id): # [START spanner_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. + # + # 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) @@ -1907,14 +2147,18 @@ def query_data_with_parameter(instance_id, database_id): param_types={"lastName": 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_query_with_parameter] def write_with_dml_transaction(instance_id, database_id): """Transfers part of a marketing budget from one album to another.""" # [START spanner_dml_getting_started_update] + from google.cloud.spanner_v1.transaction import Transaction + # instance_id = "your-spanner-instance" # database_id = "your-spanner-db-id" @@ -1922,54 +2166,85 @@ def write_with_dml_transaction(instance_id, database_id): instance = spanner_client.instance(instance_id) database = instance.database(database_id) - def transfer_budget(transaction): + def transfer_budget(transaction: Transaction) -> None: + """Moves 200000 of marketing budget from one album to another. + + The budget moves from the album with SingerId 2 and AlbumId 2 to the + album with SingerId 1 and AlbumId 1. The client library commits the + transaction after this function returns, and calls this function + again if Spanner aborts the transaction, so the print statement can + run more than once. If this function raises ValueError, the client + library rolls the transaction back, so the transaction changes no + budget. + + Raises: + ValueError: One of the two album rows is missing, its + MarketingBudget is NULL, or the second album has less than + the transfer amount. Recovery: run insert_data if the rows + are missing, then run update_data, which sets both budgets. + google.api_core.exceptions.InvalidArgument: The Albums table or + its MarketingBudget column does not exist. Recovery: use a + database created by create_database, and run add_column on + it. + """ # Transfer marketing budget from one album to another. Performed in a # single transaction to ensure that the transfer is atomic. second_album_result = transaction.execute_sql( "SELECT MarketingBudget from Albums WHERE SingerId = 2 and AlbumId = 2" ) - second_album_row = list(second_album_result)[0] - second_album_budget = second_album_row[0] + second_album_rows = list(second_album_result) + if not second_album_rows: + raise ValueError("Album not found: SingerId=2, AlbumId=2") + (second_album_budget,) = second_album_rows[0] + if second_album_budget is None: + raise ValueError("MarketingBudget is NULL: SingerId=2, AlbumId=2") transfer_amount = 200000 - # Transaction will only be committed if this condition still holds at - # the time of commit. Otherwise it will be aborted and the callable - # will be rerun by the client library - if second_album_budget >= transfer_amount: - first_album_result = transaction.execute_sql( - "SELECT MarketingBudget from Albums WHERE SingerId = 1 and AlbumId = 1" - ) - first_album_row = list(first_album_result)[0] - first_album_budget = first_album_row[0] - - second_album_budget -= transfer_amount - first_album_budget += transfer_amount - - # Update first album - transaction.execute_update( - "UPDATE Albums " - "SET MarketingBudget = @AlbumBudget " - "WHERE SingerId = 1 and AlbumId = 1", - params={"AlbumBudget": first_album_budget}, - param_types={"AlbumBudget": spanner.param_types.INT64}, + # Transaction will only be committed if the second album still has + # enough budget at the time of commit. Otherwise it will be aborted + # and the callable will be rerun by the client library. + if second_album_budget < transfer_amount: + raise ValueError( + "Insufficient MarketingBudget: SingerId=2, AlbumId=2, " + f"{second_album_budget=}, {transfer_amount=}" ) - # Update second album - transaction.execute_update( - "UPDATE Albums " - "SET MarketingBudget = @AlbumBudget " - "WHERE SingerId = 2 and AlbumId = 2", - params={"AlbumBudget": second_album_budget}, - param_types={"AlbumBudget": spanner.param_types.INT64}, - ) + first_album_result = transaction.execute_sql( + "SELECT MarketingBudget from Albums WHERE SingerId = 1 and AlbumId = 1" + ) + first_album_rows = list(first_album_result) + if not first_album_rows: + raise ValueError("Album not found: SingerId=1, AlbumId=1") + (first_album_budget,) = first_album_rows[0] + if first_album_budget is None: + raise ValueError("MarketingBudget is NULL: SingerId=1, AlbumId=1") - print( - "Transferred {} from Album2's budget to Album1's".format( - transfer_amount - ) - ) + second_album_budget -= transfer_amount + first_album_budget += transfer_amount + + # Update first album + transaction.execute_update( + "UPDATE Albums " + "SET MarketingBudget = @AlbumBudget " + "WHERE SingerId = 1 and AlbumId = 1", + params={"AlbumBudget": first_album_budget}, + param_types={"AlbumBudget": spanner.param_types.INT64}, + ) + + # Update second album + transaction.execute_update( + "UPDATE Albums " + "SET MarketingBudget = @AlbumBudget " + "WHERE SingerId = 2 and AlbumId = 2", + params={"AlbumBudget": second_album_budget}, + param_types={"AlbumBudget": spanner.param_types.INT64}, + ) + + print("Transferred {} from Album2's budget to Album1's".format(transfer_amount)) + # Raises google.api_core.exceptions.NotFound if the instance or the + # database does not exist. Recovery: check instance_id and database_id. database.run_in_transaction(transfer_budget) # [END spanner_dml_getting_started_update]