[Catalyst] example of sep db config args (was Re: Accessing DB from external model)

Darren Duncan darren at darrenduncan.net
Mon Nov 8 20:18:15 GMT 2010


Darren Duncan wrote:
>     sub _lazy_default_for_dbc {
>         my ($process) = @_;
>         my $dbc = try {
>             my $dsn = sprintf( q{dbi:Pg:dbname=%s;host=%s;port=%s},
>                 $process->db_name(), $process->db_host(), 
> $process->db_port() );
>             my $dbc = DBIx::Connector->new( $dsn,
>                 $process->db_user(), $process->db_pass(),
>                 { 'RaiseError' => 1, 'AutoCommit' => 1 },
>             );
>             my $dbh = $dbc->dbh();
>             # SET UP ANY OTHER CLIENT SETTINGS HERE ON $dbh
>             return $dbc;
>         }
>         catch {
>             confess sprintf( q{Could not open connection to Pg server or 
> db: %s}, $_ );
>         };
>         return $dbc;
>     }

As an addendum ...

While this isn't relevant to the main point of my post, which is how to separate 
config params for a database connection used by a Catalyst app, I noticed that 
my code had a different flaw, which is now hopefully corrected in the version below:

     sub _lazy_default_for_dbc {
         my ($process) = @_;
         my $dbc = try {
             my $dsn = sprintf( q{dbi:Pg:dbname=%s;host=%s;port=%s},
                 $process->db_name(), $process->db_host(), $process->db_port() );
             my $dbc = DBIx::Connector->new( $dsn,
                 $process->db_user(), $process->db_pass(), {
                     RaiseError => 1,
                     AutoCommit => 1,
                     Callbacks  => {
                         connected => sub {
                             my ($dbh) = @_;
                             $process->_do_post_connect( $dbh );
                         },
                     },
                 },
             );
             return $dbc;
         }
         catch {
             confess sprintf( q{Could not open connection to Pg server or db: 
%s}, $_ );
         };
         return $dbc;
     }

     sub _do_post_connect {
         my ($process, $dbh) = @_;
         # SET UP ANY OTHER CLIENT SETTINGS HERE ON $dbh
     }

The flaw is that if DBIx::Connector had to reconnect to the database, an event 
that users shouldn't have to be aware of having occurred, the client settings 
done by "SET UP ..." would not have been done on the new connection.

-- Darren Duncan



More information about the Catalyst mailing list