Skip to content

Commit

Permalink
Fix get_or_create using nested session
Browse files Browse the repository at this point in the history
  • Loading branch information
omar-selo committed Aug 11, 2023
1 parent 2049940 commit 4a8ab9e
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions backend/test_observer/data_access/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@


from sqlalchemy import and_, func
from sqlalchemy.orm import Session, joinedload
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload

from .models import Artefact, DataModel, Family, Stage
from .models_enums import FamilyName
from .models import DataModel, Family, Stage, Artefact


def get_stage_by_name(
Expand Down Expand Up @@ -117,10 +117,11 @@ def get_or_create(

try:
# Attempt to add and commit the new instance
db.add(instance)
db.commit()
return instance
except Exception:
# Use a nested transaction to avoid rolling back the entire session
with db.begin_nested():
db.add(instance)
except IntegrityError:
# Query and return the existing instance
return db.query(model).filter_by(**filter_kwargs).one()
instance = db.query(model).filter_by(**filter_kwargs).one()

return instance

0 comments on commit 4a8ab9e

Please sign in to comment.