RSS Git Download  Clone
Raw Blame History
package LIMS::Model::Roles::DBIxSimple;

use Moose::Role;

use DateTime::Format::MySQL;
use LIMS::Local::DBIxSimple;
use Data::Dumper;

has params => ( is => 'rw', isa => 'HashRef', default => sub { {} } );
has constraints => (
    is         => 'ro',
    isa        => 'ArrayRef[Str]',
    traits     => ['Array'],
    default    => sub { [] },
	handles    => {
        all_constraints => 'elements', # array accessor
        add_constraint  => 'push',
    },
);
has bind_vars => (
    is         => 'ro',
    isa        => 'ArrayRef[Str]',
    traits     => ['Array'],
    default    => sub { [] },
    handles    => {
        add_bind_vars => 'push',
        all_bind_vars => 'elements',
    },
);
has constraint_title => ( is => 'rw', isa => 'Str' ); # for chart & template titles
has lims_dbix        => ( is => 'ro', isa => 'DBIx::Simple', lazy_build => 1 );

# requires 'lims_dbix'; # LIMS::Model::Base method

sub get_cols {
	my ($self, $table) = @_;
	
	my $dbh = $self->lims_dbix;
	
	my $meta = $self->dbix_get_meta($table); # warn Dumper $meta;
	
	my @cols = keys %$meta; # warn Dumper \@cols;
	return \@cols;
}

sub dbix_get_meta { # !!!!!!! keep distinct from Model::Base::get_meta_data()
	my ($self, $table) = @_;
	
	my $dbh = $self->lims_dbix;
	
	my $t = $dbh->query("show columns from $table")->hashes; # warn Dumper $t;
	
	my %meta = map { $_->{field} => $_ } @$t; # warn Dumper \%meta;	
	return \%meta;
}

sub get_enum_opts {
	my ($self, $table, $col) = @_;

	my $meta = $self->dbix_get_meta($table);
	
	my $col_type = $meta->{$col}->{type};
	
	my ($enum) = $col_type =~ /enum\((.*)\)/; # warn $enum;
	my @opts = sort grep { $_ =~ s/\'//g } split ',', $enum; # warn Dumper \@opts;
	return \@opts;
}

sub inflate_mysql_date_to_datetime {
	my $self = shift;
	my $date = shift;
	
	return DateTime::Format::MySQL->parse_date($date);
}

# plural of above:
sub inflate_mysql_dates_to_datetime {
	my $self = shift;
	my $data = shift; # hashref
	my $cols = shift; # array(ref) of cols to inflate
	
	map {
		$data->{$_} = DateTime::Format::MySQL->parse_date($data->{$_});
	} grep $data->{$_}, @$cols;	
}

sub inflate_mysql_timestamp_to_datetime {
	my $self = shift;
	my $data = shift; # hashref
	my $cols = shift; # array(ref) of cols to inflate
	
	map {
		$data->{$_} = DateTime::Format::MySQL->parse_datetime($data->{$_});
	} grep $data->{$_}, @$cols;	
}

#-------------------------------------------------------------------------------
sub _build_lims_dbix {
    my $self = shift;
    
	my $dbh = $self->lims_db->dbh;
	
	my $dbix = LIMS::Local::DBIxSimple->new($dbh);
    
    return $dbix;
}

1;