+ # patch foreign keys
+ my $foreign_key_definition = "SL::DB::AUTO::$package"->meta->perl_foreign_keys_definition(%args);
+ $foreign_key_definition =~ s/::AUTO::/::/g;
+
+ if ($foreign_key_definition && ($definition =~ /\Q$foreign_key_definition\E/)) {
+ # These positions refer to the whole setup call, not just the
+ # parameters/actual relationship definitions.
+ my ($start, $end) = ($-[0], $+[0]);
+
+ # Match the function parameters = the actual relationship
+ # definitions
+ next unless $foreign_key_definition =~ m/\(\n(.+)\n\)/s;
+
+ my ($list_start, $list_end) = ($-[0], $+[0]);
+
+ # Split the whole chunk on double new lines. The resulting
+ # elements are one relationship each. Then fix the relationship
+ # names and sort them by their new names.
+ my @new_foreign_keys = sort map { fix_relationship_names($domain, $table, $_) } split m/\n\n/m, $1;
+
+ # Replace the function parameters = the actual relationship
+ # definitions with the new ones.
+ my $sorted_foreign_keys = "(\n" . join("\n\n", @new_foreign_keys) . "\n)";
+ substr $foreign_key_definition, $list_start, $list_end - $list_start, $sorted_foreign_keys;
+
+ # Replace the whole setup call in the auto-generated output with
+ # our new version.
+ substr $definition, $start, $end - $start, $foreign_key_definition;
+ }
+
+ $definition =~ s/(meta->table.*)\n/$1\n$schema_str/m if $schema;
+