Coverage for dj/models/base.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.2.3, created at 2023-04-17 20:05 -0700

1""" 

2A base SQLModel class with a default naming convention. 

3""" 

4from sqlalchemy.engine.default import DefaultExecutionContext 

5from sqlmodel import SQLModel 

6 

7NAMING_CONVENTION = { 

8 "ix": "ix_%(column_0_label)s", 

9 "uq": "uq_%(table_name)s_%(column_0_name)s", 

10 "ck": "ck_%(table_name)s_%(auto_constraint_name)s", 

11 "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", 

12 "pk": "pk_%(table_name)s", 

13} 

14 

15 

16class BaseSQLModel(SQLModel): 

17 """ 

18 Base model object with naming convention for constraints. This forces alembic's 

19 autogenerate functionality to generate constraints with explicit names. 

20 """ 

21 

22 metadata = SQLModel.metadata 

23 metadata.naming_convention = NAMING_CONVENTION 

24 

25 def update(self, data: dict) -> "BaseSQLModel": 

26 """ 

27 Helper method that updates the current model with new data and validates. 

28 """ 

29 update = self.dict() 

30 update.update(data) 

31 for key, value in self.validate(update).dict(exclude_defaults=True).items(): 

32 setattr(self, key, value) 

33 return self 

34 

35 

36def labelize(value: str) -> str: 

37 """ 

38 Turn a system name into a human-readable name. 

39 """ 

40 

41 return value.replace(".", ": ").replace("_", " ").title() 

42 

43 

44def generate_display_name(column_name: str): 

45 """ 

46 SQLAlchemy helper to generate a human-readable version of the given system name. 

47 """ 

48 

49 def default_function(context: DefaultExecutionContext) -> str: 

50 column_value = context.current_parameters.get(column_name) 

51 return labelize(column_value) 

52 

53 return default_function