#!/usr/bin/perl -w

use strict;
use DBI;

my $tolerate_errors = $ARGV[0] eq "E" and shift;

my $numeric = '';
@ARGV == 3
	and $numeric = pop @ARGV;

@ARGV == 2
	or die "syntax: $0 E dsn sql < input > status\n";

my ($dsn, $user, $pass, $attr) = split / /, shift, 4;
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";

my $line;
my @input_row;

if (defined ($line = <STDIN>)) {
	chomp $line;
	@input_row = split /\t/, $line, -1;
	for (@input_row) {
		if ($_ eq "\0") {
			undef $_;
		} else {
			s/([^\\]|^)((?:\\\\)*)\\0/$1$2\0/g;
			s/([^\\]|^)((?:\\\\)*)\\n/$1$2\n/g;
			s/([^\\]|^)((?:\\\\)*)\\t/$1$2\t/g;
			s/\\\\/\\/g;
		}
		$numeric =~ /(.)/g;
		($1||'') =~ /\d/ and $_ = 0+$_;
	}
	my $count = $sth->execute(@input_row)
		or !$tolerate_errors && die "cannot execute: ".$sth->errstr."\n";
	print ((defined $count ? $count : $sth->errstr),"\n");

	while (defined ($line = <STDIN>)) {
		chomp $line;
		@input_row = split /\t/, $line, -1;
		for (@input_row) {
			if ($_ eq "\0") {
				undef $_;
			} else {
				s/([^\\]|^)((?:\\\\)*)\\0/$1$2\0/g;
				s/([^\\]|^)((?:\\\\)*)\\n/$1$2\n/g;
				s/([^\\]|^)((?:\\\\)*)\\t/$1$2\t/g;
				s/\\\\/\\/g;
			}
		}
		my $count = $sth->execute(@input_row)
			or !$tolerate_errors && die "cannot execute: ".$sth->errstr."\n";
		print ((defined $count ? $count : $sth->errstr),"\n");
	}
}

$sth->finish;

$dbh->disconnect;
