in reply to DBI determine primary key

Specifically for mysql, you can use a special SQL command: DESCRIBE $table. Yes that works in DBI too. Here's a test table "foo", which I put into the database "test" (present by default):
CREATE TABLE foo( id int(10) unsigned NOT NULL AUTO_INCREMENT, letter char(1) NOT NULL, name text NOT NULL, num float NULL, PRIMARY KEY (id) );
And here's some demo code checking what we've got:
#!/usr/local/bin/perl -w use DBI; my $dbh = DBI->connect('dbi:mysql:test', "", "", { PrintError => 0 , R +aiseError => 1}); END { $dbh->disconnect if $dbh } use Data::Dumper; my $sth = $dbh->prepare('DESCRIBE foo'); $sth->execute; while(my $r = $sth->fetchrow_hashref) { print Dumper $r; }
which shows:
$VAR1 = { 'Extra' => 'auto_increment', 'Field' => 'id', 'Default' => undef, 'Key' => 'PRI', 'Type' => 'int(10) unsigned', 'Null' => '' }; $VAR1 = { 'Extra' => '', 'Field' => 'letter', 'Default' => '', 'Key' => '', 'Type' => 'char(1)', 'Null' => '' }; $VAR1 = { 'Extra' => '', 'Field' => 'name', 'Default' => '', 'Key' => '', 'Type' => 'text', 'Null' => '' }; $VAR1 = { 'Extra' => '', 'Field' => 'num', 'Default' => undef, 'Key' => '', 'Type' => 'float', 'Null' => 'YES' };
4 records, one for each field. 'Field' contains the field name. In particular, check out the contents of the field 'Key': its value is "PRI" for the primary key, the empty string for the rest.

Replies are listed 'Best First'.
Re: Re: DBI determine primary key
by Anonymous Monk on Apr 09, 2004 at 02:37 UTC
    Actually, a different way using a different SQL query (which I was hoping to avoid, since that's dependent on parsing specific output):
    my $keys_ref = $dbh->selectall_arrayref("SHOW KEYS FROM $table"); + foreach my $row ( @{$keys_ref} ) { print "Primary key: $row->[4]" if $row->[2] eq 'PRIMARY'; }
    It'd probably be more readable to use a selectall_hashref and (in the MySQL case) snag
    $row->{'Column_name'} if $row->{'Key_name'} eq 'PRIMARY'

    Edited by Chady -- added code tags.