From 52be1773bdfc6f519c5b2d9a7ee7a68abdde821f Mon Sep 17 00:00:00 2001 From: Veesh Goldman Date: Fri, 24 Feb 2023 00:56:44 +0200 Subject: [PATCH] don't include schema or database when generationg FK or PK names for Postgres --- lib/SQL/Translator/Producer/PostgreSQL.pm | 18 +++++++++++------- t/47postgres-producer.t | 11 +++++++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/lib/SQL/Translator/Producer/PostgreSQL.pm b/lib/SQL/Translator/Producer/PostgreSQL.pm index 453ae441..7010808e 100644 --- a/lib/SQL/Translator/Producer/PostgreSQL.pm +++ b/lib/SQL/Translator/Producer/PostgreSQL.pm @@ -1070,13 +1070,17 @@ sub alter_drop_constraint { if( $c->name ) { # Already has a name, just use it $c_name = $c->name; - } elsif ( $c->type eq FOREIGN_KEY ) { - # Doesn't have a name, and is foreign key, append '_fkey' - $c_name = $c->table->name . '_' . ($c->fields)[0] . '_fkey'; - } elsif ( $c->type eq PRIMARY_KEY ) { - # Doesn't have a name, and is primary key, append '_pkey' - $c_name = $c->table->name . '_pkey'; - } + } else { + # if the name is dotted we need the table, not schema nor database + my ($tablename) = reverse split /[.]/, $c->table->name; + if ( $c->type eq FOREIGN_KEY ) { + # Doesn't have a name, and is foreign key, append '_fkey' + $c_name = $tablename . '_' . ($c->fields)[0] . '_fkey'; + } elsif ( $c->type eq PRIMARY_KEY ) { + # Doesn't have a name, and is primary key, append '_pkey' + $c_name = $tablename . '_pkey'; + } + } return sprintf( 'ALTER TABLE %s DROP CONSTRAINT %s', diff --git a/t/47postgres-producer.t b/t/47postgres-producer.t index 44a14fb5..099b5885 100644 --- a/t/47postgres-producer.t +++ b/t/47postgres-producer.t @@ -115,6 +115,17 @@ is($pk_constraint_def_ref->[0], 'CONSTRAINT foo PRIMARY KEY (myfield)', 'Create my $alter_pk_constraint = SQL::Translator::Producer::PostgreSQL::alter_drop_constraint($pk_constraint); is($alter_pk_constraint, 'ALTER TABLE mytable DROP CONSTRAINT foo', 'Alter drop Primary Key constraint works'); +subtest 'Dotted tables (schema)' => sub { + my $dotted_table = SQL::Translator::Schema::Table->new( name => 'dotted.mytable'); + my $dotted_pk_constraint = SQL::Translator::Schema::Constraint->new( + table => $dotted_table, + fields => [qw(myfield)], + type => 'PRIMARY_KEY', + ); + my $alter_dotted_pk = SQL::Translator::Producer::PostgreSQL::alter_drop_constraint($dotted_pk_constraint); + is($alter_dotted_pk, 'ALTER TABLE dotted.mytable DROP CONSTRAINT mytable_pkey', 'generate correct PK name for dotted tables'); +}; + my $table2 = SQL::Translator::Schema::Table->new( name => 'mytable2'); my $field1_2 = SQL::Translator::Schema::Field->new( name => 'myfield_2',