validate_partitioned_foreign_key should ignore partitions that don't have the foreign key
validate_partitioned_foreign_key
iterates through all the partitions to validate the foreign keys. Because we create partitions from the initializer there could be cases where the partitions are created after the migrations are executed, leaving partitions without FK.
Steps to reproduce:
- create a migration that adds foreign keys between partitions
- drop and recreate the database
- execute migrations
- after the migrations are executed, the initializer will create new partitions for the tables
- attempt to validate the FK, it should fail with an FK missing error on the new partition
Proposal
Skip validation if the FK doesn't exist on partition. Caliing add_concurrent_partitioned_foreign_key
will add and validate the FK on the partition when it will create the FK on the partitioned table.
diff --git a/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers.rb b/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers.rb
index 7d9c12d776e5..154227dd8c8c 100644
--- a/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers.rb
+++ b/lib/gitlab/database/partitioning_migration_helpers/foreign_key_helpers.rb
@@ -95,6 +95,8 @@ def validate_partitioned_foreign_key(source, column, name: nil)
assert_not_in_transaction_block(scope: ERROR_SCOPE)
Gitlab::Database::PostgresPartitionedTable.each_partition(source) do |partition|
+ next unless foreign_key_exists?(partition.identifier, name: name)
+
validate_foreign_key(partition.identifier, column, name: name)
end
end