Package: google-cloud-spanner
Cloud Spanneris the world’s first fully managed relational database service
to offer both strong consistency and horizontal scalability for
mission-critical online transaction processing (OLTP) applications. With Cloud
Spanner you enjoy all the traditional benefits of a relational database; but
unlike any other relational database service, Cloud Spanner scales horizontally
to hundreds or thousands of servers to handle the biggest transactional
workloads.Client Library DocumentationProduct DocumentationQuick StartIn order to use this library, you first need to go through the following steps:Select or create a Cloud Platform project.Enable billing for your project.Enable the Google Cloud Spanner API.Setup Authentication.InstallationInstall this library in avirtualenvusing pip.virtualenvis a tool to
create isolated Python environments. The basic problem it addresses is one of
dependencies and versions, and indirectly permissions.Withvirtualenv, it’s possible to install this library without needing system
install permissions, and without clashing with the installed system
dependencies.Supported Python VersionsPython >= 3.7Deprecated Python VersionsPython == 2.7.
Python == 3.5.
Python == 3.6.Mac/Linuxpip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-spannerWindowspip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-cloud-spannerExample UsageExecuting Arbitrary SQL in a TransactionGenerally, to work with Cloud Spanner, you will want a transaction. The
preferred mechanism for this is to create a single function, which executes
as a callback todatabase.run_in_transaction:# First, define the function that represents a single "unit of work"# that should be run within the transaction.defupdate_anniversary(transaction,person_id,unix_timestamp):# The query itself is just a string.## The use of @parameters is recommended rather than doing your# own string interpolation; this provides protections against# SQL injection attacks.query="""SELECT anniversary FROM people
        WHERE id = @person_id"""# When executing the SQL statement, the query and parameters are sent# as separate arguments. When using parameters, you must specify# both the parameters themselves and their types.row=transaction.execute_sql(query=query,params={'person_id':person_id},param_types={'person_id':types.INT64_PARAM_TYPE,},).one()# Now perform an update on the data.old_anniversary=row[0]new_anniversary=_compute_anniversary(old_anniversary,years)transaction.update('people',['person_id','anniversary'],[person_id,new_anniversary],)# Actually run the `update_anniversary` function in a transaction.database.run_in_transaction(update_anniversary,person_id=42,unix_timestamp=1335020400,)Select records using a TransactionOnce you have a transaction object (such as the first argument sent torun_in_transaction), reading data is easy:# Define a SELECT query.query="""SELECT e.first_name, e.last_name, p.telephone
    FROM employees as e, phones as p
    WHERE p.employee_id == e.employee_id"""# Execute the query and return results.result=transaction.execute_sql(query)forrowinresult.rows:print(row)Insert records using Data Manipulation Language (DML) with a TransactionUse theexecute_update()method to execute a DML statement:spanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)definsert_singers(transaction):row_ct=transaction.execute_update("INSERT Singers (SingerId, FirstName, LastName) "" VALUES (10, 'Virginia', 'Watson')")print("{}record(s) inserted.".format(row_ct))database.run_in_transaction(insert_singers)Insert records using Mutations with a TransactionTo add one or more records to a table, useinsert:transaction.insert('citizens',columns=['email','first_name','last_name','age'],values=[['phred@exammple.com','Phred','Phlyntstone',32],['bharney@example.com','Bharney','Rhubble',31],],)Update records using Data Manipulation Language (DML) with a Transactionspanner_client=spanner.Client()instance=spanner_client.instance(instance_id)database=instance.database(database_id)defupdate_albums(transaction):row_ct=transaction.execute_update("UPDATE Albums ""SET MarketingBudget = MarketingBudget * 2 ""WHERE SingerId = 1 and AlbumId = 1")print("{}record(s) updated.".format(row_ct))database.run_in_transaction(update_albums)Update records using Mutations with a TransactionTransaction.updateupdates one or more existing records in a table.  Fails
if any of the records does not already exist.transaction.update('citizens',columns=['email','age'],values=[['phred@exammple.com',33],['bharney@example.com',32],],)Connection APIConnection API represents a wrap-around for Python Spanner API, written in accordance with PEP-249, and provides a simple way of communication with a Spanner database through connection objects:fromgoogle.cloud.spanner_dbapi.connectionimportconnectconnection=connect("instance-id","database-id")connection.autocommit=Truecursor=connection.cursor()cursor.execute("SELECT * FROM table_name")result=cursor.fetchall()Aborted Transactions Retry MechanismIn!autocommitmode, transactions can be aborted due to transient errors. In most cases retry of an aborted transaction solves the problem. To simplify it, connection tracks SQL statements, executed in the current transaction. In case the transaction aborted, the connection initiates a new one and re-executes all the statements. In the process, the connection checks that retried statements are returning the same results that the original statements did. If results are different, the transaction is dropped, as the underlying data changed, and auto retry is impossible.Auto-retry of aborted transactions is enabled only for!autocommitmode, as inautocommitmode transactions are never aborted.Next StepsSee theClient Library Documentationto learn how to connect to Cloud
Spanner using this Client Library.Read theProduct documentationto learn
more about the product and see How-to Guides.