OnlineDDL/Helper/MySQL.pm

filter: Statementstmt 17.9% 29 / 162 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 25.8% 8 / 31 Podpod 100% 15 / 15 totaltotal 19.8% 52 / 262 CC 25 SCAR 39.3
CC
25
Cov
14%
post_fk_add_cleanup_stmts
156.0
foreign_key_info
90.0
rename_fks_in_table_sql
12.0
CRAP 51.1
« OnlineDDL.pm ↑ Summary OnlineDDL/Helper/Base.pm »
1 package DBIx::OnlineDDL::Helper::MySQL;
2  
3 1 our $AUTHORITY = 'cpan:GSG';
4 # ABSTRACT: Private OnlineDDL helper for MySQL-specific code
5 1 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 our $VERSION = 'v0.940.0'; # VERSION
7  
8 1 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 extends 'DBIx::OnlineDDL::Helper::Base';
12  
13 1 ▶use Types::Standard qw( InstanceOf );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 1 ▶use DBI::Const::GetInfoType;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use List::Util qw( first );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Sub::Util qw( set_subname );
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 1 ▶use namespace::clean; # don't export the above
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 #pod =encoding utf8
22 #pod
23 #pod =head1 DESCRIPTION
24 #pod
25 #pod This is a private helper module for any MySQL-specific code. B<As a private module, any
26 #pod methods or attributes here are subject to change.>
27 #pod
28 #pod You should really be reading documentation for L<DBIx::OnlineDDL>. Or, if you want to
29 #pod create a helper module for a different RDBMS, read the docs for
30 #pod L<DBIx::OnlineDDL::Helper::Base>.
31 #pod
32 #pod =cut
33  
34 0 ▶sub dbms_uses_global_fk_namespace { 1 }
Subroutine dbms_uses_global_fk_namespace: not called CC=1 SCAR=6.9
Pod documented
35 0 ▶sub child_fks_need_adjusting { 1 }
Subroutine child_fks_need_adjusting: not called CC=1 SCAR=6.9
Pod documented
36 0 ▶sub null_safe_equals_op { '<=>' }
Subroutine null_safe_equals_op: not called CC=1 SCAR=6.9
Pod documented
37  
38 sub current_catalog_schema {
39 0 ▶ my $self = shift;
Subroutine current_catalog_schema: not called CC=1 SCAR=6.9
Pod documented
40  
41 0 my ($schema) = $self->dbh->selectrow_array('SELECT DATABASE()');
42 0 return (undef, $schema);
43 }
44  
45 sub insert_select_stmt {
46 0 ▶ my ($self, $column_list_str) = @_;
Subroutine insert_select_stmt: not called CC=1 SCAR=6.9
Pod documented
47  
48 0 my $dbh = $self->dbh;
49  
50 0 my $id_name_quote = $dbh->quote_identifier( $self->copy_opts->{id_name} );
51  
52 0 my $orig_table_name_quote = $dbh->quote_identifier($self->table_name);
53 0 my $new_table_name_quote = $dbh->quote_identifier($self->new_table_name);
54  
55 # Use INSERT IGNORE to ignore dupe key errors. The LOCK IN SHARE MODE write-locks
56 # the source rows until they are copied. If anything needs to make any changes after
57 # that, the triggers will cover those.
58 0 return join("\n",
59 "INSERT IGNORE INTO $new_table_name_quote",
60 " ($column_list_str)",
61 "SELECT",
62 " $column_list_str",
63 "FROM $orig_table_name_quote",
64 "WHERE $id_name_quote BETWEEN ? AND ?",
65 "LOCK IN SHARE MODE"
66 );
67 }
68  
69 sub post_connection_stmts {
70 0 ▶ my $self = shift;
Subroutine post_connection_stmts: not called CC=1 SCAR=6.9
Pod documented
71  
72 0 my $db_timeouts = $self->db_timeouts;
73 return (
74 # Use the right database, just in case it's not in the DSN.
75 "USE ".$self->dbh->quote_identifier($self->vars->{schema}),
76  
77 # Foreign key constraints should not interrupt the process. Nor should they be
78 # checked when trying to add or remove them. This would cause a simple FK DDL
79 # to turn into a long-running operation on pre-existing tables.
80 'SET SESSION foreign_key_checks=0',
81  
82 # DB timeouts
83 'SET SESSION wait_timeout='.$db_timeouts->{session},
84 'SET SESSION lock_wait_timeout='.$db_timeouts->{lock_db},
85 'SET SESSION innodb_lock_wait_timeout='.$db_timeouts->{lock_row},
86 0 );
87 }
88  
89 sub is_error_retryable {
90 0 ▶ my ($self, $error) = @_;
Subroutine is_error_retryable: not called CC=1 SCAR=6.9
Pod documented
91  
92 # Disable /x flag to allow for whitespace within string, but turn it on for newlines
93 # and comments.
94 0 return $error =~ m<
95 # Locks
96 (?-x:deadlock found)|
97 (?-x:wsrep detected deadlock/conflict)|
98 (?-x:lock wait timeout exceeded)|
99  
100 # Connections
101 (?-x:mysql server has gone away)|
102 (?-x:lost connection to mysql server)|
103  
104 # Queries
105 (?-x:query execution was interrupted)|
106  
107 # Failovers
108 (?-x:wsrep has not yet prepared node for application use)
109 >xi;
110 }
111  
112 sub create_table_sql {
113 0 ▶ my ($self, $table_name) = @_;
Subroutine create_table_sql: not called CC=1 SCAR=6.9
Pod documented
114  
115 0 my $table_name_quote = $self->dbh->quote_identifier($table_name);
116  
117 0 my $create_sql;
118 $self->dbh_runner(run => set_subname '_create_table_sql', sub {
119 0 ▶ $create_sql = $_->selectrow_hashref("SHOW CREATE TABLE $table_name_quote")->{'Create Table'};
Subroutine __ANON__: not called CC=1 SCAR=6.9
120 0 });
121  
122 0 return $create_sql;
123 }
124  
125 sub rename_fks_in_table_sql {
126 0 ▶ my ($self, $table_name, $table_sql) = @_;
Subroutine rename_fks_in_table_sql: not called CC=3 SCAR=24.8
Pod documented
127  
128 0 my $dbh = $self->dbh;
129  
130 # Since MySQL uses a global namespace for foreign keys, these will have to be renamed
131 0 ▶ my $iq_chars = $dbh->get_info( $GetInfoType{SQL_IDENTIFIER_QUOTE_CHAR} ) || '`';
Condition0%0/2
$dbh->get_info($DBIx::OnlineDDL::Helper::MySQL::GetInfoType{'SQL_IDENTIFIER_QUOTE_CHAR'}) || '`'
l!l
00
MC/DC0%0/1
$dbh->get_info($DBIx::OnlineDDL::Helper::MySQL::GetInfoType{'SQL_IDENTIFIER_QUOTE_CHAR'}) || '`'
$dbh->get_info($DBIx::OnlineDDL::Helper::MySQL::GetInfoType{'SQL_IDENTIFIER_QUOTE_CHAR'})
Truth table0%0/2
A
A= $dbh->get_info($DBIx::OnlineDDL::Helper::MySQL::GetInfoType{'SQL_IDENTIFIER_QUOTE_CHAR'})
Aresult
11
00
132 0 $iq_chars .= '"'; # include ANSI quotes
133  
134 0 my $iqre = '['.quotemeta($iq_chars).']';
135 0 my $noniq_re = '[^'.quotemeta($iq_chars).'\s]';
136  
137 0 my @fk_names = ($table_sql =~ /CONSTRAINT ${iqre}(${noniq_re}+)${iqre} FOREIGN KEY/ig);
138  
139 0 foreach my $fk_name (@fk_names) {
140 my $new_fk_name = $self->find_new_identifier(
141 "_${fk_name}" => set_subname '_fk_name_finder', sub {
142 0 ▶ $_[0]->selectrow_array(
Subroutine __ANON__: not called CC=1 SCAR=6.9
143 'SELECT table_name FROM information_schema.key_column_usage WHERE '.join(' AND ',
144 'constraint_schema = DATABASE()',
145 'constraint_name = ?',
146 # This is required for MySQL 5 server table cache optimization in the EXPLAIN plan
147 'table_schema = DATABASE()',
148 ), undef, $_[1]
149 );
150 },
151 0 );
152 0 $self->vars->{foreign_keys}{orig_names}{"$table_name.$new_fk_name"} = $fk_name;
153  
154 0 my $fk_name_re = quotemeta $fk_name;
155 0 $table_sql =~ s/(?<=CONSTRAINT ${iqre})$fk_name_re(?=${iqre} FOREIGN KEY)/$new_fk_name/;
156 }
157  
158 0 return $table_sql;
159 }
160  
161 sub has_conflicting_triggers_on_table {
162 0 ▶ my ($self, $table_name) = @_;
Subroutine has_conflicting_triggers_on_table: not called CC=2 SCAR=17.9
Pod documented
163 0 my $mmver = $self->mmver;
164  
165 # Multiple triggers aren't allowed in MySQL 5.6
166 0 ▶ if ($mmver < 5.007) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mmver < 5.007) { } 0 0 0
167 return $self->dbh_runner(run => set_subname '_has_triggers_on_table', sub {
168 0 ▶ $_->selectrow_array(
Subroutine __ANON__: not called CC=1 SCAR=6.9
169 'SELECT trigger_name FROM information_schema.triggers WHERE event_object_schema = DATABASE() AND event_object_table = ?',
170 undef, $table_name
171 );
172 0 });
173 }
174 # MySQL 5.7+ allows them, so look for anything that looks like a leftover OnlineDDL
175 # trigger name.
176 else {
177 return $self->dbh_runner(run => set_subname '_has_onlineddl_triggers_on_table', sub {
178 0 ▶ $_->selectrow_array(
Subroutine __ANON__: not called CC=1 SCAR=6.9
179 'SELECT trigger_name FROM information_schema.triggers WHERE '.join(' AND ',
180 'event_object_schema = DATABASE()',
181 'event_object_table = ?',
182 'trigger_name LIKE ?',
183 ), undef, $table_name, "\%${table_name}\\_onlineddl\\_\%"
184 );
185 0 });
186 }
187 }
188  
189 sub find_new_trigger_identifier {
190 0 ▶ my ($self, $trigger_name) = @_;
Subroutine find_new_trigger_identifier: not called CC=1 SCAR=6.9
Pod documented
191  
192 return $self->find_new_identifier(
193 $trigger_name => sub {
194 0 ▶ $_[0]->selectrow_array(
Subroutine __ANON__: not called CC=1 SCAR=6.9
195 'SELECT trigger_name FROM information_schema.triggers WHERE event_object_schema = DATABASE() AND trigger_name = ?',
196 undef, $_[1]
197 );
198 },
199 0 );
200 }
201  
202 sub modify_trigger_dml_stmts {
203 0 ▶ my ($self, $stmts) = @_;
Subroutine modify_trigger_dml_stmts: not called CC=1 SCAR=6.9
Pod documented
204  
205 # Ignore errors
206 0 $stmts->{delete_for_update} =~ s/^DELETE/DELETE IGNORE/;
207 0 $stmts->{delete_for_update} =~ s/^DELETE/DELETE IGNORE/;
208 }
209  
210 # Keep Base->analyze_table
211  
212 sub swap_tables {
213 0 ▶ my ($self, $new_table_name, $orig_table_name, $old_table_name) = @_;
Subroutine swap_tables: not called CC=1 SCAR=6.9
Pod documented
214 0 my $dbh = $self->dbh;
215  
216 0 my $new_table_name_quote = $dbh->quote_identifier($new_table_name);
217 0 my $orig_table_name_quote = $dbh->quote_identifier($orig_table_name);
218 0 my $old_table_name_quote = $dbh->quote_identifier($old_table_name);
219  
220 0 $self->dbh_runner_do(
221 "RENAME TABLE $orig_table_name_quote TO $old_table_name_quote, $new_table_name_quote TO $orig_table_name_quote"
222 );
223 }
224  
225 ### NOTE: The typical SQL in DBD::mysql is badly optimized for MySQL 5 and very large sets
226 ### of databases/table/column combos. Furthermore, the kludgy join to TABLE_CONSTRAINTS
227 ### is entirely unnecessary. See also: https://github.com/perl5-dbi/DBD-mysql/issues/326
228 sub foreign_key_info {
229 0 ▶ my $self = shift;
Subroutine foreign_key_info: not called CC=9 SCAR=45.0
Pod documented
230 0 my $dbh = $self->dbh;
231 0 my $mmver = $self->mmver;
232  
233 # MySQL 8's information_schema implementation isn't a complete dumpster fire of
234 # in-memory jank, and totes won't send your precious DB server into a horrible
235 # OOM death. So, skip this noise in that case.
236 #
237 # More info: https://mysqlserverteam.com/mysql-8-0-improvements-to-information_schema/
238 0 ▶ return $dbh->foreign_key_info(@_) if $mmver >= 8;
Branch: 1 branch
BranchTrueFalseTotal
if $mmver >= 8 0 0 0
239 0 ▶ return if $mmver < 5; # not supported by OnlineDDL, anyway
Branch: 1 branch
BranchTrueFalseTotal
if $mmver < 5 0 0 0
240  
241 my (
242 0 $pk_catalog, $pk_schema, $pk_table,
243 $fk_catalog, $fk_schema, $fk_table,
244 ) = @_;
245  
246 0 my $sql = <<'EOF';
247 SELECT
248 NULL AS PKTABLE_CAT,
249 REFERENCED_TABLE_SCHEMA AS PKTABLE_SCHEM,
250 REFERENCED_TABLE_NAME AS PKTABLE_NAME,
251 REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME,
252 TABLE_CATALOG AS FKTABLE_CAT,
253 TABLE_SCHEMA AS FKTABLE_SCHEM,
254 TABLE_NAME AS FKTABLE_NAME,
255 COLUMN_NAME AS FKCOLUMN_NAME,
256 ORDINAL_POSITION AS KEY_SEQ,
257 NULL AS UPDATE_RULE,
258 NULL AS DELETE_RULE,
259 CONSTRAINT_NAME AS FK_NAME,
260 NULL AS PK_NAME,
261 NULL AS DEFERABILITY,
262 NULL AS UNIQUE_OR_PRIMARY
263 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
264 EOF
265  
266 ### XXX: This breaks OnlineDDL's re-applying of cross-database FKs in foreign child
267 ### tables. But, without this fix, MySQL has to scan all databases to find them.
268 ### Again, this is no longer a problem with MySQL 8.
269 0 ▶ $fk_schema //= $pk_schema;
Condition0%0/3
$fk_schema //= $pk_schema
l!l&&r!l&&!r
000
MC/DC0%0/2
$fk_schema //= $pk_schema
$fk_schema $pk_schema
Truth table0%0/3
A //= B
A= $fk_schemaB= $pk_schema
ABresult
1X1
011
000
270  
271 0 my @where;
272 my @bind;
273  
274 0 ▶ if (defined $pk_schema) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pk_schema) 0 0 0
275 0 push @where, 'REFERENCED_TABLE_SCHEMA = ?';
276 0 push @bind, $pk_schema;
277 }
278  
279 0 ▶ if (defined $pk_table) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pk_table) 0 0 0
280 0 push @where, 'REFERENCED_TABLE_NAME = ?';
281 0 push @bind, $pk_table;
282 }
283  
284 0 ▶ if (defined $fk_schema) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fk_schema) 0 0 0
285 0 push @where, 'TABLE_SCHEMA = ?';
286 0 push @bind, $fk_schema;
287 }
288  
289 0 ▶ if (defined $fk_table) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fk_table) 0 0 0
290 0 push @where, 'TABLE_NAME = ?';
291 0 push @bind, $fk_table;
292 }
293  
294 0 ▶ if (@where) {
Branch: 1 branch
BranchTrueFalseTotal
if (@where) 0 0 0
295 0 $sql .= "\nWHERE ";
296 0 $sql .= join ' AND ', @where;
297 }
298 0 $sql .= "\nORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION";
299  
300 0 local $dbh->{FetchHashKeyName} = 'NAME_uc';
301 0 my $sth = $dbh->prepare($sql);
302 0 $sth->execute(@bind);
303  
304 0 return $sth;
305 }
306  
307 # MySQL uses 'FOREIGN KEY' on DROPs, for some reason
308 around 'remove_fks_from_child_tables_stmts' => sub {
309 0 ▶ my $orig = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
310 0 my @stmts = $orig->(@_);
311  
312 0 return map { s/ DROP CONSTRAINT / DROP FOREIGN KEY /; $_ } @stmts;
313 1 };
314  
315 around 'rename_fks_back_to_original_stmts' => sub {
316 0 ▶ my $orig = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
317 0 my @stmts = $orig->(@_);
318  
319 0 return map { s/ DROP CONSTRAINT / DROP FOREIGN KEY /; $_ } @stmts;
320 1 };
321  
322 # Keep Base->add_fks_back_to_child_tables_stmts (no DROPs on those)
323  
324 # Look for default FK-created indexes that get mysteriously renamed after the FKs are
325 # recreated. (SM-3039)
326 sub post_fk_add_cleanup_stmts {
327 0 ▶ my $self = shift;
Subroutine post_fk_add_cleanup_stmts: not called CC=12 SCAR=50.5
Pod documented
328 0 my $dbh = $self->dbh;
329 0 my $mmver = $self->mmver;
330 0 my $vars = $self->vars;
331 0 my $catalog = $vars->{catalog};
332 0 my $schema = $vars->{schema};
333 0 my $idx_hash = $vars->{indexes}{definitions};
334  
335 0 my @stmts;
336 0 foreach my $table_name (sort keys %$idx_hash) {
337 0 my %old_idx_data = %{ $idx_hash->{$table_name} };
338 0 my %new_idx_data = %{ $self->get_idx_hash($table_name) };
339  
340 0 foreach my $index_name (sort keys %old_idx_data) {
341 0 ▶ next if $index_name eq 'PRIMARY';
Branch: 1 branch
BranchTrueFalseTotal
if $index_name eq "PRIMARY" 0 0 0
342  
343 0 my $old_idx = $old_idx_data{$index_name};
344 0 my $new_idx = $new_idx_data{$index_name};
345 0 my $old_col_str = join ', ', @{$old_idx->{columns}};
346  
347 next if $new_idx &&
348 0 $old_col_str eq join(', ', @{$new_idx->{columns}}) &&
349 $old_idx->{unique} == $new_idx->{unique}
350 0 ▶ ;
Branch: 1 branch
BranchTrueFalseTotal
if $new_idx and $old_col_str eq join(", ", @{$new_idx->{"columns"};}) and $old_idx->{"unique"} == $new_idx->{"unique"} 0 0 0
Condition0%0/6
$new_idx and $old_col_str eq join(", ", @{$new_idx->{"columns"};}) and $old_idx->{"unique"} == $new_idx->{"unique"}
!ll&&!rl&&r
000
$new_idx and $old_col_str eq join(", ", @{$new_idx->{"columns"};})
!ll&&!rl&&r
000
MC/DC0%0/3
$new_idx and $old_col_str eq join(", ", @{$new_idx->{"columns"};}) and $old_idx->{"unique"} == $new_idx->{"unique"}
$new_idx $old_col_str eq join(", ", @{$new_idx->{"columns"};}) $old_idx->{"unique"} == $new_idx->{"unique"}
Truth table0%0/4
A and B and C
A= $new_idxB= $old_col_str eq join(", ", @{$new_idx->{"columns"};})C= $old_idx->{"unique"} == $new_idx->{"unique"}
ABCresult
0XX0
10X0
1100
1111
351  
352 # It failed one of the other checks?
353 0 ▶ if ($new_idx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_idx) 0 0 0
354 my $conditional =
355 $old_idx->{unique} != $new_idx->{unique} ?
356 ($new_idx->{unique} ? "it is now UNIQUE" : "it is no longer UNIQUE") :
357 0 ▶ "its columns have changed (".join(', ', @{$new_idx->{columns}}).")"
Branch: 2 branches
BranchTrueFalseTotal
$old_idx->{'unique'} != $new_idx->{'unique'} ? : 0 0 0
$new_idx->{'unique'} ? : 0 0 0
358 ;
359  
360 0 $self->progress->message( join "\n",
361 '',
362 "WARNING: Found index $table_name.$index_name ($old_col_str), but $conditional!",
363 "Please double-check that the indexes on the table are what you expect!",
364 '',
365 );
366 0 next;
367 }
368  
369 # It looks like we have a mismatch at this point. Try to find the renamed index.
370 $new_idx = first {
371 $_->{name} ne 'PRIMARY' &&
372 0 $old_col_str eq join(', ', @{$_->{columns}}) &&
373 $old_idx->{unique} == $_->{unique}
374 0 ▶ } values %new_idx_data;
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
$_->{"name"} ne "PRIMARY" and $old_col_str eq join(", ", @{$_->{"columns"};}) and $old_idx->{"unique"} == $_->{"unique"} 0 0 0
Condition0%0/3
$_->{"name"} ne "PRIMARY" and $old_col_str eq join(", ", @{$_->{"columns"};})
!ll&&!rl&&r
000
MC/DC0%0/2
$_->{"name"} ne "PRIMARY" and $old_col_str eq join(", ", @{$_->{"columns"};})
$_->{"name"} ne "PRIMARY" $old_col_str eq join(", ", @{$_->{"columns"};})
Truth table0%0/3
A and B
A= $_->{"name"} ne "PRIMARY"B= $old_col_str eq join(", ", @{$_->{"columns"};})
ABresult
0X0
100
111
375  
376 # It disappeared?
377 0 ▶ unless ($new_idx) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($new_idx) 0 0 0
378 0 $self->progress->message( join "\n",
379 '',
380 "WARNING: Found index $table_name.$index_name ($old_col_str), which may have been renamed, but a matching index cannot be found!",
381 "Please double-check that the indexes on the table are what you expect!",
382 '',
383 );
384 0 next;
385 }
386  
387 0 my $new_index_name = $new_idx->{name};
388  
389 # We can only rename in MySQL 5.7
390 0 ▶ if ($mmver < 5.007) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mmver < "5.007") 0 0 0
391 0 $self->progress->message( join "\n",
392 '',
393 "WARNING: Found index $table_name.$index_name ($old_col_str), which was renamed to $new_index_name!",
394 "The index cannot safely renamed in MySQL $mmver, so you may need to DROP/ADD this",
395 "index a different way to correct the problem.",
396 '',
397 );
398 0 next;
399 }
400  
401 # Finally, add a RENAME INDEX statement
402 0 push @stmts, join(' ',
403 "ALTER TABLE",
404 $dbh->quote_identifier( $table_name ),
405 "RENAME INDEX",
406 $dbh->quote_identifier( $new_index_name ),
407 "TO",
408 $dbh->quote_identifier( $index_name ),
409 );
410 }
411 }
412  
413 0 return @stmts;
414 }
415  
416 1 1;
417  
418 __END__
« OnlineDDL.pm ↑ Summary OnlineDDL/Helper/Base.pm »