Skip to content

Commit 5c9b250

Browse files
committed
[ADD] util.get_common_columns
Function to get the ColumnList of common columns of two tables. Part-of: #237 Related: odoo/upgrade#7421 Signed-off-by: Christophe Simonis (chs) <[email protected]>
1 parent 5a5acb2 commit 5c9b250

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/util/pg.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,6 +1068,39 @@ def get_columns(cr, table, ignore=("id",)):
10681068
return ColumnList(*cr.fetchone())
10691069

10701070

1071+
def get_common_columns(cr, table1, table2, ignore=("id",)):
1072+
"""
1073+
Return a list of columns present in both tables.
1074+
1075+
:param str table1: first table name whose columns are retrieved
1076+
:param str table2: second table name whose columns are retrieved
1077+
:param list(str) ignore: list of column names to ignore in the returning list
1078+
:return: a list of column names present in both tables
1079+
:rtype: :class:`~odoo.upgrade.util.pg.ColumnList`
1080+
"""
1081+
_validate_table(table1)
1082+
_validate_table(table2)
1083+
1084+
cr.execute(
1085+
"""
1086+
WITH _common AS (
1087+
SELECT column_name
1088+
FROM information_schema.columns
1089+
WHERE table_schema = 'public'
1090+
AND table_name IN %s
1091+
AND column_name != ALL(%s)
1092+
GROUP BY column_name
1093+
HAVING count(table_name) = 2
1094+
)
1095+
SELECT coalesce(array_agg(column_name::varchar ORDER BY column_name), ARRAY[]::varchar[]),
1096+
coalesce(array_agg(quote_ident(column_name) ORDER BY column_name), ARRAY[]::varchar[])
1097+
FROM _common
1098+
""",
1099+
[(table1, table2), list(ignore)],
1100+
)
1101+
return ColumnList(*cr.fetchone())
1102+
1103+
10711104
def rename_table(cr, old_table, new_table, remove_constraints=True):
10721105
"""
10731106
Rename a table.

0 commit comments

Comments
 (0)