Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
There's more than one way to do things.
 
PerlMonks

CGI::Session + DBD::SQLite = closing dbh with active statement handles

by bash (Novice)
 | Log in | Create a new user | The Monastery Gates | Super Search | 
 | Seekers of Perl Wisdom | Meditations | PerlMonks Discussion | 
 | Obfuscation | Reviews | Cool Uses For Perl | Perl News | Q&A | Tutorials | 
 | Poetry | Recent Threads | Newest Nodes | Donate | What's New | 

on Feb 02, 2008 at 09:52 UTC ( #665714=perlquestion: print w/ replies, xml ) Need Help??
bash has asked for the wisdom of the Perl Monks concerning the following question:

Hello Guru, I got unexpected error using CGI::Session + DBD::SQLite. This is my simple perl program:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use CGI::Session; my $session = new CGI::Session( 'driver:sqlite;serializer:Storable', "91b85831787f534e3f9b6448da10af18", {DataSource => 'db/sessions.db'} ) or die (CGI::Session->errstr);
But it returns warnings all the times:
DBI::db=HASH(0x89601c)->disconnect invalidates 1 active statement hand +le (either destroy statement handles or call finish on them before di +sconnecting) at /Library/Perl/5.8.8/CGI/Session/Driver/DBI.pm line 13 +3. closing dbh with active statement handles at /Library/Perl/5.8.8/CGI/S +ession/Driver/DBI.pm line 133.
After little investigation I found that this problems goes from this code snippet:
/Library/Perl/5.8.8/CGI/Session/Driver/DBI.pm: [...] sub retrieve { my $self = shift; my ($sid) = @_; croak "retrieve(): usage error" unless $sid; my $dbh = $self->{Handle}; my $sth = $dbh->prepare_cached("SELECT a_session FROM " . $self->t +able_name . " WHERE id=?", undef, 3); unless ( $sth ) { return $self->set_error( "retrieve(): DBI->prepare failed with + error message " . $dbh->errstr ); } $sth->execute( $sid ) or return $self->set_error( "retrieve(): \$s +th->execute failed with error message " . $sth->errstr); my ($row) = $sth->fetchrow_array(); return 0 unless $row; return $row; } [...]
If substitute prepare_cached with prepare my program executes without warnings. But maybe exist solution how to fix it without modification of CGI::Session?

Comment on CGI::Session + DBD::SQLite = closing dbh with active statement handles
Select or Download Code
Re: CGI::Session + DBD::SQLite = closing dbh with active statement handles
by dsheroh (Vicar) on Feb 02, 2008 at 18:45 UTC
    I don't think you're going to be able to fix this without modifying CGI::Session.

    Basically, what the "active statement handle" warning means is that the database connection is going away while there's a query still active which might have results which haven't been retrieved yet. Some database drivers are smart enough to recognize that a query has had all results retrieved when the last row is fetched. Others don't recognize this until you attempt to fetch a row that isn't there. You are apparently either using one which falls into the latter category (more likely) or the session table has gotten messed up such that the id you're testing with has multiple a_session records.

    The reason that switching to prepare would fix this is that it allows $sth to be destroyed when it falls out of scope at the end of the sub. prepare_cached stores a second copy of the statement handle in case that same query is prepared again later; it is this second (cached) copy which is still active when your database connection goes away and triggers the warning.

    A better solution, IMO, would be to continue using prepare_cached and add the line $sth->finish; immediately after my ($row) = $sth->fetchrow_array();. This will tell the database engine that you're done with the query's results even if it thinks there may still be additional rows to return.

      Database does not contain duplicated records, so fetchrow_array() returns all data. Here is my test-case program for current situation:
      #!/usr/bin/perl -w use strict; use DBI; use Data::Dumper; use Storable; use warnings; sub get_session { my ($dbh) = shift; #$dbh->{TraceLevel} = 2; my $sid = $ARGV[0]; my $SQL = sprintf("select a_session from sessions where id = %s", +$dbh->quote($sid)); my $sth = $dbh->prepare_cached($SQL, undef, 3); $sth->execute; my ($val) = $sth->fetchrow_array; #[1] my ($val2) = $sth->fetchrow_array; #[2] $sth->finish; my $session = Storable::thaw($val); } my $dbh = DBI->connect('dbi:SQLite:dbname=db/sessions.db'); print Dumper(get_session($dbh)); $dbh->disconnect;
      If we run program as it looks, result will be:
      DBI::db=HASH(0x87a79c)->disconnect invalidates 1 active statement hand +le (either destroy statement handles or call finish on them before di +sconnecting) at ./decode_sessions.pl line 26. closing dbh with active statement handles at ./decode_sessions.pl line + 26.
      If I uncomment (1), (2) or (1)+(2) result:
      closing dbh with active statement handles at ./decode_sessions.pl line + 26.
      PS. I have found that something like this already in CPAN bug list: http://rt.cpan.org/Public/Bug/Display.html?id=31239
        I think i found solution. The problem is that DBD::SQlite->disconnect() method execute sqlite3_close() function. This function return SQLITE_BUSY in case if there are any active statement. From API: "Applications should finalize all prepared statements and close all BLOBs associated with the sqlite3 object prior to attempting to close the sqlite3 object." Currently DBD::SQLite can finalize statements only via DESTROY method. In simplest case you can always use "undef $sth" or wait untill it goes out of scope which will finalize statement. But if you prepared statement via cache (prepare_cached) it will not work for you, because statement is till inside DBI cache. In this case we can call DESTROY on our cached statement only via DESTROY for database handler. And we can achieve it by "undef $dbh". "undef $dbh" - will close all cached statements and close database without any errors. Conclusion: avoid using $dbh->disconnect() for DBD::SQLite, instead use "undef $dbh".
Re: CGI::Session + DBD::SQLite = closing dbh with active statement handles
by bash (Novice) on Feb 05, 2008 at 05:12 UTC
    New solution will be this: We need to add new method to sqlite.pm from CGI::Session package. In this case we will be still able to cache prepared statement which is good for performance.
    sub DESTROY { my $self = shift; unless ( $self->{Handle}->{AutoCommit} ) { $self->{Handle}->commit; } if ( $self->{_disconnect} ) { undef $self->{Handle}; } }
Re: CGI::Session + DBD::SQLite = closing dbh with active statement handles
by markjugg (Curate) on Feb 05, 2008 at 14:39 UTC
    Hi,

    I'm a CGI::Session maintainer. Is the expectation that this bug has always been there in the driver, or that something changed in a newer version of DBD::SQLite which causes it?

    I'm trying to determine if the proposed fix would be backwards compatible.

      I don't know exactly. At one my server I can't reproduce it. But many people says that DBD::SQLite has spewed this warning for as long as they can remember.

Login:
Password
remember me
What's my password?
Create A New User

Node Status?
node history
Node Type: perlquestion [id://665714]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (20)
ikegami
Corion
GrandFather
Your Mother
toolic
holli
JavaFan
kennethk
thezip
Eyck
NodeReaper
tubaandy
dirving
ssandv
VinsWorldcom
jonasbn
elTriberium
MikeDexter
d5e5
brp4h
As of 2010-02-09 21:05 GMT
Sections?
The Monastery Gates
Seekers of Perl Wisdom
Meditations
PerlMonks Discussion
Categorized Q&A
Tutorials
Obfuscated Code
Perl Poetry
Cool Uses for Perl
Perl News
Information?
PerlMonks FAQ
Guide to the Monastery
What's New at PerlMonks
Voting/Experience System
Tutorials
Reviews
Library
Perl FAQs
Other Info Sources
Find Nodes?
Nodes You Wrote
Super Search
List Nodes By Users
Newest Nodes
Recently Active Threads
Selected Best Nodes
Best Nodes
Worst Nodes
Saints in our Book
Leftovers?
The St. Larry Wall Shrine
Offering Plate
Awards
Craft
Snippets Section
Code Catacombs
Quests
Editor Requests
Buy PerlMonks Gear
PerlMonks Merchandise
Planet Perl
Perlsphere
Use Perl
Perl.com
Perl 5 Wiki
Perl Jobs
Perl Mongers
Perl Directory
Perl documentation
CPAN
Random Node
Voting Booth?

What level of existential comfort do you require?

Palace
Executive suite at the best hotel
Regular hotel in a decent part of town
Motel
Boarding house
Sleeping Bag on Couch in Basement
Any port in a storm
Camping under the freeway overpass
Jail
Other

Results (279 votes), past polls