1515
1616from datetime import datetime
1717import uuid
18- from sqlalchemy import text , String
19- from sqlalchemy .orm import DeclarativeBase
18+ from sqlalchemy import text , String , create_engine
19+ from sqlalchemy .orm import DeclarativeBase , Session
2020from sqlalchemy .orm import Mapped
2121from sqlalchemy .orm import mapped_column
22+ from sample_helper import run_sample
2223
2324
2425class Base (DeclarativeBase ):
@@ -41,7 +42,7 @@ class Base(DeclarativeBase):
4142
4243
4344class Singer (Base ):
44- __tablename__ = "singers "
45+ __tablename__ = "singers_with_sentinel "
4546 id : Mapped [str ] = mapped_column (
4647 String (36 ),
4748 primary_key = True ,
@@ -56,3 +57,28 @@ class Singer(Base):
5657 inserted_at : Mapped [datetime ] = mapped_column (
5758 server_default = text ("CURRENT_TIMESTAMP()" )
5859 )
60+
61+
62+ # Shows how to insert data using SQLAlchemy, including relationships that are
63+ # defined both as foreign keys and as interleaved tables.
64+ def insertmany ():
65+ engine = create_engine (
66+ "spanner:///projects/sample-project/"
67+ "instances/sample-instance/"
68+ "databases/sample-database" ,
69+ echo = True ,
70+ )
71+ # Create the sample table.
72+ Base .metadata .create_all (engine )
73+
74+ # Insert two singers in one session. These two singers will be inserted using
75+ # a single INSERT statement with a THEN RETURN clause to return the generated
76+ # creation timestamp.
77+ with Session (engine ) as session :
78+ session .add (Singer (name = "John Smith" ))
79+ session .add (Singer (name = "Jane Smith" ))
80+ session .commit ()
81+
82+
83+ if __name__ == "__main__" :
84+ run_sample (insertmany )
0 commit comments