Skip to content

ref: fix types in several models #72802

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 17, 2024
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 src/sentry/models/apitoken.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class NotSupported(Exception):
pass


class ApiTokenManager(ControlOutboxProducingManager):
class ApiTokenManager(ControlOutboxProducingManager["ApiToken"]):
def create(self, *args, **kwargs):
token_type: AuthTokenType | None = kwargs.get("token_type", None)

Expand Down
1 change: 1 addition & 0 deletions src/sentry/models/avatars/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class AvatarBase(Model):
# abstract
AVATAR_TYPES: ClassVar[tuple[tuple[int, str], ...]]
FILE_TYPE: ClassVar[str]
avatar_type: models.Field[int, int]

ident = models.CharField(max_length=32, unique=True, db_index=True)

Expand Down
4 changes: 2 additions & 2 deletions src/sentry/models/files/abstractfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,10 @@ def assemble_from_file_blob_ids(self, file_blob_ids, checksum):
)
):
try:
file_blobs = self.FILE_BLOB_MODEL.objects.filter(id__in=file_blob_ids).all()
file_blobs_qs = self.FILE_BLOB_MODEL.objects.filter(id__in=file_blob_ids).all()

# Ensure blobs are in the order and duplication as provided
blobs_by_id = {blob.id: blob for blob in file_blobs}
blobs_by_id = {blob.id: blob for blob in file_blobs_qs}
file_blobs = [blobs_by_id[blob_id] for blob_id in file_blob_ids]
except Exception:
# Most likely a `KeyError` like `SENTRY-11QP` because an `id` in
Expand Down
4 changes: 2 additions & 2 deletions src/sentry/models/groupowner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import itertools
from collections import defaultdict
from datetime import timedelta
from datetime import datetime, timedelta
from enum import Enum
from typing import Any, TypedDict

Expand Down Expand Up @@ -46,7 +46,7 @@ class OwnerRuleType(Enum):
class OwnersSerialized(TypedDict):
type: str
owner: str
date_added: models.DateTimeField
date_added: datetime


@region_silo_model
Expand Down
6 changes: 3 additions & 3 deletions src/sentry/models/integrations/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ def delete(self, *args, **kwds):

@staticmethod
def outboxes_for_update(identifier: int) -> list[ControlOutbox]:
org_ids: list[int] = OrganizationIntegration.objects.filter(
integration_id=identifier
).values_list("organization_id", flat=True)
org_ids = OrganizationIntegration.objects.filter(integration_id=identifier).values_list(
"organization_id", flat=True
)
return [
ControlOutbox(
shard_scope=OutboxScope.INTEGRATION_SCOPE,
Expand Down
9 changes: 5 additions & 4 deletions src/sentry/models/organizationmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging
import secrets
from collections import defaultdict
from collections.abc import Mapping, MutableMapping
from collections.abc import Mapping
from datetime import timedelta
from enum import Enum
from hashlib import md5
Expand Down Expand Up @@ -165,11 +165,12 @@ def get_member_invite_query(self, id: int) -> QuerySet:
id=id,
)

def get_teams_by_user(self, organization: Organization) -> Mapping[int, list[int]]:
user_teams: MutableMapping[int, list[int]] = defaultdict(list)
def get_teams_by_user(self, organization: Organization) -> dict[int, list[int]]:
queryset = self.filter(organization_id=organization.id).values_list("user_id", "teams")
user_teams: dict[int, list[int]] = defaultdict(list)
for user_id, team_id in queryset:
user_teams[user_id].append(team_id)
if user_id is not None:
user_teams[user_id].append(team_id)
return user_teams

def get_members_by_email_and_role(self, email: str, role: str) -> QuerySet:
Expand Down
14 changes: 11 additions & 3 deletions src/sentry/models/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,8 @@ def get_by_users(self, users: Iterable[User | RpcUser]) -> Mapping[int, Iterable

projects_by_user_id = defaultdict(set)
for project_id, user_id in project_rows:
projects_by_user_id[user_id].add(project_id)
if user_id is not None:
projects_by_user_id[user_id].add(project_id)
return projects_by_user_id

def get_for_user_ids(self, user_ids: Collection[int]) -> QuerySet:
Expand Down Expand Up @@ -472,6 +473,7 @@ def transfer_to(self, organization):
for rule_id, environment_id in Rule.objects.filter(
project_id=self.id, environment_id__isnull=False
).values_list("id", "environment_id"):
assert environment_id is not None
rules_by_environment_id[environment_id].add(rule_id)

environment_names = dict(
Expand Down Expand Up @@ -605,7 +607,7 @@ def get_security_token(self):
def get_lock_key(self):
return f"project_token:{self.id}"

def copy_settings_from(self, project_id):
def copy_settings_from(self, project_id: int) -> bool:
"""
Copies project level settings of the inputted project
- General Settings
Expand All @@ -624,7 +626,13 @@ def copy_settings_from(self, project_id):
from sentry.models.projectteam import ProjectTeam
from sentry.models.rule import Rule

model_list = [EnvironmentProject, ProjectOwnership, ProjectTeam, Rule]
# XXX: this type sucks but it helps the type checker understand
model_list: tuple[type[EnvironmentProject | ProjectOwnership | ProjectTeam | Rule], ...] = (
EnvironmentProject,
ProjectOwnership,
ProjectTeam,
Rule,
)

project = Project.objects.get(id=project_id)
try:
Expand Down
9 changes: 7 additions & 2 deletions src/sentry/models/pullrequest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ class PullRequestManager(BaseManager["PullRequest"]):
def update_or_create(
self,
defaults: Mapping[str, Any] | None = None,
create_defaults: Mapping[str, Any] | None = None,
**kwargs: Any,
) -> tuple[Model, bool]:
) -> tuple[PullRequest, bool]:
"""
Wraps `update_or_create()` and ensures `post_save` signals are fired for
updated records as `GroupLink` functionality is dependent on signals
Expand All @@ -41,7 +42,11 @@ def update_or_create(
key = kwargs.pop("key")

affected, created = super().update_or_create(
organization_id=organization_id, repository_id=repository_id, key=key, defaults=defaults
organization_id=organization_id,
repository_id=repository_id,
key=key,
defaults=defaults,
create_defaults=create_defaults,
)
if created is False:
instance = self.get(
Expand Down
4 changes: 1 addition & 3 deletions src/sentry/models/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,7 @@ def get_for_user(
projects_by_team[team_id].append(project)

# these kinds of queries make people sad :(
for idx, team in enumerate(results):
team_projects = projects_by_team[team.id]
results[idx] = (team, team_projects)
return [(team, projects_by_team[team.id]) for team in results]

return results

Expand Down
1 change: 0 additions & 1 deletion src/sentry/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,6 @@ def merge_to(from_user: User, to_user: User) -> None:
"user.merge", extra={"from_user_id": from_user_id, "to_user_id": to_user_id}
)

organization_ids: list[int]
organization_ids = OrganizationMemberMapping.objects.filter(
user_id=from_user_id
).values_list("organization_id", flat=True)
Expand Down
4 changes: 3 additions & 1 deletion src/sentry/models/userrole.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from collections.abc import Sequence

from django.conf import settings
from django.db import models
from django.utils import timezone
Expand Down Expand Up @@ -30,7 +32,7 @@ class UserRole(OverwritableConfigMixin, ControlOutboxProducingModel):
date_added = models.DateTimeField(default=timezone.now, null=True)

name = models.CharField(max_length=MAX_USER_ROLE_NAME_LENGTH, unique=True)
permissions = ArrayField()
permissions: models.Field[Sequence[str], list[str]] = ArrayField()
users = models.ManyToManyField("sentry.User", through="sentry.UserRoleUser")

class Meta:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ def get_participants_with_group_subscription_reason(self) -> ParticipantMap:

def get_users_by_teams(self) -> Mapping[int, list[int]]:
if not self.user_id_team_lookup:
lookup: Mapping[int, list[int]] = OrganizationMember.objects.get_teams_by_user(
self.organization
)
lookup = OrganizationMember.objects.get_teams_by_user(self.organization)
self.user_id_team_lookup = lookup
return self.user_id_team_lookup

Expand Down
Loading