1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-26 21:14:19 +00:00

Create Makeable class

This commit is contained in:
Steffo 2020-11-10 15:57:45 +01:00
parent 3e4ed89047
commit 23d612c373
2 changed files with 39 additions and 0 deletions

View file

@ -1,3 +1,4 @@
from .func import *
from .make import *
from .repr import *
from .update import *

View file

@ -0,0 +1,38 @@
from royalnet.typing import *
import sqlalchemy.orm as o
T = TypeVar('T')
class Makeable:
"""
A mixin that can be added to a declared class to add the make and unmake methods, that try find an item with
specific properties and either create it if it doesn't exist or delete it if it exists.
"""
@classmethod
def make(cls: Type[T], session: o.session.Session, **kwargs) -> T:
"""Find the item with the specified name, or create it if it doesn't exist."""
# Find the item
item = session.query(cls).filter_by(**kwargs).one_or_none()
# Create the item
if item is None:
item = cls(**kwargs)
session.add(item)
# Return the item
return item
@classmethod
def unmake(cls: Type[T], session: o.session.Session, **kwargs) -> None:
"""Find the item with the specified name, and delete it if it exists."""
# Find the item
item = session.query(cls).filter_by(**kwargs).one_or_none()
# Delete the item
if item is not None:
session.delete(item)
__all__ = (
"Makeable",
)