# (C) 2001 Christian Jacobi
# (C) 2001 Christoph Berg
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# cb 010727
# $Id: tante_db.pm,v 1.5 2001/09/19 11:40:17 tesh Exp $

$ENV{'TZ'} = "CET";

use Pg;
@PG_RESULTSTATUS = qw/PGRES_EMPTY_QUERY PGRES_COMMAND_OK PGRES_TUPLES_OK PGRES_COPY_OUT PGRES_COPY_IN PGRES_BAD_RESPONSE PGRES_NONFATAL_ERROR PGRES_FATAL_ERROR/;
$tante_pw_file = "/home/tante/secret/tante-pw";

$PGHOST = "wjpserver";
#$PGHOST = "goedel";

sub tante_pw {
	open F, $tante_pw_file or die "$tante_pw_file: $!";
	my $pw = <F>;
	chomp $pw;
	close F;
	return $pw;
}


sub open_db {
	# $conn ist global, NICHT mit 'my' deklarieren!
	my $pw = tante_pw();
	#my $pw = "tantepw";
	$conn = Pg::connectdb("host=$PGHOST dbname=tante user=tante password=$pw");

	if($conn->status != PGRES_CONNECTION_OK) {
		die "postgres error: ". $conn->errorMessage;
	}
}	


sub do_query {
	my $query = shift;
	my $result = $conn->exec($query);

	if($result->resultStatus == PGRES_TUPLES_OK) {
		push @query_queue, "$query: $PG_RESULTSTATUS[$result->resultStatus], ". $result->ntuples ." Tuples";
	} else {
		push @query_queue, "$query: $PG_RESULTSTATUS[$result->resultStatus]";
	}
	shift @query_queue if @query_queue > 10;
	$query_queue = join "\n", @query_queue;

	if($result->resultStatus != PGRES_TUPLES_OK and
			$result->resultStatus != PGRES_COMMAND_OK ) {
		die "Postgres query '$query' returned ".
			$PG_RESULTSTATUS[$result->resultStatus]. ": ".
			$conn->errorMessage;
	}
	return $result;
}

sub sql_exec {
	my $result = do_query($inp_sql_query);
	my @tuples;

	$sql_output = "";
	while(@tuples = $result->fetchrow) {
		$sql_output .= (join " | ", @tuples) ."\n";
	}
}

$query_queue = "TET SQL Trace";

1;
