【问题标题】:How do I get schemas from Perl's DBI?如何从 Perl 的 DBI 中获取模式?
【发布时间】:2016-12-18 21:30:13
【问题描述】:

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

【问题讨论】:

    标签: perl schema dbi


    【解决方案1】:

    你要找的是:DBI->table_info()

    这样称呼它:

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

    【讨论】:

    • 我昨天根据这个想法写了一个脚本,但是DBI::ODBC不支持table_info,我需要访问一个*.mdb
    • PS:当前两个参数是 undef 时它确实支持它!
    • DBD::ODBC 确实支持 table_info。您需要阅读 ODBC 规范,了解需要传递给 table_info 的内容。您可能还需要 1.46_1 中的错误修复 - 请参阅 search.cpan.org/~mjevans/DBD-ODBC-1.46_2/…
    【解决方案2】:

    这行得通。

    创建数据库:

    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
            };
    

    【讨论】:

      【解决方案3】:

      将 ODBC 用于 Oracle 数据库,我不得不在 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";
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-19
        • 2011-06-13
        • 2011-04-07
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 2012-05-02
        相关资源
        最近更新 更多