Verified Commit bd46f183 authored by Jakob Moser's avatar Jakob Moser
Browse files

Indicate type of primary key using generics

parent 78d1bec2
Loading
Loading
Loading
Loading
+4 −5
Original line number Diff line number Diff line
from __future__ import annotations

from collections.abc import Sequence
from typing import Any

from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, MappedColumn
@@ -9,7 +8,7 @@ from sqlalchemy.orm import DeclarativeBase, MappedColumn
from poolpay import db


class Retrievable(DeclarativeBase):
class Retrievable[PrimaryKey](DeclarativeBase):
    """
    A type whose instances can be retrieved from the database.

@@ -30,7 +29,7 @@ class Retrievable(DeclarativeBase):
        return None

    @classmethod
    def get_all[T](cls: type[T]) -> Sequence[T]:
    def get_all[T: Retrievable](cls: type[T]) -> Sequence[T]:
        """
        Return all instances of this type.
        """
@@ -44,7 +43,7 @@ class Retrievable(DeclarativeBase):
        )

    @classmethod
    def get_only[T](cls: type[T], primary_key: Any) -> T | None:
    def get_only[T: Retrievable](cls: type[T], primary_key: PrimaryKey) -> T | None:
        """
        Return the instance of this type with the given primary key or None if it doesn't exist.
        """
@@ -54,7 +53,7 @@ class Retrievable(DeclarativeBase):
        return db.session.get(cls, primary_key)

    @property
    def primary_key(self) -> Any:
    def primary_key(self) -> PrimaryKey:
        """
        Return the primary key that can be used to identify an instance of this class.
        """