#!/usr/local/bin/perl -w

use strict;
use DBI;

my $dbh = DBI->connect('DBI:Pg:dbname=foo;host=localhost', 'bar', '', {
    AutoCommit => 0,
    RaiseError => 0,
});

### correct way *without* using deferred triggers:
my $sql = <<SQL;
INSERT INTO country (id, name) values (1, 'Netherlands');
INSERT INTO city (id, name, city_id) values (1, 'Amsterdam', 1);
SQL
print STDERR "\n$sql\n";
my $sth = $dbh->prepare($sql);
$sth->execute() or warn "Error=" . $dbh->errstr();
$dbh->commit() or warn "Error=" . $dbh->errstr();

### correct way using deferred triggers:
$sql = <<SQL;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO city (id, name, city_id) values (2, 'Brussels', 2);
INSERT INTO country (id, name) values (2, 'Belgium');
SQL
print STDERR "\n$sql\n";
$sth = $dbh->prepare($sql);
$sth->execute() or warn "Error=" . $dbh->errstr();
$dbh->commit() or warn "Error=" . $dbh->errstr();

### illegal way without deferred triggers:
$sql = <<SQL;
INSERT INTO city (id, name, city_id) values (3, 'Paris', 9);
SQL
print STDERR "\n$sql\n";
$sth = $dbh->prepare($sql);
$sth->execute() or warn "Error=" . $dbh->errstr();
$dbh->commit() or warn "Error=" . $dbh->errstr();

### illegal with deferred triggers:
$sql = <<SQL;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO city (id, name, city_id) values (3, 'Paris', 9);
SQL
print STDERR "\n$sql\n";
$sth = $dbh->prepare($sql);
$sth->execute() or warn "Error=" . $dbh->errstr();
$dbh->commit() or warn "Error=" . $dbh->errstr();

### cleanup database for next run:
$sql = <<SQL;
DELETE FROM city;
DELETE FROM country;
SQL
print STDERR "\n$sql\n";
$sth = $dbh->prepare($sql);
$sth->execute() or warn "Error=" . $dbh->errstr();
$dbh->commit() or warn "Error=" . $dbh->errstr();

print STDERR "\ncalling dbh->disconnect()\n";
### finishing will trigger a NOTICE from the backend:
$dbh->disconnect() or warn "Error=" . $dbh->errstr();
