如何从Perl的DBI获取模式?

时间:2010-05-25 10:58:58

标签: perl schema dbi

我正在使用Perl DBI。我知道$dbase->tables()将返回相应数据库中的所有表。同样,我想知道数据库中可用的模式。有没有可用的功能?

3 个答案:

答案 0 :(得分:11)

您正在寻找的是:DBI->table_info()

这样称呼:

my $sth = $dbh->table_info('', '%', '');
my $schemas = $dbh->selectcol_arrayref($sth, {Columns => [2]});
print "Schemas: ", join ', ', @$schemas;

答案 1 :(得分:1)

这很有效。

创建数据库:

echo 'create table foo (bar integer primary key, quux varchar(30));' | sqlite3 foobar.sqlite

打印模式的Perl程序:

use 5.010;
use Data::Dumper qw(Dumper);
use DBIx::Class::Schema::Loader qw();
DBIx::Class::Schema::Loader->naming('current');
DBIx::Class::Schema::Loader->use_namespaces(1);

my $dbi_dsn = 'dbi:SQLite:dbname=foobar.sqlite';
my ($dbi_user, $dbi_pass);
my $schema = DBIx::Class::Schema::Loader->connect(
    $dbi_dsn, $dbi_user, $dbi_pass, {'AutoCommit' => 1, 'RaiseError' => 1,}
);

for my $source_name ($schema->sources) {
    say "*** Source: $source_name";
    my $result_source = $schema->source($source_name);
    for my $column_name ($result_source->columns) {
        say "Column: $column_name";
        say Dumper $result_source->column_info($column_name);
    }
}

输出:

*** Source: Foo
Column: bar
$VAR1 = {
          'data_type' => 'integer',
          'is_auto_increment' => 1,
          'is_nullable' => 1
        };

Column: quux
$VAR1 = {
          'data_type' => 'varchar',
          'is_nullable' => 1,
          'size' => 30
        };

答案 2 :(得分:0)

使用ODBC到Oracle数据库,我不得不在Uncle Arnie的回答中使用这个变体:

my $table_info = $dbh->table_info(undef, '%', undef);
my $schemas    = $table_info->fetchall_arrayref([1]);

print "Schemas :\n",
      join( "\n", map {$_->[0]} @$schemas ), "\n";

否则,在尝试使用$schemas时,selectcol_arrayref($sth, ...)将是未定义的。