Skip to content

Commit 6684e88

Browse files
authored
better upsert of adaptor properties (#157)
1 parent 0df12c1 commit 6684e88

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

cads_broker/database.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import sqlalchemy.orm.exc
1515
import sqlalchemy_utils
1616
import structlog
17-
from sqlalchemy.dialects.postgresql import JSONB
17+
from sqlalchemy.dialects.postgresql import JSONB, insert
1818
from typing_extensions import Iterable
1919

2020
import alembic.command
@@ -804,19 +804,15 @@ def ensure_adaptor_properties(
804804
session: sa.orm.Session,
805805
) -> None:
806806
"""Create adaptor properties (if not exists) or update its timestamp."""
807-
try:
808-
adaptor_properties = AdaptorProperties(hash=hash, config=config, form=form)
809-
session.add(adaptor_properties)
810-
session.commit()
811-
except sa.exc.IntegrityError: # hash already present
812-
session.rollback()
813-
statement = (
814-
AdaptorProperties.__table__.update()
815-
.where(AdaptorProperties.__table__.c.hash == hash)
816-
.values(timestamp=datetime.datetime.now())
817-
)
818-
session.execute(statement)
819-
session.commit()
807+
insert_stmt = insert(AdaptorProperties.__table__).values(
808+
hash=hash, config=config, form=form
809+
)
810+
do_update_stmt = insert_stmt.on_conflict_do_update(
811+
constraint="adaptor_properties_pkey",
812+
set_=dict(timestamp=datetime.datetime.now()),
813+
)
814+
session.execute(do_update_stmt)
815+
session.commit()
820816

821817

822818
def add_event(

0 commit comments

Comments
 (0)