Skip to content

tux.database.controllers.snippet

Classes:

Name Description
SnippetController

Controller for managing snippets.

Classes

SnippetController()

Bases: BaseController[Snippet]

Controller for managing snippets.

This controller provides methods for managing snippet records in the database. It inherits common CRUD operations from BaseController.

Initialize the SnippetController with the snippet table.

Methods:

Name Description
get_all_snippets

Get all snippets.

get_all_snippets_by_guild_id

Get all snippets for a guild.

get_all_snippets_sorted

Get all snippets sorted by creation time.

find_one

Return the first row that matches where or None.

get_snippet_by_name

Get a snippet by name.

find_many

Return a list of rows matching where (or all rows).

get_snippet_by_name_and_guild_id

Get a snippet by name and guild ID.

create_snippet

Create a new snippet.

get_snippet_by_id

Get a snippet by its ID.

delete_snippet_by_id

Delete a snippet by its ID.

create_snippet_alias

Create a new snippet alias.

execute_transaction

Execute callback inside a database session / transaction block.

safe_get_attr

Return getattr(obj, attr, default) - keeps old helper available.

connect_or_create_relation

Return a dict with a single key that can be merged into data dicts.

get_all_aliases

Get all aliases for a snippet name within a guild.

update_snippet_by_id

Update a snippet's content.

increment_snippet_uses

Increment the use counter for a snippet.

lock_snippet_by_id

Lock a snippet.

unlock_snippet_by_id

Unlock a snippet.

toggle_snippet_lock_by_id

Toggle a snippet's lock state.

count_snippets_by_guild_id

Count the number of snippets in a guild.

bulk_delete_snippets_by_guild_id

Delete all snippets for a guild.

Source code in tux/database/controllers/snippet.py
Python
def __init__(self) -> None:
    """Initialize the SnippetController with the snippet table."""
    super().__init__(Snippet)

Functions

get_all_snippets() -> list[Snippet] async

Get all snippets.

Returns:

Type Description
list[Snippet]

List of all snippets

Source code in tux/database/controllers/snippet.py
Python
async def get_all_snippets(self) -> list[Snippet]:
    """Get all snippets.

    Returns
    -------
    list[Snippet]
        List of all snippets
    """
    return await self.find_many(where={})
get_all_snippets_by_guild_id(guild_id: int, include_guild: bool = False) -> list[Snippet] async

Get all snippets for a guild.

Parameters:

Name Type Description Default
guild_id int

The ID of the guild to get snippets for

required
include_guild bool

Whether to include the guild relation

False

Returns:

Type Description
list[Snippet]

List of snippets for the guild

Source code in tux/database/controllers/snippet.py
Python
async def get_all_snippets_by_guild_id(self, guild_id: int, include_guild: bool = False) -> list[Snippet]:
    """Get all snippets for a guild.

    Parameters
    ----------
    guild_id : int
        The ID of the guild to get snippets for
    include_guild : bool
        Whether to include the guild relation

    Returns
    -------
    list[Snippet]
        List of snippets for the guild
    """
    include = {"guild": True} if include_guild else None
    return await self.find_many(where={"guild_id": guild_id}, include=include)
_execute_query(op: Callable[[AsyncSession], Any], span_desc: str) -> Any async

Run op inside a managed session & sentry span (if enabled).

Source code in tux/database/controllers/snippet.py
Python
    -------
    list[Snippet]
        List of snippets for the guild
    """
    include = {"guild": True} if include_guild else None
    return await self.find_many(where={"guild_id": guild_id}, include=include)

async def get_all_snippets_sorted(self, newestfirst: bool = True, limit: int | None = None) -> list[Snippet]:
    """Get all snippets sorted by creation time.

    Parameters
    ----------
    newestfirst : bool
        Whether to sort with newest first
    limit : int | None
        Optional maximum number of snippets to return

    Returns
    -------
get_all_snippets_sorted(newestfirst: bool = True, limit: int | None = None) -> list[Snippet] async

Get all snippets sorted by creation time.

Parameters:

Name Type Description Default
newestfirst bool

Whether to sort with newest first

True
limit int | None

Optional maximum number of snippets to return

None

Returns:

Type Description
list[Snippet]

List of sorted snippets

Source code in tux/database/controllers/snippet.py
Python
async def get_all_snippets_sorted(self, newestfirst: bool = True, limit: int | None = None) -> list[Snippet]:
    """Get all snippets sorted by creation time.

    Parameters
    ----------
    newestfirst : bool
        Whether to sort with newest first
    limit : int | None
        Optional maximum number of snippets to return

    Returns
    -------
    list[Snippet]
        List of sorted snippets
    """
    return await self.find_many(
        where={},
        order={"snippet_created_at": "desc" if newestfirst else "asc"},
        take=limit,
    )
find_one(*, where: dict[str, Any], include: dict[str, bool] | None = None, **__: Any) -> ModelT | None async

Return the first row that matches where or None.

Source code in tux/database/controllers/snippet.py
Python
        order={"snippet_created_at": "desc" if newestfirst else "asc"},
        take=limit,
    )

async def get_snippet_by_name(self, snippet_name: str, include_guild: bool = False) -> Snippet | None:
    """Get a snippet by name.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet to get
    include_guild : bool
        Whether to include the guild relation

    Returns
get_snippet_by_name(snippet_name: str, include_guild: bool = False) -> Snippet | None async

Get a snippet by name.

Parameters:

Name Type Description Default
snippet_name str

The name of the snippet to get

required
include_guild bool

Whether to include the guild relation

False

Returns:

Type Description
Snippet | None

The snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def get_snippet_by_name(self, snippet_name: str, include_guild: bool = False) -> Snippet | None:
    """Get a snippet by name.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet to get
    include_guild : bool
        Whether to include the guild relation

    Returns
    -------
    Snippet | None
        The snippet if found, None otherwise
    """

    async def _op(session: AsyncSession):
        stmt = select(Snippet)
        pattern = f"%{snippet_name}%"
        stmt = stmt.where(func.lower(Snippet.snippet_name).like(pattern.lower()))
        result = await session.execute(stmt)  # type: ignore[attr-defined]
        snippet_obj = result.scalar_one_or_none()  # type: ignore[attr-defined]
        if include_guild and snippet_obj is not None:
            # Access relationship to ensure it is loaded; ignore typing for dynamic attribute
            getattr(snippet_obj, "guild", None)  # type: ignore[attr-defined]
        return snippet_obj

    return await self._execute_query(_op, "get_snippet_by_name")
find_many(*, where: dict[str, Any] | None = None, include: dict[str, bool] | None = None, order: dict[str, str] | None = None, take: int | None = None, skip: int | None = None) -> list[ModelT] async

Return a list of rows matching where (or all rows).

Source code in tux/database/controllers/snippet.py
Python
            getattr(snippet_obj, "guild", None)  # type: ignore[attr-defined]
        return snippet_obj

    return await self._execute_query(_op, "get_snippet_by_name")

async def get_snippet_by_name_and_guild_id(
    self,
    snippet_name: str,
    guild_id: int,
    include_guild: bool = False,
) -> Snippet | None:
    """Get a snippet by name and guild ID.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet to get
    guild_id : int
        The ID of the guild to get the snippet from
    include_guild : bool
        Whether to include the guild relation

    Returns
    -------
    Snippet | None
        The snippet if found, None otherwise
    """
get_snippet_by_name_and_guild_id(snippet_name: str, guild_id: int, include_guild: bool = False) -> Snippet | None async

Get a snippet by name and guild ID.

Parameters:

Name Type Description Default
snippet_name str

The name of the snippet to get

required
guild_id int

The ID of the guild to get the snippet from

required
include_guild bool

Whether to include the guild relation

False

Returns:

Type Description
Snippet | None

The snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def get_snippet_by_name_and_guild_id(
    self,
    snippet_name: str,
    guild_id: int,
    include_guild: bool = False,
) -> Snippet | None:
    """Get a snippet by name and guild ID.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet to get
    guild_id : int
        The ID of the guild to get the snippet from
    include_guild : bool
        Whether to include the guild relation

    Returns
    -------
    Snippet | None
        The snippet if found, None otherwise
    """

    async def _op(session: AsyncSession):
        stmt = select(Snippet).where(
            func.lower(Snippet.snippet_name) == snippet_name.lower(),  # type: ignore[arg-type]
            Snippet.guild_id == guild_id,  # type: ignore[arg-type]
        )
        result = await session.execute(stmt)  # type: ignore[attr-defined]
        snippet_obj = result.scalar_one_or_none()  # type: ignore[attr-defined]
        if include_guild and snippet_obj is not None:
            getattr(snippet_obj, "guild", None)  # type: ignore[attr-defined]
        return snippet_obj

    return await self._execute_query(_op, "get_snippet_by_name_and_guild_id")
create_snippet(snippet_name: str, snippet_content: str, snippet_created_at: datetime.datetime, snippet_user_id: int, guild_id: int) -> Snippet async

Create a new snippet.

Parameters:

Name Type Description Default
snippet_name str

The name of the snippet

required
snippet_content str

The content of the snippet

required
snippet_created_at datetime

The creation time of the snippet

required
snippet_user_id int

The ID of the user creating the snippet

required
guild_id int

The ID of the guild the snippet belongs to

required

Returns:

Type Description
Snippet

The created snippet

Source code in tux/database/controllers/snippet.py
Python
async def create_snippet(
    self,
    snippet_name: str,
    snippet_content: str,
    snippet_created_at: datetime.datetime,
    snippet_user_id: int,
    guild_id: int,
) -> Snippet:
    """Create a new snippet.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet
    snippet_content : str
        The content of the snippet
    snippet_created_at : datetime.datetime
        The creation time of the snippet
    snippet_user_id : int
        The ID of the user creating the snippet
    guild_id : int
        The ID of the guild the snippet belongs to

    Returns
    -------
    Snippet
        The created snippet
    """
    # Use connect_or_create pattern instead of ensure_guild_exists
    return await self.create(
        data={
            "snippet_name": snippet_name,
            "snippet_content": snippet_content,
            "snippet_created_at": snippet_created_at,
            "snippet_user_id": snippet_user_id,
            "guild": self.connect_or_create_relation("guild_id", guild_id),
            "uses": 0,
            "locked": False,
        },
        include={"guild": True},
    )
get_snippet_by_id(snippet_id: int, include_guild: bool = False) -> Snippet | None async

Get a snippet by its ID.

Parameters:

Name Type Description Default
snippet_id int

The ID of the snippet to get

required
include_guild bool

Whether to include the guild relation

False

Returns:

Type Description
Snippet | None

The snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def get_snippet_by_id(self, snippet_id: int, include_guild: bool = False) -> Snippet | None:
    """Get a snippet by its ID.

    Parameters
    ----------
    snippet_id : int
        The ID of the snippet to get
    include_guild : bool
        Whether to include the guild relation

    Returns
    -------
    Snippet | None
        The snippet if found, None otherwise
    """
    include = {"guild": True} if include_guild else None
    return await self.find_unique(where={"snippet_id": snippet_id}, include=include)
delete_snippet_by_id(snippet_id: int) -> Snippet | None async

Delete a snippet by its ID.

Parameters:

Name Type Description Default
snippet_id int

The ID of the snippet to delete

required

Returns:

Type Description
Snippet | None

The deleted snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def delete_snippet_by_id(self, snippet_id: int) -> Snippet | None:
    """Delete a snippet by its ID.

    Parameters
    ----------
    snippet_id : int
        The ID of the snippet to delete

    Returns
    -------
    Snippet | None
        The deleted snippet if found, None otherwise
    """
    return await self.delete(where={"snippet_id": snippet_id})
create_snippet_alias(snippet_name: str, snippet_alias: str, snippet_created_at: datetime.datetime, snippet_user_id: int, guild_id: int) -> Snippet async

Create a new snippet alias.

Parameters:

Name Type Description Default
snippet_name str

The name of the snippet this is an alias for.

required
snippet_alias str

The alias name.

required
snippet_created_at datetime

The creation time of the alias.

required
snippet_user_id int

The ID of the user creating the alias.

required
guild_id int

The ID of the guild the alias belongs to.

required

Returns:

Type Description
Snippet

The created snippet alias record.

Source code in tux/database/controllers/snippet.py
Python
async def create_snippet_alias(
    self,
    snippet_name: str,
    snippet_alias: str,
    snippet_created_at: datetime.datetime,
    snippet_user_id: int,
    guild_id: int,
) -> Snippet:
    """Create a new snippet alias.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet this is an alias for.
    snippet_alias : str
        The alias name.
    snippet_created_at : datetime.datetime
        The creation time of the alias.
    snippet_user_id : int
        The ID of the user creating the alias.
    guild_id : int
        The ID of the guild the alias belongs to.

    Returns
    -------
    Snippet
        The created snippet alias record.
    """
    # Use connect_or_create pattern for guild relation
    return await self.create(
        data={
            "snippet_name": snippet_name,
            "alias": snippet_alias,  # Assuming 'alias' is the correct field name
            "snippet_created_at": snippet_created_at,
            "snippet_user_id": snippet_user_id,
            "guild": self.connect_or_create_relation("guild_id", guild_id),
            "uses": 0,  # Set default values
            "locked": False,
        },
        include={"guild": True},
    )
execute_transaction(callback: Callable[[], Any]) -> Any async

Execute callback inside a database session / transaction block.

Source code in tux/database/controllers/snippet.py
Python
    guild_id: int,
) -> Snippet:
    """Create a new snippet alias.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet this is an alias for.
    snippet_alias : str
        The alias name.
    snippet_created_at : datetime.datetime
        The creation time of the alias.
    snippet_user_id : int
safe_get_attr(obj: Any, attr: str, default: Any = None) -> Any staticmethod

Return getattr(obj, attr, default) - keeps old helper available.

Source code in tux/database/controllers/snippet.py
Python
-------
Snippet
    The created snippet alias record.
"""
connect_or_create_relation(id_field: str, model_id: Any, *_: Any, **__: Any) -> dict[str, Any] staticmethod

Return a dict with a single key that can be merged into data dicts.

The calling code does something like::

Text Only
data = {"guild": connect_or_create_relation("guild_id", guild_id)}

We map that pattern to a very small helper that collapses to {"guild_id": guild_id}.

Source code in tux/database/controllers/snippet.py
Python
            "alias": snippet_alias,  # Assuming 'alias' is the correct field name
            "snippet_created_at": snippet_created_at,
            "snippet_user_id": snippet_user_id,
            "guild": self.connect_or_create_relation("guild_id", guild_id),
            "uses": 0,  # Set default values
            "locked": False,
        },
        include={"guild": True},
    )

async def get_all_aliases(self, snippet_name: str, guild_id: int) -> list[Snippet]:
get_all_aliases(snippet_name: str, guild_id: int) -> list[Snippet] async

Get all aliases for a snippet name within a guild.

Parameters:

Name Type Description Default
snippet_name str

The name of the snippet to find aliases for.

required
guild_id int

The ID of the guild to search within.

required

Returns:

Type Description
list[Snippet]

A list of Snippet objects representing the aliases.

Source code in tux/database/controllers/snippet.py
Python
async def get_all_aliases(self, snippet_name: str, guild_id: int) -> list[Snippet]:
    """Get all aliases for a snippet name within a guild.

    Parameters
    ----------
    snippet_name : str
        The name of the snippet to find aliases for.
    guild_id : int
        The ID of the guild to search within.

    Returns
    -------
    list[Snippet]
        A list of Snippet objects representing the aliases.
    """
    return await self.find_many(
        where={"alias": {"equals": snippet_name, "mode": "insensitive"}, "guild_id": guild_id},
    )
update_snippet_by_id(snippet_id: int, snippet_content: str) -> Snippet | None async

Update a snippet's content.

Parameters:

Name Type Description Default
snippet_id int

The ID of the snippet to update

required
snippet_content str

The new content for the snippet

required

Returns:

Type Description
Snippet | None

The updated snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def update_snippet_by_id(self, snippet_id: int, snippet_content: str) -> Snippet | None:
    """Update a snippet's content.

    Parameters
    ----------
    snippet_id : int
        The ID of the snippet to update
    snippet_content : str
        The new content for the snippet

    Returns
    -------
    Snippet | None
        The updated snippet if found, None otherwise
    """
    return await self.update(
        where={"snippet_id": snippet_id},
        data={"snippet_content": snippet_content},
    )
increment_snippet_uses(snippet_id: int) -> Snippet | None async

Increment the use counter for a snippet.

This method uses a transaction to ensure atomicity.

Parameters:

Name Type Description Default
snippet_id int

The ID of the snippet to increment

required

Returns:

Type Description
Snippet | None

The updated snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def increment_snippet_uses(self, snippet_id: int) -> Snippet | None:
    """Increment the use counter for a snippet.

    This method uses a transaction to ensure atomicity.

    Parameters
    ----------
    snippet_id : int
        The ID of the snippet to increment

    Returns
    -------
    Snippet | None
        The updated snippet if found, None otherwise
    """

    async def increment_tx():
        snippet = await self.find_unique(where={"snippet_id": snippet_id})
        if snippet is None:
            return None

        # Safely get the current uses value
        snippet_uses = self.safe_get_attr(snippet, "uses", 0)

        return await self.update(
            where={"snippet_id": snippet_id},
            data={"uses": snippet_uses + 1},
        )

    return await self.execute_transaction(increment_tx)
lock_snippet_by_id(snippet_id: int) -> Snippet | None async

Lock a snippet.

Parameters:

Name Type Description Default
snippet_id int

The ID of the snippet to lock

required

Returns:

Type Description
Snippet | None

The updated snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def lock_snippet_by_id(self, snippet_id: int) -> Snippet | None:
    """Lock a snippet.

    Parameters
    ----------
    snippet_id : int
        The ID of the snippet to lock

    Returns
    -------
    Snippet | None
        The updated snippet if found, None otherwise
    """
    return await self.update(
        where={"snippet_id": snippet_id},
        data={"locked": True},
    )
unlock_snippet_by_id(snippet_id: int) -> Snippet | None async

Unlock a snippet.

Parameters:

Name Type Description Default
snippet_id int

The ID of the snippet to unlock

required

Returns:

Type Description
Snippet | None

The updated snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def unlock_snippet_by_id(self, snippet_id: int) -> Snippet | None:
    """Unlock a snippet.

    Parameters
    ----------
    snippet_id : int
        The ID of the snippet to unlock

    Returns
    -------
    Snippet | None
        The updated snippet if found, None otherwise
    """
    return await self.update(
        where={"snippet_id": snippet_id},
        data={"locked": False},
    )
toggle_snippet_lock_by_id(snippet_id: int) -> Snippet | None async

Toggle a snippet's lock state.

This method uses a transaction to ensure atomicity.

Parameters:

Name Type Description Default
snippet_id int

The ID of the snippet to toggle

required

Returns:

Type Description
Snippet | None

The updated snippet if found, None otherwise

Source code in tux/database/controllers/snippet.py
Python
async def toggle_snippet_lock_by_id(self, snippet_id: int) -> Snippet | None:
    """Toggle a snippet's lock state.

    This method uses a transaction to ensure atomicity.

    Parameters
    ----------
    snippet_id : int
        The ID of the snippet to toggle

    Returns
    -------
    Snippet | None
        The updated snippet if found, None otherwise
    """

    async def toggle_lock_tx():
        snippet = await self.find_unique(where={"snippet_id": snippet_id})
        if snippet is None:
            return None

        # Safely get the current locked state
        is_locked = self.safe_get_attr(snippet, "locked", False)

        return await self.update(
            where={"snippet_id": snippet_id},
            data={"locked": not is_locked},
        )

    return await self.execute_transaction(toggle_lock_tx)
count_snippets_by_guild_id(guild_id: int) -> int async

Count the number of snippets in a guild.

Parameters:

Name Type Description Default
guild_id int

The ID of the guild to count snippets for

required

Returns:

Type Description
int

The number of snippets in the guild

Source code in tux/database/controllers/snippet.py
Python
async def count_snippets_by_guild_id(self, guild_id: int) -> int:
    """Count the number of snippets in a guild.

    Parameters
    ----------
    guild_id : int
        The ID of the guild to count snippets for

    Returns
    -------
    int
        The number of snippets in the guild
    """
    return await self.count(where={"guild_id": guild_id})
bulk_delete_snippets_by_guild_id(guild_id: int) -> int async

Delete all snippets for a guild.

Parameters:

Name Type Description Default
guild_id int

The ID of the guild to delete snippets for

required

Returns:

Type Description
int

The number of snippets deleted

Source code in tux/database/controllers/snippet.py
Python
async def bulk_delete_snippets_by_guild_id(self, guild_id: int) -> int:
    """Delete all snippets for a guild.

    Parameters
    ----------
    guild_id : int
        The ID of the guild to delete snippets for

    Returns
    -------
    int
        The number of snippets deleted
    """
    return await self.delete_many(where={"guild_id": guild_id})