Coverage for .tox/coverage/lib/python3.11/site-packages/wuttjamaican/db/util.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2024-08-30 20:36 -0500

1# -*- coding: utf-8; -*- 

2################################################################################ 

3# 

4# WuttJamaican -- Base package for Wutta Framework 

5# Copyright © 2023-2024 Lance Edgar 

6# 

7# This file is part of Wutta Framework. 

8# 

9# Wutta Framework is free software: you can redistribute it and/or modify it 

10# under the terms of the GNU General Public License as published by the Free 

11# Software Foundation, either version 3 of the License, or (at your option) any 

12# later version. 

13# 

14# Wutta Framework is distributed in the hope that it will be useful, but 

15# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 

16# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 

17# more details. 

18# 

19# You should have received a copy of the GNU General Public License along with 

20# Wutta Framework. If not, see <http://www.gnu.org/licenses/>. 

21# 

22################################################################################ 

23""" 

24Database Utilities 

25""" 

26 

27import sqlalchemy as sa 

28 

29from wuttjamaican.util import make_uuid 

30 

31 

32# nb. this convention comes from upstream docs 

33# https://docs.sqlalchemy.org/en/14/core/constraints.html#constraint-naming-conventions 

34naming_convention = { 

35 'ix': 'ix_%(column_0_label)s', 

36 'uq': 'uq_%(table_name)s_%(column_0_name)s', 

37 'ck': 'ck_%(table_name)s_%(constraint_name)s', 

38 'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s', 

39 'pk': 'pk_%(table_name)s', 

40} 

41 

42 

43class ModelBase: 

44 """ """ 

45 

46 def __iter__(self): 

47 # nb. we override this to allow for `dict(self)` 

48 state = sa.inspect(self) 

49 fields = [attr.key for attr in state.attrs] 

50 return iter([(field, getattr(self, field)) 

51 for field in fields]) 

52 

53 def __getitem__(self, key): 

54 # nb. we override this to allow for `x = self['field']` 

55 state = sa.inspect(self) 

56 if hasattr(state.attrs, key): 

57 return getattr(self, key) 

58 

59 

60def uuid_column(*args, **kwargs): 

61 """ 

62 Returns a UUID column for use as a table's primary key. 

63 """ 

64 kwargs.setdefault('primary_key', True) 

65 kwargs.setdefault('nullable', False) 

66 kwargs.setdefault('default', make_uuid) 

67 return sa.Column(sa.String(length=32), *args, **kwargs) 

68 

69 

70def uuid_fk_column(target_column, *args, **kwargs): 

71 """ 

72 Returns a UUID column for use as a foreign key to another table. 

73 

74 :param target_column: Name of the table column on the remote side, 

75 e.g. ``'user.uuid'``. 

76 """ 

77 return sa.Column(sa.String(length=32), sa.ForeignKey(target_column), *args, **kwargs)