How do I have a persistent DBIx::Class in CGI::Application with mod_perl?

688 views Asked by At

I am using CGI::Application on mod_perl with DBIx::Class and I'd like to have something like new define a new dbic schema on instantiation. So far I haven't been able to get it to work. The closest thing I have come to is a superclass that has a connect() method that returns a new object, but I would rather it be already be connected and instantiated.

I would really appreciate any thoughts at all.

Thanks!

Note: Ok, so obviously no help yet, but, in the meantime I made an accessor that lazily instantiates the DBIx::Class, so that might be a little bit better. Check it:

sub schema {
    my $self = shift;
    unless ($self->{schema}) {
        $self->{schema} = ACD::Model->connect(@{$self->cfg->{$ENV{MODE}}->{connect_params}});
    }
    return $self->{schema};
}

and then of course to use it you'd do something like:

$self->schema->resultset('Foo')->find(1234);
2

There are 2 answers

0
Penfold On

I don't have a single answer, but http://lists.scsys.co.uk/pipermail/dbix-class/2006-June/001690.html is probably worth a read, so you understand how DBIC manages connections.

0
Mark On

Of course you can't serialise a database connection into a session file or whatever, and you can't create it before apache forks, but you can keep one live per child process.

An option for creating it ahead of time is to do it in your base mod_perl handler sub, but since the client connection has already started at that point it doesn't buy you any response time improvement.

So I would do a lazy implementation like you have above, but instead of caching the schema object in $self, cache it in a package level private variable, which will mean each apache child process has exactly one schema connection:

my $_schema;

sub schema {
    return $_schema
        if $_schema; # actually, you should check the db connection is live

    return $_schema = ACD::Model->connect(...);
}