3
MySQLデータベース内の特定のInnoDBテーブルの外部キーをプログラムで検索します。Perl/DBI/MySQL/InnoDBを使用した外部キー情報の検索
私はPerlを使用していますが、私は$dbh->foreign_key_info
を見つけました。私はちょうどそれを使用してみましたが、それは少し欠陥があるようです。
ON DELETEおよびON UPDATE情報は返すことはできません。また、通常のインデックスを返すこともあります。
ありがとうございました。
use strict;
use warnings;
use DBI;
use Data::Dumper;
my $dbh = DBI->connect("DBI:mysql:database=db;host=localhost", "user", "password");
my $sth = $dbh->foreign_key_info(undef, undef, undef, undef, undef, "table_name");
print Dumper $sth->fetchall_hashref("FK_NAME");
そして出力:
$VAR1 = {
'some_table_ibfk_3' => {
'PK_NAME' => undef,
'DEFERABILITY' => undef,
'FKTABLE_CAT' => undef,
'PKTABLE_SCHEM' => 'db',
'UNIQUE_OR_PRIMARY' => undef,
'PKTABLE_CAT' => undef,
'FKTABLE_NAME' => 'some_table',
'FKTABLE_SCHEM' => 'db',
'PKTABLE_NAME' => 'some_other_table',
'FKCOLUMN_NAME' => 'some_other_table_id',
'FK_NAME' => 'some_table_ibfk_3',
'DELETE_RULE' => undef,
'PKCOLUMN_NAME' => 'id',
'KEY_SEQ' => '1',
'UPDATE_RULE' => undef
},
'user_id_2' => {
'PK_NAME' => undef,
'DEFERABILITY' => undef,
'FKTABLE_CAT' => undef,
'PKTABLE_SCHEM' => undef,
'UNIQUE_OR_PRIMARY' => undef,
'PKTABLE_CAT' => undef,
'FKTABLE_NAME' => 'some_table',
'FKTABLE_SCHEM' => 'db',
'PKTABLE_NAME' => undef,
'FKCOLUMN_NAME' => 'some_other_table_id',
'FK_NAME' => 'user_id_2',
'DELETE_RULE' => undef,
'PKCOLUMN_NAME' => undef,
'KEY_SEQ' => '2',
'UPDATE_RULE' => undef
},
'PRIMARY' => {
'PK_NAME' => undef,
'DEFERABILITY' => undef,
'FKTABLE_CAT' => undef,
'PKTABLE_SCHEM' => undef,
'UNIQUE_OR_PRIMARY' => undef,
'PKTABLE_CAT' => undef,
'FKTABLE_NAME' => 'some_table',
'FKTABLE_SCHEM' => 'db',
'PKTABLE_NAME' => undef,
'FKCOLUMN_NAME' => 'id',
'FK_NAME' => 'PRIMARY',
'DELETE_RULE' => undef,
'PKCOLUMN_NAME' => undef,
'KEY_SEQ' => '1',
'UPDATE_RULE' => undef
},
'some_table_ibfk_1' => {
'PK_NAME' => undef,
'DEFERABILITY' => undef,
'FKTABLE_CAT' => undef,
'PKTABLE_SCHEM' => 'db',
'UNIQUE_OR_PRIMARY' => undef,
'PKTABLE_CAT' => undef,
'FKTABLE_NAME' => 'some_table',
'FKTABLE_SCHEM' => 'db',
'PKTABLE_NAME' => 'user_bk2',
'FKCOLUMN_NAME' => 'user_id',
'FK_NAME' => 'some_table_ibfk_1',
'DELETE_RULE' => undef,
'PKCOLUMN_NAME' => 'id',
'KEY_SEQ' => '1',
'UPDATE_RULE' => undef
},
'some_table_ibfk_2' => {
'PK_NAME' => undef,
'DEFERABILITY' => undef,
'FKTABLE_CAT' => undef,
'PKTABLE_SCHEM' => 'db',
'UNIQUE_OR_PRIMARY' => undef,
'PKTABLE_CAT' => undef,
'FKTABLE_NAME' => 'some_table',
'FKTABLE_SCHEM' => 'db',
'PKTABLE_NAME' => 'user_bk2',
'FKCOLUMN_NAME' => 'coach_id',
'FK_NAME' => 'some_table_ibfk_2',
'DELETE_RULE' => undef,
'PKCOLUMN_NAME' => 'id',
'KEY_SEQ' => '1',
'UPDATE_RULE' => undef
}
};
ありがとうございました。十分に実装されていないのは残念です。ここで正規表現が来る... – aidan