Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion migrations_lockfile.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ replays: 0001_squashed_0007_organizationmember_replay_access

seer: 0033_seer_run_pr_iteration

sentry: 1166_externalissue_provider_assignee_updated_at
sentry: 1167_organizationmemberteam_drop_new_id_pending

social_auth: 0001_squashed_0003_social_auth_json_field

Expand Down
6 changes: 0 additions & 6 deletions src/sentry/backup/comparators.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,12 +892,6 @@ def get_default_comparators() -> dict[str, list[JSONScrubbingComparator]]:
DateUpdatedComparator("date_updated", "date_added"),
HashObfuscatingComparator("token"),
],
"sentry.organizationmemberteam": [
# `new_id` mirrors the primary key, which is reassigned on import, so
# comparing its value across an export cycle is meaningless. The
# `new_id == id` invariant is enforced on write instead.
IgnoredComparator("new_id"),
],
"sentry.projectkey": [
HashObfuscatingComparator("public_key", "secret_key"),
SecretHexComparator(16, "public_key", "secret_key"),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Generated by Django 5.2.16 on 2026-09-08 21:08

import sentry.db.models.fields.bounded
from django.db import migrations

from sentry.new_migrations.migrations import CheckedMigration
from sentry.new_migrations.monkey.fields import SafeRemoveField
from sentry.new_migrations.monkey.state import DeletionAction


class Migration(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment

is_post_deployment = False

dependencies = [
("sentry", "1166_externalissue_provider_assignee_updated_at"),
]

operations = [
# `SafeRemoveField` refuses a column that is neither nullable nor has a `db_default`.
migrations.AlterField(
model_name="organizationmemberteam",
name="new_id",
field=sentry.db.models.fields.bounded.BoundedIntegerField(null=True),
),
# State-only removal: drops the field from Django's model state but keeps the column
# in the database, so app servers still running the old code can continue to SELECT
# it during the rolling deploy. The column itself goes in a follow-up migration.
SafeRemoveField(
model_name="organizationmemberteam",
name="new_id",
deletion_action=DeletionAction.MOVE_TO_PENDING,
),
]
76 changes: 3 additions & 73 deletions src/sentry/models/organizationmemberteam.py
Original file line number Diff line number Diff line change
@@ -1,91 +1,34 @@
from __future__ import annotations

from collections.abc import Iterable
from typing import Any, ClassVar
from typing import Any, ClassVar, Self

from django.db import connections, models, router
from django.db import models

from sentry import features, roles
from sentry.backup.scopes import RelocationScope
from sentry.db.models import (
BoundedBigAutoField,
BoundedIntegerField,
FlexibleForeignKey,
Model,
cell_silo_model,
sane_repr,
)
from sentry.db.models.manager.base import BaseManager
from sentry.db.models.manager.base_query_set import BaseQuerySet
from sentry.roles import team_roles
from sentry.roles.manager import TeamRole

MAX_RESERVED_IDS = 100_000


def _reserve_ids(model: type[Model], count: int, using: str) -> list[int]:
"""Claim `count` values from the model's primary key sequence ahead of insert.

Sequences are per-database, so `using` must be where the rows are written —
drawing from another hands out ids that are already taken.
"""
if not 1 <= count <= MAX_RESERVED_IDS:
raise ValueError(f"Cannot reserve {count} ids, expected 1 to {MAX_RESERVED_IDS}.")

with connections[using].cursor() as cursor:
cursor.execute(
"SELECT nextval(%s) FROM generate_series(1,%s);",
[f"{model._meta.db_table}_id_seq", count],
)
return [row_id for (row_id,) in cursor.fetchall()]


class OrganizationMemberTeamQuerySet(BaseQuerySet["OrganizationMemberTeam"]):
"""Keeps `new_id` equal to `id` on bulk inserts.

This lives on the queryset rather than the manager because not every bulk insert
goes through `objects`: adding a team via a member's `teams` accessor, or any
`.using(...)` call, reaches the queryset directly.
"""

def bulk_create(
self, objs: Iterable[OrganizationMemberTeam], *args: Any, **kwds: Any
) -> list[OrganizationMemberTeam]:
rows = list[OrganizationMemberTeam](objs)
if not rows:
return super().bulk_create(rows, *args, **kwds)

# `self.db` would give the read database here.
using = self._db # type: ignore[attr-defined]
if using is None:
using = router.db_for_write(self.model, **self._hints) # type: ignore[attr-defined]

# Claim the pks up front so `new_id` can be written in the same INSERT.
rows_with_ids = zip(rows, _reserve_ids(self.model, len(rows), using))
for row, row_id in rows_with_ids:
row.id = row_id
row.new_id = row_id
return super().bulk_create(rows, *args, **kwds)


OrganizationMemberTeamManager = BaseManager.from_queryset(
OrganizationMemberTeamQuerySet, "OrganizationMemberTeamManager"
)


@cell_silo_model
class OrganizationMemberTeam(Model):
"""
Identifies relationships between organization members and the teams they are on.
"""

objects: ClassVar[BaseManager[OrganizationMemberTeam]] = OrganizationMemberTeamManager()
objects: ClassVar[BaseManager[Self]] = BaseManager()

__relocation_scope__ = RelocationScope.Organization

id = BoundedBigAutoField(primary_key=True)
# Narrow leftover of the id widening, still written on every insert until it is dropped.
new_id = BoundedIntegerField()
team = FlexibleForeignKey("sentry.Team")
organizationmember = FlexibleForeignKey("sentry.OrganizationMember")
# an inactive membership simply removes the team from the default list
Expand All @@ -100,19 +43,6 @@ class Meta:

__repr__ = sane_repr("team_id", "organizationmember_id")

def save(self, **kwds: Any) -> None:
if self.id is None:
# Claim the pk up front so `new_id` can be written in the same INSERT.
using = kwds.get("using")
if using is None:
using = router.db_for_write(type(self), instance=self)
self.id = _reserve_ids(type(self), 1, using)[0]
self.new_id = self.id
# A freshly claimed pk cannot already exist, so skip the UPDATE probe
# Django would otherwise run before inserting.
kwds["force_insert"] = True
super().save(**kwds)

def get_audit_log_data(self) -> dict[str, Any]:
return {
"team_slug": self.team.slug,
Expand Down

This file was deleted.

Loading
Loading