Skip to content
This repository was archived by the owner on Mar 13, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 2 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
64 changes: 64 additions & 0 deletions samples/date_and_timestamp_sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Copyright 2024 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import uuid

from sqlalchemy import create_engine
from sqlalchemy.orm import Session

from sample_helper import run_sample
from model import Singer, Concert, Venue


# Shows how to map and use the DATE and TIMESTAMP data types in Spanner.
def date_and_timestamp_sample():
engine = create_engine(
"spanner:///projects/sample-project/"
"instances/sample-instance/"
"databases/sample-database",
echo=True,
)
with Session(engine) as session:
# Singer has a property birthdate, which is mapped to a DATE column.
# Use the datetime.date type for this.
singer = Singer(
id=str(uuid.uuid4()),
first_name="John",
last_name="Doe",
birthdate=datetime.date(1979, 10, 14),
)
venue = Venue(code="CH", name="Concert Hall", active=True)
# Concert has a property `start_time`, which is mapped to a TIMESTAMP
# column. Use the datetime.datetime type for this.
concert = Concert(
venue=venue,
start_time=datetime.datetime(2024, 11, 7, 19, 30, 0),
singer=singer,
title="John Doe - Live in Concert Hall",
)
session.add_all([singer, venue, concert])
session.commit()

# Use AUTOCOMMIT for sessions that only read. This is more
# efficient than using a read/write transaction to only read.
session.connection(execution_options={"isolation_level": "AUTOCOMMIT"})
print(
f"{singer.full_name}, born on {singer.birthdate}, has planned "
f"a concert that starts on {concert.start_time} in {venue.name}."
Comment on lines +58 to +59

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (private)](1) as clear text.
)


if __name__ == "__main__":
run_sample(date_and_timestamp_sample)
31 changes: 31 additions & 0 deletions samples/hello_world_sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright 2024 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from sqlalchemy import create_engine, select, text
from sample_helper import run_sample


def quickstart():
engine = create_engine(
"spanner:///projects/sample-project/"
"instances/sample-instance/"
"databases/sample-database"
)
with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as connection:
results = connection.execute(select(text("'Hello World!'"))).fetchall()
print("\nMessage from Spanner: ", results[0][0], "\n")


if __name__ == "__main__":
run_sample(quickstart)
73 changes: 73 additions & 0 deletions samples/insert_data_sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Copyright 2024 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import uuid

from sqlalchemy import create_engine
from sqlalchemy.orm import Session

from sample_helper import run_sample
from model import Singer, Album, Track

# Shows how to insert data using SQLAlchemy, including relationships that are
# defined both as foreign keys and as interleaved tables.
def insert_data():
engine = create_engine(
"spanner:///projects/sample-project/"
"instances/sample-instance/"
"databases/sample-database",
echo=True,
)
with Session(engine) as session:
singer = Singer(
id=str(uuid.uuid4()),
first_name="John",
last_name="Smith",
albums=[
Album(
id=str(uuid.uuid4()),
title="Rainforest",
tracks=[
# Track is INTERLEAVED IN PARENT Album, but can be treated
# as a normal relationship in SQLAlchemy.
Track(track_number=1, title="Green"),
Track(track_number=2, title="Blue"),
Track(track_number=3, title="Yellow"),
],
),
Album(
id=str(uuid.uuid4()),
title="Butterflies",
tracks=[
Track(track_number=1, title="Purple"),
Track(track_number=2, title="Cyan"),
Track(track_number=3, title="Mauve"),
],
),
],
)
session.add(singer)
session.commit()

# Use AUTOCOMMIT for sessions that only read. This is more
# efficient than using a read/write transaction to only read.
session.connection(execution_options={"isolation_level": "AUTOCOMMIT"})
print(
f"Inserted singer {singer.full_name} with {len(singer.albums)} "
f"albums successfully"
)


if __name__ == "__main__":
run_sample(insert_data)
155 changes: 155 additions & 0 deletions samples/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
# Copyright 2024 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
from typing import Optional, List

from sqlalchemy import (
String,
Computed,
Date,
LargeBinary,
Integer,
Numeric,
ForeignKey,
JSON,
Boolean,
DateTime,
BigInteger,
ARRAY,
ForeignKeyConstraint,
Sequence,
TextClause,
)
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
pass


# Most models in this sample use a client-side generated UUID as primary key.
# This allows inserts to use Batch DML, as the primary key value does not need
# to be returned from Spanner using a THEN RETURN clause.
#
# The TicketSale model uses a bit-reversed sequence for primary key generation.
# This is achieved by creating a bit-reversed sequence and assigning the id
# column of the model a server_default value that gets the next value from that
# sequence.


class Singer(Base):
__tablename__ = "singers"
id: Mapped[str] = mapped_column(String(36), primary_key=True)
first_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
last_name: Mapped[str] = mapped_column(String(200), nullable=False)
full_name: Mapped[str] = mapped_column(
String, Computed("COALESCE(first_name || ' ', '') || last_name")
)
birthdate: Mapped[Optional[datetime.date]] = mapped_column(Date, nullable=True)
picture: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
albums: Mapped[List["Album"]] = relationship(
back_populates="singer", cascade="all, delete-orphan"
)
concerts: Mapped[List["Concert"]] = relationship(
back_populates="singer", cascade="all, delete-orphan"
)


class Album(Base):
__tablename__ = "albums"
id: Mapped[str] = mapped_column(String(36), primary_key=True)
title: Mapped[str] = mapped_column(String(200), nullable=False)
release_date: Mapped[Optional[datetime.date]] = mapped_column(Date, nullable=True)
singer_id: Mapped[str] = mapped_column(ForeignKey("singers.id"))
singer: Mapped["Singer"] = relationship(back_populates="albums")
tracks: Mapped[List["Track"]] = relationship(
back_populates="album",
primaryjoin="Album.id == foreign(Track.id)",
)


class Track(Base):
__tablename__ = "tracks"
# This interleaves the table `tracks` in its parent `albums`.
__table_args__ = {
"spanner_interleave_in": "albums",
"spanner_interleave_on_delete_cascade": True,
}
id: Mapped[str] = mapped_column(String(36), primary_key=True)
track_number: Mapped[int] = mapped_column(Integer, primary_key=True)
title: Mapped[str] = mapped_column(String(200), nullable=False)
duration: Mapped[Optional[float]] = mapped_column(Numeric, nullable=True)
album: Mapped["Album"] = relationship(
back_populates="tracks",
foreign_keys=[id],
primaryjoin="Track.id == Album.id",
remote_side="Album.id",
)


# SQLAlchemy does not know what 'spanner_interleave_in' means, so we need to
# explicitly tell SQLAlchemy that `tracks` depends on `albums`, and that
# `albums` therefore must be created before `tracks`.
Track.__table__.add_is_dependent_on(Album.__table__)


class Venue(Base):
__tablename__ = "venues"
code: Mapped[str] = mapped_column(String(10), primary_key=True)
name: Mapped[str] = mapped_column(String(200), nullable=False)
description: Mapped[str] = mapped_column(JSON, nullable=True)
active: Mapped[bool] = mapped_column(Boolean, nullable=False)
concerts: Mapped[List["Concert"]] = relationship(
back_populates="venue", cascade="all, delete-orphan"
)


class Concert(Base):
__tablename__ = "concerts"
venue_code: Mapped[str] = mapped_column(
String(10), ForeignKey("venues.code"), primary_key=True
)
start_time: Mapped[Optional[datetime.datetime]] = mapped_column(
DateTime, primary_key=True, nullable=False
)
singer_id: Mapped[str] = mapped_column(
String(36), ForeignKey("singers.id"), primary_key=True
)
title: Mapped[str] = mapped_column(String(200), nullable=False)
singer: Mapped["Singer"] = relationship(back_populates="concerts")
venue: Mapped["Venue"] = relationship(back_populates="concerts")


class TicketSale(Base):
__tablename__ = "ticket_sales"
__table_args__ = (
ForeignKeyConstraint(
["venue_code", "start_time", "singer_id"],
["concerts.venue_code", "concerts.start_time", "concerts.singer_id"],
),
)
id: Mapped[int] = mapped_column(
BigInteger,
Sequence("ticket_sale_id"),
server_default=TextClause("GET_NEXT_SEQUENCE_VALUE(SEQUENCE ticket_sale_id)"),
primary_key=True,
)
customer_name: Mapped[str] = mapped_column(String(200), nullable=False)
seats: Mapped[list[str]] = mapped_column(ARRAY(String(20)), nullable=False)
venue_code: Mapped[str] = mapped_column(String(10), ForeignKey("venues.code"))
start_time: Mapped[Optional[datetime.datetime]] = mapped_column(
DateTime, nullable=False
)
singer_id: Mapped[str] = mapped_column(String(36), ForeignKey("singers.id"))
36 changes: 36 additions & 0 deletions samples/noxfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Copyright 2024 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import nox


@nox.session()
def hello_world(session):
_sample(session)


@nox.session()
def create_tables(session):
_sample(session)


def _sample(session):
session.install("testcontainers")
session.install("sqlalchemy")
session.install("setuptools")
session.install(
"git+https://github.com/googleapis/python-spanner.git#egg=google-cloud-spanner"
)
session.install("../.")
session.run("python", session.name + "_sample.py")
Loading