Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #463: Through tables for grandchildren with relationships #468

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 45 additions & 38 deletions pgsync/querybuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,46 @@ def _json_build_object(

return expression

def get_foreign_keys_through_model(self, node_a: Node, node_b: Node) -> dict:
if (node_a, node_b) not in self._cache:
fkeys: dict = defaultdict(list)
if node_a.model.foreign_keys:
for key in node_a.model.original.foreign_keys:
if key._table_key() == str(node_b.model.original):
fkeys[
f"{key.parent.table.schema}."
f"{key.parent.table.name}"
].append(str(key.parent.name))
fkeys[
f"{key.column.table.schema}."
f"{key.column.table.name}"
].append(str(key.column.name))
if not fkeys:
if node_b.model.original.foreign_keys:
for key in node_b.model.original.foreign_keys:
if key._table_key() == str(node_a.model.original):
fkeys[
f"{key.parent.table.schema}."
f"{key.parent.table.name}"
].append(str(key.parent.name))
fkeys[
f"{key.column.table.schema}."
f"{key.column.table.name}"
].append(str(key.column.name))
if not fkeys:
raise ForeignKeyError(
f"No foreign key relationship between "
f"{node_a.model.original} and {node_b.model.original}"
)

foreign_keys: dict = {}
for table, columns in fkeys.items():
foreign_keys[table] = columns

self._cache[(node_a, node_b)] = foreign_keys

return self._cache[(node_a, node_b)]

# this is for handling non-through tables
def get_foreign_keys(self, node_a: Node, node_b: Node) -> dict:
if (node_a, node_b) not in self._cache:
Expand All @@ -108,42 +148,9 @@ def get_foreign_keys(self, node_a: Node, node_b: Node) -> dict:
foreign_keys[node_b.name] = sorted(
node_b.relationship.foreign_key.child
)

self._cache[(node_a, node_b)] = foreign_keys
else:
fkeys: dict = defaultdict(list)
if node_a.model.foreign_keys:
for key in node_a.model.original.foreign_keys:
if key._table_key() == str(node_b.model.original):
fkeys[
f"{key.parent.table.schema}."
f"{key.parent.table.name}"
].append(str(key.parent.name))
fkeys[
f"{key.column.table.schema}."
f"{key.column.table.name}"
].append(str(key.column.name))
if not fkeys:
if node_b.model.original.foreign_keys:
for key in node_b.model.original.foreign_keys:
if key._table_key() == str(node_a.model.original):
fkeys[
f"{key.parent.table.schema}."
f"{key.parent.table.name}"
].append(str(key.parent.name))
fkeys[
f"{key.column.table.schema}."
f"{key.column.table.name}"
].append(str(key.column.name))
if not fkeys:
raise ForeignKeyError(
f"No foreign key relationship between "
f"{node_a.model.original} and {node_b.model.original}"
)

for table, columns in fkeys.items():
foreign_keys[table] = columns

self._cache[(node_a, node_b)] = foreign_keys
self.get_foreign_keys_through_model(node_a, node_b)

return self._cache[(node_a, node_b)]

Expand Down Expand Up @@ -439,9 +446,9 @@ def _children(self, node: Node) -> None:

def _through(self, node: Node) -> None: # noqa: C901
through: Node = node.relationship.throughs[0]
foreign_keys: dict = self.get_foreign_keys(node, through)
foreign_keys: dict = self.get_foreign_keys_through_model(node, through)

for key, values in self.get_foreign_keys(through, node.parent).items():
for key, values in self.get_foreign_keys_through_model(through, node.parent).items():
if key in foreign_keys:
for value in values:
if value not in foreign_keys[key]:
Expand Down Expand Up @@ -650,7 +657,7 @@ def _through(self, node: Node) -> None: # noqa: C901
sa.func.JSON_AGG(outer_subquery.c.anon).label(node.label),
]

foreign_keys: dict = self.get_foreign_keys(node.parent, through)
foreign_keys: dict = self.get_foreign_keys_through_model(node.parent, through)

for column in foreign_keys[through.name]:
columns.append(through.model.c[str(column)])
Expand Down
135 changes: 114 additions & 21 deletions tests/test_unique_behaviour.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ def data(
user_cls,
contact_cls,
contact_item_cls,
author_cls,
book_author_cls,
):
session = sync.session
contacts = [
Expand All @@ -31,8 +33,8 @@ def data(
# contact_item_cls(name="Contact Item 2", contact=contacts[1]),
]
users = [
user_cls(name="Fonzy Bear", contact=contacts[0]),
user_cls(name="Jack Jones", contact=contacts[1]),
user_cls(id=1, name="Fonzy Bear", contact=contacts[0]),
user_cls(id=2, name="Jack Jones", contact=contacts[1]),
]
books = [
book_cls(
Expand All @@ -43,6 +45,22 @@ def data(
seller=users[1],
),
]
authors = [
author_cls(
id=1,
name="Roald Dahl",
birth_year=1916,
),
author_cls(
id=2,
name="Haruki Murakami",
birth_year=1949,
),
]
book_authors = [
book_author_cls(id=1, book=books[0], author=authors[0]),
book_author_cls(id=2, book=books[0], author=authors[1]),
]
with subtransactions(session):
conn = session.connection().engine.connect().connection
cursor = conn.cursor()
Expand All @@ -54,6 +72,8 @@ def data(
session.add_all(contact_items)
session.add_all(users)
session.add_all(books)
session.add_all(authors)
session.add_all(book_authors)

sync.logical_slot_get_changes(
f"{sync.database}_testdb",
Expand All @@ -65,6 +85,8 @@ def data(
contacts,
contact_items,
users,
authors,
book_authors,
)

with subtransactions(session):
Expand All @@ -80,6 +102,8 @@ def data(
contact_item_cls.__table__.name,
contact_cls.__table__.name,
user_cls.__table__.name,
author_cls.__table__.name,
book_author_cls.__table__.name,
]
)

Expand All @@ -99,9 +123,18 @@ def data(
session.connection().engine.dispose()
sync.search_client.close()

@pytest.fixture(scope="function")
def nodes(self):
return {
def test_sync_multiple_children_empty_leaf(
self,
sync,
data,
):
"""
----> User(buyer) ----> Contact ----> ContactItem
Book ----|
----> User(seller) ----> Contact ----> ContactItem
Test regular sync produces the correct result
"""
nodes = {
"table": "book",
"columns": ["isbn", "title", "description"],
"children": [
Expand Down Expand Up @@ -194,26 +227,11 @@ def nodes(self):
],
}

def test_sync_multiple_children_empty_leaf(
self,
sync,
data,
nodes,
book_cls,
user_cls,
contact_cls,
contact_item_cls,
):
"""
----> User(buyer) ----> Contact ----> ContactItem
Book ----|
----> User(seller) ----> Contact ----> ContactItem
Test regular sync produces the correct result
"""
sync.tree.__nodes = {}
sync.tree = Tree(sync.models, nodes)
docs = [sort_list(doc) for doc in sync.sync()]
docs = sorted(docs, key=lambda k: k["_id"])

assert docs == [
{
"_id": "abc",
Expand Down Expand Up @@ -253,3 +271,78 @@ def test_sync_multiple_children_empty_leaf(
]

assert_resync_empty(sync, nodes)

def test_though_table_for_grandchildren(
self,
sync,
data,
):
nodes = {
"table": "user",
"columns": ["id", "name"],
"children": [
{
"table": "book",
"label": "books",
"columns": ["isbn", "title", "description"],
"relationship": {
"variant": "object",
"type": "one_to_many",
"foreign_key": {
"parent": ["id"],
"child": ["buyer_id"],
},
},
"children": [
{
"table": "author",
"label": "authors",
"columns": ["id", "name"],
"relationship": {
"type": "one_to_many",
"variant": "object",
"through_tables": ["book_author"],
},
}
]
}
]
}

sync.tree.__nodes = {}
sync.tree.__post_init__()
sync.nodes = nodes
sync.root = sync.tree.build(nodes)
docs = [sort_list(doc) for doc in sync.sync()]
docs = sorted(docs, key=lambda k: k["_id"])

assert docs == [
{'_id': '1',
'_index': 'testdb',
'_source': {
'id': 1,
'name': 'Fonzy Bear',
'books': [{
'isbn': 'abc',
'title': 'The Tiger Club',
'authors': [
{'id': 1, 'name': 'Roald Dahl'},
{'id': 2, 'name': 'Haruki Murakami'}
],
'description': 'Tigers are fierce creatures'
}],
'_meta': {
'book': {'isbn': ['abc']},
'author': {'id': [1, 2]},
'book_author': {'id': [1, 2]}
}
}},
{'_id': '2',
'_index': 'testdb',
'_source': {
'id': 2,
'name': 'Jack Jones',
'books': None,
'_meta': {}
}}
]