Python Client for Cloud Spanner
===============================
|GA| |pypi| |versions|
`Cloud Spanner`_ is 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 Documentation`_
- `Product Documentation`_
.. |GA| image:: https://img.shields.io/badge/support-GA-gold.svg
:target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#general-availability
.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-spanner.svg
:target: https://pypi.org/project/google-cloud-spanner/
.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-spanner.svg
:target: https://pypi.org/project/google-cloud-spanner/
.. _Cloud Spanner: https://cloud.google.com/spanner/
.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/spanner/latest
.. _Product Documentation: https://cloud.google.com/spanner/docs
Quick Start
-----------
In order to use this library, you first need to go through the following steps:
1. `Select or create a Cloud Platform project.`_
2. `Enable billing for your project.`_
3. `Enable the Google Cloud Spanner API.`_
4. `Setup Authentication.`_
.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project
.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project
.. _Enable the Google Cloud Spanner API.: https://cloud.google.com/spanner
.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html
Installation
~~~~~~~~~~~~
Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to
create isolated Python environments. The basic problem it addresses is one of
dependencies and versions, and indirectly permissions.
With `virtualenv`_, it's possible to install this library without needing system
install permissions, and without clashing with the installed system
dependencies.
.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/
Supported Python Versions
^^^^^^^^^^^^^^^^^^^^^^^^^
Python >= 3.7
Deprecated Python Versions
^^^^^^^^^^^^^^^^^^^^^^^^^^
Python == 2.7.
Python == 3.5.
Python == 3.6.
Mac/Linux
^^^^^^^^^
.. code-block:: console
pip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-spanner
Windows
^^^^^^^
.. code-block:: console
pip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-cloud-spanner
Example Usage
-------------
Executing Arbitrary SQL in a Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generally, 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 to ``database.run_in_transaction``:
.. code:: python
# First, define the function that represents a single "unit of work"
# that should be run within the transaction.
def update_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 Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Once you have a transaction object (such as the first argument sent to
``run_in_transaction``), reading data is easy:
.. code:: python
# 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)
for row in result.rows:
print(row)
Insert records using Data Manipulation Language (DML) with a Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use the ``execute_update()`` method to execute a DML statement:
.. code:: python
spanner_client = spanner.Client()
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
def insert_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 Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To add one or more records to a table, use ``insert``:
.. code:: python
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 Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: python
spanner_client = spanner.Client()
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
def update_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 Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``Transaction.update`` updates one or more existing records in a table. Fails
if any of the records does not already exist.
.. code:: python
transaction.update(
'citizens',
columns=['email', 'age'],
values=[
['phred@exammple.com', 33],
['bharney@example.com', 32],
],
)
Connection API
--------------
Connection 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:
.. code:: python
from google.cloud.spanner_dbapi.connection import connect
connection = connect("instance-id", "database-id")
connection.autocommit = True
cursor = connection.cursor()
cursor.execute("SELECT * FROM table_name")
result = cursor.fetchall()
Aborted Transactions Retry Mechanism
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In ``!autocommit`` mode, 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 ``!autocommit`` mode, as in ``autocommit`` mode transactions are never aborted.
Next Steps
~~~~~~~~~~
- See the `Client Library Documentation`_ to learn how to connect to Cloud
Spanner using this Client Library.
- Read the `Product documentation`_ to learn
more about the product and see How-to Guides.
Raw data
{
"_id": null,
"home_page": "https://github.com/googleapis/python-spanner",
"name": "google-cloud-spanner",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": null,
"author": "Google LLC",
"author_email": "googleapis-packages@google.com",
"download_url": "https://files.pythonhosted.org/packages/f5/42/1459e6677381389cd96c098b5f515b4c6da28c899389d84043e9ac11b096/google_cloud_spanner-3.50.1.tar.gz",
"platform": "Posix; MacOS X; Windows",
"description": "Python Client for Cloud Spanner\n===============================\n\n|GA| |pypi| |versions| \n\n`Cloud Spanner`_ is the world's first fully managed relational database service\nto offer both strong consistency and horizontal scalability for\nmission-critical online transaction processing (OLTP) applications. With Cloud\nSpanner you enjoy all the traditional benefits of a relational database; but\nunlike any other relational database service, Cloud Spanner scales horizontally\nto hundreds or thousands of servers to handle the biggest transactional\nworkloads.\n\n\n- `Client Library Documentation`_\n- `Product Documentation`_\n\n.. |GA| image:: https://img.shields.io/badge/support-GA-gold.svg\n :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#general-availability\n.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-spanner.svg\n :target: https://pypi.org/project/google-cloud-spanner/\n.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-spanner.svg\n :target: https://pypi.org/project/google-cloud-spanner/\n.. _Cloud Spanner: https://cloud.google.com/spanner/\n.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/spanner/latest\n.. _Product Documentation: https://cloud.google.com/spanner/docs\n\nQuick Start\n-----------\n\nIn order to use this library, you first need to go through the following steps:\n\n1. `Select or create a Cloud Platform project.`_\n2. `Enable billing for your project.`_\n3. `Enable the Google Cloud Spanner API.`_\n4. `Setup Authentication.`_\n\n.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project\n.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project\n.. _Enable the Google Cloud Spanner API.: https://cloud.google.com/spanner\n.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html\n\nInstallation\n~~~~~~~~~~~~\n\nInstall this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to\ncreate isolated Python environments. The basic problem it addresses is one of\ndependencies and versions, and indirectly permissions.\n\nWith `virtualenv`_, it's possible to install this library without needing system\ninstall permissions, and without clashing with the installed system\ndependencies.\n\n.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/\n\n\nSupported Python Versions\n^^^^^^^^^^^^^^^^^^^^^^^^^\nPython >= 3.7\n\nDeprecated Python Versions\n^^^^^^^^^^^^^^^^^^^^^^^^^^\nPython == 2.7.\nPython == 3.5.\nPython == 3.6.\n\n\nMac/Linux\n^^^^^^^^^\n\n.. code-block:: console\n\n pip install virtualenv\n virtualenv <your-env>\n source <your-env>/bin/activate\n <your-env>/bin/pip install google-cloud-spanner\n\n\nWindows\n^^^^^^^\n\n.. code-block:: console\n\n pip install virtualenv\n virtualenv <your-env>\n <your-env>\\Scripts\\activate\n <your-env>\\Scripts\\pip.exe install google-cloud-spanner\n\n\nExample Usage\n-------------\n\n\nExecuting Arbitrary SQL in a Transaction\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nGenerally, to work with Cloud Spanner, you will want a transaction. The\npreferred mechanism for this is to create a single function, which executes\nas a callback to ``database.run_in_transaction``:\n\n.. code:: python\n\n # First, define the function that represents a single \"unit of work\"\n # that should be run within the transaction.\n def update_anniversary(transaction, person_id, unix_timestamp):\n # The query itself is just a string.\n #\n # The use of @parameters is recommended rather than doing your\n # own string interpolation; this provides protections against\n # SQL injection attacks.\n query = \"\"\"SELECT anniversary FROM people\n WHERE id = @person_id\"\"\"\n\n # When executing the SQL statement, the query and parameters are sent\n # as separate arguments. When using parameters, you must specify\n # both the parameters themselves and their types.\n row = transaction.execute_sql(\n query=query,\n params={'person_id': person_id},\n param_types={\n 'person_id': types.INT64_PARAM_TYPE,\n },\n ).one()\n\n # Now perform an update on the data.\n old_anniversary = row[0]\n new_anniversary = _compute_anniversary(old_anniversary, years)\n transaction.update(\n 'people',\n ['person_id', 'anniversary'],\n [person_id, new_anniversary],\n )\n\n # Actually run the `update_anniversary` function in a transaction.\n database.run_in_transaction(update_anniversary,\n person_id=42,\n unix_timestamp=1335020400,\n )\n\n\nSelect records using a Transaction\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nOnce you have a transaction object (such as the first argument sent to\n``run_in_transaction``), reading data is easy:\n\n.. code:: python\n\n # Define a SELECT query.\n query = \"\"\"SELECT e.first_name, e.last_name, p.telephone\n FROM employees as e, phones as p\n WHERE p.employee_id == e.employee_id\"\"\"\n\n # Execute the query and return results.\n result = transaction.execute_sql(query)\n for row in result.rows:\n print(row)\n\n\nInsert records using Data Manipulation Language (DML) with a Transaction\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nUse the ``execute_update()`` method to execute a DML statement:\n\n.. code:: python\n\n spanner_client = spanner.Client()\n instance = spanner_client.instance(instance_id)\n database = instance.database(database_id)\n\n def insert_singers(transaction):\n row_ct = transaction.execute_update(\n \"INSERT Singers (SingerId, FirstName, LastName) \"\n \" VALUES (10, 'Virginia', 'Watson')\"\n )\n\n print(\"{} record(s) inserted.\".format(row_ct))\n\n database.run_in_transaction(insert_singers)\n\n\nInsert records using Mutations with a Transaction\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo add one or more records to a table, use ``insert``:\n\n.. code:: python\n\n transaction.insert(\n 'citizens',\n columns=['email', 'first_name', 'last_name', 'age'],\n values=[\n ['phred@exammple.com', 'Phred', 'Phlyntstone', 32],\n ['bharney@example.com', 'Bharney', 'Rhubble', 31],\n ],\n )\n\n\nUpdate records using Data Manipulation Language (DML) with a Transaction\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: python\n\n spanner_client = spanner.Client()\n instance = spanner_client.instance(instance_id)\n database = instance.database(database_id)\n\n def update_albums(transaction):\n row_ct = transaction.execute_update(\n \"UPDATE Albums \"\n \"SET MarketingBudget = MarketingBudget * 2 \"\n \"WHERE SingerId = 1 and AlbumId = 1\"\n )\n\n print(\"{} record(s) updated.\".format(row_ct))\n\n database.run_in_transaction(update_albums)\n\n\nUpdate records using Mutations with a Transaction\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``Transaction.update`` updates one or more existing records in a table. Fails\nif any of the records does not already exist.\n\n.. code:: python\n\n transaction.update(\n 'citizens',\n columns=['email', 'age'],\n values=[\n ['phred@exammple.com', 33],\n ['bharney@example.com', 32],\n ],\n )\n\n\nConnection API\n--------------\nConnection 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:\n\n.. code:: python\n\n from google.cloud.spanner_dbapi.connection import connect\n\n connection = connect(\"instance-id\", \"database-id\")\n connection.autocommit = True\n\n cursor = connection.cursor() \n cursor.execute(\"SELECT * FROM table_name\")\n\n result = cursor.fetchall()\n\n\nAborted Transactions Retry Mechanism\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn ``!autocommit`` mode, 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.\n\nAuto-retry of aborted transactions is enabled only for ``!autocommit`` mode, as in ``autocommit`` mode transactions are never aborted.\n\n\nNext Steps\n~~~~~~~~~~\n\n- See the `Client Library Documentation`_ to learn how to connect to Cloud\n Spanner using this Client Library.\n- Read the `Product documentation`_ to learn\n more about the product and see How-to Guides.\n",
"bugtrack_url": null,
"license": "Apache 2.0",
"summary": "Google Cloud Spanner API client library",
"version": "3.50.1",
"project_urls": {
"Homepage": "https://github.com/googleapis/python-spanner"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "1cce35abda83da7eacf458a55f628d350bb7c8f91215767b45a5cd2da4528e9b",
"md5": "adfea621ddd0ce6709ad30ea3d038491",
"sha256": "9d399aa53fae58816023a4eb31fa267333c3a879a9221229e7f06fdda543884a"
},
"downloads": -1,
"filename": "google_cloud_spanner-3.50.1-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "adfea621ddd0ce6709ad30ea3d038491",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": ">=3.7",
"size": 416477,
"upload_time": "2024-11-14T10:29:53",
"upload_time_iso_8601": "2024-11-14T10:29:53.503736Z",
"url": "https://files.pythonhosted.org/packages/1c/ce/35abda83da7eacf458a55f628d350bb7c8f91215767b45a5cd2da4528e9b/google_cloud_spanner-3.50.1-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "f5421459e6677381389cd96c098b5f515b4c6da28c899389d84043e9ac11b096",
"md5": "9c6e6b200436351a40d271917cfd1987",
"sha256": "82937ea03b55de86bddf622f555aeae65ae86bb4f28ab35bd920ac505917c9bf"
},
"downloads": -1,
"filename": "google_cloud_spanner-3.50.1.tar.gz",
"has_sig": false,
"md5_digest": "9c6e6b200436351a40d271917cfd1987",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 575566,
"upload_time": "2024-11-14T10:29:55",
"upload_time_iso_8601": "2024-11-14T10:29:55.300403Z",
"url": "https://files.pythonhosted.org/packages/f5/42/1459e6677381389cd96c098b5f515b4c6da28c899389d84043e9ac11b096/google_cloud_spanner-3.50.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-14 10:29:55",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "googleapis",
"github_project": "python-spanner",
"travis_ci": false,
"coveralls": true,
"github_actions": true,
"lcname": "google-cloud-spanner"
}