#!/usr/bin/perl -w

use strict;
use Getopt::Long;
use DBI;
use Relation::Tools qw(header dsn);

my $progname = "sqlquery";

my $no_header;

GetOptions('N|no-header' => \$no_header) and @ARGV == 2
	or die "syntax: $progname [options] dsn sql\n";

my ($dsn, $user, $pass, $attr) = dsn(shift);
my $sql = shift;

my $dbh = DBI->connect($dsn, $user, $pass, $attr && eval $attr)
	or die "cannot connect to $dsn: ".DBI->errstr."\n";

my $sth = $dbh->prepare($sql)
	or die "cannot prepare: ".$dbh->errstr."\n";

$sth->execute
	or die "cannot execute: ".$dbh->errstr."\n";

my $output_row;

if (!$no_header) {
	header(@{$sth->{NAME}});
}

while (defined ($output_row = $sth->fetchrow_arrayref)) {
	for (@$output_row) {
		if (defined $_) {
			s/\\/\\\\/g;
			s/\t/\\t/g;
			s/\n/\\n/g;
			s/\0/\\0/g;
		} else {
			$_ = "\\";
		}
	}
	print join "\t", @$output_row;
	print "\n";
}

$sth->err
	and die "cannot fetch: ".$sth->errstr."\n";

$sth->finish;

$dbh->disconnect;

