Skip to content

Commit

Permalink
Ensure add_domain migration creates the default domain correctly
Browse files Browse the repository at this point in the history
Also modify get_domain_pk to use raw SQL to avoid problems with running inside migrations
  • Loading branch information
gerrod3 committed Feb 18, 2025
1 parent 5f8a7b2 commit 40d3569
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
17 changes: 13 additions & 4 deletions pulpcore/app/migrations/0101_add_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,12 @@

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_lifecycle.mixins
import pulpcore.app.models.access_policy
import pulpcore.app.models.fields
import pulpcore.app.models.upload
import pulpcore.app.util
import uuid



DEFAULT_DELETE_TRIGGER = """
CREATE OR REPLACE FUNCTION protect_default() RETURNS TRIGGER as $protect_default$
BEGIN
Expand All @@ -30,6 +26,18 @@
DROP FUNCTION IF EXISTS protect_default();
"""


def create_default_domain(apps, schema_editor):
Domain = apps.get_model('core', 'Domain')
try:
default_domain = Domain.objects.get(name="default")
except Domain.DoesNotExist:
default_domain = Domain(
name="default", storage_class=settings.STORAGES["default"]["BACKEND"]
)
default_domain.save(skip_hooks=True)


class Migration(migrations.Migration):

dependencies = [
Expand Down Expand Up @@ -58,4 +66,5 @@ class Migration(migrations.Migration):
bases=(django_lifecycle.mixins.LifecycleModelMixin, models.Model, pulpcore.app.models.access_policy.AutoAddObjPermsMixin),
),
migrations.RunSQL(DEFAULT_DELETE_TRIGGER, reverse_sql=REMOVE_DEFAULT_DELETE_TRIGGER),
migrations.RunPython(code=create_default_domain, reverse_code=migrations.RunPython.noop),
]
16 changes: 14 additions & 2 deletions pulpcore/app/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ def set_current_user_lazy(user):

def get_default_domain():
global default_domain
# This can be run in a migration, and once after
# This will run in a post-migration hook
if default_domain is None:
try:
Domain = models.Domain
Expand All @@ -595,7 +595,19 @@ def get_domain():


def get_domain_pk():
return get_domain().pk
"""
THIS CAN/WILL BE RAN IN MIGRATIONS. DO NOT USE ORM FOR IT MIGHT GENERATE INVALID SQL.
"""
if domain := current_domain.get():
return domain.pk
# Same behavior as get_domain: use currently set domain, else assume default domain
if default_domain:
return default_domain.pk
# If we haven't cached the default_domain then use raw SQL to get its PK
with connection.cursor() as cursor:
cursor.execute("SELECT pulp_id FROM core_domain WHERE name = 'default'")
row = cursor.fetchone()
return row[0]


def set_domain(new_domain):
Expand Down

0 comments on commit 40d3569

Please sign in to comment.