FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Use a dataclass to encapsulate foreign key constraints · NeoTim/python-spanner-orm@c87ab42 · GitHub

Commit c87ab42

Browse files
committed
Use a dataclass to encapsulate foreign key constraints
1 parent 33d4bf5 commit c87ab42

4 files changed

Lines changed: 28 additions & 42 deletions

File tree

‎spanner_orm/admin/update.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,14 @@ def ddl(self) -> str:
5555
]
5656
key_fields_ddl = ', '.join(key_fields)
5757
for relation in self._model.foreign_key_relations.values():
58-
for referencing_table_col, referenced_table_col in relation.constraints.items():
58+
for constraint in relation.constraints:
5959
key_fields_ddl += (
60-
', FOREIGN KEY ({referencing_table_col}) REFERENCES'
61-
' {parent} ({referenced_table_col})').format(
62-
parent=relation.destination,
63-
referencing_table_col=referencing_table_col,
64-
referenced_table_col=referenced_table_col,
65-
)
60+
', FOREIGN KEY ({referencing_column}) REFERENCES'
61+
' {referenced_table} ({referenced_column})').format(
62+
referencing_column=constraint.referencing_column,
63+
referenced_table=constraint.referenced_table_name,
64+
referenced_column=constraint.referenced_column,
65+
)
6666
index_ddl = 'PRIMARY KEY ({})'.format(', '.join(self._model.primary_keys))
6767
statement = 'CREATE TABLE {} ({}) {}'.format(self._model.table,
6868
key_fields_ddl, index_ddl)

‎spanner_orm/foreign_key_relationship.py‎

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,17 @@
1414
# limitations under the License.
1515
"""Helps define a foreign key relationship between two models."""
1616

17-
from typing import Any, List, Mapping, Type, Union
17+
from typing import List, Mapping
1818

1919
import dataclasses
20-
from spanner_orm import error
2120
from spanner_orm import registry
2221

2322

2423
@dataclasses.dataclass
2524
class ForeignKeyRelationshipConstraint:
2625
referencing_column: str
27-
referenced_columns: str
26+
referenced_column: str
2827
referenced_table_name: str
29-
3028

3129

3230
class ForeignKeyRelationship(object):
@@ -38,8 +36,7 @@ def __init__(self,
3836
"""Creates a ForeignKeyRelationship.
3937
4038
Args:
41-
referenced_table_name: Destination model class or fully qualified class
42-
name of the destination model.
39+
referenced_table_name: Name of the table which the foreign key references.
4340
constraints: Dictionary where the keys are names of columns from the
4441
referencing table and the values are the names of the columns in the
4542
referenced table.
@@ -52,31 +49,20 @@ def __init__(self,
5249

5350
@property
5451
def constraints(self) -> List[ForeignKeyRelationshipConstraint]:
55-
return self._constraints
56-
57-
@property
58-
def destination(self) -> Type[Any]:
59-
return registry.model_registry().get(self._referenced_table_name).table
60-
if not self._destination:
61-
self._destination = registry.model_registry().get(
62-
self._referenced_table_name)
63-
return self._destination
52+
return self._parse_constraints()
6453

6554
def _parse_constraints(self) -> List[ForeignKeyRelationshipConstraint]:
66-
"""Validates the dictionary of constraints and turns it into Conditions."""
55+
"""Returns a list of Constraints for the relationship."""
6756
constraints = []
68-
for origin_column, destination_column in self._constraints.items():
69-
if origin_column not in self.origin.fields:
70-
raise error.ValidationError(
71-
'Origin column must be present in origin model')
72-
73-
if destination_column not in self.destination.fields:
74-
raise error.ValidationError(
75-
'Destination column must be present in destination model')
76-
77-
# TODO(dbrandao): remove when pytype #234 is fixed
57+
referenced_table = registry.model_registry().get(
58+
self._referenced_table_name)
59+
for referencing_column, referenced_column in self._constraints.items():
7860
constraints.append(
79-
RelationshipConstraint(self.destination, destination_column,
80-
self.origin, origin_column)) # type: ignore
61+
ForeignKeyRelationshipConstraint(
62+
referencing_column,
63+
referenced_column,
64+
referenced_table.table,
65+
)
66+
)
8167

8268
return constraints

‎spanner_orm/metadata.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,11 @@ def __init__(self,
4545
table: Optional[str] = None,
4646
fields: Optional[Dict[str, field.Field]] = None,
4747
relations: Optional[Dict[str, relationship.Relationship]] = None,
48-
foreign_key_relations: Optional[Dict[str, foreign_key_relationship.ForeignKeyRelationship]] = None,
48+
foreign_key_relations: Optional[
49+
Dict[
50+
str,
51+
foreign_key_relationship.ForeignKeyRelationship]
52+
] = None,
4953
indexes: Optional[Dict[str, index.Index]] = None,
5054
interleaved: Optional[str] = None,
5155
model_class: Optional[Type[Any]] = None):

‎spanner_orm/model.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,6 @@ def __new__(mcs, name: str, bases: Any, attrs: Dict[str, Any], **kwargs: Any):
5353
model_metadata.table = value
5454
elif key == '__interleaved__':
5555
model_metadata.interleaved = value
56-
elif key == '__foreign_key__':
57-
model_metadata.foreign_key = value
5856
if isinstance(value, field.Field):
5957
model_metadata.add_field(key, value)
6058
elif isinstance(value, index.Index):
@@ -121,11 +119,9 @@ def relations(cls) -> Dict[str, relationship.Relationship]:
121119
return cls.meta.relations
122120

123121
@property
124-
def foreign_key_relations(cls) -> Dict[str, foreign_key_relationship.ForeignKeyRelationship]:
122+
def foreign_key_relations(
123+
cls) -> Dict[str, foreign_key_relationship.ForeignKeyRelationship]:
125124
return cls.meta.foreign_key_relations
126-
#if cls.meta.foreign_key:
127-
# return registry.model_registry().get(cls.meta.foreign_key)
128-
#return None
129125

130126

131127
@property

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL