Skip to content

Commit

Permalink
update the signal repo function (#682)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrian-codecov authored Sep 4, 2024
1 parent d4a0f9b commit 9424c8b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
22 changes: 15 additions & 7 deletions database/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,25 @@ def _sync_repo(repository: Repository):


@event.listens_for(Repository, "after_insert")
def after_insert_repo(mapper, connection, target):
log.info("After insert signal")
def after_insert_repo(mapper, connection, target: Repository):
log.info("After insert signal", extra=dict(repoid=target.repoid))
_sync_repo(target)


@event.listens_for(Repository, "after_update")
def after_update_repo(mapper, connection, target):
def after_update_repo(mapper, connection, target: Repository):
state = inspect(target)

for attr in state.attrs:
if attr.key in ["name", "upload_token"] and attr.history.has_changes():
log.info("After update signal")
_sync_repo(target)
break
if attr.key in ["name", "upload_token"]:
history = attr.history
# Detects if there are changes and if said changes are different.
# has_changes() is True when you update the an entry with the same value,
# so we must ensure those values are different to trigger the signal
if history.has_changes() and history.deleted and history.added:
old_value = history.deleted[0]
new_value = history.added[0]
if old_value != new_value:
log.info("After update signal", extra=dict(repoid=target.repoid))
_sync_repo(target)
break
11 changes: 9 additions & 2 deletions database/tests/unit/test_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def test_shelter_repo_sync(dbsession, mock_configuration, mocker):
publish = mocker.patch("google.cloud.pubsub_v1.PublisherClient.publish")

# this triggers the publish via SQLAlchemy events (after_insert)
repo = RepositoryFactory(repoid=91728376)
repo = RepositoryFactory(repoid=91728376, name="test-123")
dbsession.add(repo)
dbsession.commit()

Expand All @@ -33,8 +33,15 @@ def test_shelter_repo_sync(dbsession, mock_configuration, mocker):

publish = mocker.patch("google.cloud.pubsub_v1.PublisherClient.publish")

# Synchronize object flush for history.deleted to be perceived by sqlalchemy
dbsession.refresh(repo)

# this triggers the publish via SQLAlchemy events (after_update)
repo.name = "testing"
repo.name = "test-456"
dbsession.commit()

# same name shouldn't trigger (after_update)
repo.name = "test-456"
dbsession.commit()

# this wouldn't trigger the publish via SQLAlchemy events (after_update) since it's an unimportant attribute
Expand Down

0 comments on commit 9424c8b

Please sign in to comment.