Skip to content

Commit

Permalink
feat: add helper function for insert-or-update
Browse files Browse the repository at this point in the history
Adds helper functions for insert-or-update and insert-or-ignore
and samples for how to use these functions.

Fixes #391
  • Loading branch information
olavloite committed Nov 28, 2024
1 parent ac64472 commit d76c7d6
Show file tree
Hide file tree
Showing 3 changed files with 134 additions and 0 deletions.
26 changes: 26 additions & 0 deletions google/cloud/sqlalchemy_spanner/dml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 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 Insert, insert
from sqlalchemy.sql._typing import _DMLTableArgument


def insert_or_update(table: _DMLTableArgument) -> Insert:
"""Construct a Spanner-specific insert-or-update statement."""
return insert(table).prefix_with("OR UPDATE")


def insert_or_ignore(table: _DMLTableArgument) -> Insert:
"""Construct a Spanner-specific insert-or-ignore statement."""
return insert(table).prefix_with("OR IGNORE")
54 changes: 54 additions & 0 deletions samples/insert_or_ignore_sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 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, select
from sqlalchemy.orm import Session

from google.cloud.sqlalchemy_spanner.dml import insert_or_ignore
from sample_helper import run_sample
from model import Singer

# Shows how to use insert-or-ignore using SQLAlchemy and Spanner.
def insert_or_ignore_sample():
engine = create_engine(
"spanner:///projects/sample-project/"
"instances/sample-instance/"
"databases/sample-database",
echo=True,
)
with Session(engine) as session:
stmt = (
insert_or_ignore(Singer)
.values(
id=str(uuid.uuid4()),
first_name="John",
last_name="Smith",
)
.returning(Singer.id)
)
singer_id = session.execute(stmt).scalar()
print(singer_id)

# 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"})
stmt = select(Singer).where(Singer.id == singer_id)
singer = session.execute(stmt).scalar()
print(f"Inserted or ignored singer {singer.full_name} successfully")


if __name__ == "__main__":
run_sample(insert_or_ignore_sample)
54 changes: 54 additions & 0 deletions samples/insert_or_update_sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 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, select
from sqlalchemy.orm import Session

from google.cloud.sqlalchemy_spanner.dml import insert_or_update
from sample_helper import run_sample
from model import Singer

# Shows how to use insert-or-update using SQLAlchemy and Spanner.
def insert_or_update_sample():
engine = create_engine(
"spanner:///projects/sample-project/"
"instances/sample-instance/"
"databases/sample-database",
echo=True,
)
with Session(engine) as session:
stmt = (
insert_or_update(Singer)
.values(
id=str(uuid.uuid4()),
first_name="John",
last_name="Smith",
)
.returning(Singer.id)
)
singer_id = session.execute(stmt).scalar()
print(singer_id)

# 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"})
stmt = select(Singer).where(Singer.id == singer_id)
singer = session.execute(stmt).scalar()
print(f"Inserted or updated singer {singer.full_name} successfully")


if __name__ == "__main__":
run_sample(insert_or_update_sample)

0 comments on commit d76c7d6

Please sign in to comment.