bradcathey has asked for the wisdom of the Perl Monks concerning the following question:

In an attempt to update some ancient straight-up DBI methods, e.g., prepare-> and execute->, I'm using a CGI::Application plugin that I've used a hundred times successfully. This time it's returning:

Error executing run mode 'sl': must call dbh_config() before calling dbh(). at [some line].

This is close to the question in this node, but was never answered.

Start by setting up the connection using dbh_config():

use base 'CGI::Application'; use CGI::Application::Plugin::DBH (qw/dbh_config dbh/); sub cgiapp_init { my $self = shift; # connect to dssubscriber DB $self->config_file('/usr/home/[somepath]/conf/subscriber.conf'); # +config_file is a C::A::P::C::S method my $data_source = sprintf 'DBI:mysql:database=%s;host=%s', $self->config_param('mysql.database'), $self->config_param('mysql.host'); $self->dbh_config('subscriber', [$data_source, $self->config_param('mysql.username'), $self->config_param('mysql.password'), { RaiseError => 1 } ]); }

Here's the sub that uses the connection and throws the error:

sub get_setup { my $self = shift; my $subscriber_id = shift; my $stmt = 'SELECT * FROM admin_setup WHERE subscriber_id = ?'; my %setup = % { $self->dbh('subscribers')->selectrow_hashref($stmt +, undef, $subscriber_id) }; return \%setup; }

Data Dump of $self:

'__DBH_CONFIG' => { 'subscriber' => [ 'DBI:mysql:database=dssubscribers;h +ost=qs4821.pair.com', '1045567_6_w', 'jkgda9leUe89', { 'RaiseError' => 1 } ] }, '__DBH' => { 'subscriber' => bless( {}, 'DBI::db' ) }

I looked at the plugin's code and it looks like this should work:

unless ($self->{__DBH_CONFIG}{$name}){ __auto_config($self, $name); croak "must call dbh_config() before calling dbh()." unless $s +elf->{__DBH_CONFIG}{$name}; }

What am I missing?

—Brad
"The important work of moving the world forward does not wait to be done by perfect men." George Eliot

Replies are listed 'Best First'.
Re: Puzzling error in CGI:Application: "must call dbh_config() before calling dbh()"
by Corion (Patriarch) on Apr 30, 2023 at 06:19 UTC

    I think the error message is misleading - you are setting up a DB handle but not the one you later request:

    $self->dbh_config('subscriber', [$data_source, $self->config_param('mysql.username'), $self->config_param('mysql.password'), { RaiseError => 1 } ]);

    ... vs ...

    $self->dbh('subscribers')

    Consider using either a constant or global variable for the name of the database handle (subscriber vs. subscribers).

      Duh, Brad. Thanks for the extra set of eyes on this.

      —Brad
      "The important work of moving the world forward does not wait to be done by perfect men." George Eliot