package Orchard::DB::Schema;

use strict;
use warnings;

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

use lib '/app/tools/common/lib';
use Orchard::DB::Connect;

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

sub getdbx {
    my $self = shift;
    my $name = shift;
    my $dsn  = Orchard::DB::Connect->dsn($name);
    push @{ $dsn->{'conn'} }, { 'mysql_enable_utf8' => 1 };
    my $dbx = __PACKAGE__->connect( @{$dsn->{'conn'}} );
    $dbx->connection->storage->{'dblist'} = $dsn->{'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;
