
package AwayMsg;

use strict;
use warnings;

use DBI;

BEGIN {
    use Exporter ();
    our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
    $VERSION     = 1.00;
    @ISA         = qw(Exporter);
    @EXPORT      = qw(&db_connect &db_commit $dbh);
    %EXPORT_TAGS = ( );
    @EXPORT_OK   = qw();
}

our ($dbh);

sub db_connect () {
    my $dbf;
    foreach my $d (@INC) {
	$dbf = "$d/away.db";
	if (stat $dbf) {
	    chdir($d) or die $!;
	    last;
	}
    }
    $dbh = DBI->connect("dbi:SQLite:away.db",
			 { AutoCommit=>0,
			   RaiseError=>1, ShowErrorStatement=>1
			 })
        or die "$DBI::errstr ?";
}

sub nooutput ($) {
    my ($stmt) = @_;
    my $sth= $dbh->prepare($stmt);
    $sth->execute();
    my $row;
    if ($row= $sth->fetchrow_hashref()) {
	die("REFERENTIAL INTEGRITY ERROR\n".
	    "\n$stmt\n". Dumper($row),"\n");
    }
}


sub db_commit () {
    nooutput("SELECT * FROM addresses LEFT JOIN config USING (emailaddr)");
    nooutput("SELECT * FROM addresses LEFT JOIN texts USING (textid)");
    $dbh->do("COMMIT");
}

1;
