MSSQL/Storage.pm

filter: Statementstmt 82.5% 198 / 240 Branchbran 82.1% 115 / 140 Conditioncond 65.8% 54 / 82 MC/DCmcdc 46.1% 24 / 52 Subroutinesub 76.7% 33 / 43 Podpod 80.0% 4 / 5 totaltotal 76.1% 428 / 562 CC 103 SCAR 31.1
CC
103
Cov
79%
_prep_for_execute
84.0
_bind_host_into_dsn
30.1
_bulk_binary_values_as_bytes
17.7
CRAP 22.4
« MSSQL/DDL.pm ↑ Summary MSSQL/Introspect/Views.pm »
1 package DBIO::MSSQL::Storage;
2 # ABSTRACT: Base Class for Microsoft SQL Server support in DBIO
3  
4 24 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 24 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 24 our $VERSION = '0.900007';
8  
9 24 ▶use base qw/
Subroutine BEGIN: called CC=1 SCAR=0.0
10 DBIO::Storage::DBI::UniqueIdentifier
11 DBIO::Storage::DBI::IdentityInsert
12 24 /;
13 24 ▶use mro 'c3';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 24 ▶use Context::Preserve 'preserve_context';
Subroutine BEGIN: called CC=1 SCAR=0.0
16 24 ▶use Scope::Guard ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 24 ▶use DBIO::Util qw(is_literal_value is_plain_value);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 24 ▶use DBIO::MSSQL::Storage::StopAtFirstError ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 24 ▶use DBIO::MSSQL::DDL ();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 24 ▶use DBIO::MSSQL::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 24 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 24 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 24 __PACKAGE__->mk_group_accessors(simple => qw/
25 _identity _identity_method _no_scope_identity_query
26 /);
27  
28 24 __PACKAGE__->sql_maker_class('DBIO::MSSQL::SQLMaker');
29  
30 24 __PACKAGE__->register_driver('MSSQL' => __PACKAGE__);
31  
32 24 __PACKAGE__->sql_quote_char([qw/[ ]/]);
33  
34 24 __PACKAGE__->datetime_parser_type (
35 'DBIO::MSSQL::Storage::DateTime::Format'
36 );
37  
38 24 __PACKAGE__->new_guid('NEWID()');
39  
40 # ADR 0037. The base rendering of DBIO::Storage::DBI::_exists_value_sql --
41 #
42 # SELECT CASE WHEN EXISTS <inner> THEN 1 ELSE 0 END
43 #
44 # -- is grammatical Transact-SQL exactly as core writes it, so this driver
45 # declares the capability and deliberately does NOT override the hook. The
46 # declaration means somebody read the grammar, so here is what was read, in
47 # the three places the fragment could have broken:
48 #
49 # * no FROM. SELECT (Transact-SQL) gives <query_specification> as
50 # "SELECT <select_list> [ INTO ... ] [ FROM { <table_source> } [ ,...n ] ]"
51 # -- FROM is optional, so SQL Server needs none of the dummy tables Oracle
52 # (DUAL), DB2 (SYSIBM.SYSDUMMY1) and Firebird (RDB$DATABASE) do.
53 # * CASE in the select list. "CASE can be used in any statement or clause
54 # that allows a valid expression ... such as SELECT", and the searched
55 # form is "CASE WHEN Boolean_expression THEN result_expression ... END".
56 # * EXISTS as that Boolean_expression. EXISTS (Transact-SQL) is
57 # "EXISTS ( subquery )" with return type Boolean, and Microsoft's own CASE
58 # page (example E) writes "CASE WHEN EXISTS (SELECT * FROM ...) THEN ..."
59 # verbatim. What T-SQL does not have is EXISTS as a *value* expression --
60 # bare SELECT EXISTS (...) is a syntax error here, which is precisely the
61 # PostgreSQL-ism ADR 0037 moved core off.
62 24 __PACKAGE__->_use_supports_exists_query(1);
63  
64 # F02 / F10, karr k23 (handoff from core karr k130). Every other declaration in
65 # this family bar PostgreSQL's is a 0, where the declaration records a decision
66 # and changes nothing. This one changes what runs:
67 # DBIO::Deploy::Base::_execute_ddl brackets the install / apply batch in
68 # $storage->txn_do, and DBIO::DeploymentHandler brackets a whole upgrade (which
69 # has a consequence of its own -- see "Transactional DDL" in
70 # DBIO::MSSQL::Deploy). A 1 is therefore a promise about the statements THIS
71 # driver emits, not about Transact-SQL at large, and the inventory below was
72 # walked rather than assumed.
73 #
74 # THE ENGINE FACT, and the first thing to be honest about: Microsoft nowhere
75 # says "SQL Server rolls DDL back" for SQL Server. That sentence exists only in
76 # the Fabric Data Warehouse documentation, which is a different product. The
77 # SQL Server documentation states the rule the other way round, as a CLOSED
78 # EXCEPTION LIST -- which is weaker prose and much stronger evidence, because it
79 # is checkable against an inventory. "Transaction locking and row versioning
80 # guide", section "Explicit transactions": "You can use all Transact-SQL
81 # statements in an explicit transaction, except for the following statements:
82 # CREATE DATABASE, ALTER DATABASE, DROP DATABASE, CREATE FULLTEXT CATALOG,
83 # ALTER FULLTEXT CATALOG, DROP FULLTEXT CATALOG, DROP FULLTEXT INDEX, ALTER
84 # FULLTEXT INDEX, CREATE FULLTEXT INDEX, BACKUP, RESTORE, RECONFIGURE, Full-text
85 # system stored procedures, sp_dboption ... or any system procedure that
86 # modifies the master database".
87 #
88 # The same passage then carves out the one statement that is allowed in a
89 # transaction but not undone by one -- "UPDATE STATISTICS can be used inside an
90 # explicit transaction. However, UPDATE STATISTICS commits independently of the
91 # enclosing transaction and can't be rolled back" -- and that carve-out is what
92 # makes the list usable rather than merely suggestive: Microsoft distinguishes
93 # "may not appear in a transaction" from "appears but does not roll back", and
94 # names the single member of the second category. Two more pieces corroborate
95 # the rollback half for the statements this driver actually emits: the
96 # transaction log guide lists "Creating or dropping a table or index" among the
97 # operations recorded in the log, alongside "data definition language (DDL)
98 # statements to any table"; and the online-index guidelines say outright "To
99 # make sure that the index operation can be rolled back, the transaction log
100 # can't be truncated until the index operation is completed".
101 #
102 # THE INVENTORY that reaches _execute_ddl is DBIO::MSSQL::DDL::install_ddl plus
103 # DBIO::MSSQL::Diff::as_sql, and it is exactly ten shapes:
104 #
105 # CREATE TABLE ... (inline PRIMARY KEY / UNIQUE / FOREIGN KEY, IDENTITY(1,1))
106 # CREATE VIEW ... AS ...
107 # CREATE [UNIQUE ][CLUSTERED|NONCLUSTERED ]INDEX ... ON ...
108 # DROP TABLE ...
109 # DROP INDEX ... ON ...
110 # ALTER TABLE ... ADD <column>
111 # ALTER TABLE ... DROP COLUMN ...
112 # ALTER TABLE ... ALTER COLUMN ...
113 # ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY ...
114 # ALTER TABLE ... DROP CONSTRAINT ...
115 #
116 # Not one is on the list, and not one carries an option that is. Four near
117 # misses were checked and are near misses only because this driver emits none
118 # of them:
119 #
120 # * RESUMABLE = ON -- "The DDL command with RESUMABLE = ON can't be executed
121 # inside an explicit transaction" (CREATE INDEX / ALTER INDEX). A hard
122 # prohibition, and the one that would bite if index options were ever made
123 # configurable.
124 # * ALTER INDEX REORGANIZE -- "Not rolled back when performed within a
125 # transaction and the transaction is rolled back" (ALTER INDEX). This driver
126 # has no ALTER INDEX at all: a definition change is a DROP INDEX / CREATE
127 # INDEX pair.
128 # * memory-optimized tables -- "Memory-optimized tables and natively compiled
129 # stored procedures cannot be created or dropped in the context of a user
130 # transaction" (Transact-SQL Constructs Not Supported by In-Memory OLTP).
131 # This is the only documented prohibition that touches plain CREATE TABLE,
132 # and it is reached only through WITH (MEMORY_OPTIMIZED = ON), which neither
133 # DBIO::MSSQL::DDL nor DBIO::MSSQL::Diff::Table can render -- they emit no
134 # WITH clause on a table at all.
135 # * ONLINE = ON -- NOT forbidden, only cautioned ("be careful when you run an
136 # online index operation inside an explicit user transaction ... causes the
137 # locks to be held until the end of the transaction", Guidelines for online
138 # index operations). Named here because it is the one that gets repeated as
139 # a prohibition and is not one. This driver renders no index options either.
140 #
141 # So core's per-statement escape hatch -- _ddl_statement_is_transactional, the
142 # ADR 0026 addendum PostgreSQL needs for ALTER TYPE ... ADD VALUE -- is
143 # deliberately NOT overridden here. There is nothing for it to except.
144 # t/42-deploy-transactional-ddl.t sweeps the emitted set against both lists and
145 # goes red if an emitter ever grows one, which is when the hook becomes the
146 # answer rather than a downgrade of this declaration.
147 #
148 # CREATE DATABASE and DROP DATABASE are the forbidden statements this
149 # distribution does issue, and they are irrelevant to this capability because
150 # they never travel the batch path: DBIO::MSSQL::Deploy::_create_temp_db and
151 # _drop_temp_db hand them to $dbh->do directly on a handle in AutoCommit mode (a handle with
152 # AutoCommit off is refused, karr k80),
153 # which is exactly the autocommit mode their reference pages require ("The DROP
154 # DATABASE statement must run in autocommit mode and isn't allowed in an
155 # explicit or implicit transaction").
156 #
157 # BOTH TRANSPORTS carry the promise, and the declaration sits on this
158 # transport-neutral base because the transport has no vote in it. Over DBD::ODBC
159 # the bracket is core's begin_work / commit / rollback on the connection; over
160 # DBD::Sybase + FreeTDS it is DBIO::Sybase::Storage::FreeTDS's _exec_txn_*,
161 # which issue literal BEGIN TRAN / COMMIT / ROLLBACK -- the explicit transaction
162 # the documentation above is written about, in the most literal form. The known
163 # FreeTDS hazard does not reach here as long as no cursor is open on the
164 # handle: DBD::Sybase has no real MARS and fakes a second active statement with
165 # a child connection that deadlocks against a write in a transaction (which is
166 # why t/10 skips the MAS complexes), but _execute_ddl runs one
167 # statement after another on ONE handle and $dbh->do on DDL leaves no rowset
168 # pending, so no second statement is ever active. It is the same shape as any
169 # other txn_do this driver already runs on that transport.
170 #
171 # RESTRICTION, NOT MEASURED FOR THE DEPLOY PATH (karr k44): with a cursor open
172 # on the handle while the deploy runs, BEGIN TRAN goes out on the second
173 # connection (t/61, karr k41) and the DDL then runs without a transaction --
174 # the capability promises more than the transport keeps in that case.
175 #
176 # WHERE THIS MUST NOT MOVE: DBIO::MSSQL::Storage::Sybase is
177 # `use base qw/ DBIO::Sybase::Storage DBIO::MSSQL::Storage /` under mro c3, so
178 # the Sybase transport class precedes this one in the linearisation that
179 # Class::Accessor::Grouped::get_inherited walks. Sybase ASE is an
180 # implicit-commit engine and dbio-sybase declares 0 for it; that 0 lives on
181 # DBIO::Sybase::Storage::ASE today, which is not in that chain. If it ever rises
182 # to DBIO::Sybase::Storage it would shadow this 1 silently for every DBD::Sybase
183 # connection. t/42 pins the declaring class per subclass so that surfaces as a
184 # red test naming the offender rather than as a lost guarantee.
185 #
186 # THE ONE DOCUMENTED WAY TO BREAK THIS, and it is a session setting rather than
187 # a statement: SNAPSHOT isolation. "The Database Engine doesn't support
188 # versioning of metadata. For this reason, there are restrictions on what DDL
189 # operations can be performed in an explicit transaction that's running under
190 # snapshot isolation. The following DDL statements aren't permitted under
191 # snapshot isolation after a BEGIN TRANSACTION statement: ALTER TABLE, CREATE
192 # INDEX, CREATE XML INDEX, ALTER INDEX, DROP INDEX, DBCC REINDEX, ALTER
193 # PARTITION FUNCTION, ALTER PARTITION SCHEME, or any common language runtime
194 # (CLR) DDL statement ... Violations of this principle can cause error 3961"
195 # (same locking guide). That covers half this driver's inventory, so the
196 # declaration is bounded by it: a caller whose session runs at SET TRANSACTION
197 # ISOLATION LEVEL SNAPSHOT will see 3961 out of a bracketed deploy where an
198 # unbracketed one succeeded. Nothing here sets that isolation level and core
199 # does not either, so it is opt-in -- and it would break a hand-written txn_do
200 # around the same DDL identically. Worth knowing that the enabling database
201 # option is on by default in Azure SQL Database ("set to OFF for user databases
202 # in SQL Server and Azure SQL Managed Instance, and set to ON for databases in
203 # Azure SQL Database"), though the session still has to ask for the isolation
204 # level. If this ever turns up in the field, the fix is the per-statement hook
205 # or a documented refusal, not a silent downgrade.
206 #
207 # WHAT IS NOT VERIFIED: no SQL Server was run for this. The reasoning is
208 # documentary (the pages named above) plus this driver's own statement
209 # inventory, which is a string question and is swept offline in t/42. It holds
210 # for the SQL Server engine and, with the snapshot caveat above, for Azure SQL
211 # Database and Managed Instance, whose reference pages repeat the same
212 # prohibitions verbatim. Azure Synapse dedicated SQL pools were checked and are
213 # no worse for DDL -- "The CREATE DATABASE and DROP DATABASE (Transact-SQL)
214 # commands cannot be used inside an explicit transaction" is the whole of their
215 # extra list -- but they have no savepoints and no nesting, which is a separate
216 # matter from this capability and not addressed here. A live run should check
217 # the one thing a document cannot: that a mid-batch failure under DBD::ODBC and
218 # under DBD::Sybase really does leave the earlier statements gone.
219 24 __PACKAGE__->_use_transactional_ddl(1);
220  
221 2 ▶sub dbio_deploy_class { 'DBIO::MSSQL::Deploy' }
Subroutine dbio_deploy_class: called CC=1 SCAR=0.0
Pod undocumented
222  
223 0 ▶sub deploy_setup { }
Subroutine deploy_setup: not called CC=1 SCAR=0.0
Pod documented
224  
225  
226 186 ▶sub _prep_for_execute {
Subroutine _prep_for_execute: called CC=20 SCAR=44.3
227 186 my $self = shift;
228 186 my ($op, $ident, $args) = @_;
229  
230 # cast MONEY values properly
231 186 ▶ if ($op eq 'insert' || $op eq 'update') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "insert" or $op eq "update") 109 77 186
Condition100%3/3
$op eq "insert" or $op eq "update"
l!l&&r!l&&!r
100977
MC/DC100%2/2
$op eq "insert" or $op eq "update"
$op eq "insert" $op eq "update"
Truth table100%3/3
A or B
A= $op eq "insert"B= $op eq "update"
ABresult
1X1
011
000
232 109 my $fields = $args->[0];
233  
234 109 my $colinfo = $ident->columns_info([keys %$fields]);
235  
236 109 for my $col (keys %$fields) {
237 # $ident is a result source object with INSERT/UPDATE ops
238 153 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($colinfo->{$col}{"data_type"} and $colinfo->{$col}{"data_type"} =~ /^money\z/i) 0 153 153
Condition33%1/3
$colinfo->{$col}{"data_type"} and $colinfo->{$col}{"data_type"} =~ /^money\z/i
!ll&&!rl&&r
01530
MC/DC0%0/2
$colinfo->{$col}{"data_type"} and $colinfo->{$col}{"data_type"} =~ /^money\z/i
$colinfo->{$col}{"data_type"} $colinfo->{$col}{"data_type"} =~ /^money\z/i
Truth table33%1/3
A and B
A= $colinfo->{$col}{"data_type"}B= $colinfo->{$col}{"data_type"} =~ /^money\z/i
ABresult
0X0
100
111
239 $colinfo->{$col}{data_type}
240 &&
241 $colinfo->{$col}{data_type} =~ /^money\z/i
242 ) {
243 0 ▶ if(
Branch: 1 branch
BranchTrueFalseTotal
if (length ref $fields->{$col} and my $lit = &is_literal_value($fields->{$col})) { } 0 0 0
Condition0%0/3
length ref $fields->{$col} and my $lit = &is_literal_value($fields->{$col})
!ll&&!rl&&r
000
MC/DC0%0/2
length ref $fields->{$col} and my $lit = &is_literal_value($fields->{$col})
length ref $fields->{$col} my $lit = &is_literal_value($fields->{$col})
Truth table0%0/3
A and B
A= length ref $fields->{$col}B= my $lit = &is_literal_value($fields->{$col})
ABresult
0X0
100
111
244 length ref $fields->{$col}
245 and
246 my $lit = is_literal_value( $fields->{$col} )
247 ) {
248 # We are being fed a literal value
249 # Generally there is not much we can do about it, *except*
250 # in the unambiguous case of a lone bind parameter
251 0 ▶ $fields->{$col} = \[ 'CAST(? AS MONEY)', @{$lit}[ 1 .. $#$lit ] ]
Branch: 1 branch
BranchTrueFalseTotal
if $lit->[0] eq "?" 0 0 0
252 if $lit->[0] eq '?';
253 }
254 # nonliteral - wrap away
255 else {
256 0 $fields->{$col} = \['CAST(? AS MONEY)', [ $col => $fields->{$col} ]];
257 }
258 }
259 }
260 }
261  
262 # UNIQUEIDENTIFIER columns that look like is_auto_increment are
263 # actually populated by NEWID() (see DBIO::Storage::DBI::UniqueIdentifier
264 # _prefetch_autovalues) - they are NOT real IDENTITY columns. Suppress
265 # the SET IDENTITY_INSERT wrapper the parent IdentityInsert would emit
266 # for any autoinc column with a value, otherwise MSSQL complains that
267 # the table has no IDENTITY property.
268 186 my $suppress_identity_insert = 0;
269 186 ▶ if ($op eq 'insert' and $self->_autoinc_supplied_for_op) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "insert" and $self->_autoinc_supplied_for_op) 0 186 186
Condition66%2/3
$op eq "insert" and $self->_autoinc_supplied_for_op
!ll&&!rl&&r
861000
MC/DC0%0/2
$op eq "insert" and $self->_autoinc_supplied_for_op
$op eq "insert" $self->_autoinc_supplied_for_op
Truth table66%2/3
A and B
A= $op eq "insert"B= $self->_autoinc_supplied_for_op
ABresult
0X0
100
111
270 0 my $colinfo = $ident->columns_info;
271 0 my $is_guid_autoinc = 0;
272 0 for my $col (keys %$colinfo) {
273 0 ▶ next unless $colinfo->{$col}{is_auto_increment};
Branch: 1 branch
BranchTrueFalseTotal
unless $colinfo->{$col}{"is_auto_increment"} 0 0 0
274 0 ▶ my $dt = $colinfo->{$col}{data_type} || '';
Condition0%0/2
$colinfo->{$col}{'data_type'} || ''
l!l
00
MC/DC0%0/1
$colinfo->{$col}{'data_type'} || ''
$colinfo->{$col}{'data_type'}
Truth table0%0/2
A
A= $colinfo->{$col}{'data_type'}
Aresult
11
00
275 0 ▶ if ($dt =~ /^(?:uniqueidentifier(?:str)?|guid)\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dt =~ /^(?:uniqueidentifier(?:str)?|guid)\z/i) 0 0 0
276 0 $is_guid_autoinc = 1;
277 0 last;
278 }
279 }
280 0 ▶ $suppress_identity_insert = 1 if $is_guid_autoinc;
Branch: 1 branch
BranchTrueFalseTotal
if $is_guid_autoinc 0 0 0
281 }
282  
283 186 my ($sql, $bind);
284 186 ▶ if ($suppress_identity_insert) {
Branch: 1 branch
BranchTrueFalseTotal
if ($suppress_identity_insert) { } 0 186 186
285 0 local $self->{_autoinc_supplied_for_op} = 0;
286 0 ($sql, $bind) = $self->next::method(@_);
287 }
288 else {
289 186 ($sql, $bind) = $self->next::method(@_);
290 }
291  
292 # SELECT SCOPE_IDENTITY only works within a statement scope. We
293 # must try to always use this particular idiom first, as it is the
294 # only one that guarantees retrieving the correct id under high
295 # concurrency. When this fails we will fall back to whatever secondary
296 # retrieval method is specified in _identity_method, but at this
297 # point we don't have many guarantees we will get what we expected.
298 # http://msdn.microsoft.com/en-us/library/ms190315.aspx
299 # http://davidhayden.com/blog/dave/archive/2006/01/17/2736.aspx
300 186 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_perform_autoinc_retrieval and not $self->_no_scope_identity_query and not $suppress_identity_insert) 95 91 186
Condition66%4/6
$self->_perform_autoinc_retrieval and not $self->_no_scope_identity_query and not $suppress_identity_insert
!ll&&!rl&&r
91095
$self->_perform_autoinc_retrieval and not $self->_no_scope_identity_query
!ll&&!rl&&r
91095
MC/DC33%1/3
$self->_perform_autoinc_retrieval and not $self->_no_scope_identity_query and not $suppress_identity_insert
$self->_perform_autoinc_retrieval not $self->_no_scope_identity_query not $suppress_identity_insert
Truth table50%2/4
A and not(B) and not(C)
A= $self->_perform_autoinc_retrievalB= not $self->_no_scope_identity_queryC= not $suppress_identity_insert
ABCresult
0XX0
10X0
1100
1111
301 $self->_perform_autoinc_retrieval
302 and
303 not $self->_no_scope_identity_query
304 and
305 not $suppress_identity_insert
306 ) {
307 95 $sql .= "\nSELECT SCOPE_IDENTITY()";
308 }
309  
310 186 return ($sql, $bind);
311 }
312  
313 181 ▶sub _execute {
Subroutine _execute: called CC=6 SCAR=18.5
314 181 my $self = shift;
315  
316 # always list ctx - we need the $sth
317 181 my ($rv, $sth, @bind) = $self->next::method(@_);
318  
319 149 ▶ if ($self->_perform_autoinc_retrieval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_perform_autoinc_retrieval) 79 70 149
320  
321 # attempt to bring back the result of SELECT SCOPE_IDENTITY() we tacked
322 # on in _prep_for_execute above
323 79 my $identity;
324  
325 # we didn't even try on ftds
326 79 ▶ unless ($self->_no_scope_identity_query) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_no_scope_identity_query) 79 0 79
327 79 ▶ ($identity) = try { $sth->fetchrow_array };
Subroutine __ANON__: called CC=1 SCAR=0.0
328 79 $sth->finish;
329 }
330  
331 # SCOPE_IDENTITY failed, but we can do something else
332 79 ▶ if ( (! $identity) && $self->_identity_method) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $identity and $self->_identity_method) 0 79 79
Condition33%1/3
not $identity and $self->_identity_method
!ll&&!rl&&r
0790
MC/DC0%0/2
not $identity and $self->_identity_method
not $identity $self->_identity_method
Truth table33%1/3
not(A) and B
A= not $identityB= $self->_identity_method
ABresult
0X0
100
111
333 0 ($identity) = $self->_dbh->selectrow_array(
334 'select ' . $self->_identity_method
335 );
336 }
337  
338 79 $self->_identity($identity);
339 }
340  
341 149 ▶ return wantarray ? ($rv, $sth, @bind) : $rv;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 137 12 149
342 }
343  
344 # karr k62. Core's void-context populate executes its rows with
345 # execute_for_fetch, which DBI runs to the end of the data whatever became of
346 # the tuple before. SQL Server rolls the whole transaction back on some
347 # statement errors (Msg 8114), so the tuples after the failing one would run
348 # in autocommit and stay, while the ones before it are gone with the
349 # transaction. The handle core is given stops at the first failing tuple.
350 5 ▶sub _dbh_execute_for_fetch {
Subroutine _dbh_execute_for_fetch: called CC=1 SCAR=0.0
351 5 my ($self, $source, $sth, @rest) = @_;
352  
353 5 return $self->next::method(
354 $source, DBIO::MSSQL::Storage::StopAtFirstError->new($sth), @rest,
355 );
356 }
357  
358  
359 # karr k50. Three questions about a binary value, asked by the two access path
360 # classes -- each binds such a value in its own way, and this class, which
361 # knows no transport, in none.
362  
363 # Is this the data type of a column whose values are bytes? The native binary
364 # types, and the names DBIO::MSSQL::DDL makes a binary column of. Not "bit"
365 # (a boolean here) and not "timestamp" (a date and time to DBIO).
366 537 ▶sub _is_binary_data_type {
Subroutine _is_binary_data_type: called CC=3 SCAR=11.0
367 537 my ($self, $data_type) = @_;
368  
369 537 ▶ return 0 unless defined $data_type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data_type 33 504 537
370  
371 504 ▶ return $data_type =~ /\A \s*
Branch: 1 branch
BranchTrueFalseTotal
$data_type =~ /\A \s* (?: (?:var)? binary (?: \s+ varying )? | image | blob | bytea | (?: tiny | medium | long ) blob ) \s* (?: \( [^)]* \) )? \s* \z/xi ? : 143 361 504
372 (?: (?:var)? binary (?: \s+ varying )?
373 | image | blob | bytea | (?: tiny | medium | long ) blob
374 )
375 \s* (?: \( [^)]* \) )? \s* \z/xi ? 1 : 0;
376 }
377  
378 # karr k47, k58. The type a column has ON THE SERVER, from the declaration:
379 # the one DBIO::MSSQL::DDL deploys it as, which resolves a portable name
380 # through DBIO::MSSQL::Adapter (text is nvarchar(max), varchar and string
381 # are nvarchar, char is nchar). Both access paths decide what to do with a
382 # value by this and not by the DBIO name -- a 'text' column is an NVARCHAR(MAX)
383 # and must be read and written as one. Takes the column info (data_type, size)
384 # or a bare data type; returns the lower-cased type, 'nvarchar(max)' or
385 # 'ntext', and the data type as it was when the DDL has no answer for it (a
386 # size it refuses, an unknown name). A type with parentheses is the server's
387 # own and stands (varchar(max) is a VARCHAR(MAX)).
388 191 ▶sub _server_data_type {
Subroutine _server_data_type: called CC=4 SCAR=13.9
389 191 my ($self, $column) = @_;
390  
391 191 ▶ my $info = ref $column eq 'HASH' ? $column : { data_type => $column };
Branch: 1 branch
BranchTrueFalseTotal
ref $column eq 'HASH' ? : 146 45 191
392  
393 191 ▶ return undef unless defined $info->{data_type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $info->{"data_type"} 1 190 191
394  
395 190 my $native = eval { DBIO::MSSQL::DDL::_mssql_column_type($info) };
396  
397 190 ▶ return lc( defined $native ? $native : $info->{data_type} );
Branch: 1 branch
BranchTrueFalseTotal
defined $native ? : 189 1 190
398 }
399  
400 # The bytes of a value for such a column: its characters 0 to 255, whatever
401 # form Perl holds the string in. A character above 255 is no byte; it is
402 # refused, not turned into the bytes of its UTF-8 form.
403 58 ▶sub _binary_value_bytes {
Subroutine _binary_value_bytes: called CC=6 SCAR=18.0
404 58 my ($self, $value, $column) = @_;
405  
406 58 ▶ return $value if not defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 57 58
407  
408 57 ▶ if (length ref $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (length ref $value) 1 56 57
409 1 ▶ return $value unless is_plain_value $value; # as core binds it: untouched
Branch: 1 branch
BranchTrueFalseTotal
unless &is_plain_value($value) 0 1 1
410 1 $value = "$value";
411 }
412  
413 57 my $bytes = $value;
414 57 ▶ return $bytes if utf8::downgrade($bytes, 1);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::downgrade($bytes, 1) 53 4 57
415  
416 4 my ($position) = grep { ord( substr $value, $_, 1 ) > 255 } 0 .. length($value) - 1;
417  
418 4 ▶ $self->throw_exception(sprintf
Branch: 1 branch
BranchTrueFalseTotal
defined $column ? : 4 0 4
419 'A value for the binary column%s has a character above 255 (U+%04X at '
420 . 'position %d of %d), which is no byte. A binary value is the bytes of '
421 . 'the string given, one per character: encode a text before it is stored '
422 . 'in a binary column.',
423 ( defined $column ? " '$column'" : '' ),
424 ord( substr $value, $position, 1 ), $position, length $value,
425 );
426 }
427  
428 # populate in void context hands the storage the rows, not bind values. The
429 # data set with every value bound to a binary column as its bytes, and
430 # whether there is such a value at all. Throws for a character above 255,
431 # before anything is sent.
432 14 ▶sub _bulk_binary_values_as_bytes {
Subroutine _bulk_binary_values_as_bytes: called CC=10 SCAR=28.7
433 14 my ($self, $source, $cols, $data) = @_;
434  
435 14 my $colinfos = $source->columns_info($cols);
436 my @binary = map {
437 14 ▶ $self->_is_binary_data_type( $colinfos->{ $cols->[$_] }{data_type} ) ? 1 : 0
Branch: 1 branch
BranchTrueFalseTotal
$self->_is_binary_data_type($$colinfos{$cols->[$_]}{'data_type'}) ? : 6 18 24
438 } 0 .. $#$cols;
439  
440 14 my $found = 0;
441 my @rows = map {
442 14 my @row = @$_;
443  
444 31 for my $i (0 .. $#row) {
445 # a literal with bind values, \[ $sql, @bind ]: each bind has its own type
446 0 ▶ if (ref $row[$i] eq 'REF' and ref ${ $row[$i] } eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $row[$i] eq 'REF' and ref ${$row[$i];} eq 'ARRAY') { } 0 52 52
elsif ($binary[$i] and ref $row[$i] ne 'SCALAR') { } 13 78 91
Condition33%1/3
ref $row[$i] eq "REF" and ref ${$row[$i];} eq "ARRAY"
!ll&&!rl&&r
5200
MC/DC0%0/2
ref $row[$i] eq "REF" and ref ${$row[$i];} eq "ARRAY"
ref $row[$i] eq "REF" ref ${$row[$i];} eq "ARRAY"
Truth table33%1/3
A and B
A= ref $row[$i] eq "REF"B= ref ${$row[$i];} eq "ARRAY"
ABresult
0X0
100
111
447 0 my ($sql, @bind) = @${ $row[$i] };
448 0 my $resolved = $self->_resolve_bindattrs($source, \@bind, $colinfos);
449  
450 next unless grep {
451 0 ▶ $self->_is_binary_data_type( $_->[0]{sqlt_datatype} )
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$self->_is_binary_data_type($_->[0]{"sqlt_datatype"});} @$resolved 0 0 0
452 0 } @$resolved;
453  
454 0 $found = 1;
455 0 $row[$i] = \[ $sql, map { [
456 $_->[0],
457 $self->_is_binary_data_type( $_->[0]{sqlt_datatype} )
458 ? $self->_binary_value_bytes( $_->[1], $_->[0]{dbic_colname} )
459 0 ▶ : $_->[1],
Branch: 1 branch
BranchTrueFalseTotal
$self->_is_binary_data_type($_->[0]{'sqlt_datatype'}) ? : 0 0 0
460 ] } @$resolved ];
461 }
462 ▶ elsif ($binary[$i] and ref $row[$i] ne 'SCALAR') {
Condition66%2/3
$binary[$i] and ref $row[$i] ne "SCALAR"
!ll&&!rl&&r
39013
MC/DC50%1/2
$binary[$i] and ref $row[$i] ne "SCALAR"
$binary[$i] ref $row[$i] ne "SCALAR"
Truth table66%2/3
A and B
A= $binary[$i]B= ref $row[$i] ne "SCALAR"
ABresult
0X0
100
111
463 13 $found = 1;
464 13 $row[$i] = $self->_binary_value_bytes( $row[$i], $cols->[$i] );
465 }
466 }
467  
468 29 \@row;
469 } @$data;
470  
471 12 ▶ return $found ? ( \@rows, 1 ) : ( $data, 0 );
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 4 8 12
472 }
473  
474 79 ▶sub last_insert_id { shift->_identity }
Subroutine last_insert_id: called CC=1 SCAR=0.0
Pod documented
475  
476  
477 #
478 # MSSQL is retarded wrt ordered subselects. One needs to add a TOP
479 # to *all* subqueries, but one also *can't* use TOP 100 PERCENT
480 # http://sqladvice.com/forums/permalink/18496/22931/ShowThread.aspx#22931
481 #
482 38 ▶sub _select_args_to_query {
Subroutine _select_args_to_query: called CC=4 SCAR=13.9
483 #my ($self, $ident, $select, $cond, $attrs) = @_;
484 38 my $self = shift;
485 38 my $attrs = $_[3];
486  
487 38 my $sql_bind = $self->next::method (@_);
488  
489 # see if this is an ordered subquery
490 38 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (not $$sql_bind->[0] =~ /^ \s* \( \s* SELECT \s+ TOP \s+ \d+ \s+ /xi and scalar $self->_extract_order_criteria($attrs->{"order_by"})) 12 26 38
Condition50%1/2
not $$sql_bind->[0] =~ /^ \s* \( \s* SELECT \s+ TOP \s+ \d+ \s+ /xi and scalar $self->_extract_order_criteria($attrs->{"order_by"})
!ll
038
MC/DC0%0/1
not $$sql_bind->[0] =~ /^ \s* \( \s* SELECT \s+ TOP \s+ \d+ \s+ /xi and scalar $self->_extract_order_criteria($attrs->{"order_by"})
not $$sql_bind->[0] =~ /^ \s* \( \s* SELECT \s+ TOP \s+ \d+ \s+ /xi
Truth table50%1/2
not(A)
A= not $$sql_bind->[0] =~ /^ \s* \( \s* SELECT \s+ TOP \s+ \d+ \s+ /xi
Aresult
00
11
491 $$sql_bind->[0] !~ /^ \s* \( \s* SELECT \s+ TOP \s+ \d+ \s+ /xi
492 and
493 scalar $self->_extract_order_criteria ($attrs->{order_by})
494 ) {
495 $self->throw_exception(
496 'An ordered subselect encountered - this is not safe! Please see "Ordered Subselects" in DBIO::MSSQL::Storage'
497 12 ▶ ) unless $attrs->{unsafe_subselect_ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $attrs->{"unsafe_subselect_ok"} 2 10 12
498  
499 10 $$sql_bind->[0] =~ s/^ \s* \( \s* SELECT (?=\s) / '(SELECT TOP ' . $self->sql_maker->__max_int /exi;
500 }
501  
502 36 $sql_bind;
503 }
504  
505  
506 # savepoint syntax is the same as in Sybase ASE
507  
508 0 ▶sub _exec_svp_begin {
Subroutine _exec_svp_begin: not called CC=1 SCAR=6.9
509 0 my ($self, $name) = @_;
510  
511 0 $self->_dbh->do("SAVE TRANSACTION $name");
512 }
513  
514 # A new SAVE TRANSACTION with the same name releases the previous one.
515 0 ▶sub _exec_svp_release { 1 }
Subroutine _exec_svp_release: not called CC=1 SCAR=6.9
516  
517 0 ▶sub _exec_svp_rollback {
Subroutine _exec_svp_rollback: not called CC=1 SCAR=6.9
518 0 my ($self, $name) = @_;
519  
520 0 $self->_dbh->do("ROLLBACK TRANSACTION $name");
521 }
522  
523 0 ▶sub sqlt_type { 'SQLServer' }
Subroutine sqlt_type: not called CC=1 SCAR=6.9
Pod documented
524  
525  
526 30 ▶sub _connect_params_dsn {
Subroutine _connect_params_dsn: called CC=7 SCAR=19.5
527 30 my ($self, $driver, $params) = @_;
528  
529 # $driver is the name this class is registered for -- 'MSSQL', which no DBD
530 # carries -- so it is not what goes into the DSN.
531 30 my ($dbname, $host, $port) = @{$params}{qw(dbname host port)};
532  
533 30 my $pair = 'DBD::Sybase reaches a server by its address only when it has '
534 . 'both (dbi:Sybase:host=<host>;port=<port>)';
535  
536 30 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if defined $host and not defined $port 4 26 30
Condition100%3/3
defined $host and not defined $port
!ll&&!rl&&r
8184
MC/DC100%2/2
defined $host and not defined $port
defined $host not defined $port
Truth table100%3/3
A and not(B)
A= defined $hostB= not defined $port
ABresult
0X0
100
111
537 'Cannot build a DBD::Sybase DSN from the connection parameter host '
538 . "without a port: $pair, and a host alone it ignores. No port is assumed "
539 . 'here -- 1433 is only where a default instance usually listens. Give '
540 . 'port as well, or supply a dsn instead (dbi:Sybase:... or dbi:ODBC:...).'
541 ) if defined $host && !defined $port;
542  
543 26 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if defined $port and not defined $host 4 22 26
Condition100%3/3
defined $port and not defined $host
!ll&&!rl&&r
4184
MC/DC100%2/2
defined $port and not defined $host
defined $port not defined $host
Truth table100%3/3
A and not(B)
A= defined $portB= not defined $host
ABresult
0X0
100
111
544 'Cannot build a DBD::Sybase DSN from the connection parameter port '
545 . "without a host: $pair, and a port alone it ignores. Give host as well, "
546 . 'leave port out, or supply a dsn instead (dbi:Sybase:... or dbi:ODBC:...).'
547 ) if defined $port && !defined $host;
548  
549 22 ▶ return 'dbi:Sybase:' . join ';',
Branch: 2 branches
BranchTrueFalseTotal
defined $host ? : 18 4 22
defined $dbname ? : 16 6 22
550 ( defined $host ? ("host=$host", "port=$port") : () ),
551 ( defined $dbname ? "database=$dbname" : () );
552 }
553  
554  
555 36 ▶sub _bind_host_into_dsn {
Subroutine _bind_host_into_dsn: called CC=30 SCAR=34.0
556 36 my ($self, $driver, $dsn, $host, $port) = @_;
557  
558 # DBD::Sybase takes host=/port= (core's default, which also declines
559 # server=NAME); any other DBD is not this seam's to translate.
560 36 ▶ return $self->next::method($driver, $dsn, $host, $port)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $driver and lc $driver eq "odbc" 4 32 36
Condition66%2/3
defined $driver and lc $driver eq "odbc"
!ll&&!rl&&r
0432
MC/DC50%1/2
defined $driver and lc $driver eq "odbc"
defined $driver lc $driver eq "odbc"
Truth table66%2/3
A and B
A= defined $driverB= lc $driver eq "odbc"
ABresult
0X0
100
111
561 unless defined $driver and lc $driver eq 'odbc';
562  
563 32 ▶ return (undef, 'a DSN without a dbi:ODBC: prefix')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dsn and $dsn =~ /\A(dbi:odbc(?:\([^)]*\))?:)(.*)\z/is 1 31 32
Condition66%2/3
defined $dsn and $dsn =~ /\A(dbi:odbc(?:\([^)]*\))?:)(.*)\z/is
!ll&&!rl&&r
0131
MC/DC50%1/2
defined $dsn and $dsn =~ /\A(dbi:odbc(?:\([^)]*\))?:)(.*)\z/is
defined $dsn $dsn =~ /\A(dbi:odbc(?:\([^)]*\))?:)(.*)\z/is
Truth table66%2/3
A and B
A= defined $dsnB= $dsn =~ /\A(dbi:odbc(?:\([^)]*\))?:)(.*)\z/is
ABresult
0X0
100
111
564 unless defined $dsn and $dsn =~ /\A(dbi:odbc(?:\([^)]*\))?:)(.*)\z/is;
565 31 my ($prefix, $rest) = ($1, $2);
566  
567 # Parts split on ';' outside braces ({ODBC Driver 18 for SQL Server}, or a
568 # value holding a ';').
569 31 my @parts;
570 31 my $at = 0;
571 31 ▶ while ($rest =~ /\G((?:[^;{]|\{[^}]*\})*)(;|\z)/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ /\G((?:[^;{]|\{[^}]*\})*)(;|\z)/cg) 77 1 78
572 77 push @parts, $1;
573 77 $at = pos $rest;
574 77 ▶ last unless length $2;
Branch: 1 branch
BranchTrueFalseTotal
unless length $2 30 47 77
575 }
576 31 ▶ return (undef, 'an unbalanced { in the DSN') unless $at == length $rest;
Branch: 1 branch
BranchTrueFalseTotal
unless $at == length $rest 1 30 31
577  
578 30 my (@server, @port);
579 30 for my $i (0 .. $#parts) {
580 75 ▶ next unless length $parts[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless length $parts[$i] 1 74 75
581 74 ▶ return (undef, 'a part without key=value form (a data source name)')
Branch: 1 branch
BranchTrueFalseTotal
unless $parts[$i] =~ /\A\s*(\w+)\s*=/ 1 73 74
582 unless $parts[$i] =~ /\A\s*(\w+)\s*=/;
583 73 my $key = $1;
584 73 my $lkey = lc $key;
585  
586 73 ▶ return (undef, "the key '$key' naming a data source or a configured server, "
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq "dsn" or $lkey eq "filedsn" or $lkey eq "servername" 8 65 73
Condition100%6/6
$lkey eq "dsn" or $lkey eq "filedsn" or $lkey eq "servername"
l!l&&r!l&&!r
6265
$lkey eq "dsn" or $lkey eq "filedsn"
l!l&&r!l&&!r
5167
MC/DC100%3/3
$lkey eq "dsn" or $lkey eq "filedsn" or $lkey eq "servername"
$lkey eq "dsn" $lkey eq "filedsn" $lkey eq "servername"
Truth table100%4/4
A or B or C
A= $lkey eq "dsn"B= $lkey eq "filedsn"C= $lkey eq "servername"
ABCresult
1XX1
01X1
0011
0000
587 . 'which holds no host to replace')
588 if $lkey eq 'dsn' or $lkey eq 'filedsn' or $lkey eq 'servername';
589 65 ▶ return (undef, "the key '$key' naming the server's address beside Server")
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq "address" or $lkey eq "addr" 1 64 65
Condition66%2/3
$lkey eq "address" or $lkey eq "addr"
l!l&&r!l&&!r
1064
MC/DC50%1/2
$lkey eq "address" or $lkey eq "addr"
$lkey eq "address" $lkey eq "addr"
Truth table66%2/3
A or B
A= $lkey eq "address"B= $lkey eq "addr"
ABresult
1X1
011
000
590 if $lkey eq 'address' or $lkey eq 'addr';
591  
592 64 ▶ push @server, $i if $lkey eq 'server';
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq "server" 20 44 64
593 64 ▶ push @port, $i if $lkey eq 'port';
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq "port" 7 57 64
594 }
595  
596 20 ▶ return (undef, "the key 'Server' more than once") if @server > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @server > 1 1 19 20
597 19 ▶ return (undef, "the key 'Port' more than once") if @port > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @port > 1 0 19 19
598 19 ▶ return (undef, 'a DSN without a Server key') unless @server;
Branch: 1 branch
BranchTrueFalseTotal
unless @server 1 18 19
599  
600 18 my ($skey, $svalue) = $parts[ $server[0] ] =~ /\A\s*(\w+)\s*=(.*)\z/s;
601  
602 18 ▶ return (undef, "the key '$skey' with a braced value") if $svalue =~ /\A\s*\{/;
Branch: 1 branch
BranchTrueFalseTotal
if $svalue =~ /\A\s*\{/ 1 17 18
603 17 ▶ return (undef, "the key '$skey' with an instance name (host\\instance)")
Branch: 1 branch
BranchTrueFalseTotal
if $svalue =~ /\\/ 1 16 17
604 if $svalue =~ /\\/;
605 16 ▶ return (undef, "the key '$skey' with a ':' in its value (a protocol prefix "
Branch: 1 branch
BranchTrueFalseTotal
if $svalue =~ /:/ 1 15 16
606 . 'such as tcp:, or an IPv6 address)')
607 if $svalue =~ /:/;
608  
609 15 ▶ if ($svalue =~ /\A[^,]*,(.*)\z/s) {
Branch: 2 branches
BranchTrueFalseTotal
if ($svalue =~ /\A[^,]*,(.*)\z/s) { } 6 9 15
elsif (@port) { } 6 3 9
610 # Server=host,port
611 6 my $old_port = $1;
612 6 ▶ return (undef, "both a port after the comma of '$skey' and a Port key")
Branch: 1 branch
BranchTrueFalseTotal
if @port 1 5 6
613 if @port;
614 5 ▶ $parts[ $server[0] ] = "$skey=$host," . ($port // $old_port);
Condition66%2/3
$port // $old_port
l!l&&r!l&&!r
410
MC/DC0%0/2
$port // $old_port
$port $old_port
Truth table66%2/3
A // B
A= $portB= $old_port
ABresult
1X1
011
000
615 }
616 elsif (@port) {
617 # Server=host;Port=n
618 6 $parts[ $server[0] ] = "$skey=$host";
619 6 ▶ if (defined $port) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $port) 5 1 6
620 5 my ($pkey) = $parts[ $port[0] ] =~ /\A\s*(\w+)/;
621 5 $parts[ $port[0] ] = "$pkey=$port";
622 }
623 }
624 else {
625 3 ▶ return (undef, "the key '$skey' without a port form (a ',port' behind it "
Branch: 1 branch
BranchTrueFalseTotal
if defined $port 1 2 3
626 . 'or a Port key) beside a port of the view')
627 if defined $port;
628 2 $parts[ $server[0] ] = "$skey=$host";
629 }
630  
631 13 return $prefix . join ';', @parts;
632 }
633  
634  
635 # The class of this driver for each DBD that reaches SQL Server (ADR 0035).
636 24 my %ACCESS_PATH_CLASS = (
637 ODBC => 'DBIO::MSSQL::Storage::ODBC',
638 Sybase => 'DBIO::MSSQL::Storage::Sybase',
639 );
640  
641 81 ▶sub _adapt_to_access_path {
Subroutine _adapt_to_access_path: called CC=15 SCAR=27.8
642 81 my ($self, $dbd) = @_;
643  
644 # A connection coderef names no DBD until it has run, and core does not run
645 # it for the hook. Connect info without a DSN -- a schema that only writes
646 # SQL -- has nothing to run and stays the declared class.
647 $dbd = $self->_get_dbh->{Driver}{Name}
648 81 ▶ if not defined $dbd and ref $self->_dbi_connect_info->[0];
Branch: 1 branch
BranchTrueFalseTotal
if not defined $dbd and ref $self->_dbi_connect_info->[0] 4 77 81
Condition66%2/3
not defined $dbd and ref $self->_dbi_connect_info->[0]
!ll&&!rl&&r
7704
MC/DC50%1/2
not defined $dbd and ref $self->_dbi_connect_info->[0]
not defined $dbd ref $self->_dbi_connect_info->[0]
Truth table66%2/3
not(A) and B
A= not defined $dbdB= ref $self->_dbi_connect_info->[0]
ABresult
0X0
100
111
649  
650 # The DBD of another driver, or one nobody knows: core judges that.
651 81 ▶ my $class = defined $dbd && $ACCESS_PATH_CLASS{$dbd}
Branch: 1 branch
BranchTrueFalseTotal
my $class = defined $dbd && $ACCESS_PATH_CLASS{$dbd} or return 75 6 81
Condition66%2/3
defined $dbd && $ACCESS_PATH_CLASS{$dbd}
!ll&&!rl&&r
0675
MC/DC50%1/2
defined $dbd && $ACCESS_PATH_CLASS{$dbd}
defined $dbd $ACCESS_PATH_CLASS{$dbd}
Truth table66%2/3
A && B
A= defined $dbdB= $ACCESS_PATH_CLASS{$dbd}
ABresult
0X0
100
111
652 or return;
653  
654 # A storage pinned to the access-path class itself is already there.
655 75 ▶ return if $self->isa($class);
Branch: 1 branch
BranchTrueFalseTotal
if $self->isa($class) 20 55 75
656  
657 # Only the declared base moves. A private subclass pinned by hand has to
658 # stay an instance of itself -- core checks that after the hook and throws
659 # -- and neither class above inherits it. (A layer class core composed over
660 # the declared base does not count as one: core's declared class is the
661 # base then.)
662 55 ▶ unless ( ( $self->_declared_storage_class || ref $self ) eq __PACKAGE__ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (($self->_declared_storage_class || ref $self) eq __PACKAGE__) 9 46 55
Condition33%1/3
$self->_declared_storage_class || ref $self
l!l&&r!l&&!r
5500
MC/DC0%0/2
$self->_declared_storage_class || ref $self
$self->_declared_storage_class ref $self
Truth table33%1/3
A || B
A= $self->_declared_storage_classB= ref $self
ABresult
1X1
011
000
663  
664 # Over DBD::Sybase such a class is refused (karr k42, k43; ADR 0008): the
665 # base is transport-neutral and has none of what the Sybase class does for
666 # this DBD. Over DBD::ODBC it is left alone.
667 # The DBD::ODBC class (or a derivation of it) is no derivation of the base
668 # that lacks anything: it is the wrong class for this DBD (karr k42).
669 $self->throw_exception(
670 'A storage class derived from ' . __PACKAGE__ . ' (' . ($self->_declared_storage_class || ref $self)
671 . ') is built for DBD::ODBC and cannot be used over DBD::Sybase: the '
672 . 'class and the DSN contradict each other. Pin '
673 . 'DBIO::MSSQL::Storage::Sybase (or a class derived from it) for '
674 . 'dbi:Sybase:, or give a dbi:ODBC: DSN.'
675 9 ▶ ) if $dbd eq 'Sybase' and $self->isa($ACCESS_PATH_CLASS{ODBC});
Branch: 1 branch
BranchTrueFalseTotal
if $dbd eq "Sybase" and $self->isa($ACCESS_PATH_CLASS{"ODBC"}) 2 7 9
Condition66%4/6
$dbd eq "Sybase" and $self->isa($ACCESS_PATH_CLASS{"ODBC"})
!ll&&!rl&&r
162
$self->_declared_storage_class || ref $self
l!l&&r!l&&!r
200
MC/DC100%2/2
$dbd eq "Sybase" and $self->isa($ACCESS_PATH_CLASS{"ODBC"})
$dbd eq "Sybase" $self->isa($ACCESS_PATH_CLASS{"ODBC"})
MC/DC0%0/2
$self->_declared_storage_class || ref $self
$self->_declared_storage_class ref $self
Truth table100%3/3
A and B
A= $dbd eq "Sybase"B= $self->isa($ACCESS_PATH_CLASS{"ODBC"})
ABresult
0X0
100
111
Truth table33%1/3
A || B
A= $self->_declared_storage_classB= ref $self
ABresult
1X1
011
000
676  
677 7 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $dbd eq "Sybase" 6 1 7
Condition33%1/3
$self->_declared_storage_class || ref $self
l!l&&r!l&&!r
600
MC/DC0%0/2
$self->_declared_storage_class || ref $self
$self->_declared_storage_class ref $self
Truth table33%1/3
A || B
A= $self->_declared_storage_classB= ref $self
ABresult
1X1
011
000
678 'A storage class derived from ' . __PACKAGE__ . ' (' . ($self->_declared_storage_class || ref $self)
679 . ') cannot be used over DBD::Sybase: the base class is transport-neutral '
680 . 'and has none of what this access path needs (transaction statements, '
681 . 'the 4000 byte limit of bind values, reading binary values). Derive '
682 . 'from DBIO::MSSQL::Storage::Sybase instead, or connect through '
683 . 'DBD::ODBC (dbi:ODBC:...).'
684 ) if $dbd eq 'Sybase';
685  
686 1 return;
687 }
688  
689 $self->throw_exception(
690 46 ▶ 'A connection to Microsoft SQL Server through DBD::Sybase needs '
Branch: 1 branch
BranchTrueFalseTotal
if $dbd eq "Sybase" and not $self->load_optional_class("DBIO::Sybase::Storage") 1 45 46
Condition100%3/3
$dbd eq "Sybase" and not $self->load_optional_class("DBIO::Sybase::Storage")
!ll&&!rl&&r
18271
MC/DC100%2/2
$dbd eq "Sybase" and not $self->load_optional_class("DBIO::Sybase::Storage")
$dbd eq "Sybase" not $self->load_optional_class("DBIO::Sybase::Storage")
Truth table100%3/3
A and not(B)
A= $dbd eq "Sybase"B= not $self->load_optional_class("DBIO::Sybase::Storage")
ABresult
0X0
100
111
691 . 'DBIO::Sybase, which is not installed: DBIO::MSSQL::Storage::Sybase, the '
692 . 'storage class for this access path, is built on DBIO::Sybase::Storage. '
693 . 'Install DBIO::Sybase, or connect through DBD::ODBC (dbi:ODBC:...).'
694 ) if $dbd eq 'Sybase'
695 and not $self->load_optional_class('DBIO::Sybase::Storage');
696  
697 45 $self->ensure_class_loaded($class);
698 45 bless $self, $class;
699  
700 # The turn of the class the storage became: what is left to decide on that
701 # access path is its own (NoBindVars over DBD::Sybase).
702 45 $self->_adapt_to_access_path($dbd);
703 }
704  
705  
706 1 ▶sub _random_function { 'NEWID()' }
Subroutine _random_function: called CC=1 SCAR=0.0
707  
708 # karr k22 / ADR 0040 -- the WHOLE operation of obtaining a query plan. Core's
709 # inherited operation is "EXPLAIN <query>" and Transact-SQL has no EXPLAIN
710 # statement at all, so there is nothing here for the server to parse. SQL
711 # Server is one of the two engines ADR 0040 widened this seam from a string to
712 # a method for, and spelling is not the reason: obtaining a plan here is not a
713 # statement but a SESSION SETTING, three round-trips with state left behind in
714 # between.
715 #
716 # The OFF is a Scope::Guard rather than a third line, and that is the whole
717 # point of this method's shape. If the middle statement throws -- a syntax
718 # error in the explained query, a dropped connection, anything -- an unguarded
719 # OFF is skipped and the SESSION IS LEFT POISONED: SHOWPLAN_ALL stays on for
720 # the life of that connection, so every later query on it returns a plan
721 # instead of its rows, with no error anywhere to notice. Well-formed rowsets,
722 # silently answering a question nobody asked, for as long as the handle is
723 # pooled -- a worse defect than the missing EXPLAIN this override fixes, and
724 # unlike it, quiet. The guard fires on both paths and touches nothing in
725 # flight, so the explained query's own exception is what propagates.
726 #
727 # All three statements go through _execute_rendered, which ADR 0040 section 3
728 # makes a requirement of the contract with no engine-named exceptions: it keeps
729 # _query_start / _query_end tracing and therefore redact_bind_value (ADR 0025)
730 # over the caller's own WHERE-clause values, dbh_do retry, NoBindVars
731 # interpolation, and the read handler rather than the master's on a replicated
732 # storage. Core delegates this whole method rather than the statements inside
733 # it, so all three land on one connection -- which a session setting requires.
734 3 ▶sub _explain_query {
Subroutine _explain_query: called CC=1 SCAR=0.0
735 3 my ($self, $sql, $bind) = @_;
736  
737 # Alone in its batch, which each _execute_rendered call is.
738 3 $self->_execute_rendered('SET SHOWPLAN_ALL ON', []);
739  
740 # Created only now, on purpose: a SET that failed was never applied, and
741 # turning off a setting the session never got would replace the real error
742 # with a second one.
743 2 ▶ my $showplan_off = Scope::Guard->new(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
744 2 $self->_execute_rendered('SET SHOWPLAN_ALL OFF', []);
745 2 });
746  
747 # Not executed while the setting is on -- the server answers this statement
748 # with its plan. The binds still travel with it: the statement is parsed, so
749 # its placeholders are still its own.
750 2 my (undef, $sth) = $self->_execute_rendered($sql, $bind);
751  
752 # Fetched BEFORE the guard fires (return evaluates, then the scope unwinds).
753 # Also deliberate: the OFF is a statement, and issuing one with an unfetched
754 # rowset pending is what desynchronises a DBD::Sybase connection.
755 1 return $sth->fetchall_arrayref;
756 }
757  
758 # ADR 0039. Transact-SQL has four of the six set operations, spelled the ANSI
759 # way, so the only opinion this driver has is a refusal -- everything else goes
760 # to next::method and inherits the base keyword.
761 #
762 # The engine fact, read rather than assumed: the <query_expression> production
763 # in SELECT (Transact-SQL) is
764 #
765 # { <query_specification> | ( <query_expression> ) }
766 # [ { UNION [ ALL ] | EXCEPT | INTERSECT }
767 # <query_specification> | ( <query_expression> ) [ ...n ] ]
768 #
769 # -- the optional ALL sits inside the UNION alternative only. The dedicated
770 # EXCEPT and INTERSECT page carries the same production, "{ EXCEPT | INTERSECT }",
771 # opens with "Returns distinct rows by comparing the results of two queries",
772 # and does not contain the word ALL anywhere on the page.
773 #
774 # ADR 0039 section 7 makes the hook a static class fact and then asks a driver
775 # whose gap is version-BOUNDED to choose between refusing unconditionally and a
776 # class-level opt-in. Neither choice arises here, and that is worth stating
777 # rather than leaving as an unexplained pick: this gap is not version-bounded.
778 # The grammar reads the same at both ends of what Microsoft documents -- the
779 # archived SQL Server 2008 R2 reference and the current one -- and EXCEPT /
780 # INTERSECT have never had an ALL form to lose. So the refusal is unconditional
781 # because the fact is, not as the price of deciding without a connection, and
782 # the ODBC / DBD::Sybase rebless split this repo already has (section 7's
783 # option (b)) has nothing to distinguish: both transports reach the same
784 # engine.
785 19 ▶sub _set_operation_keyword {
Subroutine _set_operation_keyword: called CC=4 SCAR=13.9
786 19 my ($self, $op) = @_;
787  
788 # let the base throw for an undefined operation (ADR 0039)
789 19 ▶ return $self->next::method($op) unless defined $op;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $op 1 18 19
790  
791 18 ▶ if ($op eq 'except_all' or $op eq 'intersect_all') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "except_all" or $op eq "intersect_all") 9 9 18
Condition100%3/3
$op eq "except_all" or $op eq "intersect_all"
l!l&&r!l&&!r
639
MC/DC100%2/2
$op eq "except_all" or $op eq "intersect_all"
$op eq "except_all" $op eq "intersect_all"
Truth table100%3/3
A or B
A= $op eq "except_all"B= $op eq "intersect_all"
ABresult
1X1
011
000
792 9 (my $distinct_form = $op) =~ s/_all\z//;
793  
794 9 $self->throw_exception(
795 "SQL Server has no $op: Transact-SQL spells set difference and set "
796 . 'intersection EXCEPT and INTERSECT, both of which always return '
797 . 'distinct rows, and has no ALL variant of either. This refusal is '
798 . 'unconditional and is not a version compromise -- the grammar reads '
799 . '"{ EXCEPT | INTERSECT }" in every version Microsoft documents '
800 . '(checked at both ends: the SQL Server 2008 R2 reference and the '
801 . 'current one), while UNION on the same engine is documented as '
802 . '"UNION [ ALL ]". The nearest available operation is '
803 . "->$distinct_form(), but it is not a substitute: it collapses "
804 . 'duplicate rows, so it answers a different question.'
805 );
806 }
807  
808 9 return $self->next::method($op);
809 }
810  
811  
812 32 ▶sub _mask_error_values {
Subroutine _mask_error_values: called CC=4 SCAR=13.9
813 32 my ($self, $text, $values, $statement) = @_;
814  
815 $text = DBIO::MSSQL::Util::mask_error_details(
816 $text, $values, $statement, ref $self ? $self->{_dbio_server_diag} : undef
817 32 ▶ ) if defined $text and !ref $text;
Branch: 2 branches
BranchTrueFalseTotal
if defined $text and not ref $text 24 8 32
ref $self ? : 24 0 24
Condition100%3/3
defined $text and not ref $text
!ll&&!rl&&r
4424
MC/DC100%2/2
defined $text and not ref $text
defined $text not ref $text
Truth table100%3/3
A and not(B)
A= defined $textB= not ref $text
ABresult
0X0
100
111
818  
819 32 return $self->next::method($text, $values, $statement);
820 }
821  
822 9 ▶sub _ping {
Subroutine _ping: called CC=2 SCAR=7.1
823 9 my $self = shift;
824  
825 9 ▶ my $dbh = $self->_dbh or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->_dbh or return 0 9 0 9
826  
827 9 local $dbh->{RaiseError} = 1;
828 9 local $dbh->{PrintError} = 0;
829  
830 9 ▶ return try {
Subroutine __ANON__: called CC=1 SCAR=0.0
831 9 $dbh->do('select 1');
832 9 1;
833 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
834 0 0;
835 9 };
836 }
837  
838 0 ▶sub with_deferred_fk_checks {
Subroutine with_deferred_fk_checks: not called CC=1 SCAR=6.9
Pod documented
839 0 my ( $self, $sub ) = @_;
840  
841 0 my $txn_scope_guard = $self->txn_scope_guard;
842  
843 0 $self->_do_query(
844 'EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL"');
845  
846 my $sg = Scope::Guard->new(
847 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
848 0 $self->_do_query(
849 'EXEC sp_msforeachtable "ALTER TABLE ? CHECK CONSTRAINT ALL"'
850 );
851 0 } );
852  
853 0 ▶ return preserve_context { $sub->() } after => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
854 # explicitly check constraints because MSSQL does not check when
855 # re-enabling them
856 0 $self->_do_query(
857 'EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL"'
858 );
859 0 $txn_scope_guard->commit;
860 0 $sg->dismiss;
861 0 };
862 }
863  
864  
865  
866 24 1;
867  
868 __END__
« MSSQL/DDL.pm ↑ Summary MSSQL/Introspect/Views.pm »