package Common::DB::Schema;

use strict;
use warnings;

use base 'DBIx::Class::Schema';

use lib '/app/tools/common/lib';
use Common::DB::Connection;

__PACKAGE__->load_namespaces( result_namespace => '+Common::DB::Schema' );

sub getdbx {
    my $self = shift;
    my $name = shift;
    my $conn = Common::DB::Connection->new($name);
    my $dsn  = $conn->dsn;
    push @{$dsn}, { 'mysql_enable_utf8' => 1 };
    my $dbx = __PACKAGE__->connect( @{$dsn} );
	$dbx->connection->storage->{'dblist'} = $conn;
    $dbx;
}

sub dblist {
	my $self = shift;
    $self->connection->storage->{'dblist'};
}

sub getdbh {
    my $self = shift;
    my $dbh  = $self->connection->storage->dbh;
    $dbh;
}

sub current_schema {
    my $self = shift;
    my $dbh  = $self->getdbh;
    my $res  = $dbh->selectcol_arrayref('select database();');
    $res->[0];
}

sub has_schema {
    my $self = shift;
    defined $self->current_schema ? 1 : 0;
}

sub switch_schema {
    my $self = shift;
    my $name = shift;
    my $dbh  = $self->getdbh;
    $dbh->do("use $name;");
}

1;
