summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorYorhel <git@yorhel.nl>2020-12-25 13:43:06 +0100
committerYorhel <git@yorhel.nl>2020-12-25 13:43:06 +0100
commit0a4f9dec767141b0e2e6f44365839a230f4aeaa4 (patch)
tree66934c1beb9710a216152e8b146eebecb4f1cd63
parentdd18ccc27c55c870fa403fa56a1b098b5a12fc18 (diff)
Allow using database methods during initialization + lazily load DB connection
-rw-r--r--lib/TUWF.pm14
-rw-r--r--lib/TUWF/DB.pm11
2 files changed, 15 insertions, 10 deletions
diff --git a/lib/TUWF.pm b/lib/TUWF.pm
index fa80f58..6289f89 100644
--- a/lib/TUWF.pm
+++ b/lib/TUWF.pm
@@ -105,24 +105,26 @@ sub import {
sub set {
return $OBJ->{_TUWF}{$_[0]} if @_ == 1;
$OBJ->{_TUWF} = { %{$OBJ->{_TUWF}}, @_ };
+ # Make sure to load TUWF::DB as soon as we have database settings.
+ $OBJ->_load_module('TUWF::DB', 1) if $OBJ->{_TUWF}{db_login};
}
sub run {
- # load the database module if requested
- $OBJ->_load_module('TUWF::DB', 1) if $OBJ->{_TUWF}{db_login};
-
# install a warning handler to write to the log file
$SIG{__WARN__} = sub { $TUWF::OBJ->log($_) for @_; };
# load optional modules
require Time::HiRes if $OBJ->debug || $OBJ->{_TUWF}{log_slow_pages};
- # initialize DB connection
- $OBJ->dbInit if $OBJ->{_TUWF}{db_login};
+ # roll back any transaction that is currently active, so we start with a
+ # clean slate for the next incoming request. Code running SQL queries during
+ # initialization is responsible for doing an explicit dbCommit() if changes
+ # should be kept.
+ $OBJ->dbRollBack if $OBJ->{_TUWF}{db_login};
# In a FastCGI environment, STDIN will be a listen socket; getpeername() will
- # return a ENOTCONN on those, giving us a reliably way to differentiate
+ # return a ENOTCONN on those, giving us a reliable way to differentiate
# between CGI (env vars), FastCGI (STDIN socket), and others.
my(undef) = (getpeername \*STDIN);
my $isfastcgi = $!{ENOTCONN};
diff --git a/lib/TUWF/DB.pm b/lib/TUWF/DB.pm
index a583609..1e04a33 100644
--- a/lib/TUWF/DB.pm
+++ b/lib/TUWF/DB.pm
@@ -44,13 +44,16 @@ sub dbInit {
sub dbh {
- return shift->{_TUWF}{DB}{sql};
+ my($self) = @_;
+ $self->dbInit if !$self->{_TUWF}{DB}{sql};
+ $self->{_TUWF}{DB}{sql};
}
sub dbCheck {
my $self = shift;
my $info = $self->{_TUWF}{DB};
+ return $self->dbInit if !$info || !$info->{sql};
my $start = time;
$info->{queries} = [];
@@ -65,21 +68,21 @@ sub dbCheck {
sub dbDisconnect {
- shift->{_TUWF}{DB}{sql}->disconnect();
+ (shift->{_TUWF}{DB}{sql} // return)->disconnect();
}
sub dbCommit {
my $self = shift;
my $start = [Time::HiRes::gettimeofday()] if $self->debug || $self->{_TUWF}{log_slow_pages};
- $self->{_TUWF}{DB}{sql}->commit();
+ ($self->{_TUWF}{DB}{sql} // return)->commit();
push(@{$self->{_TUWF}{DB}{queries}}, [ 'commit', {}, Time::HiRes::tv_interval($start) ])
if $self->debug || $self->{_TUWF}{log_slow_pages};
}
sub dbRollBack {
- shift->{_TUWF}{DB}{sql}->rollback();
+ (shift->{_TUWF}{DB}{sql} // return)->rollback();
}