diff --git a/backend/src/core/identity-migration/migrations/001_migrate_user_id_to_uuid.sql b/backend/src/core/identity-migration/migrations/001_migrate_user_id_to_uuid.sql index 8500037..230a3b2 100644 --- a/backend/src/core/identity-migration/migrations/001_migrate_user_id_to_uuid.sql +++ b/backend/src/core/identity-migration/migrations/001_migrate_user_id_to_uuid.sql @@ -76,6 +76,20 @@ UPDATE user_notifications SET user_profile_id = up.id UPDATE user_preferences SET user_profile_id = up.id FROM user_profiles up WHERE user_preferences.user_id = up.auth0_sub AND user_preferences.user_profile_id IS NULL; +-- 2a-fix. user_preferences has rows where user_id already contains user_profiles.id (UUID) +-- instead of auth0_sub. Match these directly by casting to UUID. +UPDATE user_preferences SET user_profile_id = up.id + FROM user_profiles up + WHERE user_preferences.user_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND user_preferences.user_id::uuid = up.id + AND user_preferences.user_profile_id IS NULL; + +-- Delete truly orphaned user_preferences (UUID user_id with no matching user_profile) +DELETE FROM user_preferences + WHERE user_profile_id IS NULL + AND user_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND NOT EXISTS (SELECT 1 FROM user_profiles WHERE id = user_preferences.user_id::uuid); + UPDATE saved_stations SET user_profile_id = up.id FROM user_profiles up WHERE saved_stations.user_id = up.auth0_sub AND saved_stations.user_profile_id IS NULL;