develooper Front page | perl.dbi.dev | Postings from February 2004

[NEW CODE] Printing data from database aligned into table

Thread Next
From:
rajo
Date:
February 19, 2004 02:48
Subject:
[NEW CODE] Printing data from database aligned into table
Message ID:
20040219104908.GA21717@Idea.Platon.SK
Hi!

I'm working on database plugin for editor vim. I need print data fetched
from database to stdout. I write method DBI::st::dump_data(). This peace
of code follows. This code can be found (with little modification) also
on website:

   http://platon.sk/cvs/cvs.php/vimconfig/vim/modules/database-client.vim

Output produced by this method look like output from standard MySQL
client: (output from executed SQL command 'SHOW DATABASES')

+----------+
| Database |
+----------+
| mysql    |
| system   |
| test     |
+----------+

Can be this method included into DBI Perl module?

Have a nice day, Lubomir Host.


-----------------------------------%<-----------------------------------
	package DBI::st;

	# fetch and print data from _executed_ DBI statement handler
	sub dump_data ($)
	{ # {{{
		my $sth = shift;

		my $numFields     = $sth->{'NUM_OF_FIELDS'};
		my $column_names  = $sth->{'NAME'};
		my $column_sizes  = $sth->{'mysql_max_length'};
		my $column_is_num = $sth->{'mysql_is_num'};

		# build column name's line
		my $header_names = "";
		foreach (my $i = 0; $i < $numFields; $i++) {
			# numeric columns have smaller length as column name, overwrite ...
			$$column_sizes[$i] = $$column_sizes[$i] > length($$column_names[$i])
				? $$column_sizes[$i]
				: ($$column_is_num[$i] ? -1 : 1) * length($$column_names[$i]); # WARN: negative length! - used for right aligment of numbers
			$header_names .= sprintf("%s%s", $i ? " | " : "| ", $$column_names[$i] . " " x ($$column_sizes[$i] - length($$column_names[$i])));
		}
		$header_names .= " |\n";

		# build header separator
		my $separator = "";
		foreach (my $i = 0; $i < $numFields; $i++) {
			$separator .= "+" . ("-" x (abs($$column_sizes[$i]) + 2));
		}
		$separator .= "+\n"; # the end

		# print header
		print $separator;
		print $header_names;
		print $separator;

		# print data
		while (my @row = $sth->fetchrow_array()) {
			my $line = "";
			foreach (my $i = 0; $i < $numFields; $i++) {
				$line .= sprintf("%s%s", $i ? " | " : "| ",
					$$column_sizes[$i] > 0 # usage of negative length
						? $row[$i] . " " x ($$column_sizes[$i] - length($row[$i]))
						: " " x (- $$column_sizes[$i] - length($row[$i])) . $row[$i]
				);
			}
			print "$line |\n";
		}

		# print footer
		print $separator;

	} # }}}
-----------------------------------%<-----------------------------------

-- 
Lubomir Host 'rajo' <rajo AT platon.sk>        ICQ #:  257322664
Platon Software Development Group              http://platon.sk/
http://www.gnu.org/philosophy/no-word-attachments.html

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About