#!/usr/bin/perl
#
# eg6a: use DBI to connect to a PostgreSQL database, using sql_foreach()
#
use strict;
use warnings;
use Function::Parameters;

use DBI;

my $db   = "films";
my $host = "db.doc.ic.ac.uk";
my $port = 5432;
my $user = 'lab';
my $password = 'lab';

fun sql_foreach( $dbh, $sql, $recordcb )
{
	my $sth = $dbh->prepare( $sql );
	$sth->execute || die "Database error: " . $dbh->errstr;
	while( my $record = $sth->fetchrow_hashref )
	{
		$recordcb->( $record );
	}
	$sth->finish;
}

fun printrecord( $record )
{
	print "Title:    $record->{title}\n";  print "Director: $record->{director}\n";
	print "Origin:   $record->{origin}\n"; print "Made:     $record->{made}\n";
	my $length = $record->{length} // '';  print "Length:   $length\n"; print "-" x 30 . "\n";
}

my $dbh = DBI->connect(
	    "dbi:Pg:dbname=$db;host=$host;port=$port",
	    $user, $password
	  ) || die "can't connect to $db as $user";

sql_foreach( $dbh, "select * from films", \&printrecord );

$dbh->disconnect;
