Skip to content

Commit

Permalink
Add migration script for scoped API keys
Browse files Browse the repository at this point in the history
Update package_versions uploader with API keys owner instead of the key anonymous user.
This is linked to mamba-org#647
and allow to update existing databases.
  • Loading branch information
beenje committed Aug 2, 2023
1 parent e2a5845 commit d55636d
Showing 1 changed file with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Update scoped API key uploader id
Revision ID: 3ba25f23fb7d
Revises: d212023a8e0b
Create Date: 2023-08-02 08:03:09.961559
"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = '3ba25f23fb7d'
down_revision = 'd212023a8e0b'
branch_labels = None
depends_on = None


def upgrade():
package_versions = sa.sql.table("package_versions", sa.sql.column("uploader_id"))
conn = op.get_bind()
# Get all user_id/owner_id from channel scoped API keys
# (user is anonymous - username is null)
res = conn.execute(
"""SELECT api_keys.user_id, api_keys.owner_id FROM api_keys
INNER JOIN users ON users.id = api_keys.user_id
WHERE users.username is NULL;
"""
)
results = res.fetchall()
# Replace the uploader with the key owner (real user instead of the anonymous one)
for result in results:
op.execute(
package_versions.update()
.where(package_versions.c.uploader_id == result[0])
.values(uploader_id=result[1])
)


def downgrade():
package_versions = sa.sql.table("package_versions", sa.sql.column("uploader_id"))
conn = op.get_bind()
# Get all user_id/owner_id from channel scoped API keys
# (user is anonymous - username is null)
res = conn.execute(
"""SELECT api_keys.user_id, api_keys.owner_id FROM api_keys
INNER JOIN users ON users.id = api_keys.user_id
WHERE users.username is NULL;
"""
)
results = res.fetchall()
# Replace the uploader with the key anonymous user
for result in results:
op.execute(
package_versions.update()
.where(package_versions.c.uploader_id == result[1])
.values(uploader_id=result[0])
)

0 comments on commit d55636d

Please sign in to comment.