How do I get schemas from Perl's DBI?
Asked Answered
F

3

6

I am using Perl DBI. I know that $dbase->tables() will return all the tables in the corresponding database. Likewise, I want to know the schemas available in the database. Is there any function available for that?

Fluff answered 25/5, 2010 at 10:58 Comment(0)
O
11

What you're looking for is: DBI->table_info()

Call it like this:

my $sth = $dbh->table_info('', '%', '');
my $schemas = $dbh->selectcol_arrayref($sth, {Columns => [2]});
print "Schemas: ", join ', ', @$schemas;
Oporto answered 25/5, 2010 at 12:0 Comment(3)
I wrote a script based on this idea yesterday, but DBI::ODBC does not support table_info, and I need access to an *.mdb.Muscular
PS: it does support it when the first two arguments are undef!Muscular
DBD::ODBC certainly does support table_info. You need to read the ODBC spec for what you need to pass to table_info. You may also need the bug fix in 1.46_1 - see search.cpan.org/~mjevans/DBD-ODBC-1.46_2/…Reinke
C
1

This works.

Create a database:

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

Perl program to print schema:

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

Output:

*** 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
        };
Consistent answered 25/5, 2010 at 11:27 Comment(0)
S
0

Using ODBC to an Oracle database, I had to use this variation on Uncle Arnie's answer:

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

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

Otherwise, $schemas would be undefined when trying to use selectcol_arrayref($sth, ...).

Shopping answered 18/12, 2016 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.