Class, representing a foreign key constraint. It is a separate object, which is not connected to Table or Column objects and its `sql` property contains the ALTER TABLE clause.
| 13 | |
| 14 | |
| 15 | class Reference(SQLObject, DBMLObject): |
| 16 | ''' |
| 17 | Class, representing a foreign key constraint. |
| 18 | It is a separate object, which is not connected to Table or Column objects |
| 19 | and its `sql` property contains the ALTER TABLE clause. |
| 20 | ''' |
| 21 | required_attributes = ('type', 'col1', 'col2') |
| 22 | dont_compare_fields = ('database', '_inline') |
| 23 | |
| 24 | def __init__(self, |
| 25 | type: Literal['>', '<', '-', '<>'], |
| 26 | col1: Union[Column, Collection[Column]], |
| 27 | col2: Union[Column, Collection[Column]], |
| 28 | name: Optional[str] = None, |
| 29 | comment: Optional[str] = None, |
| 30 | on_update: Optional[str] = None, |
| 31 | on_delete: Optional[str] = None, |
| 32 | inline: bool = False): |
| 33 | self.database = None |
| 34 | self.type = type |
| 35 | self.col1 = [col1] if isinstance(col1, Column) else list(col1) |
| 36 | self.col2 = [col2] if isinstance(col2, Column) else list(col2) |
| 37 | self.name = name if name else None |
| 38 | self.comment = comment |
| 39 | self.on_update = on_update |
| 40 | self.on_delete = on_delete |
| 41 | self._inline = inline |
| 42 | |
| 43 | @property |
| 44 | def inline(self) -> bool: |
| 45 | return self._inline and not self.type == MANY_TO_MANY |
| 46 | |
| 47 | @inline.setter |
| 48 | def inline(self, val) -> None: |
| 49 | self._inline = val |
| 50 | |
| 51 | @property |
| 52 | def join_table(self) -> Optional[Table]: |
| 53 | if self.type != MANY_TO_MANY: |
| 54 | return None |
| 55 | |
| 56 | if self.table1 is None: |
| 57 | raise TableNotFoundError(f"Cannot generate join table for {self}: table 1 is unknown") |
| 58 | if self.table2 is None: |
| 59 | raise TableNotFoundError(f"Cannot generate join table for {self}: table 2 is unknown") |
| 60 | |
| 61 | return Table( |
| 62 | name=f'{self.table1.name}_{self.table2.name}', |
| 63 | schema=self.table1.schema, |
| 64 | columns=( |
| 65 | Column(name=f'{c.table.name}_{c.name}', type=c.type, not_null=True, pk=True) # type: ignore |
| 66 | for c in chain(self.col1, self.col2) |
| 67 | ), |
| 68 | abstract=True |
| 69 | ) |
| 70 | |
| 71 | @property |
| 72 | def table1(self) -> Optional[Table]: |
no outgoing calls