# Class to handle RDQL queries via the tstore_rdql tool, see exmaple.pl for
# usage example.

#  Copyright (C) 2003 Steve Harris, ECS, University of Southampton
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  $Id: RDQL.pm,v 1.4 2003/09/02 16:57:56 theno23 Exp $

package RDQL;
use IPC::Open2;
use Symbol;

sub new {
	my $that = shift;
	my $class = ref($that) || $that;
	my %params = @_;
	$cl_args = "";
	if ($params{'database'}) {
		$cl_args .= " --database=".$params{'database'}
	}
	if ($params{'user'}) {
		$cl_args .= " --user=".$params{'user'}
	}
	if ($params{'password'}) {
		$cl_args .= " --password=".$params{'password'}
	}
	if ($params{'remote'}) {
		$cl_args .= " --remote=".$params{'remote'}
	}
	$| = 1;
	my $WTR = gensym();
	my $RDR = gensym();
	my $pid = open2($RDR, $WTR, "tstore_rdql".$cl_args);
	print $WTR "SET format list;\n";
	my $this = {
		type => "pipe",
		wtr  => $WTR,
		rdr  => $RDR,
		pid  => $pid
	};
	bless $this, $class;
	return $this;
}

sub set {
	my $this = shift;
	my ($k, $v) = @_;

	my $WTR = $this->{'wtr'};
	print $WTR "SET $k $v;\n";
}

sub query {
	my $this = shift;
	my $query = shift;
	my $WTR = $this->{'wtr'};
	my $RDR = $this->{'rdr'};

	my $ret = [];
	my $row = {};
	my $count = 0;

	print $WTR $query.";\n";
	while ($line = <$RDR>) {
		last if $line =~ /^EOR\s*$/;
		if ($line =~ /^\s*$/) {
			$ret->[$count++] = $row;
			$row = {};
			next;
		}
		if ($line =~ /^(.*?)\t(.*?)\s*$/) {
			my $sym = $1;
			my $val = $2;
			$row->{$sym} = $val;
			next;
		} elsif ($line =~ /^error:/) {
			print $line." in\n$query\n";
			return $line." in\n$query\n";
		}
		print "RDQL.pm internal syntax err: $line";
		return $line;
	}

	return $ret;
}

1;

