RSS Git Download  Clone
Raw Blame History
use App::Class; # Import::Into

#===============================================================================
# provides a DBIx::Simple db connection and dump_query() method to App::DB
class DBIx :isa(DBIx::Simple); 
#===============================================================================

# use App::DB::Result; # cannot use its functions !!!!
use Data::Printer;
use App::Utils;

method query ($str, @bind) { # inherits from parent, dumps query to console if required
    $self->dump_query($str, @bind) if $ENV{SQL_TRACE}; # set at command-line, or in App::DB
    # continue on its original way:
    $self->SUPER::query($str, @bind);
}

method dump_query ($str, @bind) {
    # quote anything in @bind array other than numbers:
    $_ = $self->dbh->quote($_) for
        grep { ! Scalar::Util::looks_like_number($_) } @bind; 
    App::Utils->new->dump_query($str, @bind);
}

#===============================================================================
class App::DB; # provides a dbix method and 2 others to model
#===============================================================================

use Data::Printer;
use File::Slurper 'read_text';

field $cfg  :reader :param; # mandatory
field $dbix :reader = DBIx->connect( 'dbi:SQLite:dbname='.$cfg->{dbname} );

ADJUST { # p $cfg->{db_init}, as => "db_init file:";
  # set dbh->trace output:
    my $dbi_trace_level = $ENV{DBI_TRACE} || 0;
    $dbix->dbh->trace('SQL|'.$dbi_trace_level); # p $dbix;
  # set query output to STDOUT:
	$ENV{SQL_TRACE} //= $cfg->{sql_trace}; # can be overridden from command-line

  # init db if 1st run (creates db also if not exists)
    my $schema = read_text( $cfg->{db_init} );  # p $sql;
    my @schemata = split /\n\s*\n/, $schema;    # p @schema;
    $dbix->dbh->do($_) for @schemata; # is needed, sometimes fails to run directly
    # $dbix->dbh->do($schema);
}

method find_user ($username) { # p $dbh->{Name}; p $username;
    my $user = $dbix->select('users', '*', { username => $username })->hash; # p $user;
    return $user;
}

method total_count ($table) { $dbix->select($table => 'COUNT(*)')->list }

1;