GithubHelp home page GithubHelp logo

isabella232 / python-spanner Goto Github PK

View Code? Open in Web Editor NEW

This project forked from googleapis/python-spanner

0.0 0.0 0.0 1.94 MB

License: Apache License 2.0

Shell 2.43% Python 97.32% Dockerfile 0.25%

python-spanner's Introduction

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.

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.

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.

Supported Python Versions

Python >= 3.5

Deprecated Python Versions

Python == 2.7. Python 2.7 support will be removed on January 1, 2020.

Mac/Linux

pip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-spanner

Windows

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:

# 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:

# 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:

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:

transaction.insert(
    'citizens',
    columns=['email', 'first_name', 'last_name', 'age'],
    values=[
        ['[email protected]', 'Phred', 'Phlyntstone', 32],
        ['[email protected]', 'Bharney', 'Rhubble', 31],
    ],
)

Update records using Data Manipulation Language (DML) with a Transaction

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.

transaction.update(
    'citizens',
    columns=['email', 'age'],
    values=[
        ['[email protected]', 33],
        ['[email protected]', 32],
    ],
)

Next Steps

python-spanner's People

Contributors

busunkim96 avatar chemelnucfin avatar cnnradams avatar crwilcox avatar daniellehanks avatar daspecster avatar dhermes avatar dpebot avatar emar-kar avatar haih-g avatar hemangchothani avatar ji-han avatar jsimonweb avatar larkee avatar lukesneeringer avatar nielm avatar potiuk avatar pravindahal avatar release-please[bot] avatar renovate-bot avatar samizuh avatar sethtroisi avatar theacodes avatar tseaver avatar tswast avatar vam-google avatar wchargin avatar weiranfang avatar ylil93 avatar yoshi-automation avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.