我有一个Perl脚本,可以对postgreSQL实例进行多次查询。我可以看到查询执行,但是当我使用嵌套的foreach时,它似乎没有正确输出结果集。当没有内循环时,脚本会正确生成文件。
#!/usr/bin/perl -w
# Script to login to list of Postgres servers, execute a sql command, and write output to server/time specific file.
my $cwd= "/scan";
my $dt = POSIX::strftime( "%Y_%m_%d_%H_%M",localtime);
my $username='**********';
my $password='************';
my @db_array;
my $maxlen = 20000;
my $lsep = "\n";
my $fsep = ",";
my $output;
open(my $logfile, ">",join('',$cwd,"/postgres_", $dt, ".err")) or die "Failed to open output file: $!\n";
open (STDERR, ">>&=", $logfile);
open(my $fh_list, "<", "/home/mysql/postgres.list") or die "Failed to open input file: $!\n";
open(my $col_outfile,">",join('',$cwd,"/output/POSTGRES_", $dt, ".csv")) or die "Failed to open output file: $!\n";
while (my $line = <$fh_list>){
chomp $line;
my ($hostname,$port) = split ",",$line;
print "Now examining: $hostname on $port.\n";
eval {
my $dbh = DBI->connect("dbi:Pg:dbname=postgres;host=$hostname;port=$port",$username,$password,{HandleError => \&dbi_err_handle});
if (defined $dbh) {
my $db_sql = "select datname from pg_database where datname not in ('template1','template0', 'postgres')";
my $db_names = $dbh->selectall_arrayref($db_sql);
foreach my $db_out (@$db_names) {
my $col_sql = "SELECT 'POSTGRES', '$hostname', '$port', '$db_out', pt.tableowner, pt.tablename, ic.column_name, CASE WHEN ic.character_maximum_length IS NOT NULL THEN ic.data_type || '(' || ic.character_maximum_length || ')' WHEN ic.numeric_precision IS NOT NULL THEN ic.data_type || '(' || (ic.numeric_precision / 8) || ')' END, '','' FROM pg_tables pt JOIN information_schema.columns ic ON ic.table_schema = pt.schemaname AND ic.table_name = pt.tablename AND ic.table_schema NOT IN ('pg_catalog', 'information_schema') ORDER BY 4, 5, 6";
my $col_names = $dbh->selectall_arrayref($col_sql);
foreach my $output (@$col_names){
print $col_outfile join (",", @{$output}), "\n";
}
}
}
};
# print any errors that occur
if ( $@ ) {
print $@;
}
}
close $fh_list;
close $col_outfile;
close $logfile;
sub dbi_err_handle{
my ( $message, $handle, $first_value) = @_;
print $logfile "$message\n";
return 1;
}
回顾 - 我需要运行一个查询,通过foreach解析该结果集,然后将第二个查询的结果输出到一个文件。