How do I create multiple database connections in Catalyst with DBIC

943 views Asked by At

I am trying to connect to two postgres databases on the same host and having no luck. (These are two separate databases not two schemas.)

I am using Schema::Loader to create my result class files as well as the database connection files using the following commands:

First Database:

script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=static dbi:Pg:dbname=handshake_vt 'user' 'pw' '{ AutoCommit => 1 }'

For my Second database, should I put tables classes in the same Schema like this:

script/myapp_create.pl model DB2 DBIC::Schema MyApp::Schema create=static dbi:Pg:dbname=members_vt 'user' 'pw' '{ AutoCommit => 1 }'

or should I create a separate schema name_space like this:

script/myapp_create.pl model DB2 DBIC::Schema MyApp::Schema::Members create=static dbi:Pg:dbname=members_vt 'user' 'pw' '{ AutoCommit => 1 }'

I've tried both options and get slightly different errors with both approaches.

Below are the files I have using the single schema appropach:

1.  DB.pm

package MyApp::Model::DB;

use strict;
use base 'Catalyst::Model::DBIC::Schema';

__PACKAGE__->config(
    schema_class => 'MyApp::Schema',

    connect_info => {
        dsn => 'dbi:Pg:dbname=handshake_vt',
    }
);


2.  DB2.pm

package MyApp::Model::DB2;

use strict;
use base 'Catalyst::Model::DBIC::Schema';

__PACKAGE__->config(
    schema_class => 'MyApp::Schema',

    connect_info => {
        dsn => 'dbi:Pg:dbname=legislators_vt',
    }
);


3.  Schema.pm

package MyApp::Schema;

__PACKAGE__->load_namespaces;;

My Table Class basically looks like this:

package Handshake::Schema::Result::Country;

…

__PACKAGE__->table("countries");

Thanks for any help.

2

There are 2 answers

0
Alexander Hartmaier On BEST ANSWER

Your first approach with creating different schemas, one for each database, is the correct one.

Each database gets its own DBIx::Class schema in separate Perl namespaces.

If you will use the DBIC schema outside of your Catalyst application it makes sense to also chose a namespace outside of the Catalyst app,

for example Company::Model::DB1, Company::Model::DB2 and Company::Web::App.

Then you create a Catalyst model for each DBIx::Class schema with the different connection parameters.

In Catalyst you access the two models using $c->model('DB1') and $c->model('DB2').

0
Denis Ibaev On

You need to create two separate schemas (not one) and two models.