Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/sqlalchemy_utils/types/weekdays.py: 72%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

29 statements  

1from sqlalchemy import types 

2 

3from .. import i18n 

4from ..exceptions import ImproperlyConfigured 

5from ..primitives import WeekDay, WeekDays 

6from .bit import BitType 

7from .scalar_coercible import ScalarCoercible 

8 

9 

10class WeekDaysType(types.TypeDecorator, ScalarCoercible): 

11 """ 

12 WeekDaysType offers way of saving WeekDays objects into database. The 

13 WeekDays objects are converted to bit strings on the way in and back to 

14 WeekDays objects on the way out. 

15 

16 In order to use WeekDaysType you need to install Babel_ first. 

17 

18 .. _Babel: https://babel.pocoo.org/ 

19 

20 :: 

21 

22 

23 from sqlalchemy_utils import WeekDaysType, WeekDays 

24 from babel import Locale 

25 

26 

27 class Schedule(Base): 

28 __tablename__ = 'schedule' 

29 id = sa.Column(sa.Integer, autoincrement=True) 

30 working_days = sa.Column(WeekDaysType) 

31 

32 

33 schedule = Schedule() 

34 schedule.working_days = WeekDays('0001111') 

35 session.add(schedule) 

36 session.commit() 

37 

38 print schedule.working_days # Thursday, Friday, Saturday, Sunday 

39 

40 

41 WeekDaysType also supports scalar coercion: 

42 

43 :: 

44 

45 

46 schedule.working_days = '1110000' 

47 schedule.working_days # WeekDays object 

48 

49 """ 

50 

51 impl = BitType(WeekDay.NUM_WEEK_DAYS) 

52 

53 cache_ok = True 

54 

55 def __init__(self, *args, **kwargs): 

56 if i18n.babel is None: 

57 raise ImproperlyConfigured( 

58 "'babel' package is required to use 'WeekDaysType'" 

59 ) 

60 

61 super().__init__(*args, **kwargs) 

62 

63 @property 

64 def comparator_factory(self): 

65 return self.impl.comparator_factory 

66 

67 def process_bind_param(self, value, dialect): 

68 if isinstance(value, WeekDays): 

69 value = value.as_bit_string() 

70 

71 if dialect.name == 'mysql': 

72 return bytes(value, 'utf8') 

73 return value 

74 

75 def process_result_value(self, value, dialect): 

76 if value is not None: 

77 return WeekDays(value) 

78 

79 def _coerce(self, value): 

80 if value is not None and not isinstance(value, WeekDays): 

81 return WeekDays(value) 

82 return value