DB2/Storage.pm

filter: Statementstmt 91.5% 152 / 166 Branchbran 78.2% 61 / 78 Conditioncond 54.8% 51 / 93 MC/DCmcdc 27.4% 14 / 51 Subroutinesub 83.3% 25 / 30 Podpod 85.7% 6 / 7 totaltotal 72.7% 309 / 425 CC 78 SCAR 22.6
CC
78
Cov
78%
_prep_for_execute
18.3
_ident_table_name
17.0
_bind_host_into_dsn
16.0
CRAP 9.6
« DB2/Diff/Column.pm ↑ Summary DB2/Introspect/Indexes.pm »
1 package DBIO::DB2::Storage;
2 # ABSTRACT: IBM DB2 support for DBIO
3  
4 14 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 14 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 14 our $VERSION = '0.900007';
8  
9 14 ▶use base qw/DBIO::Storage::DBI/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 14 ▶use mro 'c3';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 14 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 14 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 14 ▶use DBIO::Exception ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 14 ▶use DBIO::DB2::Storage::Cursor ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 14 __PACKAGE__->register_driver('DB2' => __PACKAGE__);
18  
19 14 __PACKAGE__->datetime_parser_type('DBIO::DB2::Storage::DateTimeFormat');
20 14 __PACKAGE__->sql_quote_char ('"');
21 14 __PACKAGE__->sql_maker_class('DBIO::DB2::SQLMaker');
22 14 __PACKAGE__->cursor_class('DBIO::DB2::Storage::Cursor');
23  
24 0 ▶sub sqlt_type { 'DB2' }
Subroutine sqlt_type: not called CC=1 SCAR=6.9
Pod documented
25  
26  
27 # lazy-default kind of thing
28 28 ▶sub sql_name_sep {
Subroutine sql_name_sep: called CC=4 SCAR=17.9
Pod documented
29 28 my $self = shift;
30  
31 28 my $v = $self->next::method(@_);
32  
33 28 ▶ if (! defined $v and ! @_) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v or @_) 0 28 28
Condition33%1/3
defined $v or @_
l!l&&r!l&&!r
2800
MC/DC0%0/2
defined $v or @_
defined $v @_
Truth table33%1/3
A or B
A= defined $vB= @_
ABresult
1X1
011
000
34 0 ▶ $v = $self->next::method($self->_dbh_get_info('SQL_QUALIFIER_NAME_SEPARATOR') || '.');
Condition0%0/2
$self->_dbh_get_info('SQL_QUALIFIER_NAME_SEPARATOR') || '.'
l!l
00
MC/DC0%0/1
$self->_dbh_get_info('SQL_QUALIFIER_NAME_SEPARATOR') || '.'
$self->_dbh_get_info('SQL_QUALIFIER_NAME_SEPARATOR')
Truth table0%0/2
A
A= $self->_dbh_get_info('SQL_QUALIFIER_NAME_SEPARATOR')
Aresult
11
00
35 }
36  
37 28 return $v;
38 }
39  
40  
41  
42 21 ▶sub _connect_params_dsn {
Subroutine _connect_params_dsn: called CC=5 SCAR=16.1
43 21 my ($self, $driver, $params) = @_;
44  
45 21 my ($dbname, $host, $port) = @{$params}{qw(dbname host port)};
46  
47 21 my $forms = 'DBD::DB2 connects to a cataloged database alias '
48 . "(dbi:$driver:<dbname>) or, uncataloged, to a database on a server "
49 . "(dbi:$driver:DATABASE=<dbname>;HOSTNAME=<host>;PORT=<port>;PROTOCOL=TCPIP)";
50  
51 21 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dbname 6 15 21
52 'Cannot build a DBD::DB2 DSN from connection parameters without a '
53 . "dbname: $forms, and both need it. Give dbname, or supply a dsn instead."
54 ) unless defined $dbname;
55  
56 15 ▶ if (defined $host) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $host) 7 8 15
57 7 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless defined $port 2 5 7
58 'Cannot build a DBD::DB2 DSN from the connection parameters dbname and '
59 . "host without a port: $forms, and the uncataloged form has no implied "
60 . 'port. Give port as well, leave host out to connect through the '
61 . 'cataloged alias, or supply a dsn instead.'
62 ) unless defined $port;
63  
64 5 return "dbi:$driver:DATABASE=$dbname;HOSTNAME=$host;PORT=$port;PROTOCOL=TCPIP";
65 }
66  
67 $self->throw_exception(
68 8 ▶ 'Cannot build a DBD::DB2 DSN from the connection parameters dbname and '
Branch: 1 branch
BranchTrueFalseTotal
if defined $port 2 6 8
69 . "port without a host: $forms, and beside a cataloged alias the port would "
70 . 'be ignored -- the catalog decides where the connection goes. Give host '
71 . 'as well, leave port out, or supply a dsn instead.'
72 ) if defined $port;
73  
74 6 return "dbi:$driver:$dbname";
75 }
76  
77  
78 12 ▶sub _bind_host_into_dsn {
Subroutine _bind_host_into_dsn: called CC=16 SCAR=27.7
79 12 my ($self, $driver, $dsn, $host, $port) = @_;
80  
81 12 ▶ return (undef, 'a DSN without a dbi:Driver: prefix')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is 1 11 12
Condition66%2/3
defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
!ll&&!rl&&r
0111
MC/DC50%1/2
defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
defined $dsn $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
Truth table66%2/3
A and B
A= defined $dsnB= $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
ABresult
0X0
100
111
82 unless defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is;
83 11 my ($prefix, $rest) = ($1, $2);
84  
85 11 ▶ return (undef, 'a cataloged database alias; the server is not named in '
Branch: 1 branch
BranchTrueFalseTotal
if $rest =~ /^[^=;]+;*\z/ 2 9 11
86 . 'the DSN')
87 if $rest =~ /^[^=;]+;*\z/;
88  
89 9 my @parts = split /;/, $rest, -1;
90 9 my ($has_host, $has_port);
91 9 for my $part (@parts) {
92 30 ▶ next unless length $part;
Branch: 1 branch
BranchTrueFalseTotal
unless length $part 1 29 30
93 29 ▶ return (undef, 'a part without key=value form')
Branch: 1 branch
BranchTrueFalseTotal
unless $part =~ /^(\w+)=/ 1 28 29
94 unless $part =~ /^(\w+)=/;
95 28 my $key = lc $1;
96 28 ▶ $has_host = 1 if $key eq 'hostname';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "hostname" 8 20 28
97 28 ▶ $has_port = 1 if $key eq 'port';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "port" 6 22 28
98 }
99  
100 8 ▶ return (undef, 'a DSN without HOSTNAME=; the server is not named in the DSN')
Branch: 1 branch
BranchTrueFalseTotal
unless $has_host 1 7 8
101 unless $has_host;
102  
103 7 my @out;
104 7 for my $part (@parts) {
105 26 ▶ if ($part =~ /^(hostname)=/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($part =~ /^(hostname)=/i) { } 7 19 26
elsif (defined $port and $part =~ /^(port)=/i) { } 4 15 19
106 7 push @out, "$1=$host";
107 7 ▶ push @out, "PORT=$port" if defined $port and not $has_port;
Branch: 1 branch
BranchTrueFalseTotal
if defined $port and not $has_port 1 6 7
Condition100%3/3
defined $port and not $has_port
!ll&&!rl&&r
241
MC/DC100%2/2
defined $port and not $has_port
defined $port not $has_port
Truth table100%3/3
A and not(B)
A= defined $portB= not $has_port
ABresult
0X0
100
111
108 }
109 ▶ elsif (defined $port and $part =~ /^(port)=/i) {
Condition100%3/3
defined $port and $part =~ /^(port)=/i
!ll&&!rl&&r
5104
MC/DC100%2/2
defined $port and $part =~ /^(port)=/i
defined $port $part =~ /^(port)=/i
Truth table100%3/3
A and B
A= defined $portB= $part =~ /^(port)=/i
ABresult
0X0
100
111
110 4 push @out, "$1=$port";
111 }
112 else {
113 15 push @out, $part;
114 }
115 }
116  
117 7 return $prefix . join ';', @out;
118 }
119  
120  
121 # the class core blesses its HandleError into, to tell it from a foreign one
122 14 my $CORE_ERROR_HANDLER_CLASS = '__DBIO__DBH__ERROR__HANDLER__';
123  
124 22 ▶sub _connect {
Subroutine _connect: called CC=5 SCAR=16.8
125 22 my $self = shift;
126  
127 22 my $dbh = $self->next::method(@_);
128  
129 20 ▶ return $dbh if $self->unsafe;
Branch: 1 branch
BranchTrueFalseTotal
if $self->unsafe 2 18 20
130  
131 18 my $core_handler = $dbh->{HandleError};
132  
133 # core installs its handler anew on every _connect, so this never wraps a
134 # wrapper; anything else on the handle is not ours to touch
135 18 ▶ if (ref $core_handler eq $CORE_ERROR_HANDLER_CLASS) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $core_handler eq $CORE_ERROR_HANDLER_CLASS) 18 0 18
136 # DBD::DB2 leaves Statement empty on a handle for do(), and the SQL0605W
137 # message names the index that is already there, not the one refused: keep
138 # the text of the last do() for the warning (karr k47)
139 18 my $last_do;
140 18 ▶ my $user_do = $dbh->{Callbacks} && $dbh->{Callbacks}{do};
Condition66%2/3
$dbh->{'Callbacks'} && $dbh->{'Callbacks'}{'do'}
!ll&&!rl&&r
1701
MC/DC50%1/2
$dbh->{'Callbacks'} && $dbh->{'Callbacks'}{'do'}
$dbh->{'Callbacks'} $dbh->{'Callbacks'}{'do'}
Truth table66%2/3
A && B
A= $dbh->{'Callbacks'}B= $dbh->{'Callbacks'}{'do'}
ABresult
0X0
100
111
141 $dbh->{Callbacks} = {
142 18 ▶ %{ $dbh->{Callbacks} || {} },
Condition100%2/2
$dbh->{'Callbacks'} || {}
l!l
117
MC/DC100%1/1
$dbh->{'Callbacks'} || {}
$dbh->{'Callbacks'}
Truth table100%2/2
A
A= $dbh->{'Callbacks'}
Aresult
11
00
143 0 ▶ do => sub { $last_do = $_[1]; return $user_do ? $user_do->(@_) : () },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$user_do ? : 0 0 0
144 18 };
145  
146 19 ▶ $dbh->{HandleError} = bless sub {
Subroutine __ANON__: called CC=7 SCAR=20.5
147 # true = handled: DBI raises nothing and returns the method's value
148 19 ▶ return 1 if ($_[1]->state // '') =~ /^01/;
Branch: 1 branch
BranchTrueFalseTotal
if ($_[1]->state // "") =~ /^01/ 10 9 19
Condition50%1/2
$_[1]->state // ""
l!l
190
MC/DC0%0/1
$_[1]->state // ""
$_[1]->state
Truth table50%1/2
A
A= $_[1]->state
Aresult
11
00
149 # SQL0605W is a warning with an error state (42S11): no index made, as
150 # one is already there (karr k47, ADR 0010)
151 9 ▶ return _index_exists_warning($_[1], $last_do) if ($_[1]->state // '') eq '42S11'
Branch: 1 branch
BranchTrueFalseTotal
if ($_[1]->state // "") eq "42S11" and ($_[1]->err // 0) == 605 2 7 9
Condition57%4/7
($_[1]->state // "") eq "42S11" and ($_[1]->err // 0) == 605
!ll&&!rl&&r
702
$_[1]->state // ""
l!l
90
$_[1]->err // 0
l!l
20
MC/DC0%0/2
($_[1]->state // "") eq "42S11" and ($_[1]->err // 0) == 605
$_[1]->state $_[1]->err
Truth table33%1/3
A and B
A= $_[1]->stateB= $_[1]->err
ABresult
0X0
100
111
152 && ($_[1]->err // 0) == 605;
153 7 return $core_handler->(@_);
154 18 }, $CORE_ERROR_HANDLER_CLASS;
155 }
156  
157 18 return $dbh;
158 }
159  
160 # CREATE INDEX over columns an index already covers: SQL0605W, err 605, state
161 # 42S11 (not class 01, so the wrapper above does not take it), rv undef, no
162 # index made. It is no failure of the statement's purpose -- the columns are
163 # indexed -- so it is a warning naming index and table, and handled (true).
164 2 ▶sub _index_exists_warning {
Subroutine _index_exists_warning: called CC=6 SCAR=20.7
165 2 my ($h, $last_do) = @_;
166 2 my $id = qr/"(?:[^"]|"")+"|[^\s("]+/;
167 2 ▶ my ($index, $table) = ($h->{Statement} // $last_do // '')
Condition40%2/5
($h->{"Statement"} // $last_do) // ""
l!l
20
$h->{"Statement"} // $last_do
l!l&&r!l&&!r
200
MC/DC0%0/2
($h->{"Statement"} // $last_do) // ""
$h->{"Statement"} $last_do
Truth table33%1/3
A // B
A= $h->{"Statement"}B= $last_do
ABresult
1X1
011
000
168 =~ /\bINDEX\s+($id)\s+ON\s+($id)/i;
169 2 ▶ Carp::carp(sprintf 'DBIO::DB2: index %s on table %s was not created: %s',
Condition50%3/6
$index // "(unknown)"
l!l
20
$table // "(unknown)"
l!l
20
$h->errstr // "SQL0605W"
l!l
20
MC/DC0%0/1
$index // "(unknown)"
$index
MC/DC0%0/1
$table // "(unknown)"
$table
MC/DC0%0/1
$h->errstr // "SQL0605W"
$h->errstr
Truth table50%1/2
A
A= $index
Aresult
11
00
Truth table50%1/2
A
A= $table
Aresult
11
00
Truth table50%1/2
A
A= $h->errstr
Aresult
11
00
170 $index // '(unknown)', $table // '(unknown)', $h->errstr // 'SQL0605W');
171 2 return 1;
172 }
173  
174 0 ▶sub dbio_deploy_class { 'DBIO::DB2::Deploy' };
Subroutine dbio_deploy_class: not called CC=1 SCAR=6.9
Pod undocumented
175  
176 # F02 / F10 -- transactional DDL. This 0 is NOT the MySQL/Oracle kind, and the
177 # comment exists because judged by the engine alone it looks like one.
178 #
179 # Db2 LUW HAS transactional DDL. The COMMIT statement is the primary source and
180 # it says so by listing what a commit is FOR: "All changes made by the
181 # following statements executed during the unit of work are committed: ALTER,
182 # COMMENT, CREATE, DROP, GRANT, LOCK TABLE, REVOKE, SET INTEGRITY, and the data
183 # change statements (INSERT, DELETE, MERGE, UPDATE), including those nested in
184 # a query" (Db2 for Linux, UNIX and Windows SQL Reference, COMMIT statement,
185 # unchanged in 11.5.x and 12.1.x). A statement whose changes a COMMIT commits
186 # was uncommitted before it -- CREATE and DROP are in that list by name. The
187 # same topic names the rollback direction in passing: "The statement might be
188 # implicitly prepared again, as a result of DDL operations that are rolled back
189 # within the unit of work." ROLLBACK closes it: "All changes made to the
190 # database during the unit of work are backed out", with an exception list that
191 # holds only SET statements, sequence/identity values and global variables and
192 # no DDL at all, and -- for the savepoint form -- "Data and schema changes made
193 # since the savepoint was set are undone" (same Reference, ROLLBACK statement,
194 # both versions).
195 #
196 # It is an ENGINE fact, not a deployment fact. CLI/ODBC ships autocommit on
197 # ("AutoCommit = 1 | 0 ... Specifies whether the application commits each
198 # statement by default ... 1 = SQL_ATTR_AUTOCOMMIT_ON (default)", AutoCommit
199 # CLI/ODBC configuration keyword), but that is a DEFAULT for applications that
200 # never say otherwise -- the same topic warns about "overriding this default
201 # during runtime", which is precisely what txn_do does when it sets DBI's
202 # AutoCommit to 0 on the connection. No db2cli.ini or db2dsdriver.cfg setting
203 # can make the answer below true or false.
204 #
205 # Nor is there a per-statement exception to declare. The COMMIT topic singles
206 # out the statements that "behave differently than other data definition
207 # language (DDL) and data control language (DCL) statements ... only one of
208 # these statements is allowed within any one unit of work", and the list is
209 # CREATE/ALTER/DROP of SERVICE CLASS, THRESHOLD, WORK ACTION, WORK CLASS and
210 # WORKLOAD plus GRANT/REVOKE of workload privileges. This driver emits none of
211 # them, so _ddl_statement_is_transactional stays core's default.
212 #
213 # WHAT THE 0 IS FOR, then, is this driver's own deploy path. DB2 needs an
214 # existing database, so only a SCHEMA can be throwaway, and
215 # DBIO::DB2::Deploy::_build_target_model therefore deploys the compare schema
216 # through $self->_dbh -- the handle the storage itself owns. Every other
217 # transactional engine in this family (PostgreSQL, SQL Server, Firebird) builds
218 # its target model through DBIO::Deploy::Base::TempDatabase, which opens its
219 # own connection, and core deliberately never brackets a handle the storage
220 # does not own (_storage_owns_dbh). Oracle and Informix build on the live
221 # handle as this driver does, but their engines commit DDL implicitly, so DB2
222 # is the only driver in the family where a transactional engine and a
223 # throwaway build on the bracketable handle meet.
224 #
225 # That matters because the capability is read in two places, not one.
226 # DBIO::Deploy::Base::_execute_ddl would bracket only the migration DDL, which
227 # is exactly what a 1 is for -- but DBIO::DeploymentHandler::upgrade wraps its
228 # WHOLE body in txn_do, and that body is deploy_method->upgrade, i.e. diff THEN
229 # apply. So a 1 here does not merely make the migration atomic: it pulls
230 # CREATE SCHEMA DBIO_TEST_<pid>, the entire install DDL re-emitted into it, the
231 # SYSCAT introspection of it and the teardown DROPs into the same live unit of
232 # work as the migration -- a long transaction holding catalog locks open for
233 # throwaway work whose atomicity buys nothing.
234 #
235 # And none of it has been measured. No live Db2 was available when this was
236 # written, so two things behind a 1 are reasoned only. First, the diff's FK
237 # change is a drop-then-add PAIR on one name (DBIO::DB2::Diff::ForeignKey:
238 # ALTER TABLE t DROP FOREIGN KEY fk, then ALTER TABLE t ADD CONSTRAINT fk),
239 # which under a bracket lands in one unit of work; Db2 for z/OS has a code for
240 # exactly that shape -- "-679 THE OBJECT name CANNOT BE CREATED BECAUSE A DROP
241 # IS PENDING ON THE OBJECT" -- and no equivalent could be found in the LUW
242 # message set, which is not the same as knowing there is none. Second, the
243 # compare schema is created and dropped again inside what would become one unit
244 # of work. Both are cheap to settle against a server and impossible to settle
245 # without one.
246 #
247 # So: capable engine, deliberate no -- the SQLite entry in
248 # DBIO::Deploy::Base's TRANSACTIONAL DDL section, not the MySQL one. That
249 # section still lists DB2 beside MySQL and Oracle under "Implicit COMMIT on
250 # DDL"; the COMMIT and ROLLBACK topics quoted above say that grouping is wrong,
251 # and correcting it is core's to do. The price of the 0 is core's one-time
252 # "non-transactional DDL" notice, and what it says about RECOVERY is true here:
253 # an apply that fails part way leaves the earlier statements applied, and the
254 # way back is re-running the upgrade, whose diff is recomputed against live
255 # state. Value and declaredness are pinned by t/42-deploy-transactional-ddl.t.
256 14 __PACKAGE__->_use_transactional_ddl(0);
257  
258 # The one-row catalog view DB2 offers "for SQL statements in which a table
259 # reference is required, but the contents of the table are not important" (SQL
260 # Reference, SYSIBM.SYSDUMMY1). The name lives here once and is read twice:
261 # _dbh_last_insert_id selects IDENTITY_VAL_LOCAL() from it (ADR 0002), and
262 # _exists_value_sql needs it to give core's FROM-less EXISTS rendering a FROM
263 # clause (ADR 0037).
264 #
265 # $name_sep is the qualifier separator the *server* reported, and only the
266 # identity path can pass it: it is called with a $dbh in hand, so sql_name_sep
267 # may probe. _exists_value_sql must not -- it is a static class fact (ADR 0037
268 # section 2, ADR 0039 section 7: DBIO::ResultSet bakes the answer into the
269 # query while it is being built, so a probe there would open a connection
270 # during query build), and it takes the default '.', which is the separator
271 # every IBM SQL Reference spells this table with.
272 6 ▶sub _dummy_table {
Subroutine _dummy_table: called CC=2 SCAR=6.9
273 6 my ($self, $name_sep) = @_;
274  
275 6 ▶ $name_sep = '.' unless defined $name_sep;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name_sep 5 1 6
276  
277 6 return "SYSIBM${name_sep}SYSDUMMY1";
278 }
279  
280 0 ▶sub _dbh_last_insert_id {
Subroutine _dbh_last_insert_id: not called CC=2 SCAR=17.9
281 0 my ($self, $dbh, $source, $col) = @_;
282  
283 0 my $name_sep = $self->sql_name_sep;
284  
285 0 my $sth = $dbh->prepare_cached(
286 # An older equivalent of 'VALUES(IDENTITY_VAL_LOCAL())', for compat
287 # with ancient DB2 versions. Should work on modern DB2's as well:
288 # http://publib.boulder.ibm.com/infocenter/db2luw/v8/topic/com.ibm.db2.udb.doc/admin/r0002369.htm?resultof=%22%73%79%73%64%75%6d%6d%79%31%22%20
289 'SELECT IDENTITY_VAL_LOCAL() FROM ' . $self->_dummy_table($name_sep),
290 {},
291 3
292 );
293 0 $sth->execute();
294  
295 0 my @res = $sth->fetchrow_array();
296  
297 0 ▶ return @res ? $res[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@res ? : 0 0 0
298 }
299  
300 # ADR 0037 -- the complete 1/0 statement behind DBIO::ResultSet::results_exist
301 # and its two siblings. Core's base rendering has no FROM clause at all and
302 # DB2's subselect has no FROM-less form, so the statement gets the one-row
303 # catalog view above. Only the dummy table is ours -- the CASE spelling stays
304 # core's, so there is one copy of it.
305 4 ▶sub _exists_value_sql {
Subroutine _exists_value_sql: called CC=1 SCAR=0.0
306 4 my $self = shift;
307  
308 4 return $self->next::method(@_) . ' FROM ' . $self->_dummy_table;
309 }
310  
311 # ... and the capability that lets core call the above at all. Not vacuous
312 # next to the override: it is this driver asserting that somebody checked the
313 # rendering against DB2, which is why the default is 0 and why declaring is a
314 # separate act from overriding.
315 14 __PACKAGE__->_use_supports_exists_query (1);
316  
317 # ADR 0039 -- _set_operation_keyword is deliberately NOT overridden. DB2 has
318 # all six set operations and spells each one the way core's base map already
319 # answers, so there is nothing for this driver to say. The reasoning, the IBM
320 # sources and the Db2-for-i caveat are in the DESCRIPTION above;
321 # t/51-set-operations.t pins all six so the claim can fail.
322  
323 # karr k22 -- the function DBIO::ResultSet::rand drops into an order_by
324 # literal. Core answers RANDOM(), which PostgreSQL and SQLite have and the Db2
325 # LUW SQL Reference documents nowhere: the name resolves to no routine at all
326 # and the server says so (SQL0440N, SQLSTATE 42884). RAND (SYSFUN schema) is
327 # the one it does document.
328 #
329 # WITH parentheses, unlike Oracle's DBMS_RANDOM.VALUE -- this is a scalar
330 # function, and its zero-argument form is still an invocation. Without a seed
331 # on purpose: a seed makes the sequence repeat per query, which is a
332 # repeatable order rather than a shuffle. A static class fact like the base
333 # hook -- no $dbh, no version probe.
334 4 ▶sub _random_function { 'RAND()' }
Subroutine _random_function: called CC=1 SCAR=0.0
335  
336 # The schema the SECOND statement of _explain_query reads its rows from,
337 # because DB2 has two documented places to put the explain tables and the
338 # driver cannot tell which one is in use without asking. SYSTOOLS is the
339 # default because SYSPROC.SYSINSTALLOBJECTS -- IBM's preferred route -- creates
340 # them there, and because the Explain facility falls back to SYSTOOLS when the
341 # session's own schema has none. A session whose own schema DOES carry explain
342 # tables is written to there and must set this, or the read-back looks in the
343 # wrong place. Details and the failure modes: DESCRIPTION above.
344 #
345 # Qualified with a plain ".", for the same reason _dummy_table defaults to one:
346 # the separator every IBM SQL Reference spells a catalog name with, and reading
347 # the server-reported sql_name_sep instead would mean probing to build a
348 # statement string.
349 14 __PACKAGE__->mk_group_accessors('inherited' => qw/explain_table_schema/);
350 14 __PACKAGE__->explain_table_schema('SYSTOOLS');
351  
352 # karr k22 / ADR 0040 -- the WHOLE operation of obtaining a query plan, which
353 # on DB2 is two statements and is one of the shapes core widened this seam from
354 # the string-valued _explain_sql for.
355 #
356 # Core's inherited operation is "EXPLAIN <query>", which is not this engine's
357 # statement: DB2's is EXPLAIN PLAN SELECTION FOR (the bare PLAN is documented
358 # only as syntax toleration for z/OS, "there is no PLAN table"). And the
359 # spelling is the smaller half -- the statement ANSWERS WITH NOTHING. It writes
360 # the access plan into the EXPLAIN_* tables and does not execute the statement
361 # it explains, so the plan has to be read back by a second statement of this
362 # driver's own. There is no in-SQL formatter to call: db2exfmt and db2expln are
363 # OS commands outside DBI, and IBM's own documentation points at querying the
364 # explain tables instead.
365 #
366 # BOTH statements go through _execute_rendered, which ADR 0040 section 3 makes
367 # a requirement of the contract with no engine-named exceptions -- including
368 # the second one, which carries no user data but everything else: tracing and
369 # therefore redact_bind_value (ADR 0025) over the query's own WHERE-clause
370 # values, dbh_do retry over a dropped connection, NoBindVars interpolation, and
371 # the read handler rather than the master's on a replicated storage.
372 7 ▶sub _explain_query {
Subroutine _explain_query: called CC=1 SCAR=0.0
373 7 my ($self, $sql, $bind) = @_;
374  
375 # An identifier (core k391, ADR 0077): through the driver's quoting, as
376 # stored in the catalog, never joined raw into the statement.
377 7 my $maker = $self->sql_maker;
378 7 my $operators = $maker->_quote($self->explain_table_schema)
379 . '.' . $maker->_quote('EXPLAIN_OPERATOR');
380  
381 # Not a micro-optimisation dodge: the explain tables are populated when the
382 # EXPLAIN statement is COMPILED, and executing it "will perform no
383 # processing" (SQL Reference). DBI's prepare_cached returns a cached handle
384 # without preparing again, so a repeated explain of the same query would
385 # write no new plan -- and the read-back below, which can only ask for the
386 # newest one, would hand back whatever was explained last instead. Same
387 # statement, plausible rows, no error: silent. local, so it survives an
388 # exception out of either statement.
389 7 local $self->{disable_sth_caching} = 1;
390  
391 # Writes the plan and returns no rows. The query's binds travel with it:
392 # EXPLAIN parses the statement, so its parameter markers are the statement's
393 # own and have to be supplied.
394 7 $self->_execute_rendered("EXPLAIN PLAN SELECTION FOR $sql", $bind);
395  
396 # ... so the plan comes from here: one row per plan operator, in operator
397 # order, with the optimizer's cost columns. Keyed on the newest explain of
398 # this authorization ID because the explain tables are ordinary persistent
399 # tables with no session column -- the narrowest key DB2 offers, and the
400 # race it leaves is named in the DESCRIPTION rather than papered over.
401 7 my (undef, $sth) = $self->_execute_rendered (
402 'SELECT OPERATOR_ID, OPERATOR_TYPE, TOTAL_COST, IO_COST, CPU_COST'
403 . " FROM $operators"
404 . ' WHERE EXPLAIN_REQUESTER = SESSION_USER'
405 . " AND EXPLAIN_TIME = (SELECT MAX(EXPLAIN_TIME) FROM $operators"
406 . ' WHERE EXPLAIN_REQUESTER = SESSION_USER)'
407 . ' ORDER BY OPERATOR_ID',
408 [],
409 );
410  
411 7 my $rows = $sth->fetchall_arrayref;
412 7 DBIO::DB2::Storage::Cursor->decode_rows($self, $sth, @$rows);
413 7 return $rows;
414 }
415  
416  
417  
418 0 ▶sub deploy_setup { }
Subroutine deploy_setup: not called CC=1 SCAR=0.0
Pod documented
419  
420  
421  
422 2 ▶sub insert {
Subroutine insert: called CC=7 SCAR=20.9
Pod documented
423 2 my ($self, $source, $to_insert, $opts) = @_;
424  
425 2 ▶ return $self->next::method($source, $to_insert, $opts)
Branch: 1 branch
BranchTrueFalseTotal
if $to_insert and %$to_insert 1 1 2
Condition66%2/3
$to_insert and %$to_insert
!ll&&!rl&&r
011
MC/DC50%1/2
$to_insert and %$to_insert
$to_insert %$to_insert
Truth table66%2/3
A and B
A= $to_insertB= %$to_insert
ABresult
0X0
100
111
426 if $to_insert and %$to_insert;
427  
428 1 my $infos = $source->columns_info;
429 1 my ($col) = grep { $infos->{$_}{is_auto_increment} } $source->columns;
430 1 ▶ ($col) = $source->columns unless defined $col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col 0 1 1
431 1 ▶ return $self->next::method($source, $to_insert, $opts) unless defined $col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col 0 1 1
432  
433 1 my $returned = $self->next::method($source, { $col => \'DEFAULT' }, $opts);
434 delete $returned->{$col}
435 0 ▶ if ref $returned->{$col} eq 'SCALAR' and ${ $returned->{$col} } eq 'DEFAULT';
Branch: 1 branch
BranchTrueFalseTotal
if ref $returned->{$col} eq "SCALAR" and ${$returned->{$col};} eq "DEFAULT" 0 1 1
Condition33%1/3
ref $returned->{$col} eq "SCALAR" and ${$returned->{$col};} eq "DEFAULT"
!ll&&!rl&&r
100
MC/DC0%0/2
ref $returned->{$col} eq "SCALAR" and ${$returned->{$col};} eq "DEFAULT"
ref $returned->{$col} eq "SCALAR" ${$returned->{$col};} eq "DEFAULT"
Truth table33%1/3
A and B
A= ref $returned->{$col} eq "SCALAR"B= ${$returned->{$col};} eq "DEFAULT"
ABresult
0X0
100
111
436 1 return $returned;
437 }
438  
439  
440 12 ▶sub bind_attribute_by_data_type {
Subroutine bind_attribute_by_data_type: called CC=3 SCAR=11.0
Pod documented
441 12 my ($self, $data_type) = @_;
442 12 ▶ return { TYPE => -99 }
Branch: 1 branch
BranchTrueFalseTotal
if defined $data_type and $data_type =~ /\A\s*(?:clob|dbclob|(?:tiny|medium|long)?text)\s*\z/i 8 4 12
Condition66%2/3
defined $data_type and $data_type =~ /\A\s*(?:clob|dbclob|(?:tiny|medium|long)?text)\s*\z/i
!ll&&!rl&&r
048
MC/DC50%1/2
defined $data_type and $data_type =~ /\A\s*(?:clob|dbclob|(?:tiny|medium|long)?text)\s*\z/i
defined $data_type $data_type =~ /\A\s*(?:clob|dbclob|(?:tiny|medium|long)?text)\s*\z/i
Truth table66%2/3
A and B
A= defined $data_typeB= $data_type =~ /\A\s*(?:clob|dbclob|(?:tiny|medium|long)?text)\s*\z/i
ABresult
0X0
100
111
443 if defined $data_type && $data_type =~ /\A\s*(?:clob|dbclob|(?:tiny|medium|long)?text)\s*\z/i;
444 4 return $self->next::method($data_type);
445 }
446  
447  
448 1 ▶sub select_single {
Subroutine select_single: called CC=4 SCAR=15.0
Pod documented
449 1 my $self = shift;
450 1 my ($rv, $sth, @bind) = $self->_select(@_);
451 1 my @row = $sth->fetchrow_array;
452 1 ▶ my @nextrow = $sth->fetchrow_array if @row;
Branch: 1 branch
BranchTrueFalseTotal
if @row 1 0 1
453 1 ▶ if (@row && @nextrow) {
Branch: 1 branch
BranchTrueFalseTotal
if (@row and @nextrow) 0 1 1
Condition33%1/3
@row and @nextrow
!ll&&!rl&&r
010
MC/DC0%0/2
@row and @nextrow
@row @nextrow
Truth table33%1/3
A and B
A= @rowB= @nextrow
ABresult
0X0
100
111
454 0 Carp::carp('Query returned more than one row. SQL that returns multiple rows is DEPRECATED for ->find and ->single');
455 }
456 1 DBIO::DB2::Storage::Cursor->decode_rows($self, $sth, \@row);
457 1 $sth->finish();
458 1 return @row;
459 }
460  
461  
462 7 ▶sub _utf8_database {
Subroutine _utf8_database: called CC=4 SCAR=15.5
463 7 my ($self) = @_;
464 7 ▶ return $self->{_db2_utf8_database} //= do {
Condition33%1/3
$self->{"_db2_utf8_database"} //= do { my($set) = eval { do { $self->dbh_do(sub { $_[1]->selectrow_array("SELECT value FROM sysibmadm.dbcfg WHERE name = 'codeset'"); } ) } }; defined $set && $set =~ /utf-?8/i ? 1 : 0 }
l!l&&r!l&&!r
070
MC/DC0%0/2
$self->{"_db2_utf8_database"} //= do { my($set) = eval { do { $self->dbh_do(sub { $_[1]->selectrow_array("SELECT value FROM sysibmadm.dbcfg WHERE name = 'codeset'"); } ) } }; defined $set && $set =~ /utf-?8/i ? 1 : 0 }
$self->{"_db2_utf8_database"} do { my($set) = eval { do { $self->dbh_do(sub { $_[1]->selectrow_array("SELECT value FROM sysibmadm.dbcfg WHERE name = 'codeset'"); } ) } }; defined $set && $set =~ /utf-?8/i ? 1 : 0 }
Truth table33%1/3
A //= B
A= $self->{"_db2_utf8_database"}B= do { my($set) = eval { do { $self->dbh_do(sub { $_[1]->selectrow_array("SELECT value FROM sysibmadm.dbcfg WHERE name = 'codeset'"); } ) } }; defined $set && $set =~ /utf-?8/i ? 1 : 0 }
ABresult
1X1
011
000
465 7 my ($set) = eval {
466 7 ▶ $self->dbh_do(sub { $_[1]->selectrow_array(
Subroutine __ANON__: called CC=1 SCAR=0.0
467 7 q{SELECT value FROM sysibmadm.dbcfg WHERE name = 'codeset'}) });
468 };
469 7 ▶ (defined $set && $set =~ /utf-?8/i) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $set && $set =~ /utf-?8/i ? : 0 7 7
Condition33%1/3
defined $set and $set =~ /utf-?8/i
!ll&&!rl&&r
700
MC/DC0%0/2
defined $set and $set =~ /utf-?8/i
defined $set $set =~ /utf-?8/i
Truth table33%1/3
A and B
A= defined $setB= $set =~ /utf-?8/i
ABresult
0X0
100
111
470 };
471 }
472  
473 # The table a bind list is about, for a message: the name of the source of an
474 # insert, update or delete, or the first table of the FROM of a select.
475 4 ▶sub _ident_table_name {
Subroutine _ident_table_name: called CC=9 SCAR=28.3
476 4 my ($self, $ident) = @_;
477 4 ▶ if (Scalar::Util::blessed($ident) && $ident->can('name')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($ident) and $ident->can("name")) 3 1 4
Condition66%2/3
builtin::blessed($ident) and $ident->can("name")
!ll&&!rl&&r
103
MC/DC50%1/2
builtin::blessed($ident) and $ident->can("name")
builtin::blessed($ident) $ident->can("name")
Truth table66%2/3
A and B
A= builtin::blessed($ident)B= $ident->can("name")
ABresult
0X0
100
111
478 3 my $name = $ident->name;
479 3 ▶ return ref $name eq 'SCALAR' ? $$name : $name;
Branch: 1 branch
BranchTrueFalseTotal
ref $name eq 'SCALAR' ? : 0 3 3
480 }
481 1 ▶ if (ref $ident eq 'ARRAY' && ref $ident->[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ident eq "ARRAY" and ref $ident->[0] eq "HASH") 1 0 1
Condition33%1/3
ref $ident eq "ARRAY" and ref $ident->[0] eq "HASH"
!ll&&!rl&&r
001
MC/DC0%0/2
ref $ident eq "ARRAY" and ref $ident->[0] eq "HASH"
ref $ident eq "ARRAY" ref $ident->[0] eq "HASH"
Truth table33%1/3
A and B
A= ref $ident eq "ARRAY"B= ref $ident->[0] eq "HASH"
ABresult
0X0
100
111
482 # the FROM of a select: [ { -alias => 'me', -rsrc => $source }, ... ]
483 1 ▶ return $self->_ident_table_name($ident->[0]{'-rsrc'}) if $ident->[0]{'-rsrc'};
Branch: 1 branch
BranchTrueFalseTotal
if $ident->[0]{"-rsrc"} 1 0 1
484 }
485 0 ▶ return defined $ident && !ref $ident ? $ident : 'the table';
Branch: 1 branch
BranchTrueFalseTotal
defined $ident && !ref($ident) ? : 0 0 0
Condition0%0/3
defined $ident and not ref $ident
!ll&&!rl&&r
000
MC/DC0%0/2
defined $ident and not ref $ident
defined $ident not ref $ident
Truth table0%0/3
A and not(B)
A= defined $identB= not ref $ident
ABresult
0X0
100
111
486 }
487  
488  
489 14 my $CLOB_COMPARE_MAX = 32672;
490  
491 9 ▶sub _prep_for_execute {
Subroutine _prep_for_execute: called CC=16 SCAR=29.1
492 9 my ($self, $op, $ident, $args) = @_;
493 9 my ($sql, $bind) = $self->next::method($op, $ident, $args);
494  
495 9 ▶ for my $b (@{ $bind || [] }) {
Condition50%1/2
$bind || []
l!l
90
MC/DC0%0/1
$bind || []
$bind
Truth table50%1/2
A
A= $bind
Aresult
11
00
496 8 my ($meta, $value) = @$b;
497 8 ▶ next unless ref $meta eq 'HASH' && defined $value && !length ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $meta eq "HASH" and defined $value and not length ref $value 1 7 8
Condition66%4/6
ref $meta eq "HASH" and defined $value and not length ref $value
!ll&&!rl&&r
107
ref $meta eq "HASH" and defined $value
!ll&&!rl&&r
017
MC/DC33%1/3
ref $meta eq "HASH" and defined $value and not length ref $value
ref $meta eq "HASH" defined $value not length ref $value
Truth table50%2/4
A and B and not(C)
A= ref $meta eq "HASH"B= defined $valueC= not length ref $value
ABCresult
0XX0
10X0
1100
1111
498 7 ▶ my $type = lc($meta->{sqlt_datatype} // '');
Condition50%1/2
$meta->{"sqlt_datatype"} // ""
l!l
70
MC/DC0%0/1
$meta->{"sqlt_datatype"} // ""
$meta->{"sqlt_datatype"}
Truth table50%1/2
A
A= $meta->{"sqlt_datatype"}
Aresult
11
00
499 7 ▶ my $column = $meta->{dbic_colname} // '?';
Condition50%1/2
$meta->{"dbic_colname"} // "?"
l!l
70
MC/DC0%0/1
$meta->{"dbic_colname"} // "?"
$meta->{"dbic_colname"}
Truth table50%1/2
A
A= $meta->{"dbic_colname"}
Aresult
11
00
500  
501 7 ▶ DBIO::Exception->throw(sprintf
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "blob" and $value eq "" and $op eq "insert" || $op eq "update" 1 6 7
Condition66%6/9
$type eq "blob" and $value eq "" and $op eq "insert" || $op eq "update"
!ll&&!rl&&r
601
$type eq "blob" and $value eq ""
!ll&&!rl&&r
511
$op eq "insert" or $op eq "update"
l!l&&r!l&&!r
100
MC/DC50%2/4
$type eq "blob" and $value eq "" and $op eq "insert" || $op eq "update"
$type eq "blob" $value eq "" $op eq "insert" $op eq "update"
Truth table60%3/5
A and B and C or D
A= $type eq "blob"B= $value eq ""C= $op eq "insert"D= $op eq "update"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
502 'DBIO::DB2::Storage: %s on table "%s" is refused: column "%s" gets an empty string, which '
503 . 'DBD::DB2 reads back as NULL from a BLOB column; the value would not survive',
504 $op, $self->_ident_table_name($ident), $column)
505 if $type eq 'blob' && $value eq '' && ($op eq 'insert' || $op eq 'update');
506  
507 6 ▶ if (($op eq 'select' || $op eq 'delete') && $self->bind_attribute_by_data_type($type)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "select" || $op eq "delete" and $self->bind_attribute_by_data_type($type)) 3 3 6
Condition66%4/6
$op eq "select" || $op eq "delete" and $self->bind_attribute_by_data_type($type)
!ll&&!rl&&r
303
$op eq "select" or $op eq "delete"
l!l&&r!l&&!r
303
MC/DC33%1/3
$op eq "select" || $op eq "delete" and $self->bind_attribute_by_data_type($type)
$op eq "select" $op eq "delete" $self->bind_attribute_by_data_type($type)
Truth table40%2/5
A or B and C
A= $op eq "select"B= $op eq "delete"C= $self->bind_attribute_by_data_type($type)
ABCresult
00X0
1X00
0100
1X11
0111
508 3 utf8::encode(my $bytes = $value);
509 3 ▶ DBIO::Exception->throw(sprintf
Branch: 1 branch
BranchTrueFalseTotal
if length $bytes > $CLOB_COMPARE_MAX 2 1 3
510 'DBIO::DB2::Storage: %s on table "%s" is refused: column "%s" is compared with a value of '
511 . '%d bytes, and Db2 cannot compare a CLOB with more than %d bytes (SQL0433N)',
512 $op, $self->_ident_table_name($ident), $column, length $bytes, $CLOB_COMPARE_MAX)
513 if length $bytes > $CLOB_COMPARE_MAX;
514 }
515 }
516  
517 6 return ($sql, $bind);
518 }
519  
520  
521 14 1;
522  
523 __END__
« DB2/Diff/Column.pm ↑ Summary DB2/Introspect/Indexes.pm »