diff --git a/lib/DBD/SQLite.pm b/lib/DBD/SQLite.pm index 217f827..109baa3 100644 --- a/lib/DBD/SQLite.pm +++ b/lib/DBD/SQLite.pm @@ -483,6 +483,7 @@ sub foreign_key_info { my $databases = $dbh->selectall_arrayref("PRAGMA database_list", {Slice => {}}); my @fk_info; + my %table_info; for my $database (@$databases) { my $dbname = $database->{name}; next if defined $fk_schema && $fk_schema ne '%' && $fk_schema ne $dbname; @@ -504,9 +505,29 @@ sub foreign_key_info { while(my $row = $sth->fetchrow_hashref) { next if defined $pk_table && $pk_table ne '%' && $pk_table ne $row->{table}; + unless ($table_info{$row->{table}}) { + my $quoted_tb = $dbh->quote_identifier($row->{table}); + for my $db (@$databases) { + my $quoted_db = $dbh->quote_identifier($db->{name}); + my $t_sth = $dbh->prepare("PRAGMA $quoted_db.table_info($quoted_tb)"); + $t_sth->execute; + my $cols = {}; + while(my $r = $t_sth->fetchrow_hashref) { + $cols->{$r->{name}} = $r->{pk}; + } + if (keys %$cols) { + $table_info{$row->{table}} = { + schema => $db, + columns => $cols, + }; + last; + } + } + } + push @fk_info, { PKTABLE_CAT => undef, - PKTABLE_SCHEM => undef, + PKTABLE_SCHEM => $table_info{$row->{table}}{schema}, PKTABLE_NAME => $row->{table}, PKCOLUMN_NAME => $row->{to}, FKTABLE_CAT => undef, @@ -519,7 +540,7 @@ sub foreign_key_info { FK_NAME => undef, PK_NAME => undef, DEFERRABILITY => undef, - UNIQUE_OR_PRIMARY => undef, + UNIQUE_OR_PRIMARY => $table_info{$row->{table}}{columns}{$row->{to}} ? 'PRIMARY' : 'UNIQUE', }; } } diff --git a/t/50_foreign_key_info.t b/t/50_foreign_key_info.t index db53945..a0ff814 100755 --- a/t/50_foreign_key_info.t +++ b/t/50_foreign_key_info.t @@ -26,8 +26,9 @@ my @sql_statements = split /\n\n/, <<__EOSQL__; PRAGMA foreign_keys = ON; CREATE TABLE artist ( - artistid INTEGER PRIMARY KEY AUTOINCREMENT, - artistname TEXT + artistid INTEGER, + artistname TEXT, + UNIQUE(artistid) ); CREATE TABLE editor ( @@ -55,7 +56,7 @@ CREATE TABLE song( __EOSQL__ -plan tests => @sql_statements + 16; +plan tests => @sql_statements + 18; my $dbh = connect_ok( RaiseError => 1, PrintError => 0, AutoCommit => 1 ); my $sth; @@ -74,6 +75,7 @@ for ($fk_data->{albumartist}) { is($_->{KEY_SEQ}, 1, "FK albumartist, key seq"); is($_->{DELETE_RULE}, $R->{RESTRICT}, "FK albumartist, delete rule"); is($_->{UPDATE_RULE}, $R->{CASCADE}, "FK albumartist, update rule"); + is($_->{UNIQUE_OR_PRIMARY}, 'UNIQUE', "FK albumartist, unique"); } for ($fk_data->{albumeditor}) { is($_->{PKTABLE_NAME}, "editor", "FK albumeditor, table name"); @@ -82,6 +84,7 @@ for ($fk_data->{albumeditor}) { # rules are 'NO ACTION' by default is($_->{DELETE_RULE}, $R->{'NO ACTION'}, "FK albumeditor, delete rule"); is($_->{UPDATE_RULE}, $R->{'NO ACTION'}, "FK albumeditor, update rule"); + is($_->{UNIQUE_OR_PRIMARY}, 'PRIMARY', "FK albumeditor, primary"); }