Session/Store/DBI.pm

filter: Statementstmt 100% 103 / 103 Branchbran 100% 32 / 32 Conditioncond 78.1% 25 / 32 MC/DCmcdc 52.6% 10 / 19 Subroutinesub 100% 16 / 16 Podpod 0.0% 0 / 3 totaltotal 90.7% 186 / 205 CC 30 SCAR 15.1
CC
30
Cov
96%
_unchanged
8.0
_reusedHandle
6.1
DESTROY
5.0
CRAP 4.5
« Session/Store/SQLite.pm ↑ Summary Session/_common.pm »
1 package Web::Session::Store::DBI;
2  
3 26 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 26 ▶use Apache::Session::Store::DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 26 ▶use Web::Session::_common;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 26 our @ISA = qw(Apache::Session::Store::DBI);
7 26 our $VERSION = '1.0.0';
8  
9 # Connection reuse (default): returns a handle cached by DBI->connect_cached()
10 # (which pings it and reconnects if needed), opened with the attributes $attr
11 # that the store uses without reuse. Returns undef if the store is already
12 # connected, if "noreuse" is set or if a Handle is given. Unless Commit is
13 # 0, the Postgres and Patroni stores use the connection pool of the Postgres
14 # store instead, unless KeepConnections is 0 (see Store/Postgres.pm).
15 #
16 # Why AutoCommit differs between stores: each store opens its connection
17 # with the attributes of the Apache::Session store it derives from.
18 # Apache::Session::Store::Postgres uses AutoCommit off and commits in DESTROY
19 # when Commit is set. Its materialize() locks the row with
20 # "SELECT ... FOR UPDATE": the Patroni store uses it (through _try()), so a
21 # Patroni session stays locked from the tie to the commit at untie, also with
22 # the connection pool (one transaction per tie, see Store/Patroni.pm). The
23 # Postgres store doesn't lock: its materialize() comes first from
24 # Apache::Session::Store::DBI. The SQLite store copies the AutoCommit off
25 # model. Apache::Session::Store::MySQL (MySQLJSON derives from it) was
26 # written for MyISAM, which has no transaction: AutoCommit on. The lock
27 # manager of all SQL backends is Apache::Session::Lock::Null: with AutoCommit
28 # off, the transaction only spans the reads and the write of one tie.
29 # Keeping each store's own attributes keeps its behaviour unchanged.
30 #
31 # Stores don't disconnect a handle they didn't open, so a transaction that
32 # the store doesn't commit (AutoCommit off, Commit not set or commit failure)
33 # would stay open, with its locks, on the shared handle: it is rolled back
34 # when the store is destroyed, after its own DESTROY (as disconnect did)
35 204 ▶sub _reusedHandle {
Subroutine _reusedHandle: called CC=6 SCAR=18.0
36 204 my ( $self, $args, $datasource, $username, $password, $attr ) = @_;
37 return undef
38 204 ▶ if ( defined $self->{dbh} or $args->{noreuse} or exists $args->{Handle} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"dbh"} or $args->{"noreuse"} or exists $args->{"Handle"} 14 190 204
Condition83%5/6
defined $self->{"dbh"} or $args->{"noreuse"} or exists $args->{"Handle"}
l!l&&r!l&&!r
113190
defined $self->{"dbh"} or $args->{"noreuse"}
l!l&&r!l&&!r
011193
MC/DC66%2/3
defined $self->{"dbh"} or $args->{"noreuse"} or exists $args->{"Handle"}
defined $self->{"dbh"} $args->{"noreuse"} exists $args->{"Handle"}
Truth table75%3/4
A or B or C
A= defined $self->{"dbh"}B= $args->{"noreuse"}C= exists $args->{"Handle"}
ABCresult
1XX1
01X1
0011
0000
39  
40 # Fork safe, as the handles of the class methods (see _forkSafeAttr() in
41 # _common.pm): a child forked after the parent tied a session must not
42 # reuse the parent's handle, nor close its connection
43 190 ▶ my $dbh = DBI->connect_cached( $datasource, $username, $password,
Condition50%1/2
'DBI'->connect_cached($datasource, $username, $password, 'Web::Session::_common'->_forkSafeAttr($attr)) || die($DBI::errstr)
l!l
1900
MC/DC0%0/1
'DBI'->connect_cached($datasource, $username, $password, 'Web::Session::_common'->_forkSafeAttr($attr)) || die($DBI::errstr)
'DBI'->connect_cached($datasource, $username, $password, 'Web::Session::_common'->_forkSafeAttr($attr))
Truth table50%1/2
A
A= 'DBI'->connect_cached($datasource, $username, $password, 'Web::Session::_common'->_forkSafeAttr($attr))
Aresult
11
00
44 Web::Session::_common->_forkSafeAttr($attr) )
45 || die $DBI::errstr;
46 $self->{reuse_rollback} =
47 bless \$dbh, 'Web::Session::Store::DBI::Rollback'
48 190 ▶ unless ( $dbh->{AutoCommit} );
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->{"AutoCommit"} 171 19 190
49 190 return $dbh;
50 }
51  
52 # In a child created by fork(), a store connected by the parent still holds
53 # the parent's handle: connection() would return early and the child would
54 # use the parent's socket. Handles of the connection cache and of the
55 # PostgreSQL pool carry the pid of the process that opened them (see
56 # _forkSafeAttr() in _common.pm): such a handle is forgotten with its
57 # statements, neither closed (AutoInactiveDestroy) nor rolled back (see the
58 # Rollback guard below), so that connection() opens one for this process.
59 # Other handles (noreuse, Handle argument) are kept as is. Called by the
60 # connection() of every store, also by those not inheriting from this class,
61 # and by the DESTROY of the stores that commit there (the commit would go to
62 # the parent's transaction). Returns true if the handle was forgotten
63 942 ▶sub _forgetInheritedHandle {
Subroutine _forgetInheritedHandle: called CC=4 SCAR=13.9
64 942 my ($self) = @_;
65 942 ▶ my $dbh = $self->{dbh} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->{"dbh"} or return 0 445 497 942
66 445 my $pid = $dbh->{private_ws_pid};
67 445 ▶ return 0 unless ( defined $pid and $pid != $$ );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid and $pid != $$ 430 15 445
Condition100%3/3
defined $pid and $pid != $$
!ll&&!rl&&r
5637415
MC/DC100%2/2
defined $pid and $pid != $$
defined $pid $pid != $$
Truth table100%3/3
A and B
A= defined $pidB= $pid != $$
ABresult
0X0
100
111
68 15 delete @$self{ 'dbh', 'reuse_rollback', grep { /_sth\z/ } keys %$self };
69 15 return 1;
70 }
71  
72 # connection() of stores whose parent class $class (an Apache::Session::Store
73 # class) opens a connection with the attributes $attr and uses the Handle
74 # argument as is
75 31 ▶sub _connection {
Subroutine _connection: called CC=3 SCAR=11.0
76 31 my ( $self, $session, $class, $attr ) = @_;
77 31 _forgetInheritedHandle($self);
78 31 my $args = $session->{args};
79 31 my $connect = $class->can('connection');
80 31 my @credentials;
81 {
82 26 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
83 31 ▶ @credentials = map { $args->{$_} || ${"${class}::$_"} }
Condition66%2/3
$args->{$_} || ${"${class}::$_";}
l!l&&r!l&&!r
40053
MC/DC50%1/2
$args->{$_} || ${"${class}::$_";}
$args->{$_} ${"${class}::$_";}
Truth table66%2/3
A || B
A= $args->{$_}B= ${"${class}::$_";}
ABresult
1X1
011
000
84 qw(DataSource UserName Password);
85 }
86 31 ▶ if ( my $dbh = $self->_reusedHandle( $args, @credentials, $attr ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dbh = $self->_reusedHandle($args, @credentials, $attr)) 24 7 31
87 24 local $args->{Handle} = $dbh;
88 24 return $self->$connect($session);
89 }
90 7 return $self->$connect($session);
91 }
92  
93 148 ▶sub insert {
Subroutine insert: called CC=4 SCAR=13.9
Pod undocumented
94 148 my ( $self, $session ) = @_;
95  
96 148 $self->connection($session);
97  
98 148 local $self->{dbh}->{RaiseError} = 1;
99  
100 my $index =
101 ref( $session->{args}->{Index} )
102 ? $session->{args}->{Index}
103 148 ▶ : [ split /\s+/, $session->{args}->{Index} ];
Branch: 1 branch
BranchTrueFalseTotal
ref $session->{'args'}{'Index'} ? : 18 130 148
104  
105 $self->{insert_sth} //= $self->{dbh}->prepare_cached(
106 'INSERT INTO '
107 . $self->_quoteTable( $self->{table_name} ) . ' ('
108 . join( ',',
109 148 ▶ 'id', 'a_session', map { $self->_quoteColumn($_) } @$index )
Condition66%2/3
$self->{"insert_sth"} //= $self->{"dbh"}->prepare_cached('INSERT INTO ' . $self->_quoteTable($self->{"table_name"}) . ' (' . join(",", "id", "a_session", map({$self->_quoteColumn($_);} @$index)) . ') VALUES (' . join(",", ("?") x (2 + @$index)) . ')')
l!l&&r!l&&!r
11470
MC/DC0%0/2
$self->{"insert_sth"} //= $self->{"dbh"}->prepare_cached('INSERT INTO ' . $self->_quoteTable($self->{"table_name"}) . ' (' . join(",", "id", "a_session", map({$self->_quoteColumn($_);} @$index)) . ') VALUES (' . join(",", ("?") x (2 + @$index)) . ')')
$self->{"insert_sth"} $self->{"dbh"}->prepare_cached('INSERT INTO ' . $self->_quoteTable($self->{"table_name"}) . ' (' . join(",", "id", "a_session", map({$self->_quoteColumn($_);} @$index)) . ') VALUES (' . join(",", ("?") x (2 + @$index)) . ')')
Truth table66%2/3
A //= B
A= $self->{"insert_sth"}B= $self->{"dbh"}->prepare_cached('INSERT INTO ' . $self->_quoteTable($self->{"table_name"}) . ' (' . join(",", "id", "a_session", map({$self->_quoteColumn($_);} @$index)) . ') VALUES (' . join(",", ("?") x (2 + @$index)) . ')')
ABresult
1X1
011
000
110 . ') VALUES ('
111 . join( ',', ('?') x ( 2 + @$index ) ) . ')'
112 );
113  
114 145 $self->{insert_sth}->bind_param( 1, $session->{data}->{_session_id} );
115 145 $self->{insert_sth}->bind_param( 2, $session->{serialized} );
116 145 my $i = 3;
117 145 foreach my $f (@$index) {
118 307 $self->{insert_sth}->bind_param( $i, $session->{data}->{$f} );
119 307 $i++;
120 }
121  
122 145 $self->{insert_sth}->execute;
123  
124 141 $self->{insert_sth}->finish;
125 }
126  
127 134 ▶sub update {
Subroutine update: called CC=5 SCAR=16.1
Pod undocumented
128 134 my $self = shift;
129 134 my $session = shift;
130  
131 # Indexed columns are computed from the session data only: same data,
132 # same columns (unless Index lists a column added since the row was
133 # written: see RewriteUnchanged)
134 134 ▶ return if ( _unchanged( $self, $session ) );
Branch: 1 branch
BranchTrueFalseTotal
if _unchanged($self, $session) 7 127 134
135  
136 127 $self->connection($session);
137  
138 127 local $self->{dbh}->{RaiseError} = 1;
139  
140 my $index =
141 ref( $session->{args}->{Index} )
142 ? $session->{args}->{Index}
143 127 ▶ : [ split /\s+/, $session->{args}->{Index} ];
Branch: 1 branch
BranchTrueFalseTotal
ref $session->{'args'}{'Index'} ? : 1 126 127
144  
145 127 ▶ if ( !defined $self->{update_sth} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"update_sth"}) 126 1 127
146 $self->{update_sth} = $self->{dbh}->prepare_cached(
147 'UPDATE '
148 . $self->_quoteTable( $self->{table_name} ) . ' SET '
149 . join( ' = ?, ',
150 126 'a_session', map { $self->_quoteColumn($_) } @$index )
151 . ' = ? WHERE id = ?'
152 );
153 }
154  
155 127 $self->{update_sth}->bind_param( 1, $session->{serialized} );
156 127 my $i = 2;
157 127 foreach my $f (@$index) {
158 327 $self->{update_sth}->bind_param( $i, $session->{data}->{$f} );
159 327 $i++;
160 }
161 127 $self->{update_sth}->bind_param( $i, $session->{data}->{_session_id} );
162  
163 127 $self->{update_sth}->execute;
164  
165 126 $self->{update_sth}->finish;
166 126 _remember( $self, $session );
167 }
168  
169 # Unchanged sessions are not rewritten
170 #
171 # Apache::Session saves a session at untie as soon as a key was stored, even
172 # with the value it already had (Lemonldap::NG does that). An UPDATE that
173 # writes the same data is not free: PostgreSQL writes a new row version (and
174 # its WAL) that must be cleaned up later, plus a new entry in every index when
175 # the stored value of a_session changes (the indexes are expressions on it, so
176 # the update can't be HOT), for example when the keys of a json column come
177 # in another order; other databases lock and log the row. So the store keeps
178 # the serialized data it read (or last updated) and update() returns without
179 # writing when the new one is the same. insert() is unchanged: it doesn't
180 # keep what it wrote, so the first update() after it always writes.
181 #
182 # The functions below take the store as first argument, not as invocant:
183 # Web::Session::Store::MariaDBJSON and Web::Session::Store::Patroni don't
184 # inherit from this class and call them too.
185  
186 2 ▶sub materialize {
Subroutine materialize: called CC=1 SCAR=0.0
Pod undocumented
187 2 my ( $self, $session ) = @_;
188  
189 # Apache::Session::Store::DBI's one, as before this override (it comes
190 # first in the method resolution of the stores inheriting from this class)
191 2 $self->SUPER::materialize($session);
192 1 _remember( $self, $session );
193 }
194  
195 # Keep the serialized data that the database holds (after a read or an update)
196 203 ▶sub _remember {
Subroutine _remember: called CC=1 SCAR=0.0
197 203 my ( $self, $session ) = @_;
198 203 $self->{stored_serialized} = $session->{serialized};
199 }
200  
201 # Whether the serialized data to write ($session->{serialized}) is the one the
202 # database already holds
203 151 ▶sub _unchanged {
Subroutine _unchanged: called CC=8 SCAR=20.8
204 151 my ( $self, $session ) = @_;
205 151 my $old = $self->{stored_serialized};
206 151 my $new = $session->{serialized};
207 return 0
208 if ( !defined $old
209 or !defined $new
210 151 ▶ or $session->{args}->{RewriteUnchanged} );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $old && defined $new or $session->{"args"}{"RewriteUnchanged"} 107 44 151
Condition83%5/6
not defined $old && defined $new or $session->{"args"}{"RewriteUnchanged"}
l!l&&r!l&&!r
105244
defined $old && defined $new
!ll&&!rl&&r
105046
MC/DC66%2/3
not defined $old && defined $new or $session->{"args"}{"RewriteUnchanged"}
defined $old defined $new $session->{"args"}{"RewriteUnchanged"}
Truth table75%3/4
not(A && B) or C
A= defined $oldB= defined $newC= $session->{"args"}{"RewriteUnchanged"}
ABCresult
0XX1
10X1
1111
1100
211  
212 # Same bytes. Strings are compared as the bytes exchanged with the
213 # database: the serializer produces characters (UTF-8 flag on), which DBD
214 # drivers send UTF-8 encoded, but a driver may return the stored value as
215 # undecoded bytes (MySQL json columns, a handle without the utf8 option).
216 # A plain "eq" would compare characters: it would wrongly find a Latin-1
217 # byte equal to the same character sent UTF-8 encoded, and wrongly find
218 # UTF-8 bytes different from the same characters
219 44 ▶ return 1 if ( _bytes($old) eq _bytes($new) );
Branch: 1 branch
BranchTrueFalseTotal
if _bytes($old) eq _bytes($new) 10 34 44
220  
221 # Same data. Columns of type jsonb (PostgreSQL) or json (MySQL) don't
222 # return the text written but a normalized one (keys sorted by length,
223 # spaces added), and sessions written by older versions have their keys in
224 # random order: the bytes never match. The data read is then serialized
225 # again, the way the session read it, and compared. When it matches,
226 # readers already get the data that would be written, so the write
227 # changes nothing they see. Only JSON objects: the session data is a
228 # hash, so a row holding another JSON value can't hold the same data, and
229 # a row in another format (Storable, written by old versions) is still
230 # rewritten as JSON.
231 # Costs one decode and one encode when the bytes differ (at each update
232 # with jsonb or MySQL json columns), much less than a write.
233 34 ▶ return 0 unless ( $old =~ /\A\s*\{/ );
Branch: 1 branch
BranchTrueFalseTotal
unless $old =~ /\A\s*\{/ 1 33 34
234 33 local $@;
235 33 my $again = eval {
236 33 my $tmp = { serialized => $old };
237 33 $session->{unserialize}->($tmp);
238 30 $session->{serialize}->($tmp);
239 30 $tmp->{serialized};
240 };
241 33 ▶ return ( defined $again and _bytes($again) eq _bytes($new) ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $again && _bytes($again) eq _bytes($new) ? : 4 29 33
Condition100%3/3
defined $again and _bytes($again) eq _bytes($new)
!ll&&!rl&&r
3264
MC/DC100%2/2
defined $again and _bytes($again) eq _bytes($new)
defined $again _bytes($again) eq _bytes($new)
Truth table100%3/3
A and B
A= defined $againB= _bytes($again) eq _bytes($new)
ABresult
0X0
100
111
242 }
243  
244 # The bytes a DBD driver exchanges for string $s: UTF-8 encoded when it holds
245 # characters (UTF-8 flag on), as is otherwise
246 148 ▶sub _bytes {
Subroutine _bytes: called CC=2 SCAR=6.9
247 148 my $s = shift;
248 148 ▶ utf8::encode($s) if ( utf8::is_utf8($s) );
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($s) 131 17 148
249 148 return $s;
250 }
251  
252 # Table name and columns of indexed fields in SQL queries, see
253 # Web::Session::_common::_quoteIdentifier(). Stores that need
254 # another quoting override them
255 338 ▶sub _quoteTable {
Subroutine _quoteTable: called CC=1 SCAR=0.0
256 338 my ( $self, $name ) = @_;
257 return Web::Session::_common->_quoteIdentifier( $self->{dbh},
258 338 $name );
259 }
260  
261 637 ▶sub _quoteColumn {
Subroutine _quoteColumn: called CC=1 SCAR=0.0
262 637 my ( $self, $field ) = @_;
263 return Web::Session::_common->_quoteIdentifier( $self->{dbh},
264 637 $field );
265 }
266  
267 package Web::Session::Store::DBI::Rollback;
268  
269 # Ends the transaction left by a store using a reused handle (no-op if the
270 # store committed it). Not in a child created by fork(): the transaction is
271 # the parent's, on the parent's socket
272 171 ▶sub DESTROY {
Subroutine DESTROY: called CC=5 SCAR=16.2
273 171 my $dbh = ${ $_[0] };
274 171 ▶ return if ( ( $dbh->{private_ws_pid} // $$ ) != $$ );
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->{"private_ws_pid"} // $$) != $$ 9 162 171
Condition66%2/3
$dbh->{"private_ws_pid"} // $$
l!l&&r!l&&!r
17010
MC/DC0%0/2
$dbh->{"private_ws_pid"} // $$
$dbh->{"private_ws_pid"} $$
Truth table66%2/3
A // B
A= $dbh->{"private_ws_pid"}B= $$
ABresult
1X1
011
000
275 162 local $@;
276 162 ▶ eval { $dbh->rollback } if ( $dbh->{Active} and !$dbh->{AutoCommit} );
Branch: 1 branch
BranchTrueFalseTotal
if $dbh->{"Active"} and not $dbh->{"AutoCommit"} 161 1 162
Condition66%2/3
$dbh->{"Active"} and not $dbh->{"AutoCommit"}
!ll&&!rl&&r
10161
MC/DC50%1/2
$dbh->{"Active"} and not $dbh->{"AutoCommit"}
$dbh->{"Active"} not $dbh->{"AutoCommit"}
Truth table66%2/3
A and not(B)
A= $dbh->{"Active"}B= not $dbh->{"AutoCommit"}
ABresult
0X0
100
111
277 }
278  
279 26 1;
« Session/Store/SQLite.pm ↑ Summary Session/_common.pm »