package lib::sql::Query;
use lib::sql::Table;
use lib::Exception;
use strict;
use vars qw /$IMPORTED/;
$IMPORTED = {};


##
# $class->new;
# ------------
#   Constructs a new lib::sql::Query object.
##
sub new
{
    my $class = shift;
    $class = ref $class || $class;
    
    return bless { @_ }, $class;
}


##
# $obj->next;
# -----------
#   Returns next record, and bless it if necessary.
##
sub next
{
    my $self = shift;
    my $hash = $self->{sth}->fetchrow_hashref;
    my $bless_into = $self->{bless_into};
    
    if (defined $bless_into)
    {
	if (not $IMPORTED->{$bless_into})
	{
	    eval "use $bless_into" unless (defined $IMPORTED->{$bless_into});
	    if ($@) {
		throw (new lib::Exception ( code => 'CANNOT_IMPORT',
					    info => $@ ) );
	    }
	    $IMPORTED->{$bless_into} = 1;
	}
	
	bless $hash, $bless_into if (ref $hash and defined $bless_into);
    }
    return $hash;
}


##
# $obj->fetch_all;
# ----------------
#   Returns an array of all objects that could be fetched
##
sub fetch_all
{
    my $self = shift;
    my @res  = ();

    my @array = ();    
    my $bless_into = $self->{bless_into};
    if (defined $bless_into)
    {
	eval "use $bless_into" unless (defined $IMPORTED->{$bless_into});
	if ($@) {
	    throw (new lib::Exception ( code => 'CANNOT_IMPORT',
					info => $@ ) );
	}
	
	while (my $hash = $self->{sth}->fetchrow_hashref)
	{
	    bless $hash, $bless_into;
	    push @array, $hash;
	}
    }
    else
    {
	while (my $hash = $self->{sth}->fetchrow_hashref)
	{
	    push @array, $hash;
	}
    }
    
    return (wantarray) ? @array : \@array;
}


##
# $obj->fetch_all_firstvalue;
# ---------------------------
#   Returns an array of all objects that could be fetched
##
sub fetchall_arrayref
{
    my $self  = shift;
    return $self->{sth}->fetchall_arrayref;
}


1;
