codemation / pydbantic

A single model for shaping, creating, accessing, storing data within a Database
https://pydbantic.readthedocs.io/en/latest/
Apache License 2.0
223 stars 16 forks source link

Dynamic model relationships #25

Closed codemation closed 2 years ago

codemation commented 2 years ago

Description

This PR implements Dynamic model relationships, which improves the current DataBaseModel relationship & model references by implementing dynamic creation of link tables used to associate one-to-one, many-to-one, and many-to-many relationships. By implementing link-tables, nested models can be queried much more efficiently, related models dynamically receive updates on changes / deletions. Link tables also provide the ability for backward references or bidirectional (circular) between models.

Example Models

from uuid import uuid4
from datetime import datetime
from typing import List, Optional, Union
from pydbantic import DataBaseModel, PrimaryKey

class Department(DataBaseModel):
    department_id: str = PrimaryKey()
    name: str
    company: str
    is_sensitive: bool = False
    positions: List[Optional['Positions']] = []  # # Forward Reference to Positions

class Positions(DataBaseModel):
    position_id: str = PrimaryKey()
    name: str
    department: Department = None
    employees: List[Optional['Employee']] = []  # Forward Reference to Employee

class EmployeeInfo(DataBaseModel):
    ssn: str = PrimaryKey()
    first_name: str
    last_name: str
    address: str
    address2: Optional[str]
    city: Optional[str]
    zip: Optional[int]
    new: Optional[str]
    employee: Optional[Union['Employee', dict]] = None # Forward Reference to Employee

class Employee(DataBaseModel):
    employee_id: str = PrimaryKey()
    employee_info: Optional[EmployeeInfo] = None
    position: List[Optional[Positions]] = []   
    salary: float
    is_employed: bool
    date_employed: Optional[str]

Relationships & link tables are dynamically created when added to a Database. Forward / Circular references provide their associated DataBaseModel with the same access to their related DataBaseModel reference(s). Many to many relationships should have a default value of [], while Many to One or One to One should have a default value of None, allowing validation when related models are deleted.

What Else has changed