Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -1795,9 +1795,10 @@ def get_table_submodules_dependencies(self, **kwargs):
table_dependencies.extend(result)

# Remove the same table from the dependency list
for item in table_dependencies:
if 'oid' in item and item['oid'] == tid:
table_dependencies.remove(item)
table_dependencies = [
item for item in table_dependencies
if item.get('oid') != tid
]

return table_dependencies

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,10 @@ def get_fkey_dependencies(conn, tid, template_path=None):

for fk in result['rows']:
ref_name = fk['refnsp'] + '.' + fk['reftab']
deps.append({'type': 'table', 'name': ref_name})
deps.append({
'type': 'table',
'name': ref_name,
'oid': fk['confrelid']
})

return True, deps
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2026, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################

"""Unit tests for Schema Diff foreign key dependency extraction."""

from unittest.mock import MagicMock

from pgadmin.browser.server_groups.servers.databases.schemas.tables import (
TableView,
)
from pgadmin.browser.server_groups.servers.databases.schemas.tables.\
constraints.foreign_key import utils as fkey_utils
from pgadmin.utils.route import BaseTestGenerator


class TestSchemaDiffFkDependenciesUnit(BaseTestGenerator):
"""Unit tests for get_fkey_dependencies() and
TableView.get_table_submodules_dependencies()."""

scenarios = [
('get_fkey_dependencies includes referenced table OID',
dict(test_method='test_fkey_dependencies_include_oid')),
('get_fkey_dependencies handles tables with no foreign keys',
dict(test_method='test_fkey_dependencies_empty')),
('get_table_submodules_dependencies removes consecutive self '
'references',
dict(test_method='test_submodules_dependencies_strips_self_refs')),
]

def runTest(self):
getattr(self, self.test_method)()

def _make_conn(self, rows):
conn = MagicMock()
conn.manager.version = 170000
conn.execute_dict.return_value = (True, {'rows': rows})
return conn

def test_fkey_dependencies_include_oid(self):
conn = self._make_conn([
{
'refnsp': 'fk_order_repro',
'reftab': 'z_parent',
'confrelid': 16390,
},
{
'refnsp': 'shared',
'reftab': 'lookup',
'confrelid': 16410,
},
])

with self.app.app_context():
status, deps = fkey_utils.get_fkey_dependencies(conn, 16395)

self.assertTrue(status)
self.assertEqual(deps, [
{'type': 'table', 'name': 'fk_order_repro.z_parent', 'oid': 16390},
{'type': 'table', 'name': 'shared.lookup', 'oid': 16410},
])

def test_fkey_dependencies_empty(self):
conn = self._make_conn([])

with self.app.app_context():
status, deps = fkey_utils.get_fkey_dependencies(conn, 16395)

self.assertTrue(status)
self.assertEqual(deps, [])

def test_submodules_dependencies_strips_self_refs(self):
tid = 16395
view = TableView.__new__(TableView)
view.conn = self._make_conn([
# Two consecutive self-referencing FKs followed by a parent FK.
{'refnsp': 'app', 'reftab': 's_self', 'confrelid': tid},
{'refnsp': 'app', 'reftab': 's_self', 'confrelid': tid},
{'refnsp': 'app', 'reftab': 'z_parent', 'confrelid': 16390},
])
view.tables_sub_modules = []
# Consecutive self-dependency in get_dependencies() as well.
view.get_dependencies = MagicMock(return_value=[
{'type': 'table', 'name': 'app.s_self', 'oid': tid},
{'type': 'type', 'name': 'app.custom_type', 'oid': 16388},
])

raw_method = TableView.get_table_submodules_dependencies.__wrapped__
with self.app.app_context():
deps = raw_method(view, tid=tid)

self.assertEqual(deps, [
{'type': 'type', 'name': 'app.custom_type', 'oid': 16388},
{'type': 'table', 'name': 'app.z_parent', 'oid': 16390},
])
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,96 @@ export function setRecordCount(row, filterParams) {

}

function collectLeafRows(nodes, leaves = []) {
if (!Array.isArray(nodes)) return leaves;

nodes.forEach((node) => {
if (Array.isArray(node.children)) {
collectLeafRows(node.children, leaves);
} else {
leaves.push(node);
}
});

return leaves;
}

function getStillRequiredDependencyIds(gridData, selectedRowIds) {
const selectedSet = new Set(selectedRowIds);
const stillRequired = new Set();

collectLeafRows(gridData).forEach((leaf) => {
if (selectedSet.has(`${leaf.id}`)) {
(leaf.dependencieRowIds || []).forEach((depId) => {
stillRequired.add(`${depId}`);
});
}
});

return stillRequired;
}

function deselectChildAndSubChild(children, tempSelectedRows) {
children.map((chid) => {
let indx = tempSelectedRows.indexOf(chid);
indx != -1 && tempSelectedRows.splice(indx, 1);
});
}

function removeUnneededDependencies(dependencyIds, tempSelectedRows, gridData) {
if (!dependencyIds || dependencyIds.length === 0) return;

const stillRequired = getStillRequiredDependencyIds(gridData, tempSelectedRows);
Comment thread
dpage marked this conversation as resolved.
Resolved
dependencyIds.forEach((depId) => {
const idStr = `${depId}`;
if (!stillRequired.has(idStr)) {
const depIndex = tempSelectedRows.indexOf(idStr);
depIndex !== -1 && tempSelectedRows.splice(depIndex, 1);
}
});
}

export function deselectResultRows(row, tempSelectedRows, gridData = []) {
if (row.metadata.isRoot) {
deselectChildAndSubChild(row.metadata.subChildren, tempSelectedRows);

deselectChildAndSubChild(row.metadata.children, tempSelectedRows);

let rootIndex = tempSelectedRows.indexOf(`${row.id}`);
rootIndex != -1 && tempSelectedRows.splice(rootIndex, 1);

} else if (row.metadata.subChildren) {
deselectChildAndSubChild(row.metadata.subChildren, tempSelectedRows);

let isChildAllInclude = true;
row.metadata.children.map((id) => {
if (tempSelectedRows.includes(id)) {
isChildAllInclude = false;
}
});

let rootIndex = tempSelectedRows.indexOf(`${row.id}`);
rootIndex != -1 && tempSelectedRows.splice(rootIndex, 1);

let parentIndex = tempSelectedRows.indexOf(`${row.metadata.parentId}`);
(!isChildAllInclude && parentIndex != -1) && tempSelectedRows.splice(parentIndex, 1);

removeUnneededDependencies(row.metadata.dependencies, tempSelectedRows, gridData);

} else {
let elementIndex = tempSelectedRows.indexOf(`${row.id}`);
elementIndex != -1 && tempSelectedRows.splice(elementIndex, 1);

let parentElIndex = tempSelectedRows.indexOf(`${row.metadata.parentId}`);
parentElIndex != -1 && tempSelectedRows.splice(parentElIndex, 1);

let rootIndex = tempSelectedRows.indexOf(`${row.metadata.rootId}`);
rootIndex != -1 && tempSelectedRows.splice(rootIndex, 1);

removeUnneededDependencies(row.dependencieRowIds, tempSelectedRows, gridData);
}
}

function CellExpanderFormatter({
row,
isCellSelected,
Expand Down Expand Up @@ -589,59 +679,9 @@ export function ResultGridComponent({ gridData, allRowIds, filterParams, selecte
}
}

function deselectChildAndSubChild(children, tempSelectedRows) {
children.map((chid) => {
let indx = tempSelectedRows.indexOf(chid);
indx != -1 && tempSelectedRows.splice(indx, 1);
});
}

function deselectResultRows(row, tempSelectedRows) {
if (row.metadata.isRoot) {
deselectChildAndSubChild(row.metadata.subChildren, tempSelectedRows);

deselectChildAndSubChild(row.metadata.children, tempSelectedRows);

let rootIndex = tempSelectedRows.indexOf(`${row.id}`);
rootIndex != -1 && tempSelectedRows.splice(rootIndex, 1);

} else if (row.metadata.subChildren) {
deselectChildAndSubChild(row.metadata.subChildren, tempSelectedRows);

let isChildAllInclude = true;
row.metadata.children.map((id) => {
if (tempSelectedRows.includes(id)) {
isChildAllInclude = false;
}
});

let rootIndex = tempSelectedRows.indexOf(`${row.id}`);
rootIndex != -1 && tempSelectedRows.splice(rootIndex, 1);

let parentIndex = tempSelectedRows.indexOf(`${row.metadata.parentId}`);
(!isChildAllInclude && parentIndex != -1) && tempSelectedRows.splice(parentIndex, 1);

row.metadata.dependencies.map((depid) => {
let depIndex = tempSelectedRows.indexOf(`${depid}`);
depIndex != -1 && tempSelectedRows.splice(depIndex, 1);
});

} else {
let elementIndex = tempSelectedRows.indexOf(`${row.id}`);
elementIndex != -1 && tempSelectedRows.splice(elementIndex, 1);

let parentElIndex = tempSelectedRows.indexOf(`${row.metadata.parentId}`);
parentElIndex != -1 && tempSelectedRows.splice(parentElIndex, 1);

let rootIndex = tempSelectedRows.indexOf(`${row.metadata.rootId}`);
rootIndex != -1 && tempSelectedRows.splice(rootIndex, 1);

row.dependencieRowIds.map((id) => {
let deptRowIndex = tempSelectedRows.indexOf(`${id}`);
deptRowIndex != -1 && tempSelectedRows.splice(deptRowIndex, 1);
});
}
}
const handleDeselectResultRows = (row, tempSelectedRows) => {
deselectResultRows(row, tempSelectedRows, gridData);
};

function getStyleClassName(row, selectedRowIds, activeRowId) {
let clsName = null;
Expand Down Expand Up @@ -673,7 +713,7 @@ export function ResultGridComponent({ gridData, allRowIds, filterParams, selecte
renderCell: selectFormatter({
selectedRows, setSelectedRows, setRootSelection,
setActiveRow, allRowIds, selectedRowIds,
selectedResultRows, deselectResultRows
selectedResultRows, deselectResultRows: handleDeselectResultRows
}),
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,31 @@ function generateFinalScript(script_array, scriptHeader, script_body) {
return `${scriptHeader} BEGIN; \n ${script_body} END;`;
}

function isSourceOidRow(row) {
return row.status !== FILTER_NAME.TARGET_ONLY &&
!_.isUndefined(row.oid) && !_.isNull(row.oid);
}

export function populateGridDependencyRowIds(collections) {
/* Link each row's dependenciesOid to matching source-side row IDs so
selecting a dependent row in the grid selects its parents without
pulling in Target Only rows that happen to share an OID. */
collections.forEach((collection) => {
collection.children.forEach((ch) => {
if (ch.dependenciesOid?.length > 0) {
collections.forEach((el) => {
el.children.forEach((data) => {
if (isSourceOidRow(data) && ch.dependenciesOid.includes(data.oid)) {
ch.dependencieRowIds.push(`${data.id}`);
}
});
});
}
collection.metadata.dependencies.push(...ch.dependencieRowIds);
});
});
}

export function computeDependLevels(rows) {
/* Assign each row a dependLevel such that anything another row depends
on always ends up with a strictly higher level than that row, so that
Expand All @@ -59,7 +84,7 @@ export function computeDependLevels(rows) {
for that edge, rather than recursing forever. */
const oidToRow = new Map();
rows.forEach((row) => {
if (!_.isUndefined(row.oid) && !_.isNull(row.oid)) {
if (isSourceOidRow(row)) {
oidToRow.set(row.oid, row);
}
});
Expand Down Expand Up @@ -632,25 +657,14 @@ export function SchemaDiffCompare({ params }) {
dependencies: [],
};
child.children.map((ch) => {
if (ch.dependenciesOid.length > 0) {
tempData[keyItem]['children'].map((el) => {
el.children.map((data) => {
if (ch.dependenciesOid.includes(data.oid)) {
ch.dependencieRowIds.push(`${data.id}`);
}
});

});
}
ch['metadata'] = {
parentId: child.id,
rootId: tempData[keyItem].id,
children: child.children.map(({ id }) => `${id}`),

};
child['metadata']['dependencies'].push(...ch.dependencieRowIds);
});
});
populateGridDependencyRowIds(tempData[keyItem]['children']);
temp.push(tempData[keyItem]);
}

Expand Down
Loading
Loading