in reply to DBI - MySQL vs. PgSQL

Show and Describe are not in the SQL-92 standard , so you can't expect them to be supported.

DBI does allows the user to get a list of tables through the $dbh->tables command.

The way I get the column names is just run a bogus search: "select * from $table where 1 = 0". This should run very quickly and get me the information I want.

Here's a sample program:

#!/usr/bin/perl -w use strict; use DBI; my ($driver, $dbh, @tables); $driver="DBI:CSV:f_dir=Tables"; $dbh=DBI->connect($driver) or die "Can't connect: $DBI::errstr"; eval { @tables = $dbh->tables; @tables = grep { s/.*\.//o } @tables; } or die "Couldn't retrieve list of tables: $DBI::errstr\n"; for my $thisTable (@tables) { eval { my $sth=$dbh->prepare("select * from $thisTable where 1 = 0"); $sth->execute(); my $columnRef=$sth->{NAME_lc}; for my $thisColumn (@$columnRef) { print "Table: $thisTable, column is: $thisColumn\n"; # Do whatever else you want with the columns. } 1; } or die "Couldn't read table $_: $DBI::errstr\n"; } $dbh->disconnect();
A few things to note: rick

Replies are listed 'Best First'.
Re: Re: DBI - MySQL vs. PgSQL
by xtype (Deacon) on Jan 19, 2002 at 03:05 UTC
    Actually, you should be able to just use:
    #!/usr/local/bin/perl -w use strict; use DBI; use DBD::Pg; my ($dbh, @tables); my $user = "username"; my $password = ""; my $db_name="database"; my $driver="Pg"; my $db_host="localhost"; my $dsn="DBI:$driver:dbname=$db_name;host=$db_host"; $dbh=DBI->connect($dsn,$user,$password) or die "Can't connect: $DBI:: +errstr"; @tables = $dbh->tables; for my $thisTable (@tables) { my $sth=$dbh->prepare("select * from $thisTable where 1 = 0"); $sth->execute(); my $columnRef=$sth->{NAME_lc}; for my $thisColumn (@$columnRef) { print "Table: $thisTable, column is: $thisColumn\n"; # Do whatever else you want with the columns. } 1; } $dbh->disconnect();
    -
    @tables = grep { s/.*\.//o } @tables;
    Would probably complain with use strict about cat’ing to an undef…. Right? I guess that is why you used evals though.
    And $dbh->tables with DBD:Pg will just return an array of table names anyway. Of course, as the DBI perldoc states: “Warning: This method is experimental and may change.”
    So, although I agree with quikwit that you should try to write things as portable as possibly… to some extent you will not be able to (tables() returning different things with CSV vs. Pg.) unless you have all possibly platforms to test/write on.
    I did not know that SHOW was not in the SQL92 specs. either. ++quikwit for pointing that out. I have been using SHOW TABLES myself.

    If you want to access fields in the columns as DESCRIBE may have done, you should check out my question on feeding fields into an array: Just another DBI question.
    Ciao, -xtype