|
| 1 | +# Copyright 2025 Google LLC All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import datetime |
| 16 | +import uuid |
| 17 | + |
| 18 | +from sqlalchemy import create_engine |
| 19 | +from sqlalchemy.orm import Session |
| 20 | + |
| 21 | +from sample_helper import run_sample |
| 22 | +from model import Singer, Concert, Venue, TicketSale |
| 23 | + |
| 24 | + |
| 25 | +# Shows how to use an IDENTITY column for primary key generation. IDENTITY |
| 26 | +# columns use a backing bit-reversed sequence to generate unique values that are |
| 27 | +# safe to use for primary keys in Spanner. |
| 28 | +# |
| 29 | +# IDENTITY columns are used by default by the Spanner SQLAlchemy dialect for |
| 30 | +# standard primary key columns. |
| 31 | +# |
| 32 | +# id: Mapped[int] = mapped_column(primary_key=True) |
| 33 | +# |
| 34 | +# This leads to the following table definition: |
| 35 | +# |
| 36 | +# CREATE TABLE ticket_sales ( |
| 37 | +# id INT64 NOT NULL GENERATED BY DEFAULT AS IDENTITY (BIT_REVERSED_POSITIVE), |
| 38 | +# ... |
| 39 | +# ) PRIMARY KEY (id) |
| 40 | +def auto_generated_primary_key_sample(): |
| 41 | + engine = create_engine( |
| 42 | + "spanner:///projects/sample-project/" |
| 43 | + "instances/sample-instance/" |
| 44 | + "databases/sample-database", |
| 45 | + echo=True, |
| 46 | + ) |
| 47 | + with Session(engine) as session: |
| 48 | + # Venue automatically generates a primary key value using an IDENTITY |
| 49 | + # column. We therefore do not need to specify a primary key value when |
| 50 | + # we create an instance of Venue. |
| 51 | + venue = Venue(code="CH", name="Concert Hall", active=True) |
| 52 | + session.add_all([venue]) |
| 53 | + session.commit() |
| 54 | + |
| 55 | + print("Inserted a venue with ID %d" % venue.id) |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + run_sample(auto_generated_primary_key_sample) |
0 commit comments