2

the Mojolicious::Lite app is working with morbo but not working with hypnotoad.

my $dbh = DBI->connect("dbi:mysql:dbname=xxx", "uname", "pass",
    { AutoCommit =>  0, mysql_enable_utf8 => 1},  )
    or die "Couldn't connect to database: ", $DBI::errstr;

helper db => sub { $dbh };
get '/xxx' => sub {
    my $sth = $self->db->prepare("insert into posts values(?,?,?,?,?,?)");
    $sth->execute('xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx');
    $sth->finish();
    $self->db->commit;
};

when run with hypnotoad, rest of the app is working but it is not reading/writing data to/from database. please help me write code that work with hypnotoad

Grinnz
  • 9,093
  • 11
  • 18
rx57
  • 189
  • 1
  • 5

2 Answers2

2

You can use DBIx::Connector, like this

use strict;
use warnings;
use Mojolicious::Lite;
use DBIx::Connector;

helper connector => sub { 
    state $db = DBIx::Connector->new(sprintf('dbi:mysql:host=%s:database=%s',@{  $config->{mysql_database}}{qw[host db]}),@{$config->{mysql_database}}{qw[user password]}) or die "Could not connect";
};

helper mysql => sub { shift->connector->dbh };

post '/login' => sub {
    my $c = shift;

    my $user = $c->param('user_email');
    my $password = $c->param('password');

    my $sth = $c->mysql->prepare_cached('SELECT * FROM users WHERE user_email = ?') or $c->app->log->debug($DBI::errstr);

    $sth->execute($user);

    my $row = $sth->fetchrow_arrayref;

    $sth->finish;

    ## more code
};
Pradeep
  • 3,093
  • 17
  • 21
2

When hypnotoad was running as a daemon (so, forked), then the database connection was lost.

I used the database plugin:

use Mojolicious::Plugin::Database;

In the startup:

sub startup {
  my $self = shift;

  # Load configuration from hash returned by config file
  my $config = $self->plugin('Config');

  $self->plugin( 'database', {
                     dsn => $config->{dsn},
                     username => $config->{user},
                     password => $config->{password},
                     options => {
                        RaiseError => 0,
                        mysql_auto_reconnect => 1,
                        AutoCommit => 1,
                        PrintError         => 0,
                        PrintWarn          => 0,
                     },
                     helper => 'db'
                });
}

Most important is mysql_auto_reconnect!!! That solved the my issue.

Rob Lassche
  • 841
  • 10
  • 16