Session/PgJSON.pm

filter: Statementstmt 96.7% 209 / 216 Branchbran 79.5% 70 / 88 Conditioncond 88.5% 54 / 61 MC/DCmcdc 73.5% 25 / 34 Subroutinesub 100% 33 / 33 Podpod 62.5% 5 / 8 totaltotal 90.0% 396 / 440 CC 71 SCAR 21.8
CC
71
Cov
91%
deleteIfLowerThan
20.8
_searchOnQuery
15.0
updateKeys
10.0
CRAP 8.9
« Session/Store/Postgres.pm ↑ Summary Session/MariaDBJSON.pm »
1 package Web::Session::PgJSON;
2  
3 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 10 ▶use Apache::Session;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use Apache::Session::Lock::Null;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use Web::Session::Store::Postgres;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use Web::Session::_common;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use Web::Session::Generate::SHA256;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use Web::Session::Serialize::JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use JSON qw(to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 10 our $VERSION = '1.2.0';
14 10 our @ISA = qw(Apache::Session);
15  
16 50 ▶sub populate {
Subroutine populate: called CC=1 SCAR=0.0
Pod undocumented
17 50 my $self = shift;
18  
19 $self->{object_store} =
20 50 new Web::Session::Store::Postgres $self;
21 50 $self->{lock_manager} = new Apache::Session::Lock::Null $self;
22 50 $self->{generate} = \&Web::Session::Generate::SHA256::generate;
23 50 $self->{validate} = \&Web::Session::Generate::SHA256::validate;
24 50 $self->{serialize} = \&Web::Session::Serialize::JSON::serialize;
25 50 $self->{unserialize} = \&Web::Session::Serialize::JSON::unserialize;
26  
27 50 return $self;
28 }
29  
30 27 ▶sub searchOn {
Subroutine searchOn: called CC=3 SCAR=11.0
Pod documented
31 27 my ( $class, $args, $selectField, $value, @fields ) = @_;
32 27 my ( $dbh, $loan ) = $class->_borrowDbh($args);
33 27 ▶ if ( $args->{GinIndex} and !$class->_jsonbColumn( $args, $dbh ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"GinIndex"} and not $class->_jsonbColumn($args, $dbh)) 2 25 27
Condition100%3/3
$args->{"GinIndex"} and not $class->_jsonbColumn($args, $dbh)
!ll&&!rl&&r
2142
MC/DC100%2/2
$args->{"GinIndex"} and not $class->_jsonbColumn($args, $dbh)
$args->{"GinIndex"} not $class->_jsonbColumn($args, $dbh)
Truth table100%3/3
A and not(B)
A= $args->{"GinIndex"}B= not $class->_jsonbColumn($args, $dbh)
ABresult
0X0
100
111
34 2 $args = { %$args };
35 2 delete $args->{GinIndex};
36 }
37 27 return $class->_queryDbh( $dbh, $args,
38 $class->_searchOnQuery( $args, $selectField, $value ), @fields );
39 }
40  
41 # With GinIndex, add jsonb containment conditions that can use a GIN index
42 # on a_session. "->>" also returns the text of numbers and booleans, so a
43 # value that looks like one of them is searched in both forms. The "->>"
44 # comparison is kept: results are exactly the same as without GinIndex.
45 73 ▶sub _searchOnQuery {
Subroutine _searchOnQuery: called CC=15 SCAR=27.1
46 73 my ( $class, $args, $field, $value ) = @_;
47 73 my $f = $class->_sqlField($field);
48  
49 # "->>" returns arrays and objects as JSON text; jsonb rejects NUL
50 return { query => "$f =?", values => [$value] }
51 unless ( $args->{GinIndex}
52 73 ▶ and defined($value)
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"GinIndex"} and defined $value and not $value =~ /^[\[{]/ and not "$field$value" =~ /\0/ 32 41 73
Condition100%9/9
$args->{"GinIndex"} and defined $value and not $value =~ /^[\[{]/ and not "$field$value" =~ /\0/
!ll&&!rl&&r
30241
$args->{"GinIndex"} and defined $value and not $value =~ /^[\[{]/
!ll&&!rl&&r
28243
$args->{"GinIndex"} and defined $value
!ll&&!rl&&r
27145
MC/DC100%4/4
$args->{"GinIndex"} and defined $value and not $value =~ /^[\[{]/ and not "$field$value" =~ /\0/
$args->{"GinIndex"} defined $value not $value =~ /^[\[{]/ not "$field$value" =~ /\0/
Truth table100%5/5
A and B and not(C) and not(D)
A= $args->{"GinIndex"}B= defined $valueC= not $value =~ /^[\[{]/D= not "$field$value" =~ /\0/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
53 and $value !~ /^[\[{]/
54 and "$field$value" !~ /\0/ );
55  
56 # A caller may pass the UTF-8 bytes of a non-ASCII field or value without
57 # the UTF-8 flag: to_json() would then read them as Latin-1 and the JSON
58 # document wouldn't match the stored data. Decode copies, used only to
59 # build the documents: the "->>" recheck keeps the arguments as given,
60 # like the query used without GinIndex.
61 41 my ( $dfield, $dvalue ) = ( $field, $value );
62 41 for ( $dfield, $dvalue ) {
63 82 ▶ if ( !utf8::is_utf8($_) and /[\x80-\xff]/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not utf8::is_utf8($_) and /[\x80-\xff]/) 6 76 82
Condition100%3/3
not utf8::is_utf8($_) and /[\x80-\xff]/
!ll&&!rl&&r
1756
MC/DC100%2/2
not utf8::is_utf8($_) and /[\x80-\xff]/
not utf8::is_utf8($_) /[\x80-\xff]/
Truth table100%3/3
not(A) and B
A= not utf8::is_utf8($_)B= /[\x80-\xff]/
ABresult
0X0
100
111
64 6 my $decoded = $_;
65 6 ▶ $_ = $decoded if ( utf8::decode($decoded) );
Branch: 1 branch
BranchTrueFalseTotal
if utf8::decode($decoded) 3 3 6
66 }
67 }
68  
69 # Numbers beyond PostgreSQL numeric limits can't be stored in jsonb
70 41 ▶ my $literal = $value =~ /^(?:true|false)\z/
Condition100%11/11
$value =~ /^(?:true|false)\z/ || $value =~ /^-?(0|[1-9][0-9]*)(?:\.([0-9]+))?\z/ && length $1 <= 131072 && length($2 // '') <= 16383
l!l&&r!l&&!r
2831
$value =~ /^-?(0|[1-9][0-9]*)(?:\.([0-9]+))?\z/ and length $1 <= 131072 and length($2 // "") <= 16383
!ll&&!rl&&r
2928
$value =~ /^-?(0|[1-9][0-9]*)(?:\.([0-9]+))?\z/ and length $1 <= 131072
!ll&&!rl&&r
27210
$2 // ""
l!l
55
MC/DC100%4/4
$value =~ /^(?:true|false)\z/ || $value =~ /^-?(0|[1-9][0-9]*)(?:\.([0-9]+))?\z/ && length $1 <= 131072 && length($2 // '') <= 16383
$value =~ /^(?:true|false)\z/ $value =~ /^-?(0|[1-9][0-9]*)(?:\.([0-9]+))?\z/ length $1 <= 131072 $2
Truth table100%5/5
A || B and C and D
A= $value =~ /^(?:true|false)\z/B= $value =~ /^-?(0|[1-9][0-9]*)(?:\.([0-9]+))?\z/C= length $1 <= 131072D= $2
ABCDresult
1XXX1
01111
00XX0
010X0
01100
71 || ( $value =~ /^-?(0|[1-9][0-9]*)(?:\.([0-9]+))?\z/
72 and length($1) <= 131072
73 and length( $2 // '' ) <= 16383 );
74 41 my @docs = ( to_json( { $dfield => "$dvalue" } ) );
75 41 ▶ push @docs, '{' . to_json( "$dfield", { allow_nonref => 1 } ) . ":$value}"
Branch: 1 branch
BranchTrueFalseTotal
if $literal 10 31 41
76 if ($literal);
77  
78 # JSON::PP doesn't flag its result as UTF-8 when it holds only Latin-1
79 # characters: DBD::Pg would then send Latin-1 bytes
80 41 utf8::upgrade($_) foreach (@docs);
81 return {
82 41 query => '('
83 . join( ' OR ', ('a_session @> ?::jsonb') x @docs )
84 . ") AND $f =?",
85 values => [ @docs, $value ],
86 };
87 }
88  
89 # The "a_session @> ..." conditions need a jsonb column: with a json column
90 # every searchOn() would fail. Look the type up once per handle and table,
91 # warn and fall back to the plain query when it is not jsonb. An unknown type
92 # (table not created yet) isn't cached. $dbh (required) is the handle of the
93 # caller's query, from _borrowDbh(): the caller keeps the loan until its query
94 # is done.
95 6 ▶sub _jsonbColumn {
Subroutine _jsonbColumn: called CC=5 SCAR=16.1
96 6 my ( $class, $args, $dbh ) = @_;
97 6 ▶ my $table = $args->{TableName} || $Apache::Session::Store::DBI::TableName;
Condition66%2/3
$args->{'TableName'} || $Apache::Session::Store::DBI::TableName
l!l&&r!l&&!r
510
MC/DC0%0/2
$args->{'TableName'} || $Apache::Session::Store::DBI::TableName
$args->{'TableName'} $Apache::Session::Store::DBI::TableName
Truth table66%2/3
A || B
A= $args->{'TableName'}B= $Apache::Session::Store::DBI::TableName
ABresult
1X1
011
000
98 6 ▶ my $known = defined( ( $dbh->{private_asb_pgjson_type} || {} )->{$table} );
Condition100%2/2
$dbh->{'private_asb_pgjson_type'} || {}
l!l
24
MC/DC100%1/1
$dbh->{'private_asb_pgjson_type'} || {}
$dbh->{'private_asb_pgjson_type'}
Truth table100%2/2
A
A= $dbh->{'private_asb_pgjson_type'}
Aresult
11
00
99 6 my $type = $class->_columnType( $args, $dbh );
100 6 ▶ warn "GinIndex ignored: $table.a_session is not jsonb\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $known or $type eq "jsonb" 2 4 6
Condition100%3/3
$known or $type eq "jsonb"
l!l&&r!l&&!r
132
MC/DC100%2/2
$known or $type eq "jsonb"
$known $type eq "jsonb"
Truth table100%3/3
A or B
A= $knownB= $type eq "jsonb"
ABresult
1X1
011
000
101 unless ( $known or $type eq 'jsonb' );
102 6 return $type eq 'jsonb';
103 }
104  
105 # Type of the a_session column (jsonb, json, text...), '' if unknown, see
106 # _jsonbColumn()
107 14 ▶sub _columnType {
Subroutine _columnType: called CC=5 SCAR=16.1
108 14 my ( $class, $args, $dbh ) = @_;
109 14 ▶ my $table = $args->{TableName} || $Apache::Session::Store::DBI::TableName;
Condition66%2/3
$args->{'TableName'} || $Apache::Session::Store::DBI::TableName
l!l&&r!l&&!r
1310
MC/DC0%0/2
$args->{'TableName'} || $Apache::Session::Store::DBI::TableName
$args->{'TableName'} $Apache::Session::Store::DBI::TableName
Truth table66%2/3
A || B
A= $args->{'TableName'}B= $Apache::Session::Store::DBI::TableName
ABresult
1X1
011
000
110 14 ▶ my $cache = $dbh->{private_asb_pgjson_type} ||= {};
Condition100%2/2
$dbh->{"private_asb_pgjson_type"} ||= {}
l!l
410
MC/DC100%1/1
$dbh->{"private_asb_pgjson_type"} ||= {}
$dbh->{"private_asb_pgjson_type"}
Truth table100%2/2
A
A= $dbh->{"private_asb_pgjson_type"}
Aresult
11
00
111 14 ▶ unless ( defined $cache->{$table} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cache->{$table}) 11 3 14
112 11 ( $cache->{$table} ) = $dbh->selectrow_array(
113 q{SELECT t.typname FROM pg_attribute a
114 JOIN pg_type t ON t.oid = a.atttypid
115 WHERE a.attrelid = to_regclass(?) AND a.attname = 'a_session'
116 AND NOT a.attisdropped},
117 undef, $table
118 );
119 }
120 14 ▶ return $cache->{$table} // '';
Condition100%2/2
$cache->{$table} // ""
l!l
131
MC/DC100%1/1
$cache->{$table} // ""
$cache->{$table}
Truth table100%2/2
A
A= $cache->{$table}
Aresult
11
00
121 }
122  
123 # One statement, the session is not read: the keys that are not in $changes
124 # keep the value the database holds, also when another process changed them
125 # after the caller read the session. json and text columns go through jsonb
126 13 ▶sub updateKeys {
Subroutine updateKeys: called CC=10 SCAR=23.0
Pod documented
127 13 my ( $class, $args, $id, $changes ) = @_;
128 13 ▶ die "updateKeys: no session id\n" unless ( defined $id and length $id );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 2 11 13
Condition100%3/3
defined $id and length $id
!ll&&!rl&&r
1111
MC/DC100%2/2
defined $id and length $id
defined $id length $id
Truth table100%3/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
129 11 ▶ die "updateKeys: changes must be a non-empty hash\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $changes eq "HASH" and %$changes 2 9 11
Condition100%3/3
ref $changes eq "HASH" and %$changes
!ll&&!rl&&r
119
MC/DC100%2/2
ref $changes eq "HASH" and %$changes
ref $changes eq "HASH" %$changes
Truth table100%3/3
A and B
A= ref $changes eq "HASH"B= %$changes
ABresult
0X0
100
111
130 unless ( ref $changes eq 'HASH' and %$changes );
131 die "updateKeys: _session_id can't be changed\n"
132 9 ▶ if ( exists $changes->{_session_id} );
Branch: 1 branch
BranchTrueFalseTotal
if exists $changes->{"_session_id"} 1 8 9
133 8 my @delete = sort grep { !defined $changes->{$_} } keys %$changes;
134 11 my %set = map { ( $_ => $changes->{$_} ) }
135 8 grep { defined $changes->{$_} } keys %$changes;
136 8 my $json = Web::Session::Serialize::JSON::serialize( { data => \%set } );
137  
138 8 my ( $dbh, $loan ) = $class->_borrowDbh($args);
139 8 my $table = Web::Session::_common->_tableName( $dbh, $args );
140 8 my $jsonb = $class->_columnType( $args, $dbh ) eq 'jsonb';
141 8 ▶ my $value = '(' . ( $jsonb ? 'a_session' : 'a_session::jsonb' )
Branch: 1 branch
BranchTrueFalseTotal
$jsonb ? : 5 3 8
142 . ' || ?::jsonb) - ?::text[]';
143 8 ▶ $value = "($value)::json" unless ($jsonb);
Branch: 1 branch
BranchTrueFalseTotal
unless $jsonb 3 5 8
144 8 my $n = $dbh->do( "UPDATE $table SET a_session = $value WHERE id = ?",
145 undef, $json, \@delete, $id );
146 8 ▶ return ( $n and $n > 0 ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n && $n > 0 ? : 5 3 8
Condition66%2/3
$n and $n > 0
!ll&&!rl&&r
035
MC/DC50%1/2
$n and $n > 0
$n $n > 0
Truth table66%2/3
A and B
A= $nB= $n > 0
ABresult
0X0
100
111
147 }
148  
149 2 ▶sub searchOnExpr {
Subroutine searchOnExpr: called CC=1 SCAR=0.0
Pod undocumented
150 2 my ( $class, $args, $selectField, $value, @fields ) = @_;
151 2 $value =~ s/\*/%/g;
152 2 my $query = {
153 query => $class->_sqlField($selectField) . ' like ?',
154 values => [$value]
155 };
156 2 return $class->_query( $args, $query, @fields );
157 }
158  
159 35 ▶sub searchLt {
Subroutine searchLt: called CC=1 SCAR=0.0
Pod documented
160 35 my $class = shift;
161 35 return $class->_searchCompare( '<', @_ );
162 }
163  
164 11 ▶sub searchGt {
Subroutine searchGt: called CC=1 SCAR=0.0
Pod documented
165 11 my $class = shift;
166 11 return $class->_searchCompare( '>', @_ );
167 }
168  
169 # $value is checked, then inserted like deleteIfLowerThan() thresholds: bound,
170 # it would be typed bigint and decimal values would fail
171 46 ▶sub _searchCompare {
Subroutine _searchCompare: called CC=2 SCAR=6.9
172 46 my ( $class, $op, $args, $selectField, $value, @fields ) = @_;
173 46 $value =
174 Web::Session::_common->_checkSearchValue( $op, $value );
175 46 ▶ return {} unless ( defined $value );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 24 22 46
176 22 my $query = {
177 query => $class->_buildCompareExpression( $selectField, $op, $value ),
178 values => []
179 };
180 return Web::Session::_common->_searchQuery(
181 $op,
182 22 ▶ sub { $class->_query( $args, $query, @fields ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
183 9 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
184 9 Web::Session::_common::_searchByTest( $class, $args, $selectField,
185 Web::Session::_common->_compareTest( $op, $value ), @fields );
186 }
187 22 );
188 }
189  
190 6 ▶sub _query {
Subroutine _query: called CC=1 SCAR=0.0
191 6 my ( $class, $args, $query, @fields ) = @_;
192 6 my ( $dbh, $loan ) = $class->_borrowDbh($args);
193 6 return $class->_queryDbh( $dbh, $args, $query, @fields );
194 }
195  
196 # Same as _query() with an already connected handle
197 29 ▶sub _queryDbh {
Subroutine _queryDbh: called CC=6 SCAR=18.1
198 29 my ( $class, $dbh, $args, $query, @fields ) = @_;
199 29 my %res = ();
200  
201 29 my $table_name =
202 Web::Session::_common->_tableName( $dbh, $args );
203  
204 29 my $sth;
205 my $fields =
206 @fields
207 ? join( ',',
208 'id',
209 29 ▶ map { $class->_sqlField($_) . ' AS ' . $class->_sqlAlias($_) } @fields )
Branch: 1 branch
BranchTrueFalseTotal
@fields ? : 2 27 29
210 : '*';
211 29 $sth =
212 $dbh->prepare("SELECT $fields from $table_name where $query->{query}");
213 29 $sth->execute( @{ $query->{values} } );
214  
215 27 ▶ my $res = $sth->fetchall_hashref('id') or return {};
Branch: 1 branch
BranchTrueFalseTotal
my $res = $sth->fetchall_hashref("id") or return {} 27 0 27
216 27 ▶ unless (@fields) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@fields) 25 2 27
217 25 my $sub = Web::Session::_common::_unserializer($class);
218 25 foreach my $s ( keys %$res ) {
219 49 eval {
220 49 my $tmp = &$sub( { serialized => $res->{$s}->{a_session} } );
221 49 $res->{$s} = $tmp;
222 };
223 49 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 49 49
224 0 print STDERR "Error in session $s: $@\n";
225 0 delete $res->{$s};
226 }
227 }
228 }
229 27 return $res;
230 }
231  
232 16 ▶sub deleteIfLowerThan {
Subroutine deleteIfLowerThan: called CC=18 SCAR=30.4
Pod documented
233 16 my ( $class, $args, $rule ) = @_;
234 16 ▶ return wantarray ? ( 0, 0 ) : 0
Branch: 2 branches
BranchTrueFalseTotal
unless "Web::Session::_common"->_checkRule($rule) and "Web::Session::_common"->_checkThresholds($rule) 0 16 16
wantarray ? : 0 0 0
Condition33%1/3
"Web::Session::_common"->_checkRule($rule) and "Web::Session::_common"->_checkThresholds($rule)
!ll&&!rl&&r
0016
MC/DC0%0/2
"Web::Session::_common"->_checkRule($rule) and "Web::Session::_common"->_checkThresholds($rule)
"Web::Session::_common"->_checkRule($rule) "Web::Session::_common"->_checkThresholds($rule)
Truth table33%1/3
A and B
A= "Web::Session::_common"->_checkRule($rule)B= "Web::Session::_common"->_checkThresholds($rule)
ABresult
0X0
100
111
235 unless ( Web::Session::_common->_checkRule($rule)
236 and Web::Session::_common->_checkThresholds($rule) );
237 16 my ( $query, @bind );
238 16 ▶ if ( $rule->{or} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rule->{'or'}) { } 16 0 16
elsif ($rule->{'and'}) { } 0 0 0
239 $query = join ' OR ', map {
240 16 $class->_buildLowerThanExpression( $_, $rule->{or}->{$_} )
241 }
242 16 keys %{ $rule->{or} };
243 }
244 elsif ( $rule->{and} ) {
245 $query = join ' AND ', map {
246 0 $class->_buildLowerThanExpression( $_, $rule->{and}->{$_} )
247 }
248 0 keys %{ $rule->{and} };
249 }
250 16 ▶ return wantarray ? ( 0, 0 ) : 0 unless ($query);
Branch: 2 branches
BranchTrueFalseTotal
unless $query 0 16 16
wantarray ? : 0 0 0
251 16 ▶ if ( $rule->{not} and keys %{ $rule->{not} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rule->{"not"} and keys %{$$rule{"not"};}) 12 4 16
Condition66%2/3
$rule->{"not"} and keys %{$$rule{"not"};}
!ll&&!rl&&r
4012
MC/DC50%1/2
$rule->{"not"} and keys %{$$rule{"not"};}
$rule->{"not"} keys %{$$rule{"not"};}
Truth table66%2/3
A and B
A= $rule->{"not"}B= keys %{$$rule{"not"};}
ABresult
0X0
100
111
252 $query = "($query) AND " . join(
253 ' AND ',
254 map {
255 12 push @bind, $rule->{not}->{$_};
256 12 my $f = $class->_sqlField($_);
257 12 "($f IS NULL OR $f <> ?)"
258 }
259 12 keys %{ $rule->{not} }
260 );
261 }
262  
263 # Delete by batches: a single DELETE on hundreds of thousands of sessions
264 # is one long transaction (WAL spike, locks held, replication lag). Each
265 # batch is its own statement (class methods' connections are AutoCommit).
266 # The WHERE expression is the same as before, so the expression indexes
267 # are still usable by the sub-select. Rows deleted by a concurrent purge
268 # are simply not counted.
269 16 my $total = 0;
270 16 my $ok = eval {
271  
272 # Held for all the batches. A pooled connection is given back when
273 # $loan goes out of scope, also when a batch dies (it is then closed:
274 # see _flagError() in Store/Postgres.pm)
275 16 my ( $dbh, $loan ) = $class->_borrowDbh($args);
276 16 my $table_name =
277 Web::Session::_common->_tableName( $dbh, $args );
278 16 my $limit = Web::Session::_common->_batchSize;
279 16 my $sql = $class->_deleteBatchStatement( $table_name, $query, $limit );
280 16 while (1) {
281 26 my $n = $dbh->do( $sql, undef, @bind );
282 22 ▶ return 0 unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 1 21 22
283  
284 # Count unknown to the driver: a short batch can't be detected,
285 # go on while a session still matches
286 21 ▶ if ( $n == -1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n == -1) 3 18 21
287 last
288 3 ▶ unless $dbh->selectrow_array(
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->selectrow_array("SELECT 1 FROM $table_name WHERE $query LIMIT 1", undef, @bind) 1 2 3
289 "SELECT 1 FROM $table_name WHERE $query LIMIT 1",
290 undef, @bind );
291 2 next;
292 }
293 18 $total += $n;
294  
295 # A short batch means that nothing else matches (an exact
296 # multiple of the batch size costs one more, empty, batch)
297 18 ▶ last if $n < $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $n < $limit 10 8 18
298 }
299 11 1;
300 };
301 16 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 5 11 16
302 5 ▶ print STDERR "deleteIfLowerThan: $@\n" if ($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 4 1 5
303 5 ▶ return wantarray ? ( 0, $total ) : 0;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 4 1 5
304 }
305 11 ▶ return wantarray ? ( 1, $total ) : 1;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 8 3 11
306 }
307  
308 # Statement of one batch of deleteIfLowerThan(), $where being the rule
309 16 ▶sub _deleteBatchStatement {
Subroutine _deleteBatchStatement: called CC=1 SCAR=0.0
310 16 my ( $class, $table_name, $where, $limit ) = @_;
311 16 return "DELETE FROM $table_name WHERE id IN "
312 . "(SELECT id FROM $table_name WHERE $where LIMIT $limit)";
313 }
314  
315 18 ▶sub get_key_from_all_sessions {
Subroutine get_key_from_all_sessions: called CC=4 SCAR=14.0
Pod undocumented
316 18 my ( $class, $args, $data ) = @_;
317  
318 # Held until the end of the call, callbacks included: a callback that
319 # ties a session or calls a class method gets another connection of the
320 # pool, never this one (lent, it is not idle). $loan gives it back when
321 # this method returns or dies
322 18 my ( $dbh, $loan ) = $class->_borrowDbh($args);
323 18 my $table_name =
324 Web::Session::_common->_tableName( $dbh, $args );
325 18 my $sth;
326  
327 # Special case if all wanted fields are indexed
328 18 ▶ if ( $data and ref($data) ne 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data and ref $data ne "CODE") 2 16 18
Condition100%3/3
$data and ref $data ne "CODE"
!ll&&!rl&&r
2142
MC/DC100%2/2
$data and ref $data ne "CODE"
$data ref $data ne "CODE"
Truth table100%3/3
A and B
A= $dataB= ref $data ne "CODE"
ABresult
0X0
100
111
329 2 ▶ $data = [$data] unless ( ref($data) );
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data 0 2 2
330 my $fields = join ',', 'id',
331 2 map { $class->_sqlField($_) . ' AS ' . $class->_sqlAlias($_) } @$data;
332 2 $sth = $dbh->prepare("SELECT $fields from $table_name");
333 2 $sth->execute;
334 2 return $sth->fetchall_hashref('id');
335 }
336 16 my %res;
337 16 my $sub = Web::Session::_common::_unserializer($class);
338 Web::Session::_common->_forEachSession(
339 $dbh,
340 $table_name,
341 28 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=20.8
342 28 my @row = @_;
343 28 eval {
344 28 my $tmp = &$sub( { serialized => $row[1] } );
345 28 ▶ if ( ref($data) eq 'CODE' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'CODE') { } 24 4 28
elsif ($data) { } 0 4 4
346 24 $tmp = &$data( $tmp, $row[0] );
347 17 ▶ $res{ $row[0] } = $tmp if ( defined($tmp) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $tmp 17 0 17
348 }
349 elsif ($data) {
350 0 ▶ $data = [$data] unless ( ref($data) );
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data 0 0 0
351 0 $res{ $row[0] }->{$_} = $tmp->{$_} foreach (@$data);
352 }
353 else {
354 4 $res{ $row[0] } = $tmp;
355 }
356 };
357 28 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 7 21 28
358 7 print STDERR "Error in session $row[0]: $@\n";
359 7 delete $res{ $row[0] };
360 }
361 }
362 16 );
363 15 return \%res;
364 }
365  
366 20 ▶sub _buildLowerThanExpression {
Subroutine _buildLowerThanExpression: called CC=1 SCAR=0.0
367 20 my ( $class, $field, $value ) = @_;
368 20 return $class->_buildCompareExpression( $field, '<', $value );
369 }
370  
371 # Must match the documented expression indexes (_utime, _lastSeen). $op is
372 # "<" or ">", $value a number checked by the caller
373 62 ▶sub _buildCompareExpression {
Subroutine _buildCompareExpression: called CC=1 SCAR=0.0
374 62 my ( $class, $field, $op, $value ) = @_;
375 62 Web::Session::_common->_checkOp($op);
376 50 my $f = $class->_sqlField($field);
377 50 return "cast($f as bigint) $op $value";
378 }
379  
380 # Build SQL expression to get a field from a_session
381 141 ▶sub _sqlField {
Subroutine _sqlField: called CC=2 SCAR=6.9
382 141 my ( $class, $field ) = @_;
383  
384 # With standard_conforming_strings=off, backslashes are escape characters
385 # in plain literals: use an escape string literal in this case
386 141 ▶ if ( $field =~ /\\/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field =~ /\\/) 1 140 141
387 1 $field =~ s/(['\\])/$1$1/g;
388 1 return "a_session ->> E'$field'";
389 }
390 140 $field =~ s/'/''/g;
391 140 return "a_session ->> '$field'";
392 }
393  
394 # Build a column alias that preserves field name case
395 4 ▶sub _sqlAlias {
Subroutine _sqlAlias: called CC=1 SCAR=0.0
396 4 my ( $class, $field ) = @_;
397 4 $field =~ s/"/""/g;
398 4 return qq{"$field"};
399 }
400  
401 # Connection of a class method: returns ( $dbh, $loan ). Keep $loan until
402 # the handle is no longer needed: when the connection pool of
403 # Web::Session::Store::Postgres applies (see _classPool()), $dbh is lent by
404 # the pool and given back when $loan is freed, so at the end of the call,
405 # also when it dies. Otherwise $dbh is the handle of _classDbh() and $loan is
406 # undef.
407 55 ▶sub _borrowDbh {
Subroutine _borrowDbh: called CC=3 SCAR=11.0
408 55 my ( $class, $args ) = @_;
409 55 ▶ return ( $class->_classDbh($args), undef )
Branch: 1 branch
BranchTrueFalseTotal
unless $class->_classPool($args) 13 42 55
410 unless ( $class->_classPool($args) );
411 42 ▶ $args->{DataSource} or die "No datasource given !";
Branch: 1 branch
BranchTrueFalseTotal
$args->{"DataSource"} or die "No datasource given !" 42 0 42
412 42 my $loan = Web::Session::Store::Postgres->_lend($args);
413 42 return ( $loan->{dbh}, $loan );
414 }
415  
416 # Whether class methods borrow their connection from the pool: with the
417 # arguments that make sessions use it (see _poolApplies() in
418 # Store/Postgres.pm). A subclass whose sessions don't use the pool overrides
419 # it (Web::Session::Patroni)
420 50 ▶sub _classPool {
Subroutine _classPool: called CC=1 SCAR=0.0
421 50 my ( $class, $args ) = @_;
422 50 return Web::Session::Store::Postgres::_poolApplies($args);
423 }
424  
425 # Handle cached by DBI connect_cached(), used by class methods when the pool
426 # doesn't apply (see _borrowDbh())
427 14 ▶sub _classDbh {
Subroutine _classDbh: called CC=3 SCAR=11.2
428 14 my ( $class, $args ) = @_;
429  
430 14 ▶ my $datasource = $args->{DataSource} or die "No datasource given !";
Branch: 1 branch
BranchTrueFalseTotal
my $datasource = $args->{"DataSource"} or die "No datasource given !" 14 0 14
431 14 my $username = $args->{UserName};
432 14 my $password = $args->{Password};
433 14 ▶ my $dbh = DBI->connect_cached(
Condition50%1/2
'DBI'->connect_cached(Web::Session::_common::_pgDataSource($datasource), $username, $password, 'Web::Session::_common'->_forkSafeAttr({'RaiseError', 1, 'AutoCommit', 1})) || die($DBI::errstr)
l!l
140
MC/DC0%0/1
'DBI'->connect_cached(Web::Session::_common::_pgDataSource($datasource), $username, $password, 'Web::Session::_common'->_forkSafeAttr({'RaiseError', 1, 'AutoCommit', 1})) || die($DBI::errstr)
'DBI'->connect_cached(Web::Session::_common::_pgDataSource($datasource), $username, $password, 'Web::Session::_common'->_forkSafeAttr({'RaiseError', 1, 'AutoCommit', 1}))
Truth table50%1/2
A
A= 'DBI'->connect_cached(Web::Session::_common::_pgDataSource($datasource), $username, $password, 'Web::Session::_common'->_forkSafeAttr({'RaiseError', 1, 'AutoCommit', 1}))
Aresult
11
00
434 Web::Session::_common::_pgDataSource($datasource),
435 $username,
436 $password,
437 Web::Session::_common->_forkSafeAttr(
438 { RaiseError => 1, AutoCommit => 1 }
439 )
440 ) || die $DBI::errstr;
441 14 $dbh->{pg_enable_utf8} = 1;
442 14 return $dbh;
443 }
444  
445 10 1;
446 __END__
« Session/Store/Postgres.pm ↑ Summary Session/MariaDBJSON.pm »