Skip to content
Open
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
17 changes: 14 additions & 3 deletions app/db/crud/group.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from sqlalchemy.orm import selectinload, with_expression

from app.db.models import (
Group,
Expand Down Expand Up @@ -42,6 +42,7 @@ async def get_inbounds_by_tags(db: AsyncSession, tags: list[str]) -> list[ProxyI
async def load_group_attrs(group: Group, *, load_users: bool = True, load_inbounds: bool = True):
if load_users:
await group.awaitable_attrs.users
group.total_users = len(group.users)
if load_inbounds:
await group.awaitable_attrs.inbounds

Expand Down Expand Up @@ -105,7 +106,16 @@ async def get_group(db: AsyncSession, query: GroupListQuery) -> tuple[list[Group
- list[Group]: A list of Group objects
- int: The total count of groups
"""
groups = select(Group).options(selectinload(Group.users), selectinload(Group.inbounds))
total_users = (
select(func.count(users_groups_association.c.user_id))
.where(users_groups_association.c.groups_id == Group.id)
.correlate(Group)
.scalar_subquery()
)
groups = select(Group).options(
with_expression(Group.total_users, total_users),
selectinload(Group.inbounds),
)
if query.ids:
groups = groups.where(Group.id.in_(query.ids))

Expand All @@ -122,7 +132,8 @@ async def get_group(db: AsyncSession, query: GroupListQuery) -> tuple[list[Group

count = (await db.execute(count_query)).scalar_one()

# users and inbounds already eagerly loaded via selectinload above
# Inbounds are eagerly loaded; total_users is populated by the SQL expression
# without materializing the User relationship.
all_groups = (await db.execute(groups)).unique().scalars().all()

return all_groups, count
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""add reverse group membership indexes

Revision ID: a4d8c7e91b32
Revises: 7c4bd5128e62
Create Date: 2026-08-14 15:00:00.000000

"""

from alembic import op


# revision identifiers, used by Alembic.
revision = "a4d8c7e91b32"
down_revision = "7c4bd5128e62"
branch_labels = None
depends_on = None


INDEXES = (
(
"ix_inbounds_groups_association_group_id_inbound_id",
"inbounds_groups_association",
["group_id", "inbound_id"],
),
(
"ix_users_groups_association_groups_id_user_id",
"users_groups_association",
["groups_id", "user_id"],
),
)


def _create_indexes(*, concurrently: bool) -> None:
for name, table_name, columns in INDEXES:
op.create_index(
name,
table_name,
columns,
unique=False,
postgresql_concurrently=concurrently,
)


def _drop_indexes(*, concurrently: bool) -> None:
for name, table_name, _ in reversed(INDEXES):
op.drop_index(
name,
table_name=table_name,
postgresql_concurrently=concurrently,
)


def upgrade() -> None:
if op.get_bind().dialect.name == "postgresql":
# A normal PostgreSQL index build blocks membership writes. These tables
# can contain millions of rows, so keep live installations writable.
with op.get_context().autocommit_block():
_create_indexes(concurrently=True)
return

# InnoDB creates secondary indexes online by default. SQLite needs the
# regular form and is normally used for smaller, single-node deployments.
_create_indexes(concurrently=False)


def downgrade() -> None:
if op.get_bind().dialect.name == "postgresql":
with op.get_context().autocommit_block():
_drop_indexes(concurrently=True)
return

_drop_indexes(concurrently=False)
28 changes: 15 additions & 13 deletions app/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,20 @@ def fk_id_table_column(name: str, target: str, **column_kwargs: Any):
fk_id_table_column("groups_id", "groups.id", primary_key=True),
)

# The association primary keys are ordered from the owning entity to the group.
# Reverse indexes keep group-centric joins, counts, and bulk deletes from scanning
# every membership row on databases that do not auto-index foreign keys.
Index(
"ix_inbounds_groups_association_group_id_inbound_id",
inbounds_groups_association.c.group_id,
inbounds_groups_association.c.inbound_id,
)
Index(
"ix_users_groups_association_groups_id_user_id",
users_groups_association.c.groups_id,
users_groups_association.c.user_id,
)


class AdminStatus(str, Enum):
active = "active"
Expand Down Expand Up @@ -777,6 +791,7 @@ class Group(Base, IdMixin):
secondary=template_group_association, back_populates="groups", init=False
)
is_disabled: Mapped[bool] = mapped_column(server_default="0", default=False)
total_users: Mapped[int] = query_expression(repr=False)

@hybrid_property
def inbound_ids(self) -> list[int]:
Expand Down Expand Up @@ -808,19 +823,6 @@ def inbound_tags(cls):
.label("inbound_tags")
)

@hybrid_property
def total_users(self) -> int:
return len(self.users)

@total_users.expression
def total_users(cls):
return (
select(func.count(users_groups_association.c.user_id))
.where(users_groups_association.c.groups_id == cls.id)
.scalar_subquery()
.label("total_users")
)


class CoreType(str, Enum):
xray = "xray"
Expand Down