Fast/Profile/MariaDB.pm

filter: Statementstmt 17.0% 62 / 363 Branchbran 22.3% 17 / 76 Conditioncond 1.7% 1 / 58 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 16.6% 5 / 30 Podpod 73.6% 14 / 19 totaltotal 17.1% 99 / 577 CC 81 SCAR 45.7
CC
81
Cov
16%
print_connection_monitor
272.0
print_index_analysis
210.0
_analyze_index_problems
110.0
CRAP 96.7
↑ Summary Fast/X.pm »
1 package DBIx::Fast::Profile::MariaDB;
2  
3 2 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 2 our $VERSION = '0.22';
7 2 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 2 ▶class DBIx::Fast::Profile::MariaDB :isa(DBIx::Fast::Profile::Base) {
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # EXPLAIN hardening (see _validate_explainable_sql / _explain_sql):
12 # functions that stall the session or leak data through error text.
13 2 my $EXPLAIN_DENY = qr/\b(?:SLEEP|BENCHMARK|GET_LOCK|MASTER_GTID_WAIT
14 |MASTER_POS_WAIT|SOURCE_POS_WAIT
15 |WAIT_FOR_EXECUTED_GTID_SET
16 |WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS
17 |EXTRACTVALUE|UPDATEXML)\s*\(/xi;
18 2 our $EXPLAIN_TIMEOUT = 5; # seconds, MariaDB max_statement_time (tunable)
19  
20 # Strip control characters before printing strings that originate in OTHER
21 # database sessions (processlist queries, usernames): they could embed ANSI
22 # escapes that manipulate the terminal of whoever runs the monitor.
23 0 ▶ sub _term_safe ($str) {
Subroutine _term_safe: not called CC=2 SCAR=17.9
24 0 ▶ return $str unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 0 0
25 0 $str =~ s/[^\P{Cc}\n\t]//g;
26 0 return $str;
27 }
28  
29 0 ▶ method init () {
Subroutine init: not called CC=1 SCAR=6.9
Pod documented
30 0 $self->dbix->exec('SET profiling = 1');
31 0 $self->dbix->exec('SET profiling_history_size = 100');
32 0 eval { $self->dbix->exec('SET session profiling_use_getrusage = 1') };
33 2 }
34  
35 0 ▶ method get_slow_queries () {
Subroutine get_slow_queries: not called CC=1 SCAR=6.9
Pod documented
36 0 my $queries = $self->dbix->all(q{
37 SELECT
38 query_id AS query_id,
39 SUM(duration) as total_time,
40 query as sql_text,
41 COUNT(*) as stages
42 FROM information_schema.profiling
43 GROUP BY query_id, query
44 HAVING total_time > ?
45 ORDER BY total_time DESC
46 }, $self->slow_query);
47  
48 0 return $queries;
49 2 }
50  
51 0 ▶ method get_query_profile ($query_id) {
Subroutine get_query_profile: not called CC=1 SCAR=6.9
Pod documented
52 0 return $self->dbix->all(q{
53 SELECT
54 state AS state,
55 duration AS duration,
56 cpu_user AS cpu_user,
57 cpu_system AS cpu_system,
58 context_voluntary AS context_voluntary,
59 context_involuntary AS context_involuntary,
60 block_ops_in AS block_ops_in,
61 block_ops_out AS block_ops_out,
62 messages_sent AS messages_sent,
63 messages_received AS messages_received,
64 page_faults_major AS page_faults_major,
65 page_faults_minor AS page_faults_minor,
66 swaps AS swaps,
67 source_function AS source_function,
68 source_file AS source_file,
69 source_line AS source_line
70 FROM information_schema.profiling
71 WHERE query_id = ?
72 ORDER BY seq
73 }, $query_id);
74 2 }
75  
76 0 ▶ method get_stats () {
Subroutine get_stats: not called CC=1 SCAR=6.9
Pod documented
77 0 my $stats = {};
78  
79 0 my $global = $self->dbix->all(q{
80 SHOW GLOBAL STATUS WHERE Variable_name IN (
81 'Questions',
82 'Slow_queries',
83 'Com_select',
84 'Com_insert',
85 'Com_update',
86 'Com_delete',
87 'Created_tmp_tables',
88 'Created_tmp_disk_tables',
89 'Select_full_join',
90 'Select_full_range_join',
91 'Select_range',
92 'Select_range_check',
93 'Select_scan',
94 'Sort_merge_passes',
95 'Sort_range',
96 'Sort_rows',
97 'Sort_scan'
98 )
99 });
100  
101 $stats->{global} =
102 0 { map { $_->{Variable_name} => $_->{Value} } @$global };
103  
104 0 my $session = $self->dbix->hash(q{
105 SELECT
106 COUNT(*) as total_queries,
107 SUM(CASE WHEN command = 'Query' THEN 1 ELSE 0 END) as query_count,
108 SUM(CASE WHEN command = 'Sleep' THEN 1 ELSE 0 END) as sleep_count
109 FROM information_schema.processlist
110 WHERE id = CONNECTION_ID()
111 });
112  
113 0 $stats->{session} = $session;
114  
115 0 return $stats;
116 2 }
117  
118 0 ▶ method print_stats () {
Subroutine print_stats: not called CC=5 SCAR=34.0
Pod documented
119 0 my $stats = $self->get_stats();
120 0 ▶ return if $self->emit( stats => $stats );
Branch: 1 branch
BranchTrueFalseTotal
if $self->emit("stats", $stats) 0 0 0
121  
122 0 $self->out("\n=== MariaDB Query Statistics ===\n");
123 0 $self->out("\nGlobal Statistics:\n");
124 0 $self->outf("Questions: %d\n", $stats->{global}->{Questions});
125 0 $self->outf("Slow Queries: %d\n", $stats->{global}->{Slow_queries});
126 0 $self->outf("SELECT queries: %d\n", $stats->{global}->{Com_select});
127 0 $self->outf("INSERT queries: %d\n", $stats->{global}->{Com_insert});
128 0 $self->outf("UPDATE queries: %d\n", $stats->{global}->{Com_update});
129 0 $self->outf("DELETE queries: %d\n", $stats->{global}->{Com_delete});
130  
131 0 $self->out("\nOptimization Statistics:\n");
132 $self->outf("Temp tables: %d (disk: %d)\n",
133 $stats->{global}->{Created_tmp_tables},
134 0 $stats->{global}->{Created_tmp_disk_tables});
135 0 $self->outf("Full table scans: %d\n", $stats->{global}->{Select_scan});
136 0 $self->outf("Range queries: %d\n", $stats->{global}->{Select_range});
137 0 $self->outf("Sort merges: %d\n", $stats->{global}->{Sort_merge_passes});
138  
139 0 $self->out("\nSession Statistics:\n");
140 0 ▶ $self->outf("Total Queries: %d\n", $stats->{session}->{total_queries} // 0);
Condition0%0/2
$stats->{"session"}{"total_queries"} // 0
l!l
00
MC/DC0%0/1
$stats->{"session"}{"total_queries"} // 0
$stats->{"session"}{"total_queries"}
Truth table0%0/2
A
A= $stats->{"session"}{"total_queries"}
Aresult
11
00
141 0 ▶ $self->outf("Query Count: %d\n", $stats->{session}->{query_count} // 0);
Condition0%0/2
$stats->{"session"}{"query_count"} // 0
l!l
00
MC/DC0%0/1
$stats->{"session"}{"query_count"} // 0
$stats->{"session"}{"query_count"}
Truth table0%0/2
A
A= $stats->{"session"}{"query_count"}
Aresult
11
00
142 0 ▶ $self->outf("Sleep Count: %d\n", $stats->{session}->{sleep_count} // 0);
Condition0%0/2
$stats->{"session"}{"sleep_count"} // 0
l!l
00
MC/DC0%0/1
$stats->{"session"}{"sleep_count"} // 0
$stats->{"session"}{"sleep_count"}
Truth table0%0/2
A
A= $stats->{"session"}{"sleep_count"}
Aresult
11
00
143 2 }
144  
145 11 ▶ method _validate_explainable_sql ($sql_text) {
Subroutine _validate_explainable_sql: called CC=13 SCAR=26.1
146 11 ▶ return unless defined $sql_text && length $sql_text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sql_text and length $sql_text 0 11 11
Condition33%1/3
defined $sql_text and length $sql_text
!ll&&!rl&&r
0011
MC/DC0%0/2
defined $sql_text and length $sql_text
defined $sql_text length $sql_text
Truth table33%1/3
A and B
A= defined $sql_textB= length $sql_text
ABresult
0X0
100
111
147  
148 11 $sql_text =~ s/^\s+|\s+$//g;
149  
150 11 ▶ return unless $sql_text =~ /^(?:SELECT|INSERT|UPDATE|DELETE|TABLE|WITH)\b/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $sql_text =~ /^(?:SELECT|INSERT|UPDATE|DELETE|TABLE|WITH)\b/iu 0 11 11
151  
152 11 ▶ return if $sql_text =~ m{;|--|/\*|#}; # terminators / comments
Branch: 1 branch
BranchTrueFalseTotal
if $sql_text =~ m[;|--|/\*|#]u 1 10 11
153  
154 # Scan the dangerous-construct checks on a copy with quoted string
155 # literals removed, so a legitimate value like '0x41' or 'load_file note'
156 # is not mistaken for a hex literal / file function.
157 10 (my $bare = $sql_text) =~ s/'(?:[^'\\]|\\.)*'//g;
158 10 $bare =~ s/"(?:[^"\\]|\\.)*"//g;
159  
160 10 ▶ return if $bare =~ /\b0x[0-9a-f]+/i; # hex literals
Branch: 1 branch
BranchTrueFalseTotal
if $bare =~ /\b0x[0-9a-f]+/iu 1 9 10
161 9 ▶ return if $bare =~ /\bLOAD_FILE\b/i; # file read
Branch: 1 branch
BranchTrueFalseTotal
if $bare =~ /\bLOAD_FILE\b/iu 1 8 9
162 8 ▶ return if $bare =~ /\bINTO\s+(?:OUTFILE|DUMPFILE)\b/i; # file write
Branch: 1 branch
BranchTrueFalseTotal
if $bare =~ /\bINTO\s+(?:OUTFILE|DUMPFILE)\b/iu 1 7 8
163 # EXPLAIN-time DoS: older optimizers materialize derived tables.
164 7 ▶ return if $bare =~ $EXPLAIN_DENY;
Branch: 1 branch
BranchTrueFalseTotal
if $bare =~ /$EXPLAIN_DENY/u 2 5 7
165  
166 # The stripping above assumes backslash escapes; a server running in
167 # NO_BACKSLASH_ESCAPES mode parses quote boundaries differently, so a
168 # crafted literal could hide a token from $bare. Strip again WITHOUT
169 # escape handling and require both parsings to be clean, covering both
170 # server modes while still allowing benign literals like 'load_file x'.
171 5 (my $bare2 = $sql_text) =~ s/'[^']*'//g;
172 5 $bare2 =~ s/"[^"]*"//g;
173 5 ▶ return if $bare2 =~ /\b0x[0-9a-f]+/i;
Branch: 1 branch
BranchTrueFalseTotal
if $bare2 =~ /\b0x[0-9a-f]+/iu 0 5 5
174 5 ▶ return if $bare2 =~ /\bLOAD_FILE\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $bare2 =~ /\bLOAD_FILE\b/iu 1 4 5
175 4 ▶ return if $bare2 =~ /\bINTO\s+(?:OUTFILE|DUMPFILE)\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $bare2 =~ /\bINTO\s+(?:OUTFILE|DUMPFILE)\b/iu 0 4 4
176 4 ▶ return if $bare2 =~ $EXPLAIN_DENY;
Branch: 1 branch
BranchTrueFalseTotal
if $bare2 =~ /$EXPLAIN_DENY/u 0 4 4
177  
178 4 return $sql_text;
179 2 }
180  
181 0 ▶ method explain_query ($sql, @params) {
Subroutine explain_query: not called CC=2 SCAR=17.9
Pod documented
182 0 my $safe = $self->_validate_explainable_sql($sql);
183 0 ▶ return unless $safe;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe 0 0 0
184 0 return $self->dbix->all( $self->_explain_sql($safe), @params );
185 2 }
186  
187 # MariaDB's optimizer evaluates constant subqueries while building the plan,
188 # so EXPLAIN can run arbitrary functions. The deny-list above cannot be
189 # complete; the server-side time cap bounds whatever slips through.
190 0 ▶ method _explain_sql ($safe) {
Subroutine _explain_sql: not called CC=1 SCAR=6.9
191 0 return "SET STATEMENT max_statement_time=$EXPLAIN_TIMEOUT"
192 . " FOR EXPLAIN EXTENDED $safe";
193 2 }
194  
195 # Explicit lowercase aliases: MySQL 8 returns information_schema column
196 # names UPPERCASE unless aliased (MariaDB returns them as written), and
197 # Profile::mysql inherits these queries.
198 0 ▶ method get_table_stats ($table) {
Subroutine get_table_stats: not called CC=1 SCAR=6.9
Pod documented
199 0 return $self->dbix->all(q{
200 SELECT
201 table_name AS table_name,
202 engine AS engine,
203 table_rows AS table_rows,
204 avg_row_length AS avg_row_length,
205 data_length AS data_length,
206 index_length AS index_length
207 FROM information_schema.tables
208 WHERE table_schema = DATABASE()
209 AND table_name = ?
210 }, $table);
211 2 }
212  
213 0 ▶ method get_index_stats ($table) {
Subroutine get_index_stats: not called CC=1 SCAR=6.9
Pod documented
214 0 return $self->dbix->all(q{
215 SELECT
216 index_name AS index_name,
217 column_name AS column_name,
218 seq_in_index AS seq_in_index,
219 cardinality AS cardinality
220 FROM information_schema.statistics
221 WHERE table_schema = DATABASE()
222 AND table_name = ?
223 ORDER BY index_name, seq_in_index
224 }, $table);
225 2 }
226  
227 0 ▶ method analyze_indexes ($table) {
Subroutine analyze_indexes: not called CC=4 SCAR=30.0
Pod documented
228 0 my $stats = {
229 table => $table,
230 indexes => {},
231 problems => [],
232 recommendations => []
233 };
234  
235 # Every non-grouped column is aggregated: MySQL 8 enables
236 # ONLY_FULL_GROUP_BY by default and rejects bare columns here.
237 0 my $indexes = $self->dbix->all(q{
238 SELECT
239 index_name AS index_name,
240 GROUP_CONCAT(column_name ORDER BY seq_in_index) AS columns,
241 MAX(index_type) AS index_type,
242 MAX(non_unique) AS non_unique,
243 MAX(cardinality) AS cardinality,
244 MAX(nullable) AS nullable,
245 GROUP_CONCAT(seq_in_index ORDER BY seq_in_index) AS column_positions
246 FROM information_schema.statistics
247 WHERE table_schema = DATABASE()
248 AND table_name = ?
249 GROUP BY index_name
250 ORDER BY index_name
251 }, $table);
252  
253 0 for my $index (@$indexes) {
254 0 $stats->{indexes}->{ $index->{index_name} } = $index;
255 }
256  
257 0 my $index_usage = $self->dbix->all(q{
258 SELECT
259 index_name AS index_name,
260 count_star AS uses,
261 count_read AS `reads`,
262 count_write AS writes,
263 count_fetch AS fetches
264 FROM performance_schema.table_io_waits_summary_by_index_usage
265 WHERE object_schema = DATABASE()
266 AND object_name = ?
267 }, $table);
268  
269 0 for my $usage (@$index_usage) {
270 # The NULL-index row counts I/O done WITHOUT an index (table
271 # scans); it is not an index to report on.
272 0 ▶ next unless defined $usage->{index_name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $usage->{"index_name"} 0 0 0
273 0 $stats->{indexes}->{ $usage->{index_name} }->{usage} = $usage;
274 }
275  
276 0 $self->_analyze_index_problems($stats);
277 0 $self->_generate_index_recommendations($stats);
278  
279 0 return $stats;
280 2 }
281  
282 0 ▶ method _analyze_index_problems ($stats) {
Subroutine _analyze_index_problems: not called CC=10 SCAR=47.0
283 0 for my $index_name ( keys %{ $stats->{indexes} } ) {
284 0 my $index = $stats->{indexes}->{$index_name};
285 0 ▶ my $usage = $index->{usage} || {};
Condition0%0/2
$index->{'usage'} || {}
l!l
00
MC/DC0%0/1
$index->{'usage'} || {}
$index->{'usage'}
Truth table0%0/2
A
A= $index->{'usage'}
Aresult
11
00
286  
287 0 ▶ if ( !$usage->{uses} && $index_name ne 'PRIMARY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $usage->{"uses"} and $index_name ne "PRIMARY") 0 0 0
Condition0%0/3
not $usage->{"uses"} and $index_name ne "PRIMARY"
!ll&&!rl&&r
000
MC/DC0%0/2
not $usage->{"uses"} and $index_name ne "PRIMARY"
not $usage->{"uses"} $index_name ne "PRIMARY"
Truth table0%0/3
not(A) and B
A= not $usage->{"uses"}B= $index_name ne "PRIMARY"
ABresult
0X0
100
111
288 0 push @{ $stats->{problems} },
289 {
290 type => 'unused_index',
291 index => $index_name,
292 message => "Index '$index_name' has never been used"
293 };
294 }
295  
296 0 ▶ if ( $usage->{uses} && $usage->{uses} < 10
Branch: 1 branch
BranchTrueFalseTotal
if ($usage->{"uses"} and $usage->{"uses"} < 10 and $index_name ne "PRIMARY") 0 0 0
Condition0%0/6
$usage->{"uses"} and $usage->{"uses"} < 10 and $index_name ne "PRIMARY"
!ll&&!rl&&r
000
$usage->{"uses"} and $usage->{"uses"} < 10
!ll&&!rl&&r
000
MC/DC0%0/3
$usage->{"uses"} and $usage->{"uses"} < 10 and $index_name ne "PRIMARY"
$usage->{"uses"} $usage->{"uses"} < 10 $index_name ne "PRIMARY"
Truth table0%0/4
A and B and C
A= $usage->{"uses"}B= $usage->{"uses"} < 10C= $index_name ne "PRIMARY"
ABCresult
0XX0
10X0
1100
1111
297 && $index_name ne 'PRIMARY' )
298 {
299 0 push @{ $stats->{problems} },
300 {
301 type => 'rarely_used_index',
302 index => $index_name,
303 message =>
304 "Index '$index_name' is rarely used (only $usage->{uses} times)"
305 };
306 }
307  
308 0 ▶ if ( $index->{cardinality} && $index->{cardinality} < 10 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index->{"cardinality"} and $index->{"cardinality"} < 10) 0 0 0
Condition0%0/3
$index->{"cardinality"} and $index->{"cardinality"} < 10
!ll&&!rl&&r
000
MC/DC0%0/2
$index->{"cardinality"} and $index->{"cardinality"} < 10
$index->{"cardinality"} $index->{"cardinality"} < 10
Truth table0%0/3
A and B
A= $index->{"cardinality"}B= $index->{"cardinality"} < 10
ABresult
0X0
100
111
309 0 push @{ $stats->{problems} },
310 {
311 type => 'low_cardinality',
312 index => $index_name,
313 message =>
314 "Index '$index_name' has very low cardinality ($index->{cardinality})"
315 };
316 }
317 }
318  
319 0 $self->_check_redundant_indexes($stats);
320 2 }
321  
322 0 ▶ method _check_redundant_indexes ($stats) {
Subroutine _check_redundant_indexes: not called CC=3 SCAR=24.8
323 0 my %column_sets;
324 0 for my $index_name ( keys %{ $stats->{indexes} } ) {
325 0 my $index = $stats->{indexes}->{$index_name};
326 0 my @columns = split /,/, $index->{columns};
327  
328 0 my $column_key = join( ",", sort @columns );
329  
330 0 ▶ if ( $column_sets{$column_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($column_sets{$column_key}) 0 0 0
331 0 push @{ $stats->{problems} },
332 {
333 type => 'redundant_index',
334 index => $index_name,
335 0 duplicate_of => $column_sets{$column_key},
336 message =>
337 "Index '$index_name' is redundant with '$column_sets{$column_key}'"
338 };
339 }
340 0 $column_sets{$column_key} = $index_name;
341 }
342 2 }
343  
344 0 ▶ method _generate_index_recommendations ($stats) {
Subroutine _generate_index_recommendations: not called CC=7 SCAR=40.3
345 # The digest table has no sql_text column (MariaDB nor MySQL): the
346 # normalized statement is digest_text. `reads` above is quoted because
347 # READS is a reserved word on both servers.
348 my $frequent_queries = $self->dbix->all(q{
349 SELECT
350 digest_text AS sql_text,
351 count_star AS executions,
352 sum_timer_wait/1000000000000 AS total_latency
353 FROM performance_schema.events_statements_summary_by_digest
354 WHERE schema_name = DATABASE()
355 AND digest_text LIKE ?
356 ORDER BY count_star DESC
357 LIMIT 10
358 0 }, '%' . $stats->{table} . '%');
359  
360 0 for my $query (@$frequent_queries) {
361 0 my $safe_sql = $self->_validate_explainable_sql($query->{sql_text});
362 0 ▶ next unless $safe_sql;
Branch: 1 branch
BranchTrueFalseTotal
unless $safe_sql 0 0 0
363  
364 0 my $explained = eval {
365 0 $self->dbix->all($self->_explain_sql($safe_sql));
366 };
367 0 ▶ next unless $explained && @$explained;
Branch: 1 branch
BranchTrueFalseTotal
unless $explained and @$explained 0 0 0
Condition0%0/3
$explained and @$explained
!ll&&!rl&&r
000
MC/DC0%0/2
$explained and @$explained
$explained @$explained
Truth table0%0/3
A and B
A= $explainedB= @$explained
ABresult
0X0
100
111
368  
369 0 ▶ my $rows = $explained->[0]->{rows} // 0;
Condition0%0/2
$explained->[0]{"rows"} // 0
l!l
00
MC/DC0%0/1
$explained->[0]{"rows"} // 0
$explained->[0]{"rows"}
Truth table0%0/2
A
A= $explained->[0]{"rows"}
Aresult
11
00
370 0 ▶ if ( $rows > 1000 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rows > 1000) 0 0 0
371 0 push @{ $stats->{recommendations} },
372 {
373 type => 'missing_index',
374 query => $query->{sql_text},
375 0 rows => $rows,
376 message =>
377 "Consider adding an index for query executed $query->{executions} times (examines $rows rows)"
378 };
379 }
380 }
381 2 }
382  
383 0 ▶ method print_index_analysis ($table) {
Subroutine print_index_analysis: not called CC=14 SCAR=53.5
Pod documented
384 0 my $stats = $self->analyze_indexes($table);
385 0 ▶ return if $self->emit( index_analysis => $stats );
Branch: 1 branch
BranchTrueFalseTotal
if $self->emit("index_analysis", $stats) 0 0 0
386  
387 0 $self->out("\n=== Index Analysis for table '$table' ===\n\n");
388  
389 0 $self->out("Current Indexes:\n");
390 0 $self->out("-" x 80, "\n");
391 0 for my $index_name ( sort keys %{ $stats->{indexes} } ) {
392 0 my $index = $stats->{indexes}->{$index_name};
393 0 ▶ my $usage = $index->{usage} || {};
Condition0%0/2
$index->{'usage'} || {}
l!l
00
MC/DC0%0/1
$index->{'usage'} || {}
$index->{'usage'}
Truth table0%0/2
A
A= $index->{'usage'}
Aresult
11
00
394  
395 0 $self->outf("Index: %s\n", $index_name);
396 0 $self->outf(" Columns: %s\n", $index->{columns});
397 0 $self->outf(" Type: %s\n", $index->{index_type});
398 0 ▶ $self->outf(" Cardinality: %s\n", $index->{cardinality} || 'N/A');
Condition0%0/2
$index->{'cardinality'} || 'N/A'
l!l
00
MC/DC0%0/1
$index->{'cardinality'} || 'N/A'
$index->{'cardinality'}
Truth table0%0/2
A
A= $index->{'cardinality'}
Aresult
11
00
399 0 $self->outf(" Usage:\n");
400 0 ▶ $self->outf(" Total uses: %d\n", $usage->{uses} || 0);
Condition0%0/2
$usage->{'uses'} || 0
l!l
00
MC/DC0%0/1
$usage->{'uses'} || 0
$usage->{'uses'}
Truth table0%0/2
A
A= $usage->{'uses'}
Aresult
11
00
401 0 ▶ $self->outf(" Reads: %d\n", $usage->{reads} || 0);
Condition0%0/2
$usage->{'reads'} || 0
l!l
00
MC/DC0%0/1
$usage->{'reads'} || 0
$usage->{'reads'}
Truth table0%0/2
A
A= $usage->{'reads'}
Aresult
11
00
402 0 ▶ $self->outf(" Writes: %d\n", $usage->{writes} || 0);
Condition0%0/2
$usage->{'writes'} || 0
l!l
00
MC/DC0%0/1
$usage->{'writes'} || 0
$usage->{'writes'}
Truth table0%0/2
A
A= $usage->{'writes'}
Aresult
11
00
403 0 ▶ $self->outf(" Fetches: %d\n", $usage->{fetches} || 0);
Condition0%0/2
$usage->{'fetches'} || 0
l!l
00
MC/DC0%0/1
$usage->{'fetches'} || 0
$usage->{'fetches'}
Truth table0%0/2
A
A= $usage->{'fetches'}
Aresult
11
00
404 0 $self->out("\n");
405 }
406  
407 0 ▶ if ( @{ $stats->{problems} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stats->{"problems"};}) 0 0 0
408 0 $self->out("Problems Found:\n");
409 0 $self->out("-" x 80, "\n");
410 0 for my $problem ( @{ $stats->{problems} } ) {
411 0 $self->outf("* %s\n", $problem->{message});
412 }
413 0 $self->out("\n");
414 }
415  
416 0 ▶ if ( @{ $stats->{recommendations} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stats->{"recommendations"};}) 0 0 0
417 0 $self->out("Recommendations:\n");
418 0 $self->out("-" x 80, "\n");
419 0 for my $rec ( @{ $stats->{recommendations} } ) {
420 0 $self->outf("* %s\n", $rec->{message});
421 0 ▶ $self->outf(" Query: %s\n", $rec->{query}) if $rec->{query};
Branch: 1 branch
BranchTrueFalseTotal
if $rec->{"query"} 0 0 0
422 }
423 }
424 2 }
425  
426 0 ▶ method get_index_metrics ($table) {
Subroutine get_index_metrics: not called CC=1 SCAR=6.9
Pod documented
427 0 return $self->dbix->all(q{
428 SELECT
429 object_name as table_name,
430 index_name,
431 count_star as uses,
432 count_read as reads,
433 count_write as writes,
434 count_fetch as fetches,
435 sum_timer_wait/1000000000000 as total_latency,
436 avg_timer_wait/1000000000000 as avg_latency
437 FROM performance_schema.table_io_waits_summary_by_index_usage
438 WHERE object_schema = DATABASE()
439 AND object_name = ?
440 ORDER BY sum_timer_wait DESC
441 }, $table);
442 2 }
443  
444 0 ▶ method monitor_connections () {
Subroutine monitor_connections: not called CC=1 SCAR=6.9
Pod documented
445 0 my $stats = {
446 current => $self->get_current_connections(),
447 processes => $self->get_processes(),
448 variables => $self->get_connection_variables(),
449 status => $self->get_connection_status(),
450 usage => $self->get_connection_usage(),
451 problems => [],
452 };
453  
454 0 $self->_analyze_connection_problems($stats);
455  
456 0 return $stats;
457 2 }
458  
459 0 ▶ method get_current_connections () {
Subroutine get_current_connections: not called CC=1 SCAR=6.9
Pod undocumented
460 0 return $self->dbix->hash(q{
461 SELECT
462 COUNT(*) as total_connections,
463 SUM(CASE WHEN command = 'Sleep' THEN 1 ELSE 0 END) as sleeping,
464 SUM(CASE WHEN command != 'Sleep' THEN 1 ELSE 0 END) as active,
465 MAX(time) as max_connection_time
466 FROM information_schema.processlist
467 });
468 2 }
469  
470 0 ▶ method get_processes () {
Subroutine get_processes: not called CC=1 SCAR=6.9
Pod undocumented
471 # Portable across MariaDB and MySQL: no MariaDB-only time_ms column
472 # (and TIME is already the running time in seconds).
473 0 return $self->dbix->all(q{
474 SELECT
475 id AS id,
476 user AS user,
477 host AS host,
478 db AS db,
479 command AS command,
480 time AS time,
481 state AS state,
482 info AS query,
483 time AS seconds_running
484 FROM information_schema.processlist
485 ORDER BY time DESC
486 });
487 2 }
488  
489 0 ▶ method get_connection_variables () {
Subroutine get_connection_variables: not called CC=1 SCAR=6.9
Pod undocumented
490 0 my $vars = $self->dbix->all(q{
491 SHOW VARIABLES WHERE Variable_name IN (
492 'max_connections',
493 'max_user_connections',
494 'wait_timeout',
495 'interactive_timeout',
496 'connect_timeout',
497 'max_allowed_packet',
498 'thread_cache_size',
499 'thread_stack'
500 )
501 });
502 0 return { map { $_->{Variable_name} => $_->{Value} } @$vars };
503 2 }
504  
505 0 ▶ method get_connection_status () {
Subroutine get_connection_status: not called CC=1 SCAR=6.9
Pod undocumented
506 0 my $status = $self->dbix->all(q{
507 SHOW GLOBAL STATUS WHERE Variable_name IN (
508 'Threads_connected',
509 'Threads_created',
510 'Threads_cached',
511 'Threads_running',
512 'Connections',
513 'Aborted_connects',
514 'Aborted_clients',
515 'Connection_errors_accept',
516 'Connection_errors_internal',
517 'Connection_errors_max_connections',
518 'Connection_errors_peer_address',
519 'Connection_errors_select',
520 'Connection_errors_tcpwrap'
521 )
522 });
523  
524 0 return { map { $_->{Variable_name} => $_->{Value} } @$status };
525 2 }
526  
527 0 ▶ method get_connection_usage () {
Subroutine get_connection_usage: not called CC=1 SCAR=6.9
Pod undocumented
528 0 return $self->dbix->all(q{
529 SELECT
530 user as username,
531 COUNT(*) as total_connections,
532 SUM(CASE WHEN command = 'Sleep' THEN 1 ELSE 0 END) as sleeping,
533 SUM(CASE WHEN command != 'Sleep' THEN 1 ELSE 0 END) as active,
534 MAX(time) as max_time
535 FROM information_schema.processlist
536 GROUP BY user
537 });
538 2 }
539  
540 0 ▶ method _analyze_connection_problems ($stats) {
Subroutine _analyze_connection_problems: not called CC=10 SCAR=47.0
541 0 ▶ my $max_conn = $stats->{variables}->{max_connections} || 1;
Condition0%0/2
$stats->{'variables'}{'max_connections'} || 1
l!l
00
MC/DC0%0/1
$stats->{'variables'}{'max_connections'} || 1
$stats->{'variables'}{'max_connections'}
Truth table0%0/2
A
A= $stats->{'variables'}{'max_connections'}
Aresult
11
00
542 0 ▶ my $current_conn = $stats->{status}->{Threads_connected} || 0;
Condition0%0/2
$stats->{'status'}{'Threads_connected'} || 0
l!l
00
MC/DC0%0/1
$stats->{'status'}{'Threads_connected'} || 0
$stats->{'status'}{'Threads_connected'}
Truth table0%0/2
A
A= $stats->{'status'}{'Threads_connected'}
Aresult
11
00
543 0 my $usage_percent = ( $current_conn / $max_conn ) * 100;
544  
545 0 ▶ if ( $usage_percent > 80 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage_percent > 80) 0 0 0
546 0 push @{ $stats->{problems} },
547 {
548 type => 'high_connection_usage',
549 message => sprintf(
550 "High connection usage: %.2f%% (%d of %d)",
551 $usage_percent, $current_conn, $max_conn
552 ),
553 severity => 'warning'
554 };
555 }
556  
557 0 ▶ my $total_conns = $stats->{status}->{Connections} || 1;
Condition0%0/2
$stats->{'status'}{'Connections'} || 1
l!l
00
MC/DC0%0/1
$stats->{'status'}{'Connections'} || 1
$stats->{'status'}{'Connections'}
Truth table0%0/2
A
A= $stats->{'status'}{'Connections'}
Aresult
11
00
558 my $aborted_rate =
559 0 ▶ ($stats->{status}->{Aborted_connects} || 0)
Condition0%0/2
$stats->{'status'}{'Aborted_connects'} || 0
l!l
00
MC/DC0%0/1
$stats->{'status'}{'Aborted_connects'} || 0
$stats->{'status'}{'Aborted_connects'}
Truth table0%0/2
A
A= $stats->{'status'}{'Aborted_connects'}
Aresult
11
00
560 / $total_conns * 100;
561  
562 0 ▶ if ( $aborted_rate > 5 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($aborted_rate > 5) 0 0 0
563 0 push @{ $stats->{problems} },
564 {
565 type => 'high_abort_rate',
566 message => sprintf( "High connection abort rate: %.2f%%",
567 $aborted_rate ),
568 severity => 'error'
569 };
570 }
571  
572 0 ▶ if ( $stats->{current}->{sleeping} > 50 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stats->{"current"}{"sleeping"} > 50) 0 0 0
573 0 push @{ $stats->{problems} },
574 {
575 type => 'many_sleeping_connections',
576 message => sprintf(
577 "High number of sleeping connections: %d",
578 $stats->{current}->{sleeping}
579 0 ),
580 severity => 'warning'
581 };
582 }
583  
584 0 for my $error_type ( grep /^Connection_errors_/,
585 0 keys %{ $stats->{status} } )
586 {
587 0 ▶ if ( $stats->{status}->{$error_type} > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stats->{"status"}{$error_type} > 0) 0 0 0
588 0 push @{ $stats->{problems} },
589 {
590 type => 'connection_errors',
591 message => sprintf( "%s: %d occurrences",
592 0 $error_type, $stats->{status}->{$error_type} ),
593 severity => 'error'
594 };
595 }
596 }
597 2 }
598  
599 0 ▶ method print_connection_monitor () {
Subroutine print_connection_monitor: not called CC=16 SCAR=56.1
Pod documented
600 0 my $stats = $self->monitor_connections();
601 # json/callback consumers get the raw struct; _term_safe sanitization
602 # and query truncation are terminal-only concerns (JSON escapes
603 # control characters natively).
604 0 ▶ return if $self->emit( connection_monitor => $stats );
Branch: 1 branch
BranchTrueFalseTotal
if $self->emit("connection_monitor", $stats) 0 0 0
605  
606 0 $self->out("\n=== MariaDB Connection Monitor ===\n\n");
607  
608 0 $self->out("Current Connections:\n");
609 0 $self->out("-" x 80, "\n");
610 $self->outf("Total: %d (Active: %d, Sleeping: %d)\n",
611 $stats->{current}->{total_connections},
612 $stats->{current}->{active},
613 0 $stats->{current}->{sleeping});
614 $self->outf("Max Connection Time: %d seconds\n\n",
615 0 ▶ $stats->{current}->{max_connection_time} // 0);
Condition0%0/2
$stats->{"current"}{"max_connection_time"} // 0
l!l
00
MC/DC0%0/1
$stats->{"current"}{"max_connection_time"} // 0
$stats->{"current"}{"max_connection_time"}
Truth table0%0/2
A
A= $stats->{"current"}{"max_connection_time"}
Aresult
11
00
616  
617 0 $self->out("Connection Settings:\n");
618 0 $self->out("-" x 80, "\n");
619 0 for my $var ( sort keys %{ $stats->{variables} } ) {
620 0 $self->outf("%-25s: %s\n", $var, $stats->{variables}->{$var});
621 }
622 0 $self->out("\n");
623  
624 0 $self->out("Connection Status:\n");
625 0 $self->out("-" x 80, "\n");
626 0 for my $var ( sort keys %{ $stats->{status} } ) {
627 0 $self->outf("%-30s: %s\n", $var, $stats->{status}->{$var});
628 }
629 0 $self->out("\n");
630  
631 0 $self->out("Connection Usage by User:\n");
632 0 $self->out("-" x 80, "\n");
633 0 for my $user ( @{ $stats->{usage} } ) {
634 0 $self->outf("User: %s\n", _term_safe( $user->{username} ));
635 0 $self->outf(" Total Connections: %d\n", $user->{total_connections});
636 0 $self->outf(" Active: %d\n", $user->{active});
637 0 $self->outf(" Sleeping: %d\n", $user->{sleeping});
638 0 ▶ $self->outf(" Max Time: %d seconds\n", $user->{max_time} // 0);
Condition0%0/2
$user->{"max_time"} // 0
l!l
00
MC/DC0%0/1
$user->{"max_time"} // 0
$user->{"max_time"}
Truth table0%0/2
A
A= $user->{"max_time"}
Aresult
11
00
639 0 $self->out("\n");
640 }
641  
642 0 $self->out("Active Processes:\n");
643 0 $self->out("-" x 80, "\n");
644 0 for my $proc ( @{ $stats->{processes} } ) {
645 0 ▶ next if $proc->{command} eq 'Sleep';
Branch: 1 branch
BranchTrueFalseTotal
if $proc->{"command"} eq "Sleep" 0 0 0
646 0 $self->outf("ID: %d\n", $proc->{id});
647 0 $self->outf(" User: %s\n", _term_safe( $proc->{user} ));
648 0 $self->outf(" Host: %s\n", _term_safe( $proc->{host} ));
649 0 ▶ $self->outf(" DB: %s\n", _term_safe( $proc->{db} ) || 'None');
Condition0%0/2
_term_safe($proc->{'db'}) || 'None'
l!l
00
MC/DC0%0/1
_term_safe($proc->{'db'}) || 'None'
_term_safe($proc->{'db'})
Truth table0%0/2
A
A= _term_safe($proc->{'db'})
Aresult
11
00
650 0 ▶ $self->outf(" State: %s\n", _term_safe( $proc->{state} ) || 'None');
Condition0%0/2
_term_safe($proc->{'state'}) || 'None'
l!l
00
MC/DC0%0/1
_term_safe($proc->{'state'}) || 'None'
_term_safe($proc->{'state'})
Truth table0%0/2
A
A= _term_safe($proc->{'state'})
Aresult
11
00
651 # TIME is NULL for some processlist rows (e.g. daemon threads).
652 0 ▶ $self->outf(" Running Time: %d seconds\n", $proc->{seconds_running} // 0);
Condition0%0/2
$proc->{"seconds_running"} // 0
l!l
00
MC/DC0%0/1
$proc->{"seconds_running"} // 0
$proc->{"seconds_running"}
Truth table0%0/2
A
A= $proc->{"seconds_running"}
Aresult
11
00
653 0 ▶ if ( $proc->{query} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proc->{"query"}) 0 0 0
654 $self->outf(" Query: %s\n",
655 _term_safe( substr( $proc->{query}, 0, 100 )
656 0 ▶ . ( length( $proc->{query} ) > 100 ? '...' : '' ) ));
Branch: 1 branch
BranchTrueFalseTotal
length $proc->{'query'} > 100 ? : 0 0 0
657 }
658 0 $self->out("\n");
659 }
660  
661 0 ▶ if ( @{ $stats->{problems} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stats->{"problems"};}) 0 0 0
662 0 $self->out("Problems Detected:\n");
663 0 $self->out("-" x 80, "\n");
664 0 for my $problem ( @{ $stats->{problems} } ) {
665 $self->outf("[%s] %s\n",
666 uc( $problem->{severity} ),
667 0 $problem->{message});
668 }
669 }
670 2 }
671  
672 0 ▶ method start_connection_monitor ($interval = 60, $duration = 3600) {
Subroutine start_connection_monitor: not called CC=6 SCAR=37.4
Pod documented
673 0 my $start_time = time();
674 0 my $end_time = $start_time + $duration;
675  
676 0 ▶ while ( time() < $end_time ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&DBIx::Fast::Profile::MariaDB::time() < $end_time) 0 0 0
677 # Terminal chrome (clear screen, footer) only in text mode; in
678 # json/callback mode each iteration is one connection_monitor event.
679 0 ▶ $self->out("\033[2J\033[H") if $self->output_is_text;
Branch: 1 branch
BranchTrueFalseTotal
if $self->output_is_text 0 0 0
680 0 $self->print_connection_monitor();
681 0 ▶ if ( $self->output_is_text ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->output_is_text) 0 0 0
682 0 $self->out("\nMonitoring... (Press Ctrl+C to stop)\n");
683 0 $self->outf("Running for: %d seconds\n", ( time() - $start_time ));
684 }
685 0 sleep($interval);
686 }
687 2 }
688 }
689  
690 2 1;
691  
692 __END__
↑ Summary Fast/X.pm »