More specifically, you should not store a DBI handle in your app or use it across forks. You should always store a DBIx::Connector or Mojo::Pg or similar connection pool object instead, and then retrieve a connection from it in the smallest scope needed.
On Thu, May 4, 2017 at 7:10 AM, Justin Hawkins <[email protected]> wrote: > > On 4 May 2017, at 5:30 pm, Alexander Lunev <[email protected]> wrote: > > DBD::Pg::db selectall_hashref failed: server closed the connection > unexpectedly. > > > You tried to use a database handle that had been initialised in a previous > process and then forked. As you’ve realised, this doesn’t work :-) > > > And if I try to use recipe with "has => dbh", somehow i need to get access > to $self->app in lib/PortMgr/Storage/PgSQL.pm, but it is not a Mojolicious > controller class, so i need to drag $dbh from lib/PortMgr.pm to > lib/PortMgr/Controller/Hw.pm to lib/PortMgr/Model/Hw.pm to > lib/PortMgr/Storage/PgSQL.pm? > > Is there any other solution? > > > In general, if you find it difficult to test any of your classes in > isolation, you’ve got some sort of code smell. In this case, the fact that > the model instantiates it’s own database handle makes it hard to test, and > causes this issue. > > I’d suggest instantiating your database connection in the main > application, and then passing it as a parameter to your model class. No > singletons. Singletons aren’t always bad, but this one is :-) The model > class should store it as an attribute: > > package PortMgr::Model::Hw; > > use Mojo::Base qw/-base/; > > has ‘storage’; > > … > > As an added benefit, now you can test more easily: > > my $db = Test::PortMgr::Storage::PgSQL->new(); # db handle to test > database > my $model = PortMgr::Model::Hw->new(storage = >$db); > > ok($model->get_hw(), ‘can get hw’); > > Cheers, > > Justin > > > -- > You received this message because you are subscribed to the Google Groups > "Mojolicious" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To post to this group, send email to [email protected]. > Visit this group at https://groups.google.com/group/mojolicious. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "Mojolicious" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/mojolicious. For more options, visit https://groups.google.com/d/optout.
