package LIMS::Local::DBIxSimple;

# sub-classes DBIx::Simple to dump query statements to output

use strict;
use warnings;

use parent 'DBIx::Simple';
use Data::Dumper;

sub query {
    my $self  = shift;
    my $query = shift; # warn $query;
    my @bind  = @_; # warn Dumper \@bind;
    
    # try to emulate output of Rose::DB::Object::QueryBuilder :
    {
        my $key_words = join '|',
            qw(select from where join date_sub curdate interval show columns);
    
        $query =~ s/\b($key_words)\b/uc $1/eg;
        
        $query =~ s/(SELECT)(?!\n)/$1\n  /;
    
        $query =~ s/(FROM)(?!\n)/\n$1\n  /g; 
        
        $query =~ s/(WHERE)(?!\n)/\n$1\n  /g; # SORT|(GROUP BY)/
        
        $query =~ s/\t/  /g; # leading tab -> 2 spaces        
    }
    
    if ( $ENV{RDBO_DEBUG} ) {
        no warnings 'uninitialized'; # common for @bind params to be undef
        warn "$query (", join(', ', @bind), ")\n"; # modified from RDBO  
    }
    
    $self->SUPER::query($query, @bind);
}

=begin # sql already output in $dbix update/insert/delete functions ?? how
sub delete {
    my $self  = shift;
    my $table = shift; # scalar
    my $args  = shift; # hashref
    
    my @args = map { "$_ = $args->{$_}" } keys %$args;
    
    my $statement = sprintf qq!DELETE FROM $table\nWHERE %s\n!,
        join ' AND ', @args;

    warn $statement;
    
    $self->SUPER::delete($table, $args);
}

sub insert {
    my $self  = shift;
    my $table = shift; # scalar
    my $args  = shift; # hashref
    
    my $cols = join ', ', keys %$args;
    my $vals = join ', ', values %$args;
    
    my $statement = sprintf qq!INSERT INTO $table (%s)\nVALUES (%s)\n!,
       $cols, $vals;

    warn $statement;
    
    $self->SUPER::insert($table, $args);
}

sub update {
    my $self  = shift;
    my $table = shift; # scalar
    my $vals  = shift; # hashref
    my $args  = shift; # hashref (optional)
    
    my @vals = map { "$_ = $vals->{$_}" } keys %$vals;
    my @args = map { "$_ = $args->{$_}" } keys %$args;
    
    my $statement = sprintf qq!UPDATE $table\nSET %s\n!,
        join ', ', @vals;
        
    if (@args) {
        $statement .= sprintf q!WHERE %s\n!, join ' AND ', @args;
    }

    warn $statement;

    $self->SUPER::update($table, $vals, $args);
}
=cut

1;