lib/ForgeOps/Tracker/SqlStatement.pm

filter: Statementstmt 100% 96 / 96 Branchbran 79.5% 35 / 44 Conditioncond 69.7% 23 / 33 MC/DCmcdc 47.3% 9 / 19 Subroutinesub 100% 11 / 11 Podpod 0.0% 0 / 3 totaltotal 84.4% 174 / 206 CC 36 SCAR 23.5
CC
36
Cov
89%
objects
17.8
find_in
9.6
mask
7.0
CRAP 10.5
« blib/lib/ForgeOps/Tracker/MetricBuffer.pm ↑ Summary blib/lib/ForgeOps/Tracker/SpanBuffer.pm »
1 package ForgeOps::Tracker::SqlStatement;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 # Finds the SQL behind a database error and reduces it to something safe to send: the names of the
8 # stored procedures, tables and views it touched, and (only if the configuration's
9 # capture_sql_statement is on) the statement itself with every string and number replaced by "?".
10 # Ported from gems/forge_ops_tracker's SqlStatement, which is itself ported from the server's own
11 # SqlStatementMasker/SqlObjectExtractor: same rules everywhere, and the server applies them again
12 # on arrival, so a difference here can only ever mean less is masked client-side, never that
13 # something unmasked gets stored.
14 #
15 # Deliberately a single pass over a few patterns, not a SQL parser.
16 2 our @EXPORT_OK = qw(find_in mask objects);
17  
18 2 ▶use constant MASK => '?';
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use constant MAX_LENGTH => 4000;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶use constant MAX_NAMES => 10;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 2 ▶use constant MAX_NAME_LENGTH => 200;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 # db.system values where "double quotes" are a string, not a name.
24 2 my %DOUBLE_QUOTED_STRING_SYSTEMS = map { $_ => 1 } qw(mysql mariadb);
25  
26 # /a keeps \w and \d to ASCII, as they are in the Ruby original, even on a string Perl holds as
27 # characters. The prefix only counts as one when it isn't the end of a word, but the quote always
28 # does: LIKE'%x%', with no space, is still a string. A backslash can be the statement's last
29 # character ('secret\ cut off mid-escape), and the string is still masked to the end. A string's
30 # body is the Ruby original's (?:[^'\\]|\\(?:.|\z)|'')* unrolled into runs, which matches exactly
31 # the same text: Perl stops repeating a group like that one after a fixed count (65534 on Perl 5.34,
32 # fewer on older ones) and warns, so the original form would leave a string longer than that
33 # unmasked, where this only runs out at that many escapes in one string.
34 2 my $STRING = qr/(?:(?<![\w\$])(?:[EeXxNnBb]|[Uu]&))?'[^'\\]*(?:(?:\\(?:.|\z)|'')[^'\\]*)*(?:'|\z)/sa;
35 2 my $DOUBLE_QUOTED_STRING = qr/"[^"\\]*(?:(?:\\(?:.|\z)|"")[^"\\]*)*(?:"|\z)/s;
36 2 my $DOLLAR_QUOTED = qr/(?<tag>\$[A-Za-z_]*\$).*?(?:\k<tag>|\z)/s;
37 # [0-9A-Fa-f] where the Ruby original has \h: in Perl, \h is horizontal whitespace.
38 2 my $NUMBER = qr/(?<![\w\$.])(?:0[xX][0-9A-Fa-f]+|0[bB][01]+|(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)(?!\w)/a;
39  
40 2 my $LITERAL = qr/$STRING|$DOLLAR_QUOTED|$NUMBER/;
41 2 my $LITERAL_WITH_DOUBLE_QUOTES = qr/$STRING|$DOUBLE_QUOTED_STRING|$DOLLAR_QUOTED|$NUMBER/;
42  
43 2 my $PART = q{(?:[\w$#@]+|"[^"]+"|\[[^\]]+\]|`[^`]+`)};
44 2 my $NAME = qr/$PART(?:\.$PART)*/;
45 2 my %OPERATIONS = map { $_ => 1 } qw(SELECT INSERT UPDATE DELETE MERGE WITH CALL EXEC EXECUTE CREATE ALTER DROP TRUNCATE);
46 2 my $PROCEDURE_CALL = qr/\b(?:CALL|EXEC(?:UTE)?|PERFORM)\s+(?!IMMEDIATE\b|FUNCTION\b|PROCEDURE\b)($NAME)/i;
47 2 my $RELATION = qr/\b(FROM|JOIN|INTO|UPDATE|TABLE)\s+($NAME)(\s*\()?/i;
48 2 my $SELECT_FUNCTION = qr/\A\s*SELECT\s+($NAME)\s*\(/i;
49 2 my %BUILTINS = map { $_ => 1 } qw(
50 count sum min max avg now coalesce nullif lower upper length concat cast date_trunc
51 current_timestamp current_date row_number rank json_build_object json_agg array_agg
52 );
53 2 my $FROM_INSIDE_FUNCTION = qr/\b(?:EXTRACT|SUBSTRING|TRIM|OVERLAY)\s*\([^()]*\)/i;
54 2 my %KEYWORDS_NOT_NAMES = map { $_ => 1 } qw(select set values where lateral only unnest generate_series);
55  
56 # Perl has no exception type that carries the statement: DBI puts it in the error text itself
57 # instead, as `[for Statement "SELECT ..."]` when the handle has ShowErrorStatement turned on
58 # (DBIx::Class turns it on for you), sometimes followed by ` with ParamValues: ...`, which is
59 # deliberately never read: that part is the values. SQLite's own errors carry `while compiling:
60 # SELECT ...` at the end instead. Best-effort by nature: an error raised without either marker
61 # simply has no statement to find, and this returns undef rather than guessing.
62 2 my $DBI_STATEMENT = qr/\[for Statement "(.*?)"(?: with ParamValues:[^\]]*)?\]/s;
63 2 my $SQLITE_COMPILING = qr/while compiling:\s*(.+?)\s*\z/s;
64  
65 # The raw statement out of an error: a plain string ($@ after die), or an exception object with
66 # ->message or an overloaded stringification.
67 39 ▶sub find_in {
Subroutine find_in: called CC=9 SCAR=22.6
Pod undocumented
68 39 my ($error) = @_;
69 39 ▶ return undef unless defined $error;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $error 1 38 39
70  
71 38 ▶ my $text = eval { ref $error && $error->can('message') ? $error->message : "$error" };
Branch: 1 branch
BranchTrueFalseTotal
ref $error && $error->can('message') ? : 1 37 38
Condition66%2/3
ref $error and $error->can("message")
!ll&&!rl&&r
3701
MC/DC50%1/2
ref $error and $error->can("message")
ref $error $error->can("message")
Truth table66%2/3
A and B
A= ref $errorB= $error->can("message")
ABresult
0X0
100
111
72 38 ▶ return undef unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 38 38
73  
74 # Copied out of $1 before the /\S/ check: that second match would otherwise reset it.
75 38 for my $pattern ($DBI_STATEMENT, $SQLITE_COMPILING) {
76 70 ▶ if ($text =~ $pattern) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /$pattern/s) 7 63 70
77 7 my $statement = $1;
78 7 ▶ return $statement if defined $statement && $statement =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $statement and $statement =~ /\S/ 7 0 7
Condition33%1/3
defined $statement and $statement =~ /\S/
!ll&&!rl&&r
007
MC/DC0%0/2
defined $statement and $statement =~ /\S/
defined $statement $statement =~ /\S/
Truth table33%1/3
A and B
A= defined $statementB= $statement =~ /\S/
ABresult
0X0
100
111
79 }
80 }
81 31 return undef;
82 }
83  
84 # mask($statement, system => $db_system): pass the query's db.system when it's known. On mysql and
85 # mariadb "double quotes" are a string too, so they're masked there and left alone everywhere else.
86 88 ▶sub mask {
Subroutine mask: called CC=7 SCAR=19.5
Pod undocumented
87 88 my ($statement, %options) = @_;
88 88 ▶ return undef unless defined $statement && $statement =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $statement and $statement =~ /\S/ 32 56 88
Condition100%3/3
defined $statement and $statement =~ /\S/
!ll&&!rl&&r
31156
MC/DC100%2/2
defined $statement and $statement =~ /\S/
defined $statement $statement =~ /\S/
Truth table100%3/3
A and B
A= defined $statementB= $statement =~ /\S/
ABresult
0X0
100
111
89  
90 56 ▶ my $system = defined $options{system} && !ref $options{system} ? lc $options{system} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $options{'system'} && !ref($options{'system'}) ? : 9 47 56
Condition66%2/3
defined $options{"system"} and not ref $options{"system"}
!ll&&!rl&&r
4709
MC/DC50%1/2
defined $options{"system"} and not ref $options{"system"}
defined $options{"system"} not ref $options{"system"}
Truth table66%2/3
A and not(B)
A= defined $options{"system"}B= not ref $options{"system"}
ABresult
0X0
100
111
91 56 ▶ my $pattern = $DOUBLE_QUOTED_STRING_SYSTEMS{$system} ? $LITERAL_WITH_DOUBLE_QUOTES : $LITERAL;
Branch: 1 branch
BranchTrueFalseTotal
$DOUBLE_QUOTED_STRING_SYSTEMS{$system} ? : 7 49 56
92 56 (my $masked = $statement) =~ s/$pattern/MASK/ge;
93 56 ▶ return length($masked) > MAX_LENGTH ? substr($masked, 0, MAX_LENGTH) . '...' : $masked;
Branch: 1 branch
BranchTrueFalseTotal
length $masked > 4000 ? : 1 55 56
94 }
95  
96 # Takes an already-masked statement (so a keyword inside a string value can't be mistaken for
97 # SQL). Returns undef when nothing recognizable was found.
98 10 ▶sub objects {
Subroutine objects: called CC=17 SCAR=28.8
Pod undocumented
99 10 my ($masked) = @_;
100 10 ▶ return undef unless defined $masked && $masked =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $masked and $masked =~ /\S/ 0 10 10
Condition33%1/3
defined $masked and $masked =~ /\S/
!ll&&!rl&&r
0010
MC/DC0%0/2
defined $masked and $masked =~ /\S/
defined $masked $masked =~ /\S/
Truth table33%1/3
A and B
A= defined $maskedB= $masked =~ /\S/
ABresult
0X0
100
111
101  
102 10 (my $sql = $masked) =~ s/$FROM_INSIDE_FUNCTION/ /g;
103 10 my @procedures = $sql =~ /$PROCEDURE_CALL/g;
104 10 my @relations;
105  
106 10 ▶ while ($sql =~ /$RELATION/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /$RELATION/g) 5 10 15
107 5 my ($keyword, $name, $paren) = ($1, $2, $3);
108 5 ▶ next if $KEYWORDS_NOT_NAMES{ lc $name };
Branch: 1 branch
BranchTrueFalseTotal
if $KEYWORDS_NOT_NAMES{lc $name} 0 5 5
109 5 ▶ my $function_call = defined $paren && length $paren && (uc $keyword eq 'FROM' || uc $keyword eq 'JOIN');
Condition77%7/9
defined $paren && length $paren && (uc $keyword eq 'FROM' || uc $keyword eq 'JOIN')
!ll&&!rl&&r
311
defined $paren and length $paren
!ll&&!rl&&r
302
uc $keyword eq "FROM" or uc $keyword eq "JOIN"
l!l&&r!l&&!r
101
MC/DC50%2/4
defined $paren && length $paren && (uc $keyword eq 'FROM' || uc $keyword eq 'JOIN')
defined $paren length $paren uc $keyword eq "FROM" uc $keyword eq "JOIN"
Truth table60%3/5
A and B && C or D
A= defined $parenB= length $parenC= uc $keyword eq "FROM"D= uc $keyword eq "JOIN"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
110 5 ▶ push @{ $function_call ? \@procedures : \@relations }, $name;
Branch: 1 branch
BranchTrueFalseTotal
$function_call ? : 1 4 5
111 }
112  
113 10 ▶ if ($sql =~ $SELECT_FUNCTION) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /$SELECT_FUNCTION/) 2 8 10
114 2 my $function = $1;
115 2 ▶ push @procedures, $function if !$BUILTINS{ lc $function } && $sql !~ /\bFROM\b/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $BUILTINS{lc $function} or $sql =~ /\bFROM\b/i 1 1 2
Condition66%2/3
$BUILTINS{lc $function} or $sql =~ /\bFROM\b/i
l!l&&r!l&&!r
101
MC/DC50%1/2
$BUILTINS{lc $function} or $sql =~ /\bFROM\b/i
$BUILTINS{lc $function} $sql =~ /\bFROM\b/i
Truth table66%2/3
A or B
A= $BUILTINS{lc $function}B= $sql =~ /\bFROM\b/i
ABresult
1X1
011
000
116 }
117  
118 10 my ($operation) = $sql =~ /\A\s*(\w+)/;
119 10 ▶ $operation = defined $operation ? uc $operation : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $operation ? : 10 0 10
120 10 my %result;
121 10 ▶ $result{operation} = $operation if $OPERATIONS{$operation};
Branch: 1 branch
BranchTrueFalseTotal
if $OPERATIONS{$operation} 9 1 10
122 10 $result{procedures} = _clean(@procedures);
123 10 $result{relations} = _clean(@relations);
124 10 ▶ return undef if !@{ $result{procedures} } && !@{ $result{relations} } && !exists $result{operation};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$result{"procedures"};} or @{$result{"relations"};} or exists $result{"operation"} 1 9 10
Condition83%5/6
@{$result{"procedures"};} or @{$result{"relations"};} or exists $result{"operation"}
l!l&&r!l&&!r
901
@{$result{"procedures"};} or @{$result{"relations"};}
l!l&&r!l&&!r
631
MC/DC66%2/3
@{$result{"procedures"};} or @{$result{"relations"};} or exists $result{"operation"}
@{$result{"procedures"};} @{$result{"relations"};} exists $result{"operation"}
Truth table75%3/4
A or B or C
A= @{$result{"procedures"};}B= @{$result{"relations"};}C= exists $result{"operation"}
ABCresult
1XX1
01X1
0011
0000
125 9 return \%result;
126 }
127  
128 20 ▶sub _clean {
Subroutine _clean: called CC=6 SCAR=18.6
129 20 my (@names) = @_;
130 20 my (@cleaned, %seen);
131 20 for my $raw (@names) {
132 10 (my $name = $raw) =~ s/\A\s+|\s+\z//g;
133 10 ▶ $name = substr($name, 0, MAX_NAME_LENGTH) if length $name > MAX_NAME_LENGTH;
Branch: 1 branch
BranchTrueFalseTotal
if length $name > 200 0 10 10
134 10 ▶ next unless $name =~ /\A$NAME\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\A$NAME\z/ 0 10 10
135 10 ▶ next if $seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$name}++ 0 10 10
136 10 push @cleaned, $name;
137 }
138 20 ▶ splice(@cleaned, MAX_NAMES) if @cleaned > MAX_NAMES;
Branch: 1 branch
BranchTrueFalseTotal
if @cleaned > 10 0 20 20
139 20 return \@cleaned;
140 }
141  
142 2 1;
« blib/lib/ForgeOps/Tracker/MetricBuffer.pm ↑ Summary blib/lib/ForgeOps/Tracker/SpanBuffer.pm »