#!/bin/perl -w

use strict;

use DBI;
use XML::Twig;

my $file= shift;

my $dbh= connect_to_db();

my $twig= new XML::Twig( twig_roots => 
                           { include => \&include },
                         twig_print_outside_roots => 1,
                       );

$twig->parsefile( $file);

$dbh->disconnect();
exit;



# connect to the data base
sub connect_to_db
  { my $driver = "mysql";
    my $dsn = "DBI:$driver:database=test;";
    my $dbh = DBI->connect($dsn, 'test', '', {AutoCommit=>1});
    my $drh = DBI->install_driver($driver);
    return( $dbh);
  }


sub include
  { my( $twig, $include)= @_;
    my $query= $include->att( 'query');
    $query=~ s/&quot;/"/;                      # because of slight
                                               # oversight in XML::Twig
    # prepare the select
    my $select= $query;
    unless ($select=~ /;$/) { $select.= ";"; } # I always forget the ; 
    my $sth= $dbh->prepare( $select);
    $sth->execute();

    my $row= $sth->fetchrow_arrayref();        # there will be only one row
    print $row->[0];                           # and one field in the result
  }
    

