Subject: | Allow *optional* promotion of unique constraints to primary keys |
Too many "real world"(tm) databases out there have tables without a
declared Primary Key. DBIC on the other hand does not function too well
without one (there are countless places throughout the code doing my
@pks = $rsrc->primary_columns).
The good news is that more often than not the pk-less table does in fact
have a unique constraint, and even more often - there is only one such
constraint. Here is the code I wrote some time ago to make a huge MySQL
dump go through in a sane matter:
package DBIx::Class::Schema::Loader::DBI::mysql_u2p;
use strict;
use warnings;
use base 'DBIx::Class::Schema::Loader::DBI::mysql';
# turn a single unique constraint into a primary key
sub _mysql_table_get_keys {
my ($self, $table) = @_;
my $keys = $self->{_cache}->{_mysql_keys}->{$table};
if (not $keys) {
$keys = $self->next::method ($table);
my @keynames = keys %$keys;
if (@keynames == 1 and $keynames[0] ne 'PRIMARY') {
$keys->{PRIMARY} = delete $keys->{$keynames[0]};
}
}
return $keys;
}
I would like to see this functionality become a core feature, which can
be turned on-demand (no automatic inference!). As a bonus there could be
an additional mode where the largest constraint column-wise is taken as
a PK, but that's going too deep.