@@ -1061,6 +1061,19 @@ def replace_record_references_batch(cr, id_mapping, model_src, model_dst=None, r
1061
1061
FROM _upgrade_rrr r
1062
1062
WHERE r.old = t.{fk}
1063
1063
"""
1064
+ unique_indexes = _get_unique_indexes_with (cr , table , fk )
1065
+ if unique_indexes :
1066
+ conditions = ["" ]
1067
+ for _ , uniq_cols in unique_indexes :
1068
+ uniq_cols = set (uniq_cols ) - {fk } # noqa: PLW2901
1069
+ ands = (
1070
+ " AND " .join (format_query (cr , "u.{col} = t.{col}" , col = col ) for col in uniq_cols )
1071
+ if uniq_cols
1072
+ else "true"
1073
+ )
1074
+ conditions .append ("NOT EXISTS(SELECT 1 FROM {table} u WHERE u.{fk} = r.new AND %s)" % ands )
1075
+
1076
+ query += " AND " .join (conditions )
1064
1077
1065
1078
if not column_exists (cr , table , "id" ):
1066
1079
# seems to be a m2m table. Avoid duplicated entries
@@ -1091,22 +1104,15 @@ def replace_record_references_batch(cr, id_mapping, model_src, model_dst=None, r
1091
1104
col2 = col2 ,
1092
1105
)
1093
1106
)
1094
- query += """
1095
- AND NOT EXISTS(SELECT 1 FROM {table} e WHERE e.{col2} = t.{col2} AND e.{fk} = r.new);
1096
-
1097
- DELETE
1098
- FROM {table} t
1099
- USING _upgrade_rrr r
1100
- WHERE t.{fk} = r.old;
1101
- """
1107
+ query += " AND NOT EXISTS(SELECT 1 FROM {table} e WHERE e.{col2} = t.{col2} AND e.{fk} = r.new)"
1102
1108
1103
1109
col2_info = target_of (cr , table , col2 ) # col2 may not be a FK
1104
1110
if col2_info and col2_info [:2 ] == (model_src_table , "id" ):
1105
1111
# a m2m on itself, remove the self referencing entries
1106
1112
# It only handle 1-level recursions. For multi-level recursions, it should be handled manually.
1107
1113
# We can't decide which link to break.
1108
1114
# XXX: add a warning?
1109
- query += """
1115
+ query += """;
1110
1116
DELETE
1111
1117
FROM {table} t
1112
1118
USING _upgrade_rrr r
@@ -1117,13 +1123,21 @@ def replace_record_references_batch(cr, id_mapping, model_src, model_dst=None, r
1117
1123
cr .execute (format_query (cr , query , table = table , fk = fk , col2 = col2 ))
1118
1124
1119
1125
else : # it's a model
1120
- fmt_query = cr . mogrify ( format_query (cr , query , table = table , fk = fk )). decode ( )
1126
+ fmt_query = format_query (cr , query , table = table , fk = fk )
1121
1127
parallel_execute (cr , explode_query_range (cr , fmt_query , table = table , alias = "t" ))
1122
1128
1123
1129
# track default values to update
1124
1130
model = model_of_table (cr , table )
1125
1131
fk_def .append ((model , fk ))
1126
1132
1133
+ delete_query = """
1134
+ DELETE
1135
+ FROM {table} t
1136
+ USING _upgrade_rrr r
1137
+ WHERE t.{fk} = r.old
1138
+ """
1139
+ cr .execute (format_query (cr , delete_query , table = table , fk = fk ))
1140
+
1127
1141
if fk_def :
1128
1142
if table_exists (cr , "ir_values" ):
1129
1143
column_read , cast_write = _ir_values_value (cr , prefix = "v" )
0 commit comments