Coverage for backend / app / base_models.py: 100%

15 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-03-17 21:34 +0000

1"""This module defines the database table models for the application using SQLAlchemy ORM. Each class represents a table in 

2the database, with its fields defining the table's columns and relationships. The module utilizes a `CommonBase` class 

3to provide a shared structure for all models, including common attributes like `id`, `created_at`, and `created_by`.""" 

4 

5import re 

6 

7from sqlalchemy import Column, Integer, ForeignKey, TIMESTAMP, text, func 

8from sqlalchemy.ext.declarative import declared_attr 

9 

10 

11class CommonBase(object): 

12 """A base class that contains common attributes shared by all tables. 

13 The table name is automatically generated from the class name by converting CamelCase to snake_case. 

14 

15 Attributes: 

16 ----------- 

17 - `id` (int): Primary key of the record. Automatically populated upon creation. 

18 - `created_at` (datetime): The timestamp of when the record was created. Automatically populated upon creation. 

19 - `modified_at` (datetime): The timestamp of when the record was modified. Automatically updated upon updates.""" 

20 

21 # noinspection PyMethodParameters 

22 @declared_attr 

23 def __tablename__(cls) -> str: 

24 """Return the class name as table name e.g. JobApplication -> job_application""" 

25 

26 name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", cls.__name__) 

27 return re.sub("([a-z0-9])([A-Z])", r"\1_\2", name).lower() 

28 

29 id = Column(Integer, primary_key=True, nullable=False) 

30 created_at = Column(TIMESTAMP(timezone=True), server_default=text("now()"), nullable=False) 

31 modified_at = Column(TIMESTAMP(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False) 

32 

33 def __init__(self, **kwargs): 

34 

35 super().__init__(**kwargs) 

36 

37 

38class Owned(CommonBase): 

39 """A base class that contains common attributes shared by tables which entries have an owner. 

40 

41 Attributes: 

42 ----------- 

43 - `owner_id` (int): Foreign key linking the record to the user table.""" 

44 

45 owner_id = Column(Integer, ForeignKey("user.id", ondelete="CASCADE"), nullable=False)