fix: upsert evotor_connection by user_id fallback to prevent duplicate insert

When a connection row exists for the user but with a different/null
evotor_user_id, the lookup by evotor_user_id alone missed it and tried
to INSERT, hitting the unique constraint on user_id. Now looks up by
either evotor_user_id or user_id, and always syncs both fields on update.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
mguschin
2026-05-24 17:04:33 +03:00
parent fa8167af4d
commit 5b82f1bc02

View File

@@ -63,13 +63,18 @@ def _upsert_evotor_connection(
"""Create or update an evotor_connections row; always regenerates api_token."""
api_token = secrets.token_urlsafe(32)
conn = db.query(EvotorConnection).filter(
EvotorConnection.evotor_user_id == evotor_user_id
or_(
EvotorConnection.evotor_user_id == evotor_user_id,
EvotorConnection.user_id == user_id,
)
).first()
now = datetime.now(timezone.utc).replace(tzinfo=None)
if conn:
conn.api_token = api_token
if user_id is not None:
conn.user_id = user_id
if evotor_user_id:
conn.evotor_user_id = evotor_user_id
if access_token:
conn.access_token = access_token
conn.updated_at = now