Skip to content

connections

Connections.

This module contains the database connection and operations for the tool inventory application. It includes classes for handling database operations and custom exceptions for error handling.

Database

Database connection.

Source code in src/tool_inventory/connections.py
class Database:
    """Database connection."""

    def __init__(self, session: Session, /) -> None:
        """Initialize database connection.

        Args:
            session: The database session.
        """
        self.session = session

    def get_tool_by_id(self, tool_id: UUID, /) -> Tool:
        """Get a tool by ID.

        Args:
            tool_id: The UUID of the tool.

        Returns:
            The tool with the specified ID.

        Raises:
            ToolNotFoundError: If the tool is not found.
        """
        statement = select(Tool).where(Tool.id == tool_id)
        result = self.session.exec(statement)
        try:
            return result.one()
        except NoResultFound as err:
            raise ToolNotFoundError(tool_id) from err

    def get_tools(self, name: str | None = None) -> list[Tool]:
        """Get tools.

        Args:
            name: The name of the tool to filter by.

        Returns:
            A list of tools.
        """
        statement = select(Tool)
        if name:
            statement = statement.where(Tool.name == name)
        result = self.session.exec(statement)
        return list(result.all())

    def search_tools(self, query: str, /) -> list[Tool]:
        """Search tools.

        Args:
            query: The search query.

        Returns:
            A list of tools.
        """
        statement = select(Tool)
        result = self.session.exec(statement)
        matches: list[tuple[int, Tool]] = []
        for tool in result.all():
            if (score := fuzz.ratio(query.lower(), tool.name.lower())) > 50:  # noqa: PLR2004
                matches.append((score, tool))  # noqa: PERF401
        return [tool for _, tool in sorted(matches, reverse=True)]

    def create_tool(self, tool: Tool, /) -> Tool:
        """Create a tool.

        Args:
            tool: The tool to create.

        Returns:
            The created tool.

        Raises:
            ToolExistsError: If the tool already exists.
        """
        Tool.model_validate(tool)
        self.session.add(tool)
        try:
            self.session.commit()
        except IntegrityError as err:
            raise ToolExistsError(tool.id) from err
        self.session.refresh(tool)
        return tool

    def update_tool(self, tool: Tool, /) -> Tool:
        """Update a tool.

        Args:
            tool: The tool to update.

        Returns:
            The updated tool.

        Raises:
            ToolNotFoundError: If the tool is not found.
        """
        Tool.model_validate(tool)
        self.session.add(tool)
        try:
            self.session.commit()
        except IntegrityError as err:
            raise ToolNotFoundError(tool.id) from err
        self.session.refresh(tool)
        return tool

    def delete_tool(self, tool_id: UUID, /) -> None:
        """Delete a tool.

        Args:
            tool_id: The UUID of the tool to delete.

        Raises:
            ToolNotFoundError: If the tool is not found.
        """
        tool = self.get_tool_by_id(tool_id)
        self.session.delete(tool)
        self.session.commit()

__init__

__init__(session: Session) -> None

Initialize database connection.

Parameters:

Name Type Description Default
session Session

The database session.

required
Source code in src/tool_inventory/connections.py
def __init__(self, session: Session, /) -> None:
    """Initialize database connection.

    Args:
        session: The database session.
    """
    self.session = session

create_tool

create_tool(tool: Tool) -> Tool

Create a tool.

Parameters:

Name Type Description Default
tool Tool

The tool to create.

required

Returns:

Type Description
Tool

The created tool.

Raises:

Type Description
ToolExistsError

If the tool already exists.

Source code in src/tool_inventory/connections.py
def create_tool(self, tool: Tool, /) -> Tool:
    """Create a tool.

    Args:
        tool: The tool to create.

    Returns:
        The created tool.

    Raises:
        ToolExistsError: If the tool already exists.
    """
    Tool.model_validate(tool)
    self.session.add(tool)
    try:
        self.session.commit()
    except IntegrityError as err:
        raise ToolExistsError(tool.id) from err
    self.session.refresh(tool)
    return tool

delete_tool

delete_tool(tool_id: UUID) -> None

Delete a tool.

Parameters:

Name Type Description Default
tool_id UUID

The UUID of the tool to delete.

required

Raises:

Type Description
ToolNotFoundError

If the tool is not found.

Source code in src/tool_inventory/connections.py
def delete_tool(self, tool_id: UUID, /) -> None:
    """Delete a tool.

    Args:
        tool_id: The UUID of the tool to delete.

    Raises:
        ToolNotFoundError: If the tool is not found.
    """
    tool = self.get_tool_by_id(tool_id)
    self.session.delete(tool)
    self.session.commit()

get_tool_by_id

get_tool_by_id(tool_id: UUID) -> Tool

Get a tool by ID.

Parameters:

Name Type Description Default
tool_id UUID

The UUID of the tool.

required

Returns:

Type Description
Tool

The tool with the specified ID.

Raises:

Type Description
ToolNotFoundError

If the tool is not found.

Source code in src/tool_inventory/connections.py
def get_tool_by_id(self, tool_id: UUID, /) -> Tool:
    """Get a tool by ID.

    Args:
        tool_id: The UUID of the tool.

    Returns:
        The tool with the specified ID.

    Raises:
        ToolNotFoundError: If the tool is not found.
    """
    statement = select(Tool).where(Tool.id == tool_id)
    result = self.session.exec(statement)
    try:
        return result.one()
    except NoResultFound as err:
        raise ToolNotFoundError(tool_id) from err

get_tools

get_tools(name: str | None = None) -> list[Tool]

Get tools.

Parameters:

Name Type Description Default
name str | None

The name of the tool to filter by.

None

Returns:

Type Description
list[Tool]

A list of tools.

Source code in src/tool_inventory/connections.py
def get_tools(self, name: str | None = None) -> list[Tool]:
    """Get tools.

    Args:
        name: The name of the tool to filter by.

    Returns:
        A list of tools.
    """
    statement = select(Tool)
    if name:
        statement = statement.where(Tool.name == name)
    result = self.session.exec(statement)
    return list(result.all())

search_tools

search_tools(query: str) -> list[Tool]

Search tools.

Parameters:

Name Type Description Default
query str

The search query.

required

Returns:

Type Description
list[Tool]

A list of tools.

Source code in src/tool_inventory/connections.py
def search_tools(self, query: str, /) -> list[Tool]:
    """Search tools.

    Args:
        query: The search query.

    Returns:
        A list of tools.
    """
    statement = select(Tool)
    result = self.session.exec(statement)
    matches: list[tuple[int, Tool]] = []
    for tool in result.all():
        if (score := fuzz.ratio(query.lower(), tool.name.lower())) > 50:  # noqa: PLR2004
            matches.append((score, tool))  # noqa: PERF401
    return [tool for _, tool in sorted(matches, reverse=True)]

update_tool

update_tool(tool: Tool) -> Tool

Update a tool.

Parameters:

Name Type Description Default
tool Tool

The tool to update.

required

Returns:

Type Description
Tool

The updated tool.

Raises:

Type Description
ToolNotFoundError

If the tool is not found.

Source code in src/tool_inventory/connections.py
def update_tool(self, tool: Tool, /) -> Tool:
    """Update a tool.

    Args:
        tool: The tool to update.

    Returns:
        The updated tool.

    Raises:
        ToolNotFoundError: If the tool is not found.
    """
    Tool.model_validate(tool)
    self.session.add(tool)
    try:
        self.session.commit()
    except IntegrityError as err:
        raise ToolNotFoundError(tool.id) from err
    self.session.refresh(tool)
    return tool

ObjectExistsError

Bases: Exception

Object exists error.

Source code in src/tool_inventory/connections.py
class ObjectExistsError(Exception):
    """Object exists error."""

    def __init__(self, object_id: UUID, /) -> None:
        """Initialize object exists error.

        Args:
            object_id: The UUID of the object.
        """
        self.object_id = object_id
        self.detail = "Object already exists"

__init__

__init__(object_id: UUID) -> None

Initialize object exists error.

Parameters:

Name Type Description Default
object_id UUID

The UUID of the object.

required
Source code in src/tool_inventory/connections.py
def __init__(self, object_id: UUID, /) -> None:
    """Initialize object exists error.

    Args:
        object_id: The UUID of the object.
    """
    self.object_id = object_id
    self.detail = "Object already exists"

ObjectNotFoundError

Bases: Exception

Object not found error.

Source code in src/tool_inventory/connections.py
class ObjectNotFoundError(Exception):
    """Object not found error."""

    def __init__(self, object_id: UUID, /) -> None:
        """Initialize object not found error.

        Args:
            object_id: The UUID of the object.
        """
        self.object_id = object_id
        self.detail = "Object not found"

__init__

__init__(object_id: UUID) -> None

Initialize object not found error.

Parameters:

Name Type Description Default
object_id UUID

The UUID of the object.

required
Source code in src/tool_inventory/connections.py
def __init__(self, object_id: UUID, /) -> None:
    """Initialize object not found error.

    Args:
        object_id: The UUID of the object.
    """
    self.object_id = object_id
    self.detail = "Object not found"

ToolExistsError

Bases: ObjectExistsError

Tool exists error.

Source code in src/tool_inventory/connections.py
class ToolExistsError(ObjectExistsError):
    """Tool exists error."""

    def __init__(self, tool_id: UUID, /) -> None:
        """Initialize tool exists error.

        Args:
            tool_id: The UUID of the tool.
        """
        super().__init__(tool_id)
        self.detail = "Tool already exists"

__init__

__init__(tool_id: UUID) -> None

Initialize tool exists error.

Parameters:

Name Type Description Default
tool_id UUID

The UUID of the tool.

required
Source code in src/tool_inventory/connections.py
def __init__(self, tool_id: UUID, /) -> None:
    """Initialize tool exists error.

    Args:
        tool_id: The UUID of the tool.
    """
    super().__init__(tool_id)
    self.detail = "Tool already exists"

ToolNotFoundError

Bases: ObjectNotFoundError

Tool not found error.

Source code in src/tool_inventory/connections.py
class ToolNotFoundError(ObjectNotFoundError):
    """Tool not found error."""

    def __init__(self, tool_id: UUID, /) -> None:
        """Initialize tool not found error.

        Args:
            tool_id: The UUID of the tool.
        """
        super().__init__(tool_id)
        self.detail = "Tool not found"

__init__

__init__(tool_id: UUID) -> None

Initialize tool not found error.

Parameters:

Name Type Description Default
tool_id UUID

The UUID of the tool.

required
Source code in src/tool_inventory/connections.py
def __init__(self, tool_id: UUID, /) -> None:
    """Initialize tool not found error.

    Args:
        tool_id: The UUID of the tool.
    """
    super().__init__(tool_id)
    self.detail = "Tool not found"

setup_database

setup_database() -> None

Setup database.

Source code in src/tool_inventory/connections.py
def setup_database() -> None:
    """Setup database."""
    SQLModel.metadata.create_all(engine)