blib/lib/SQL/Steno.pm

filter: Statementstmt 76.5% 401 / 524 Branchbran 67.3% 280 / 416 Conditioncond 60.0% 111 / 185 MC/DCmcdc 35.1% 33 / 94 Subroutinesub 86.6% 26 / 30 Podpod 14.2% 3 / 21 totaltotal 67.2% 854 / 1270 CC 289 SCAR 37.3
CC
289
Cov
70%
helphash
119.4
help
92.9
shell
69.4
CRAP 41.7
↑ Summary
1 =encoding utf8
2  
3 =head1 NAME
4  
5 SQL::Steno - Short hand for SQL and compact output
6  
7 =head1 SYNOPSIS
8  
9 Type some short-hand, see the corresponding SQL and its output:
10  
11 steno> TABLE1;somecolumn > 2 -- ; after tables means where
12 select * from TABLE1 where somecolumn > 2;
13 prepare: 0.000s execute: 0.073s rows: 14
14 id|column1 |column2
15 | | |column3
16 | | | |somecolumn
17 ----|-------------------------------------------|----|-|-|
18 27|foo | |a|7|
19 49|bar |abcd|a|3|
20 81|baz\nbazinga\nbazurka |jk |b|9|
21 1984|bla bla bla bla bla bla bla bla bla bla bla|xyz |c|5|
22 ...
23 steno> /abc|foo/#TBL1;.socol > 2 -- /regexp/ grep, #tableabbrev, .columnabbrev
24 select * from TABLE1 where somecolumn > 2;
25 prepare: 0.000s execute: 0.039s rows: 14
26 id|column1
27 | |column2
28 | | |[column3=a]
29 | | |somecolumn
30 --|---|----|-|
31 27|foo| |7|
32 49|bar|abcd|3|
33 steno> .c1,.c2,.some;#TE1#:ob2d3 -- ; before tables means from, 2nd # alias, :macro
34 select column1,column2,somecolumn from TABLE1 TE1 order by 2 desc, 3;
35 ...
36 steno> n(), yr(), cw(,1,2,3) -- functionabbrev before (, can have initial default arg
37 select count(*), year(now()), concat_ws(',',1,2,3);
38 ...
39 steno> .col1,.clm2,.sn;#TBL1:jTBL2 u(id);mydate :b :m+3d and :d-w -- :jTABLEABBREV and :+/- family
40 select column1,column2,somecolumn from TABLE1 join TABLE2 using(id) where mydate
41 between date_format(now(),"%Y-%m-01")+interval 3 day and curdate()-interval 1 week;
42 ...
43  
44 =head1 DESCRIPTION
45  
46 You're the command-line type, but are tired of typing C<select * from TABLE
47 where CONDITION>, always forgetting the final C<;>? Output always seems far
48 too wide and at least mysql cli messes up the format when it includes
49 newlines?
50  
51 This module consists of the function C<convert> which implements a
52 configurable ultra-compact language that maps to SQL. Then there is C<run>
53 which performs normal SQL queries but has various tricks for narrowing the
54 output. It can also grep on whole rows, rather than having to list all fields
55 that you expect to match. They get combined by the function C<shell> which
56 converts and runs in an endless loop.
57  
58 This is work in progress, only recently isolated from a monolithic script.
59 Language elements and API may change as the need arises, e.g. C<:macro> used
60 to be C<@macro>, till the day I wanted to use an SQL-variable and noticed the
61 collision. In this early stage, you are more than welcome to propose
62 ammendments, especially if they make the language more powerful and/or more
63 consistent. Defaults are for MariaDB/MySQL, though the mechanism also works
64 with other DBs.
65  
66 =cut
67  
68 4 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
69  
70 package SQL::Steno v0.3.2;
71  
72 4 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
73 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
74 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
75 4 ▶use Time::HiRes qw(gettimeofday tv_interval);
Subroutine BEGIN: called CC=1 SCAR=0.0
76  
77 4 binmode $_, ':utf8' for *STDIN, *STDOUT, *STDERR;
78  
79 4 our $dbh;
80 4 our $perl_re = qr/(\{(?:(?>[^{}]+)|(?-1))*\})/;
81 4 our( %Table_Columns, $table_re );
82 0 ▶sub init {
Subroutine init: not called CC=5 SCAR=34.0
Pod undocumented
83 0 ▶ die "\$dbh is undef\n" unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $SQL::Steno::dbh 0 0 0
84 0 local @{$dbh}{qw(PrintWarn PrintError RaiseError)} = (0, 0, 0); # \todo is this right? views can barf because more restrictive.
85 0 for my $table ( @{$dbh->table_info->fetchall_arrayref} ) {
86 0 $Table_Columns{uc $table->[2]} = [];
87 0 splice @$table, 3, -1, '%';
88 0 ▶ my $info = $dbh->column_info( @$table ) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $info = $SQL::Steno::dbh->column_info(@$table) or next 0 0 0
89 0 for my $column ( @{$info->fetchall_arrayref} ) {
90 0 push @{$Table_Columns{$table->[2]}}, uc $column->[3];
91 }
92 }
93 0 undef $table_re; # (re)create below
94 }
95 4 our $init_from_query = <<\SQL;
96 select ucase(TABLE_NAME), ucase(COLUMN_NAME)
97 from information_schema.COLUMNS
98 where TABLE_SCHEMA = schema()
99 SQL
100 0 ▶sub init_from_query {
Subroutine init_from_query: not called CC=3 SCAR=24.8
Pod undocumented
101 0 ▶ die "\$dbh is undef\n" unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $SQL::Steno::dbh 0 0 0
102 0 local @{$dbh}{qw(PrintWarn PrintError RaiseError)} = (0, 0, 0); # \todo is this right?
103 0 my $sth = $dbh->prepare( $init_from_query );
104 0 $sth->execute;
105 0 $sth->bind_columns( \my( $table, $column ));
106 0 ▶ push @{$Table_Columns{$table}}, $column while $sth->fetch;
Branch: 1 branch
BranchTrueFalseTotal
$sth->fetch and do { push @{$SQL::Steno::Table_Columns{$table};}, $column } 0 0 0
107 0 undef $table_re; # (re)create below
108 }
109  
110  
111  
112 4 my %render =
113 (csv => \&render_csv,
114 table => \&render_table,
115 yaml => \&render_yaml,
116 yml => \&render_yaml);
117 4 my( $render, %opt );
118  
119 4 ▶sub set_render($@) {
Subroutine set_render: called CC=3 SCAR=11.0
Pod undocumented
120 4 ($render, %opt) = ();
121 4 for( @_ ) {
122 7 ▶ if( defined $render ) { # all further args are opts
Branch: 1 branch
BranchTrueFalseTotal
if (defined $render) { } 3 4 7
123 3 tr/ \t//d;
124 3 undef $opt{$_}; # make it exist
125 } else {
126 4 $render = substr $_, 1;
127 }
128 }
129 4 $render = $render{$render};
130 4 ''; # For use as a query
131 }
132  
133  
134  
135 4 our( %Queries_help, %Queries );
136 74 ▶sub Query {
Subroutine Query: called CC=1 SCAR=0.0
Pod undocumented
137 74 $Queries_help{$_[0]} = $_[1];
138 74 $Queries{$_[0]} = $_[2];
139 74 undef;
140 }
141 Query ".$_", " output '&.$_() this' or next query as \U$_", \&set_render
142 4 for keys %render;
143  
144 Query 'c'.substr( $_, 0, 1 ), "$_ show create (&- or similar for full display)",
145 '&{ $render ||= \&render__create; "" }=show create '.$_.' $1'
146 4 for qw(table function procedure view);
147  
148 Query @$_
149 4 for
150 ['-' => " output next query as YAML",
151 '&.yaml'],
152  
153  
154 [ps => ' show processlist (without Sleep)',
155 '{(${_}[7] // "") ne "Sleep"}=show processlist'],
156  
157 [psf => ' show full processlist (without Sleep)',
158 '{(${_}[7] // "") ne "Sleep"}=show full processlist'],
159  
160  
161 [t => 'unquotedtablename[,unquotedcolumnpattern] show fields',
162 'COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE NUL,COLUMN_KEY `KEY`,COLUMN_COMMENT;information_schema.`COLUMNS`;TABLE_SCHEMA=schema() and TABLE_NAME=$\1:ob ORDINAL_POSITION'],
163 # 'COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE NUL,COLUMN_KEY `KEY`,COLUMN_COMMENT;information_schema.`COLUMNS`;TABLE_SCHEMA=schema() and TABLE_NAME=$\1$?>? and COLUMN_NAME like$\>??:ob ORDINAL_POSITION'],
164  
165  
166 [s => 'var;value set @var = value',
167 'set @$1=$2'],
168  
169 [ss => "var;value set \@var = 'value'",
170 'set @$1=$\2'],
171  
172 [sd => 'var;value set @var = cast("value" as date)',
173 'set @$1=cast($\2 as date)'],
174  
175 [sdt => 'var;value set @var = cast("value" as datetime)',
176 'set @$1=cast($\2 as datetime)'],
177  
178 [st => 'var;value set @var = cast("value" as time)',
179 'set @$1=cast($\2 as time)'],
180  
181 [sy => ' set @a, @z yesterday is between @a and @z (see :baz)',
182 #'set @a=date(now())-interval 1 day, @z=date(now())-interval 1 second',
183 'select @a:=date(now()-interval 1 day)`@a`, @z:=date(now())-interval 1 second`@z`'];
184  
185  
186  
187 4 our( %Quotes_help, %Quotes );
188 10 ▶sub Quote {
Subroutine Quote: called CC=1 SCAR=0.0
Pod undocumented
189 10 $Quotes_help{$_[0]} = $_[1];
190 10 $Quotes{$_[0]} = $_[2];
191 10 undef;
192 }
193 Quote @$_
194 4 for
195 ['a' => 'and: unquoted joined with &&',
196 '!%&&'],
197  
198 ['o' => 'or: unquoted joined with ||',
199 '!%||'];
200  
201  
202 4 our $weekstart = 1; # Monday is the first day of the week as per ISO 8601.
203 4 my $timespec_re = qr/[yqmwdhMs]?/;
204 4 our %Join_clause;
205 our %Macros =
206 (
207 b => ' between',
208 baz => ' between @a and @z',
209 d => ' distinct',
210 h => ' having',
211 j => ' join',
212 l => ' like',
213 lj => ' left join',
214 n => ' is null',
215 nb => ' not between',
216 nc => ' sql_no_cache',
217 nl => ' not like',
218 nn => ' is not null',
219 nr => ' not rlike',
220 od => ' on duplicate key update',
221 odku => ' on duplicate key update',
222 r => ' rlike',
223 u => ' union select',
224 ua => ' union all select',
225 wr => ' with rollup',
226 2 ▶ '' => sub {
Subroutine __ANON__: called CC=17 SCAR=40.1
227 2 my $join = 'for all #TBL matching TABLE';
228 2 my $int = 'see :+ :- :y-m :q+0 :d+2h';
229 2 my $gob = 'for 0 or more digits, optionally followed by a or d';
230 2 ▶ return ([jTBL => $join], ['jTBL#' => $join], [ljTBL => $join], [1 => 'for all numbers'],
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 2 2
231 [gb147 => $gob], [ob2d5a9 => $gob],
232 ['+' => <<INT], ['-' => $int], ['d+2h' => $int], ['y-m' => $int], ['q+0' => $int])
233 :B+/-NO this B(ase) +/- N(umber, 0 for none, default 1 if O given) O(ffset)
234 optional B, O is y(ear), q(uarter), m(onth), w(eek), d(ay), h(our), M(inute), s(econd)
235 INT
236 unless @_; # help
237 2 for( $_[0] ) {
238 2 ▶ return " limit $_" if /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\d+$/u 0 2 2
239 2 ▶ if( s/^([og])b(?=(?:\d[ad]?)*$)/ $1 eq 'g' ? ' group by ' : ' order by ' /e ) {
Branch: 2 branches
BranchTrueFalseTotal
if (s/^([og])b(?=(?:\d[ad]?)*$)/$1 eq "g" ? " group by " : " order by ";/eu) 1 1 2
$1 eq 'g' ? : 0 1 1
240 1 s/(?<! )(?=\d)/, /g;
241 1 s/a/ asc/g; s/(?<!r)d/ desc/g;
242 1 return $_;
243 }
244 1 ▶ if( s/^(l?)j/#/ ) { # (l)jtbl: j or lj with any #tbl
Branch: 1 branch
BranchTrueFalseTotal
if (s/^(l?)j/#/u) 0 1 1
245 0 ▶ my $left = $1 ? ' left' : '';
Branch: 1 branch
BranchTrueFalseTotal
$1 ? : 0 0 0
246 0 &convert_table_column;
247 0 /^(\w+)/;
248 0 ▶ return "$left join $_" . ($Join_clause{$1} || $Join_clause{''} || '');
Condition0%0/5
$SQL::Steno::Join_clause{$1} || $SQL::Steno::Join_clause{''} || ''
l!l
00
$SQL::Steno::Join_clause{$1} or $SQL::Steno::Join_clause{""}
l!l&&r!l&&!r
000
MC/DC0%0/2
$SQL::Steno::Join_clause{$1} || $SQL::Steno::Join_clause{''} || ''
$SQL::Steno::Join_clause{$1} $SQL::Steno::Join_clause{""}
Truth table0%0/3
A or B
A= $SQL::Steno::Join_clause{$1}B= $SQL::Steno::Join_clause{""}
ABresult
1X1
011
000
249 }
250 1 ▶ return $_ if
Branch: 1 branch
BranchTrueFalseTotal
if s/^($timespec_re)([+-])(\d*)($timespec_re)$/({"y", " date_format(now(),\"%Y-01-01\")", "q", " date_format(now()-interval mod(month(now())+11,3) month,\"%Y-%m-01\")", "m", " date_format(now(),\"%Y-%m-01\")", "w", ' curdate()-interval weekday(now())' . ($SQL::Steno::weekstart ? " day" : "+1 day"), "d", " curdate()", "h", " date_format(now(),\"%F %H:00\")", "M", " date_format(now(),\"%F %H:%M\")", "s", " now()"}->{$1} || "") . ($3 ne 0 && " $2interval" . ($3 ? " $3" : ($4 ? " 1" : "")) . ({"y", " year", "q", " quarter", "m", " month", "w", " week", "d", " day", "h", " hour", "M", " minute", "s", " second"}->{$4} || ""));/eou 1 0 1
251 s(^($timespec_re)([+-])(\d*)($timespec_re)$) {
252 ({ y => ' date_format(now(),"%Y-01-01")',
253 q => ' date_format(now()-interval mod(month(now())+11,3) month,"%Y-%m-01")',
254 m => ' date_format(now(),"%Y-%m-01")',
255 w => ' curdate()-interval weekday(now())' . ($weekstart ? ' day' : '+1 day'),
256 d => ' curdate()',
257 h => ' date_format(now(),"%F %H:00")',
258 M => ' date_format(now(),"%F %H:%M")',
259 s => ' now()' }->{$1} || '') .
260 ($3 ne '0' &&
261 " $2interval" .
262 ($3 ? " $3" : $4 ? ' 1' : '') .
263 ({ y => ' year',
264 q => ' quarter',
265 m => ' month',
266 w => ' week',
267 d => ' day',
268 h => ' hour',
269 M => ' minute',
270 1 ▶ s => ' second' }->{$4} || ''))
Branch: 3 branches
BranchTrueFalseTotal
$SQL::Steno::weekstart ? : 1 0 1
$3 ? : 0 0 0
$4 ? : 0 0 0
Condition28%2/7
{'y', ' date_format(now(),"%Y-01-01")', 'q', ' date_format(now()-interval mod(month(now())+11,3) month,"%Y-%m-01")', 'm', ' date_format(now(),"%Y-%m-01")', 'w', ' curdate()-interval weekday(now())' . ($SQL::Steno::weekstart ? ' day' : '+1 day'), 'd', ' curdate()', 'h', ' date_format(now(),"%F %H:00")', 'M', ' date_format(now(),"%F %H:%M")', 's', ' now()'}->{$1} || ''
l!l
10
$3 ne '0' && " $2interval" . ($3 ? " $3" : ($4 ? ' 1' : '')) . ({'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4} || '')
!ll&&!rl&&r
100
{'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4} || ''
l!l
00
MC/DC0%0/1
{'y', ' date_format(now(),"%Y-01-01")', 'q', ' date_format(now()-interval mod(month(now())+11,3) month,"%Y-%m-01")', 'm', ' date_format(now(),"%Y-%m-01")', 'w', ' curdate()-interval weekday(now())' . ($SQL::Steno::weekstart ? ' day' : '+1 day'), 'd', ' curdate()', 'h', ' date_format(now(),"%F %H:00")', 'M', ' date_format(now(),"%F %H:%M")', 's', ' now()'}->{$1} || ''
{'y', ' date_format(now(),"%Y-01-01")', 'q', ' date_format(now()-interval mod(month(now())+11,3) month,"%Y-%m-01")', 'm', ' date_format(now(),"%Y-%m-01")', 'w', ' curdate()-interval weekday(now())' . ($SQL::Steno::weekstart ? ' day' : '+1 day'), 'd', ' curdate()', 'h', ' date_format(now(),"%F %H:00")', 'M', ' date_format(now(),"%F %H:%M")', 's', ' now()'}->{$1}
MC/DC0%0/2
$3 ne '0' && " $2interval" . ($3 ? " $3" : ($4 ? ' 1' : '')) . ({'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4} || '')
$3 ne '0' " $2interval" . ($3 ? " $3" : ($4 ? ' 1' : '')) . ({'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4} || '')
MC/DC0%0/1
{'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4} || ''
{'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4}
Truth table50%1/2
A
A= {'y', ' date_format(now(),"%Y-01-01")', 'q', ' date_format(now()-interval mod(month(now())+11,3) month,"%Y-%m-01")', 'm', ' date_format(now(),"%Y-%m-01")', 'w', ' curdate()-interval weekday(now())' . ($SQL::Steno::weekstart ? ' day' : '+1 day'), 'd', ' curdate()', 'h', ' date_format(now(),"%F %H:00")', 'M', ' date_format(now(),"%F %H:%M")', 's', ' now()'}->{$1}
Aresult
11
00
Truth table33%1/3
A && B
A= $3 ne '0'B= " $2interval" . ($3 ? " $3" : ($4 ? ' 1' : '')) . ({'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4} || '')
ABresult
0X0
100
111
Truth table0%0/2
A
A= {'y', ' year', 'q', ' quarter', 'm', ' month', 'w', ' week', 'd', ' day', 'h', ' hour', 'M', ' minute', 's', ' second'}->{$4}
Aresult
11
00
271 }eo;
272 }
273 4 });
274  
275 # \todo default arg n() -> n(*) time*(now())
276 4 our %Functions =
277 (
278 c => 'concat',
279 cw => 'concat_ws',
280 coa => 'coalesce',
281 gc => 'group_concat',
282 i => 'in', # not really fn, but ( follows
283 in => 'ifnull',
284 l => 'char_length',
285 lc => 'lcase',
286 m => 'min',
287 M => 'max',
288 n => 'count',
289 ni => 'not in', # -"-
290 s => 'substring',
291 u => 'using', # -"-
292 uc => 'ucase'
293 );
294  
295 # functions where the 1st argument can be now()
296 4 my @nowFunctions = qw(
297 adddate addtime convert_tz date date_add date_format date_sub datediff day
298 dayname dayofmonth dayofweek dayofyear hour last_day minute month
299 monthname quarter second subdate subtime time time_format time_to_sec
300 timediff timestamp to_days to_seconds week weekday weekofyear year
301 yearweek
302 );
303 4 our @Functions = sort @nowFunctions, qw(
304 abs acos aes_decrypt aes_encrypt ascii asin atan avg benchmark bin bit_and
305 bit_count bit_length bit_or bit_xor cast ceiling char_length char
306 character_length charset coalesce coercibility collation compress
307 concat_ws concat connection_id conv cos cot count crc32 curdate
308 current_date current_time current_timestamp current_user curtime database
309 decode default degrees des_decrypt des_encrypt elt encode encrypt exp
310 export_set field find_in_set floor format found_rows from_days
311 from_unixtime get_format get_lock greatest group_concat hex if ifnull
312 inet_aton inet_ntoa insert instr interval is_free_lock is_used_lock isnull
313 last_insert_id lcase least left length ln load_file localtime
314 localtimestamp locate log10 log2 log lower lpad ltrim make_set makedate
315 maketime master_pos_wait max md5 microsecond mid min mod name_const now
316 nullif oct octet_length old_password ord password period_add period_diff
317 pi position power quote radians rand release_lock repeat replace reverse
318 right round row_count rpad rtrim schema sec_to_time session_user sha1 sign
319 sin sleep soundex space sqrt stddev stddev_pop stddev_samp str_to_date
320 strcmp substring_index substring sum sysdate system_user tan timestampadd
321 timestampdiff trim truncate ucase uncompress uncompressed_length unhex
322 unix_timestamp upper user utc_date utc_time utc_timestamp uuid values
323 var_pop var_samp variance
324 );
325  
326 4 our %DefaultArguments = (
327 count => '*',
328 concat_ws => "','"
329 );
330 4 $DefaultArguments{$_} = 'now()' for @nowFunctions;
331  
332  
333 4 our %Tables;
334 4 our %Columns;
335  
336 5 ▶sub regexp($$) {
Subroutine regexp: called CC=6 SCAR=18.5
Pod documented
337 5 my( $str, $type ) = @_;
338 5 ▶ if( $type < 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type < 2) 2 3 5
339 2 ▶ return if $str !~ /_/; # Otherwise same as find sprintf cases
Branch: 1 branch
BranchTrueFalseTotal
unless $str =~ /_/u 2 0 2
340 0 ▶ return ($type ? '' : '^') . join '.*?_', split /_/, $str; # 0 & 1
Branch: 1 branch
BranchTrueFalseTotal
$type ? : 0 0 0
341 }
342 3 my $expr = join '.*?', split //, $str; # 2, 3 & 4
343 3 ▶ if( $type < 4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type < 4) 2 1 3
344 2 substr $expr, 0, 0, '^'; # 2 & 3
345 2 ▶ $expr .= '$' if $type == 2; # 2
Branch: 1 branch
BranchTrueFalseTotal
if $type == 2 1 1 2
346 }
347 3 $expr;
348 }
349  
350 4 my $error;
351 4 my @simple = qw(^%s$ ^%s_ ^%s _%s$ _%s %s$ %s_ %s);
352 55 ▶sub find($$$\%;\@) {
Subroutine find: called CC=12 SCAR=26.6
Pod undocumented
353 55 my( $str, $prefix, $suffix, $hash, $list ) = @_;
354 55 my $ret = $hash->{$str};
355 55 ▶ return $ret if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 42 13 55
356  
357 13 $ret = $hash->{''};
358 13 ▶ $ret = &$ret( $str ) if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 2 11 13
359 13 ▶ return $ret if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 2 11 13
360  
361 11 ▶ if( $list ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($list) 11 0 11
362 11 for my $type ( 0..@simple+4 ) { # Try to find a more and more fuzzy match.
363 23 ▶ my $expr = $type < @simple ?
Branch: 1 branch
BranchTrueFalseTotal
$type < @simple ? : 18 5 23
364 sprintf $simple[$type], $str :
365 regexp $str, $type - @simple;
366 23 ▶ next unless defined $expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expr 2 21 23
367 21 my @res = grep /$expr/i, @$list;
368 21 ▶ if( @res ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@res) 10 11 21
369 10 ▶ return $res[0] if @res == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @res == 1 10 0 10
370 0 warn "$prefix$str$suffix matches @res\n";
371 0 $error = 1;
372 0 return '';
373 }
374 }
375 }
376 # no special syntax for fields or functions, so don't fail on real one
377 1 ▶ return $str if ord $prefix == ord '.' or ord $suffix == ord '(';
Branch: 1 branch
BranchTrueFalseTotal
if ord $prefix == 46 or ord $suffix == 40 1 0 1
Condition33%1/3
ord $prefix == 46 or ord $suffix == 40
l!l&&r!l&&!r
100
MC/DC0%0/2
ord $prefix == 46 or ord $suffix == 40
ord $prefix == 46 ord $suffix == 40
Truth table33%1/3
A or B
A= ord $prefix == 46B= ord $suffix == 40
ABresult
1X1
011
000
378  
379 0 warn "$prefix$str$suffix doesn't match\n";
380 0 $error = 1;
381 }
382  
383 4 my %rq = ('[', ']',
384 '{', '}');
385 4 my $quote_re = qr(\\([^\W\d_]*)([-,:;./ #?ω^\\\@!'"`[\]{}]*)(?:%(.+?))?); # $1: name, $2: spec, $3: join
386 40 ▶sub quote($$$$) {
Subroutine quote: called CC=28 SCAR=34.6
Pod undocumented
387 40 local $_ = $_[1];
388 40 my( $named, undef, $join, @args ) = @_;
389 40 ▶ while( $named ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($named) 5 40 45
390 5 my $quotes = $Quotes{$named};
391 5 ▶ if( !defined $quotes or "\\$quotes" !~ /^$quote_re$/o ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $quotes and ("\\$quotes") =~ /^$quote_re$/ou) 0 5 5
Condition33%1/3
defined $quotes and ("\\$quotes") =~ /^$quote_re$/ou
!ll&&!rl&&r
005
MC/DC0%0/2
defined $quotes and ("\\$quotes") =~ /^$quote_re$/ou
defined $quotes ("\\$quotes") =~ /^$quote_re$/ou
Truth table33%1/3
A and B
A= defined $quotesB= ("\\$quotes") =~ /^$quote_re$/ou
ABresult
0X0
100
111
392 0 ▶ warn $quotes ? "\\$named is bad '$quotes' in \%Quotes\n" : "\\$named not found in \%Quotes\n";
Branch: 1 branch
BranchTrueFalseTotal
$quotes ? : 0 0 0
393 0 $error = 1;
394 0 return '';
395 }
396 5 $named = $1;
397 5 substr $_, 0, 0, $2;
398 5 ▶ $join //= $3;
Condition100%3/3
$join //= $3
l!l&&r!l&&!r
131
MC/DC100%2/2
$join //= $3
$join $3
Truth table100%3/3
A //= B
A= $joinB= $3
ABresult
1X1
011
000
399 }
400 40 ▶ $join //= ',';
Condition100%2/2
$join //= ","
l!l
733
MC/DC100%1/1
$join //= ","
$join
Truth table100%2/2
A
A= $join
Aresult
11
00
401 40 my $list = ref $args[0];
402 40 ▶ @args = @{$args[0]} if $list;
Branch: 1 branch
BranchTrueFalseTotal
if $list 18 22 40
403 40 ▶ return join $join, @args unless defined;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 10 30 40
404 30 /(['"`[{])/;
405 30 my( $lq ) = /(['"`[{])/;
406 30 ▶ $lq ||= "'";
Condition100%2/2
$lq ||= "'"
l!l
1020
MC/DC100%1/1
$lq ||= "'"
$lq
Truth table100%2/2
A
A= $lq
Aresult
11
00
407 30 ▶ my $rq = $rq{$lq} || $lq;
Condition66%2/3
$rq{$lq} || $lq
l!l&&r!l&&!r
6240
MC/DC0%0/2
$rq{$lq} || $lq
$rq{$lq} $lq
Truth table66%2/3
A || B
A= $rq{$lq}B= $lq
ABresult
1X1
011
000
408 30 my( $noquote, $number, $boolean, $null, $space, $var ) =
409 (tr/!//, tr/#//, tr/?//, tr/ω^//, tr/\\//, tr/@//);
410 30 ▶ my $split = tr/-// ? '-' : ''; # avoid range by putting - 1st
Branch: 1 branch
BranchTrueFalseTotal
tr/\-// ? : 0 30 30
411 30 ▶ $split .= tr/ // ? '\s' : ''; # space means any whitespace
Branch: 1 branch
BranchTrueFalseTotal
tr/ // ? : 4 26 30
412 30 $split .= join '', /([,:;.\/])/g;
413 30 ▶ $split ||= ',' unless $list;
Branch: 1 branch
BranchTrueFalseTotal
unless $list 17 13 30
Condition100%2/2
$split ||= ","
l!l
512
MC/DC100%1/1
$split ||= ","
$split
Truth table100%2/2
A
A= $split
Aresult
11
00
414 30 ▶ $split &&= $space ? qr/[$split]/ : qr/\s*[$split]\s*/;
Branch: 1 branch
BranchTrueFalseTotal
$space ? : 1 19 20
Condition66%2/3
$split &&= $space ? qr/[$split]/u : qr/\s*[$split]\s*/u
!ll&&!rl&&r
10020
MC/DC50%1/2
$split &&= $space ? qr/[$split]/u : qr/\s*[$split]\s*/u
$split $space ? qr/[$split]/u : qr/\s*[$split]\s*/u
Truth table66%2/3
A &&= B
A= $splitB= $space ? qr/[$split]/u : qr/\s*[$split]\s*/u
ABresult
0X0
100
111
415 join $join, map {
416 80 ▶ if( $noquote || $boolean && /^(?:true|false)$/i || $null && /^null$/i || $var && /^\@\w+$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($noquote or $boolean and /^(?:true|false)$/iu or $null and /^null$/iu or $var and /^\@\w+$/u) { } 13 67 80
elsif ($number and /^[-+]?(?:0b[01]+|0x[\da-f]+|(?=\.?\d)\d*\.?\d*(?:e[-+]?\d+)?)$/iu) { } 9 58 67
Condition66%12/18
$noquote or $boolean and /^(?:true|false)$/iu or $null and /^null$/iu or $var and /^\@\w+$/u
l!l&&r!l&&!r
13067
$noquote or $boolean and /^(?:true|false)$/iu or $null and /^null$/iu
l!l&&r!l&&!r
12167
$noquote or $boolean and /^(?:true|false)$/iu
l!l&&r!l&&!r
12068
$boolean and /^(?:true|false)$/iu
!ll&&!rl&&r
6800
$null and /^null$/iu
!ll&&!rl&&r
6431
$var and /^\@\w+$/u
!ll&&!rl&&r
6700
MC/DC42%3/7
$noquote or $boolean and /^(?:true|false)$/iu or $null and /^null$/iu or $var and /^\@\w+$/u
$noquote $boolean /^(?:true|false)$/iu $null /^null$/iu $var /^\@\w+$/u
Truth table25%4/16
A or B and C or D and E or F and G
A= $noquoteB= $booleanC= /^(?:true|false)$/iuD= $nullE= /^null$/iuF= $varG= /^\@\w+$/u
ABCDEFGresult
1XXXXXX1
011XXXX1
00X11XX1
01011XX1
00X0X111
00X10111
0100X111
01010111
00X0X0X0
00X0X100
00X100X0
00X10100
0100X0X0
0100X100
010100X0
01010100
417 13 $_;
418 ▶ } elsif( $number && /^[-+]?(?:0b[01]+|0x[\da-f]+|(?=\.?\d)\d*\.?\d*(?:e[-+]?\d+)?)$/i ) {
Condition100%3/3
$number and /^[-+]?(?:0b[01]+|0x[\da-f]+|(?=\.?\d)\d*\.?\d*(?:e[-+]?\d+)?)$/iu
!ll&&!rl&&r
41179
MC/DC100%2/2
$number and /^[-+]?(?:0b[01]+|0x[\da-f]+|(?=\.?\d)\d*\.?\d*(?:e[-+]?\d+)?)$/iu
$number /^[-+]?(?:0b[01]+|0x[\da-f]+|(?=\.?\d)\d*\.?\d*(?:e[-+]?\d+)?)$/iu
Truth table100%3/3
A and B
A= $numberB= /^[-+]?(?:0b[01]+|0x[\da-f]+|(?=\.?\d)\d*\.?\d*(?:e[-+]?\d+)?)$/iu
ABresult
0X0
100
111
419 9 $_;
420 } else {
421 58 s/$rq/$rq$rq/g;
422 58 "$lq$_$rq";
423 }
424 } map {
425 30 ▶ unless( $space ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($space) 49 1 50
426 49 s/\A\s*//;
427 49 s/\s*\Z//;
428 }
429 50 ▶ $split ? split $split, $_, -1 : $_;
Branch: 1 branch
BranchTrueFalseTotal
$split ? : 23 27 50
430 } @args;
431 }
432  
433 15 ▶sub convert_Query($$) {
Subroutine convert_Query: called CC=16 SCAR=27.7
Pod undocumented
434 15 my $name = $_[0];
435 15 my $res = find $name, '&', '', %Queries;
436 15 my $ref = ref $res;
437 15 my @arg;
438 15 ▶ for( $ref ? $_[1] : "$res\cA$_[1]" ) {
Branch: 1 branch
BranchTrueFalseTotal
$ref ? : 4 11 15
439 15 &convert_table_column;
440 15 ▶ ($res, $_) = split "\cA" unless $ref;
Branch: 1 branch
BranchTrueFalseTotal
unless $ref 11 4 15
441 15 @arg = split ';';
442 }
443 15 ▶ return &$res( $name, @arg ) // '' if $ref;
Branch: 1 branch
BranchTrueFalseTotal
if $ref 4 11 15
Condition50%1/2
&$res($name, @arg) // ""
l!l
40
MC/DC0%0/1
&$res($name, @arg) // ""
&$res($name, @arg)
Truth table50%1/2
A
A= &$res($name, @arg)
Aresult
11
00
444  
445 11 my( @var, %seen, @rest );
446 11 $res =~ s(\$$quote_re?(?:(\d+\b)|([*>_]))) { # $4: numbered arg, $5: special arg
447 27 ▶ if( $4 && $4 > @arg ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($4 and $4 > @arg) { } 2 25 27
Condition100%3/3
$4 and $4 > @arg
!ll&&!rl&&r
12132
MC/DC100%2/2
$4 and $4 > @arg
$4 $4 > @arg
Truth table100%3/3
A and B
A= $4B= $4 > @arg
ABresult
0X0
100
111
448 2 '';
449 } else {
450 25 ▶ push @var, [$1, $2, $3, $5 ? (undef, $5) : $4-1];
Branch: 1 branch
BranchTrueFalseTotal
$5 ? : 11 14 25
451 25 ▶ undef $seen{$4-1} if $4; # make it exist
Branch: 1 branch
BranchTrueFalseTotal
if $4 13 12 25
452 25 "\cV$#var\cZ";
453 }
454 }eg;
455 11 ▶ if( @arg > keys %seen ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@arg > keys %seen) 2 9 11
456 2 @rest = @arg;
457 2 undef $rest[$_] for keys %seen;
458 2 @rest = grep defined(), @rest;
459 }
460 11 $res =~ s(\cV(\d+)\cZ) {
461 25 my @res = @{$var[$1]};
462 25 ▶ quote $res[0], $res[1], $res[2],
Branch: 4 branches
BranchTrueFalseTotal
$res[4] ? : 11 14 25
$res[4] eq '*' ? : 5 6 11
$res[4] eq '>' ? : 6 0 6
$res[3] < 0 ? : 1 13 14
463 $res[4] ? ($res[4] eq '*' ? \@arg :
464 $res[4] eq '>' ? \@rest :
465 $_) :
466 $res[3] < 0 ? $name : $arg[$res[3]];
467 }eg;
468 11 $res;
469 }
470  
471 4 my @keys_Table_Columns;
472 33 ▶sub convert_table_column {
Subroutine convert_table_column: called CC=13 SCAR=32.1
Pod undocumented
473 33 ▶ @keys_Table_Columns = keys %Table_Columns unless @keys_Table_Columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @keys_Table_Columns 33 0 33
474 0 ▶ s&(?<!\\)#(\w+)(?:#(\w*))?&find( $1, '#', '', %Tables, @keys_Table_Columns ) . ($2 ? " $2" : defined $2 ? " $1" : '')&eg unless $error;
Branch: 3 branches
BranchTrueFalseTotal
unless $error 33 0 33
$2 ? : 0 0 0
defined $2 ? : 0 0 0
475  
476 33 ▶ unless( $table_re ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($SQL::Steno::table_re) 2 31 33
477 2 $table_re = join '|', keys %Table_Columns;
478 2 ▶ $table_re = $table_re ? qr/\b(?:$table_re)\b/ : qr/\s\b\s/;
Branch: 1 branch
BranchTrueFalseTotal
$SQL::Steno::table_re ? : 0 2 2
479 }
480 33 ▶ unless( $error ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error) 33 0 33
481 33 my %column;
482 33 for( grep /$table_re/io, split /\W+/ ) {
483 0 undef $column{$_} for @{$Table_Columns{$_}};
484 }
485 33 my @column = keys %column;
486 33 ▶ s/(^|.&|[-+\s(,;|])?(?<!\\)\.([a-z]\w*)(?:\.(\w*))?/(defined $1 ? $1 : '.') . (find $2, '.', '', %Columns, @column) . ($3 ? " $3" : defined $3 ? " $2" : '')/egi;
Branch: 3 branches
BranchTrueFalseTotal
defined $1 ? : 0 1 1
$3 ? : 0 1 1
defined $3 ? : 0 1 1
487 }
488 }
489  
490  
491 =head2 convert
492  
493 This function takes a short-hand query in C<$_> and transforms it to SQL. See
494 L</shell> for more run time oriented features.
495  
496 =head3 C<:\I<namespec>(I<strings>)> E<nbsp> or E<nbsp> C<:\I<namespec>%I<join>(I<strings>)>
497  
498 This is a special macro that transforms odd lists to SQL syntax. It takes a
499 list of unquoted strings and quotes each one of them in various ways. The
500 syntax is inspired by the Shell single character quote and Perl's C<\(...)>
501 syntax. The I<namespec> is a combination of an optional I<name> (set up with the
502 Perl function C<Quote>), followed by an optional I<spec> that extends the named
503 spec. The I<strings> can get split on a variety of one or even simultaneously
504 various characters, which you can give in any order in the I<spec>:
505  
506 =over
507  
508 =item C<\> (backslash)
509  
510 This one isn't a character to split on, but rather prevents trimming the
511 whitespace of both ends of the resulting strings.
512  
513 =item C<,> (comma), the default
514  
515 You only need to specify it, if you want to split on commas, as well as other
516 characters, at the same time. Where the C<\> (backslash) syntax is also used,
517 when given a list, there is no default splitting of list members:
518 L<C<:\{I<Perl
519 code>}>|/Perl-code-or-:-namespec-Perl-code-or-:-namespec-join-Perl-code> and
520 L<canned query's|/query-arg-...-or-query-arg-...-following-text> C<$\*> &
521 C<$\E<gt>>. In that case you must specify it, if needed, e.g. C<$\,*>.
522  
523 =item C<E<nbsp>> (space)
524  
525 This one stands for any single whitespace. Since strings are normally
526 trimmed, it's the equivalent of what the Shell does. But, if you combine it
527 with C<\>, which prevents trimming, you will get an empty string between each
528 of multiple whitespaces.
529  
530 =item C<-> (minus)
531  
532 =item C<:> (colon)
533  
534 =item C<;> (semicolon)
535  
536 =item C<.> (period)
537  
538 =item C</> (slash)
539  
540 =back
541  
542 The I<spec> can also contain several of these characters to prevent certain
543 strings from being quoted:
544  
545 =over
546  
547 =item C<#> (hash)
548  
549 All numbers, including signed, floats, binary and hexadecimal stay literal.
550 If you use C<-> as a separator, there can be no negative numbers.
551  
552 =item C<?> (question mark)
553  
554 The boolean values C<true> and C<false> stay literal.
555  
556 =item C<ω> (omega) E<nbsp> or E<nbsp> C<^> (caret)
557  
558 The value C<null> stays literal. Note that C<ω> is also a word character,
559 that would be part of a name at the beginning of I<namespec>. It is only the
560 C<null>-symbol following some non-word character, e.g. C<,> (comma).
561  
562 =item C<@> (at sign)
563  
564 Variables C<@name> stay literal.
565  
566 =item C<!> (exclamation mark)
567  
568 Everything, presumed valid sql syntax, stays literal.
569  
570 =back
571  
572 And you can give at most one I<spec> for the quotes to use:
573  
574 =over
575  
576 =item C<'> (quote), the default
577  
578 =item C<"> (double quote)
579  
580 =item C<`> (backquote)
581  
582 =item C<[]> (brackets)
583  
584 =item C<{}> (braces)
585  
586 In the latter two cases, the closing quotes are optional, for decoration only,
587 or if code completion adds them.
588  
589 =back
590  
591 The results are joined by comma, unless I<join> is given. E.g. C<:\(a,b,
592 c,NULL,true,-1.2)> gives C<'a','b','c','NULL','true','-1.2'>, while
593 C<:\:"/\#?0(a:b/ c:NULL:true/-1.2)> gives C<"a","b"," c",NULL,true,-1.2> and
594 C<:\ !%&&(a b E<nbsp>c)> gives C<a&&b&&c>.
595  
596  
597  
598 =head3 C<:I<macro>>
599  
600 These are mostly simple text-replacements stored in C<%Macros>. Unlike
601 L<C<:\>|/namespec-strings-or-:-namespec-join-strings> these do not take arguments.
602 There are also some dynamic macros. Those starting with C<:j> (join) or
603 C<:lj> (left join) may continue into a L<table spec|/tbl-or-tbl-or-tbl-alias>
604 without the leading C<#>. E.g. C<:ljtbl#t> might expand to C<left join table
605 t>.
606  
607 Those starting with C<:gb> (group by) or C<:ob> (order by) may be followed by
608 result columns numbers from 1-9, each optionally followed by a or d for asc or
609 desc. E.g. C<:ob2d3> gives C<order by 2 desc, 3>.
610  
611 =head3 C<:+I<interval>> E<nbsp> or E<nbsp> C<:I<time>+I<interval>> E<nbsp> or E<nbsp> C<:-I<interval>> E<nbsp> or E<nbsp> C<:I<time>-I<interval>>
612  
613 These are time calculation macros, where an optional leading letter indicates
614 a base time, and an optional trailing letter with an optional count means the
615 offset. The letters are:
616  
617 =over
618  
619 =item y
620  
621 (this) year(start). E.g. C<:y+2m> is march this year.
622  
623 =item q
624  
625 (this) quarter(start). E.g. C<:q+0> is this quarter, C<:q+q> is next quarter.
626  
627 =item m
628  
629 (this) month(start). E.g. C<:-3m> is whatever precedes, minus 3 months.
630  
631 =item w
632  
633 (this) week(start). E.g. C<:w+3d> is this week thursday (or wednesday if you
634 set C<$weekstart> to not follow ISO 8601 and the bible).
635  
636 =item d
637  
638 (this) day(start). E.g. C<:d-w> is midnight one week ago.
639  
640 =item h
641  
642 (this) hour(start). E.g. C<:h+30M> is half past current hour.
643  
644 =item M
645  
646 (this) minute(start). E.g. C<:+10M> is whatever precedes, plus 10min.
647  
648 =item s
649  
650 (this) second. E.g. C<:s-2h> is exactly 2h ago.
651  
652 =back
653  
654  
655 =head3 C<:{I<Perl code>}> E<nbsp> or E<nbsp> C<:\I<namespec>{I<Perl code>}> E<nbsp> or E<nbsp> C<:\I<namespec>%I<join>{I<Perl code>}>
656  
657 This gets replaced by what it returns in list context. Undefined elements get
658 rendered as C<NULL> and they all get joined by I<join> or else C<,> (comma).
659 They can become quoted like
660 L<C<:\>|/namespec-strings-or-:-namespec-join-strings>. Since the result is
661 already a list, the elements don't get split by default. If you want that,
662 you must specify it as in C<:\,{I<Perl code>}>.
663  
664  
665 =head3 C<#I<tbl>> E<nbsp> or E<nbsp> C<#I<tbl>#> E<nbsp> or E<nbsp> C<#I<tbl>#I<alias>>
666  
667 Here I<tbl> is a key of C<%Tables> or any abbreviation of known tables in
668 C<@Tables>. If followed by C<#>, the abbreviation is used as an alias, unless
669 an I<alias> directly follows, in which case that is used.
670  
671  
672 =head3 C<.I<col>> E<nbsp> or E<nbsp> C<.I<col>.> E<nbsp> or E<nbsp> C<.I<col>.I<alias>>
673  
674 Here I<col> is a key of C<%Columns> or any abbreviation of columns of any table
675 recognized in the query. If followed by C<.>, the abbreviation is used as an
676 alias, unless an I<alias> directly follows, in which case that is used. It tries
677 to be clever about whether the 1st C<.> needs to be preserved, i.e. following
678 a table name.
679  
680 =head3 C<I<func>(> E<nbsp> or E<nbsp> C<I<func>\I<namespec>(I<strings>)> E<nbsp>
681 or E<nbsp> C<I<func>\I<namespec>%I<join>(I<strings>)>
682  
683 Here I<func> is a key of C<%Functions> or any
684 abbreviation of known functions in C<@Functions>, which includes words
685 typically followed by an opening parenthesis, such as C<u(> for C<using(>.
686 C<i(> becomes C<in(>, whereas C<in(> becomes C<ifnull(>.
687  
688 If the 2nd or 3rd form is used, the I<strings> inside of the parentheses are treated
689 just like C<L<:\I<namespec>(I<strings>)|/namespec-strings-or-:-namespec-join-strings>>,
690 but in this case preserving the parentheses.
691  
692 If the 1st argument of a function is empty and the abbrev or function is found
693 in C<%DefaultArguments> the value becomes the 1st argument.
694 E.g. C<cw(,'a','b','c')> or C<cw(,:\(a,b,c))> both become
695 C<concat_ws(',','a','b','c')>.
696  
697 =head3 Abbreviated Keyword
698  
699 Finally it picks on the structure of the statement: These keywords can be
700 abbreviated: C<se(lect)>, C<ins(ert)>, C<upd(ate)> or C<del(ete)>. If none of
701 these or C<set> is present, C<select> is assumed as default (more keywords
702 need to be recognized in the future).
703  
704 For C<select>, semicolons are alternately replaced by C<from> (the 1st being
705 optional if it starts with a table name) and C<where>. If no result columns
706 are given, they default to C<*>, see L</SYNOPSIS>. For C<update>, semicolons
707 are frst replaced by C<set> and then C<where>.
708  
709 =cut
710  
711 18 ▶sub convert {
Subroutine convert: called CC=27 SCAR=35.7
Pod documented
712 18 my @strings; # extract strings to prevent following replacements inside.
713 18 ▶ until( $error ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error) 28 0 28
714 # Handle :\...{perl}
715 next if
716 28 ▶ s(:$quote_re?$perl_re){
Branch: 1 branch
BranchTrueFalseTotal
if s[:$quote_re?$SQL::Steno::perl_re][my(@ret) = map(($_ // "NULL"), eval substr($4, 1, -1)); $error = 1, warn($@) if $@; &quote($1, $2, $3, \@ret);]egou or s/(?:\b(\w+)|:)$quote_re\((.+?)\)/($1 ? "$1(" : "") . &quote($2, $3, $4, $5) . ($1 ? ")" : "");/egu 2 26 28
Condition100%3/3
s[:$quote_re?$SQL::Steno::perl_re][my(@ret) = map(($_ // "NULL"), eval substr($4, 1, -1)); $error = 1, warn($@) if $@; &quote($1, $2, $3, \@ret);]egou or s/(?:\b(\w+)|:)$quote_re\((.+?)\)/($1 ? "$1(" : "") . &quote($2, $3, $4, $5) . ($1 ? ")" : "");/egu
l!l&&r!l&&!r
1126
MC/DC100%2/2
s[:$quote_re?$SQL::Steno::perl_re][my(@ret) = map(($_ // "NULL"), eval substr($4, 1, -1)); $error = 1, warn($@) if $@; &quote($1, $2, $3, \@ret);]egou or s/(?:\b(\w+)|:)$quote_re\((.+?)\)/($1 ? "$1(" : "") . &quote($2, $3, $4, $5) . ($1 ? ")" : "");/egu
s[:$quote_re?$SQL::Steno::perl_re][my(@ret) = map(($_ // "NULL"), eval substr($4, 1, -1)); $error = 1, warn($@) if $@; &quote($1, $2, $3, \@ret);]egou s/(?:\b(\w+)|:)$quote_re\((.+?)\)/($1 ? "$1(" : "") . &quote($2, $3, $4, $5) . ($1 ? ")" : "");/egu
Truth table100%3/3
A or B
A= s[:$quote_re?$SQL::Steno::perl_re][my(@ret) = map(($_ // "NULL"), eval substr($4, 1, -1)); $error = 1, warn($@) if $@; &quote($1, $2, $3, \@ret);]egouB= s/(?:\b(\w+)|:)$quote_re\((.+?)\)/($1 ? "$1(" : "") . &quote($2, $3, $4, $5) . ($1 ? ")" : "");/egu
ABresult
1X1
011
000
717 7 ▶ my @ret = map $_ // 'NULL', eval substr $4, 1, -1; # strip {}
Condition100%2/2
$_ // "NULL"
l!l
123
MC/DC100%1/1
$_ // "NULL"
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
718 7 ▶ $error = 1, warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
719 7 quote $1, $2, $3, \@ret;
720 }ego
721  
722 # Handle function\...(str1, str2, str3) and :\...(str1, str2, str3)
723 or
724 s<(?:\b(\w+)|:)$quote_re\((.+?)\)> {
725 8 ▶ ($1 ? "$1(" : '') .
Branch: 2 branches
BranchTrueFalseTotal
$1 ? : 3 5 8
$1 ? : 3 5 8
726 quote( $2, $3, $4, $5 ) .
727 ($1 ? ')' : '')
728 }ge;
729  
730 # extract quoted strings
731 26 ▶ while( /\G.*?(['"`[{])/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G.*?(['"`[{])/cgu) 76 26 102
732 76 ▶ my $rq = $rq{$1}||$1;
Condition66%2/3
$rq{$1} || $1
l!l&&r!l&&!r
20560
MC/DC0%0/2
$rq{$1} || $1
$rq{$1} $1
Truth table66%2/3
A || B
A= $rq{$1}B= $1
ABresult
1X1
011
000
733 76 my $pos = pos;
734 76 ▶ while( /\G.*?([$rq\\])/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G.*?([$rq\\])/cgu) 92 0 92
735 92 ▶ if( $1 eq '\\' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($1 eq '\\') { } 5 87 92
elsif (not /\G$rq/cgu) { } 76 11 87
736 5 ++pos; # skip next
737 } elsif( ! /\G$rq/gc ) { # skip doubled quote
738 76 push @strings,
739 substr $_, $pos - 1, 1 - $pos + pos, # get string
740 "\cS".@strings."\cZ"; # and replace with counter
741 76 last;
742 }
743 }
744 }
745  
746 # \todo (?(?<=\w)\b)
747 next if
748 26 ▶ s&:($timespec_re[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)&find $1, ':', '', %Macros&ego;
Branch: 1 branch
BranchTrueFalseTotal
if s/:(${timespec_re}[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)/&find($1, ":", "", \%SQL::Steno::Macros);/egou 8 18 26
749 18 last;
750 }
751  
752 18 ▶ my $was_column = /^\./ or # Avoid next assumption when 1st column name is also a table name.
Branch: 1 branch
BranchTrueFalseTotal
my $was_column = /^\./u or s/^(?=#)/;/u 0 18 18
753 s&^(?=#)&;&; # Assume empty fieldlist before table name
754 18 &convert_table_column;
755 18 ▶ s&^(?=$table_re)&;& unless $was_column; # Assume empty fieldlist before table name
Branch: 1 branch
BranchTrueFalseTotal
unless $was_column 18 0 18
756  
757 18 ▶ s&\b(\w+)\((?=\s*([,)])?)&my $fn = find $1, '', '(', %Functions, @Functions; ($fn || $1).'('.($2 and $DefaultArguments{$1} || $DefaultArguments{$fn} or '')&eg unless $error;
Branch: 1 branch
BranchTrueFalseTotal
unless $error 18 0 18
Condition45%5/11
$fn || $1
l!l&&r!l&&!r
1300
$2 && ($SQL::Steno::DefaultArguments{$1} || $SQL::Steno::DefaultArguments{$fn}) || ''
l!l
013
$2 and $SQL::Steno::DefaultArguments{$1} || $SQL::Steno::DefaultArguments{$fn}
!ll&&!rl&&r
940
$SQL::Steno::DefaultArguments{$1} or $SQL::Steno::DefaultArguments{$fn}
l!l&&r!l&&!r
004
MC/DC0%0/2
$fn || $1
$fn $1
MC/DC0%0/3
$2 && ($SQL::Steno::DefaultArguments{$1} || $SQL::Steno::DefaultArguments{$fn}) || ''
$2 $SQL::Steno::DefaultArguments{$1} $SQL::Steno::DefaultArguments{$fn}
Truth table33%1/3
A || B
A= $fnB= $1
ABresult
1X1
011
000
Truth table50%2/4
A and B or C
A= $2B= $SQL::Steno::DefaultArguments{$1}C= $SQL::Steno::DefaultArguments{$fn}
ABCresult
11X1
1011
0XX0
1000
758 #s&\b(\w+)(?=\()&find $1, '', '(', %Functions, @Functions or $1&eg unless $error;
759  
760 18 ▶ return if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 18 18
761 18 s/\A\s*;/*;/;
762 18 s/;\s*\Z//;
763 18 ▶ if( s/^upd(?:a(?:t(?:e)?)?)?\b/update/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^upd(?:a(?:t(?:e)?)?)?\b/update/iu) { } 0 18 18
764 0 ▶ s/(?<!\\);(?:\s*set\s*)?/ set / && s/(?<!\\);(?:\s*where\s*)?/ where /;
Branch: 1 branch
BranchTrueFalseTotal
s/(?<!\\);(?:\s*set\s*)?/ set /u and s/(?<!\\);(?:\s*where\s*)?/ where /u 0 0 0
765 } else {
766 18 ▶ s/(?<!\\);(?:\s*where\s*)?/ where / while s/(?<!\\);(?:\s*from\s*)?/ from /;
Branch: 1 branch
BranchTrueFalseTotal
s/(?<!\\);(?:\s*from\s*)?/ from /u and do { s/(?<!\\);(?:\s*where\s*)?/ where /u } 4 18 22
767 18 ▶ s/^ins(?:e(?:r(?:t)?)?)?\b/insert/i ||
Branch: 1 branch
BranchTrueFalseTotal
s/^ins(?:e(?:r(?:t)?)?)?\b/insert/iu or s/^del(?:e(?:t(?:e)?)?)?\b/delete/iu or s/^(?!se(?:lec)?t)/select /iu 0 18 18
Condition33%1/3
s/^ins(?:e(?:r(?:t)?)?)?\b/insert/iu or s/^del(?:e(?:t(?:e)?)?)?\b/delete/iu
l!l&&r!l&&!r
0018
MC/DC0%0/2
s/^ins(?:e(?:r(?:t)?)?)?\b/insert/iu or s/^del(?:e(?:t(?:e)?)?)?\b/delete/iu
s/^ins(?:e(?:r(?:t)?)?)?\b/insert/iu s/^del(?:e(?:t(?:e)?)?)?\b/delete/iu
Truth table33%1/3
A or B
A= s/^ins(?:e(?:r(?:t)?)?)?\b/insert/iuB= s/^del(?:e(?:t(?:e)?)?)?\b/delete/iu
ABresult
1X1
011
000
768 s/^del(?:e(?:t(?:e)?)?)?\b/delete/i ||
769 s/^(?!se(?:lec)?t)/select /i;
770 }
771  
772 18 s/ $//mg;
773 18 s/ {2,}/ /g;
774 18 s/\cS(\d+)\cZ/$strings[$1]/g; # put back the strings
775  
776 18 1;
777 }
778  
779  
780 # escape map for special replacement characters
781 4 ▶my %esc = map { $_ eq 'v' ? "\013" : eval( qq!"\\$_"! ), "\\$_" } qw'0 a b e f n r t v \ "';
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'v' ? : 4 40 44
782  
783 # With an argument of total number of rows, init output counting and return undef if it is to be skipped (not stdout).
784 # Without an argument, do the counting and return undef if no more rows wanted.
785 {
786 4 my( $total, $cnt, $i );
787 16 ▶ sub count(;$) {
Subroutine count: called CC=9 SCAR=31.5
Pod undocumented
788 16 ▶ if( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 11 5 16
789 11 $total = $_[0];
790 11 $cnt = 0;
791 11 $i = 100;
792 11 ▶ return select eq 'main::STDOUT' ? 1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
select() eq 'main::STDOUT' ? : 2 9 11
793 }
794 5 ++$cnt;
795 5 ▶ if( --$i <= 0 && $cnt < $total ) {
Branch: 1 branch
BranchTrueFalseTotal
if (--$i <= 0 and $cnt < $total) 0 5 5
Condition33%1/3
--$i <= 0 and $cnt < $total
!ll&&!rl&&r
500
MC/DC0%0/2
--$i <= 0 and $cnt < $total
--$i <= 0 $cnt < $total
Truth table33%1/3
A and B
A= --$i <= 0B= $cnt < $total
ABresult
0X0
100
111
796 0 printf STDERR "How many more, * for all, or q to quit? (%d of %d) [default: 100] ",
797 $cnt, $total;
798 0 $i = <>;
799 0 ▶ if( defined $i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $i) { } 0 0 0
800 0 $i =~ tr/qQxX \t\n\r/0000/d;
801 0 ▶ $i = (0 == length $i) ? 100 :
Branch: 3 branches
BranchTrueFalseTotal
0 == length $i ? : 0 0 0
$i eq '*' ? : 0 0 0
$i == 0 ? : 0 0 0
802 $i eq '*' ? ~0 :
803 $i == 0 ? return :
804 $i;
805 } else {
806 0 print "\n";
807 0 return;
808 }
809 }
810 5 1;
811 }
812 }
813  
814 4 ▶sub render_csv($;$$) {
Subroutine render_csv: called CC=15 SCAR=27.1
Pod undocumented
815 6 my( $sth, $filter ) = @_;
816 my( $semi, $tab ) =
817 (exists $_[2]{semi},
818 exists $_[2]{tab})
819 6 ▶ if $_[2];
Branch: 1 branch
BranchTrueFalseTotal
if $_[2] 5 1 6
820 6 my $name = $sth->{NAME};
821 6 my @row = @$name;
822 6 while() {
823 18 for( @row ) {
824 162 ▶ if( defined ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_) { } 156 6 162
825 156 ▶ $_ = qq!"$_"! if
Branch: 3 branches
BranchTrueFalseTotal
if /\A\Z/u or s/"/""/gu or $semi ? tr/\n;// : ($tab ? tr/\t\n// : tr/\n,//) or /\A=/u 24 132 156
$semi ? : 49 98 147
$tab ? : 49 49 98
Condition88%8/9
/\A\Z/u or s/"/""/gu or $semi ? tr/\n;// : ($tab ? tr/\t\n// : tr/\n,//) or /\A=/u
l!l&&r!l&&!r
240132
/\A\Z/u or s/"/""/gu or $semi ? tr/\n;// : ($tab ? tr/\t\n// : tr/\n,//)
l!l&&r!l&&!r
915132
/\A\Z/u or s/"/""/gu
l!l&&r!l&&!r
36147
MC/DC75%3/4
/\A\Z/u or s/"/""/gu or $semi ? tr/\n;// : ($tab ? tr/\t\n// : tr/\n,//) or /\A=/u
/\A\Z/u s/"/""/gu $semi ? tr/\n;// : ($tab ? tr/\t\n// : tr/\n,//) /\A=/u
Truth table80%4/5
A or B or C or D
A= /\A\Z/uB= s/"/""/guC= $semi ? tr/\n;// : ($tab ? tr/\t\n// : tr/\n,//)D= /\A=/u
ABCDresult
1XXX1
01XX1
001X1
00011
00000
826 /\A\Z/ or
827 s/"/""/g or
828 $semi ? tr/;\n// : $tab ? tr/\t\n// : tr/,\n// or
829 /\A=/;
830 } else {
831 6 $_ = '';
832 }
833 162 utf8::decode $_;
834 }
835 18 ▶ print join( $semi ? ';' : $tab ? "\t" : ',', @row ) . "\n";
Branch: 2 branches
BranchTrueFalseTotal
$semi ? : 6 12 18
$tab ? : 6 6 12
836  
837 21 ▶ FETCH:
Branch: 1 branch
BranchTrueFalseTotal
@row = $sth->fetchrow_array or last 15 6 21
838 @row = $sth->fetchrow_array
839 or last;
840 15 ▶ $filter->( $name, @row ) or goto FETCH if $filter;
Branch: 1 branch
BranchTrueFalseTotal
if $filter 6 9 15
Condition80%4/5
$filter && (&$filter($name, @row) || (goto FETCH))
!ll&&!rl&&r
960
&$filter($name, @row) or goto FETCH
l!l
33
MC/DC0%0/2
$filter && (&$filter($name, @row) || (goto FETCH))
$filter &$filter($name, @row)
Truth table66%2/3
A && B
A= $filterB= &$filter($name, @row)
ABresult
0X0
100
111
841 }
842 }
843  
844 4 our $NULL = 'ω';
845 4 utf8::decode $NULL;
846 4 my( $r1, $r2, $r3, $r5 ) = ('[01]\d', '[0-2]\d', '[0-3]\d', '[0-5]\d');
847 17 ▶sub render_table($;$$) {
Subroutine render_table: called CC=49 SCAR=40.3
Pod undocumented
848 17 my( $sth, $filter ) = @_;
849 my( $null, $crlf, $date, $time ) =
850 exists $_[2]{all} ?
851 ('NULL', 1, 1, 1) :
852 (exists $_[2]{NULL} ? 'NULL' : exists $_[2]{null} ? 'null' : 0,
853 exists $_[2]{crlf},
854 exists $_[2]{date},
855 exists $_[2]{time})
856 17 ▶ if $_[2];
Branch: 4 branches
BranchTrueFalseTotal
if $_[2] 15 2 17
exists $_[2]{'all'} ? : 2 13 15
exists $_[2]{'NULL'} ? : 0 13 13
exists $_[2]{'null'} ? : 1 12 13
857 17 ▶ $null ||= $NULL;
Condition66%2/3
$null ||= $SQL::Steno::NULL
l!l&&r!l&&!r
3140
MC/DC0%0/2
$null ||= $SQL::Steno::NULL
$null $SQL::Steno::NULL
Truth table66%2/3
A ||= B
A= $nullB= $SQL::Steno::NULL
ABresult
1X1
011
000
858 17 my @name = @{$sth->{NAME}};
859 17 my @len = (0) x @name;
860 17 my( @txt, @res, @comp );
861 17 ▶ while( my @res1 = $sth->fetchrow_array ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@res1) = $sth->fetchrow_array) 80 17 97
862 80 ▶ $filter->( \@name, @res1 ) or next if $filter;
Branch: 1 branch
BranchTrueFalseTotal
if $filter 1 79 80
Condition60%3/5
$filter && (&$filter(\@name, @res1) || (next))
!ll&&!rl&&r
7910
&$filter(\@name, @res1) or next
l!l
10
MC/DC0%0/2
$filter && (&$filter(\@name, @res1) || (next))
$filter &$filter(\@name, @res1)
Truth table33%1/3
A && B
A= $filterB= &$filter(\@name, @res1)
ABresult
0X0
100
111
863 80 for my $i ( 0..$#res1 ) {
864 580 ▶ if( !defined $res1[$i] ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $res1[$i]) { } 4 576 580
elsif (not $res1[$i] =~ /^\d+(?:\.\d+)?$/u) { } 537 39 576
865 4 $res1[$i] = $null;
866 } elsif( $res1[$i] !~ /^\d+(?:\.\d+)?$/ ) {
867 537 $txt[$i] = 1;
868 537 ▶ $res1[$i] =~ s/\r\n/\\R/g unless $crlf;
Branch: 1 branch
BranchTrueFalseTotal
unless $crlf 411 126 537
869 537 $res1[$i] =~ s/([\t\n\r])/$esc{$1}/g;
870 4 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
871 537 ▶ unless( $date ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($date) 215 322 537
872 215 ▶ if( $res1[$i] =~ s/^(\d{4}-)($r1)-0[01]([T ]$r2:$r5(?::$r5(?:[.,]\d{3})?)?(?:Z|[+-]$r2:$r5)?)?$/$1/o ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res1[$i] =~ s/^(\d{4}-)($r1)-0[01]([T ]$r2:$r5(?::$r5(?:[.,]\d{3})?)?(?:Z|[+-]$r2:$r5)?)?$/$1/ou) 109 106 215
873 109 ▶ $res1[$i] .= "$2-" if $2 > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $2 > 1 24 85 109
874 109 ▶ $res1[$i] .= $3 if $3;
Branch: 1 branch
BranchTrueFalseTotal
if $3 91 18 109
875 }
876 }
877 537 ▶ unless( $time ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($time) 215 322 537
878 215 ▶ if( $res1[$i] =~ s/^(\d{4}-(?:$r1-(?:$r3)?)?[T ])?($r2):($r5)(?::($r5)(?:([.,])(\d{3}))?)?(Z|[+-]$r2:$r5)?$/$1/o ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res1[$i] =~ s/^(\d{4}-(?:$r1-(?:$r3)?)?[T ])?($r2):($r5)(?::($r5)(?:([.,])(\d{3}))?)?(Z|[+-]$r2:$r5)?$/$1/ou) 170 45 215
879 170 ▶ $res1[$i] = $1 || '';
Condition100%2/2
$1 || ''
l!l
14228
MC/DC100%1/1
$1 || ''
$1
Truth table100%2/2
A
A= $1
Aresult
11
00
880 170 ▶ if( $2 == 23 && $3 == 59 && ($4 // 59) == 59 && ($6 // 999) == 999 ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($2 == 23 and $3 == 59 and ($4 // 59) == 59 and ($6 // 999) == 999) { } 49 121 170
elsif ($6 > 0) { } 24 97 121
elsif ($4 > 0) { } 12 85 97
elsif ($3 > 0) { } 12 73 85
Condition76%10/13
$2 == 23 and $3 == 59 and ($4 // 59) == 59 and ($6 // 999) == 999
!ll&&!rl&&r
121049
$2 == 23 and $3 == 59 and ($4 // 59) == 59
!ll&&!rl&&r
121049
$2 == 23 and $3 == 59
!ll&&!rl&&r
121049
$4 // 59
l!l
3712
$6 // 999
l!l
2425
MC/DC50%2/4
$2 == 23 and $3 == 59 and ($4 // 59) == 59 and ($6 // 999) == 999
$2 == 23 $3 == 59 $4 $6
Truth table60%3/5
A and B and C and D
A= $2 == 23B= $3 == 59C= $4D= $6
ABCDresult
0XXX0
10XX0
110X0
11100
11111
881 49 $res1[$i] .= "24:";
882 } elsif( $6 > 0 ) {
883 24 $res1[$i] .= "$2:$3:$4$5$6";
884 } elsif( $4 > 0 ) {
885 12 $res1[$i] .= "$2:$3:$4";
886 } elsif( $3 > 0 ) {
887 12 $res1[$i] .= "$2:$3";
888 } else {
889 73 $res1[$i] .= "$2:";
890 }
891 170 ▶ ($res1[$i] .= $7) =~ s/:00$/:/
Branch: 1 branch
BranchTrueFalseTotal
if $7 84 86 170
892 if $7;
893 }
894 }
895 537 utf8::decode $res1[$i];
896 }
897 580 ▶ $txt[$i] = 0 if @txt < $i;
Branch: 1 branch
BranchTrueFalseTotal
if @txt < $i 10 570 580
898 580 my $len = length $res1[$i];
899 580 ▶ $len[$i] = $len if $len[$i] < $len;
Branch: 1 branch
BranchTrueFalseTotal
if $len[$i] < $len 184 396 580
900 }
901 80 ▶ if( @comp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@comp) { } 71 9 80
902 71 for my $i ( 0..$#comp ) {
903 509 ▶ undef $comp[$i] if defined $comp[$i] && $comp[$i] ne $res1[$i];
Branch: 1 branch
BranchTrueFalseTotal
if defined $comp[$i] and $comp[$i] ne $res1[$i] 62 447 509
Condition100%3/3
defined $comp[$i] and $comp[$i] ne $res1[$i]
!ll&&!rl&&r
3965162
MC/DC100%2/2
defined $comp[$i] and $comp[$i] ne $res1[$i]
defined $comp[$i] $comp[$i] ne $res1[$i]
Truth table100%3/3
A and B
A= defined $comp[$i]B= $comp[$i] ne $res1[$i]
ABresult
0X0
100
111
904 }
905 } else {
906 9 @comp = @res1;
907 }
908 80 push @res, \@res1;
909 }
910 17 ▶ if( @res ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@res) 9 8 17
911 9 ▶ @comp = () if @res == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @res == 1 1 8 9
912 9 my $fmt = '';
913 9 ▶ for( my $i = 0; $i < @name; ++$i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @name) 71 9 80
914 71 $name[$i] =~ s/\r\n/\\R/g;
915 71 $name[$i] =~ s/([\t\n\r])/$esc{$1}/g;
916 71 ▶ if( defined $comp[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $comp[$i]) 0 71 71
917 0 my $more;
918 0 ▶ while( defined $comp[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $comp[$i]) 0 0 0
919 0 ▶ printf $fmt, @name[0..$i-1] unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 0 0 0
920 0 $more = 1;
921 0 printf "[%s=%s]", $name[$i], $comp[$i];
922 0 @name[0..$i] = ('') x ($i+1);
923 0 for my $row ( \@comp, \@name, \@len, \@txt, @res ) {
924 0 splice @$row, $i, 1;
925 }
926 }
927 0 print "\n";
928 0 --$i, next;
929 }
930 71 ▶ if( $len[$i] < length $name[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len[$i] < length $name[$i]) 9 62 71
931 9 printf "$fmt%s\n", @name[0..$i];
932 9 @name[0..$i] = ('') x ($i+1);
933 }
934 71 ▶ $fmt .= '%' . ($txt[$i] ? -$len[$i] : $len[$i]) . 's|';
Branch: 1 branch
BranchTrueFalseTotal
$txt[$i] ? : 67 4 71
935 }
936 9 $fmt .= "\n";
937 9 ▶ printf $fmt, @name if $name[-1];
Branch: 1 branch
BranchTrueFalseTotal
if $name[-1] 8 1 9
938 9 printf $fmt, map '-'x$_, @len;
939 9 my $count = count @res; # init
940 9 for my $row ( @res ) {
941 80 printf $fmt, @$row;
942 80 ▶ defined count or last if defined $count;
Branch: 1 branch
BranchTrueFalseTotal
if defined $count 1 79 80
Condition60%3/5
defined $count && (defined &count() || (last))
!ll&&!rl&&r
7910
defined &count() or last
l!l
10
MC/DC0%0/2
defined $count && (defined &count() || (last))
defined $count defined &count()
Truth table33%1/3
A && B
A= defined $countB= defined &count()
ABresult
0X0
100
111
943 }
944 }
945 }
946  
947 4 my $yaml_re = join '', sort keys %esc;
948 4 $yaml_re =~ s!\\!\\\\!;
949 4 ▶my $tabsize = $ENV{TABSIZE} || 8;
Condition100%2/2
$ENV{'TABSIZE'} || 8
l!l
13
MC/DC100%1/1
$ENV{'TABSIZE'} || 8
$ENV{'TABSIZE'}
Truth table100%2/2
A
A= $ENV{'TABSIZE'}
Aresult
11
00
950 2 ▶sub render_yaml($;$$) {
Subroutine render_yaml: called CC=23 SCAR=31.7
Pod undocumented
951 2 my( $sth, $filter ) = @_;
952 2 my @label; # Fill on 0th round with same transformation as data (but \n inline)
953 2 ▶ my $count = count $DBI::rows || 1; # init \todo don't know how many unfiltered
Condition100%2/2
&count($DBI::rows) || 1
l!l
11
MC/DC100%1/1
&count($DBI::rows) || 1
&count($DBI::rows)
Truth table100%2/2
A
A= &count($DBI::rows)
Aresult
11
00
954 2 my @row = @{$sth->{NAME}};
955 2 while() {
956 6 local $_;
957 6 my $i = 0;
958 6 for( @row ) {
959 54 ▶ if( !defined ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $_) { } 2 52 54
elsif (/^(?:y(?:es)?|no?|true|false|o(?:n|ff)|-?\.inf|\.nan)$/su) { } 0 52 52
elsif (tr/\-\000-\b\cK-\037!-#%-'*,:<-@[]`{-\237// or @label ? 0 : tr/\n//) { } 15 37 52
elsif (tr/\n//) { } 1 36 37
960 2 $_ = '~';
961 } elsif( /^(?:y(?:es)?|no?|true|false|o(?:n|ff)|-?\.inf|\.nan)$/s ) { # can only be string in Perl or DB
962 0 $_ = "'$_'";
963 ▶ } elsif( tr/][{},?:`'"|<>&*!%#@=~\0-\010\013-\037\177-\237-// or @label ? 0 : tr/\n// ) {
Branch: 1 branch
BranchTrueFalseTotal
@label ? : 25 13 38
Condition100%3/3
tr/\-\000-\b\cK-\037!-#%-'*,:<-@[]`{-\237// or @label ? 0 : tr/\n//
l!l&&r!l&&!r
14137
MC/DC100%2/2
tr/\-\000-\b\cK-\037!-#%-'*,:<-@[]`{-\237// or @label ? 0 : tr/\n//
tr/\-\000-\b\cK-\037!-#%-'*,:<-@[]`{-\237// @label ? 0 : tr/\n//
Truth table100%3/3
A or B
A= tr/\-\000-\b\cK-\037!-#%-'*,:<-@[]`{-\237//B= @label ? 0 : tr/\n//
ABresult
1X1
011
000
964 15 s/([$yaml_re])/$esc{$1}/go;
965 0 s/([\0-\010\013-\037\177-\237])/sprintf "\\x%02x", ord $1/ge;
966 15 $_ = qq!"$_"!;
967 } elsif( tr/\n// ) {
968 1 my $nl = chomp;
969 1 s/^/ /mg;
970 1 ▶ substr $_, 0, 0, $nl ? "|2\n" : "|2-\n";
Branch: 1 branch
BranchTrueFalseTotal
$nl ? : 0 1 1
971 }
972 54 ▶ print "$label[$i++]$_\n" if @label;
Branch: 1 branch
BranchTrueFalseTotal
if @label 36 18 54
973 }
974 6 ▶ if( @label ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@label) { } 4 2 6
975 4 ▶ defined count or last if defined $count;
Branch: 1 branch
BranchTrueFalseTotal
if defined $count 4 0 4
Condition40%2/5
defined $count && (defined &count() || (last))
!ll&&!rl&&r
040
defined &count() or last
l!l
40
MC/DC0%0/2
defined $count && (defined &count() || (last))
defined $count defined &count()
Truth table0%0/3
A && B
A= defined $countB= defined &count()
ABresult
0X0
100
111
976 } else {
977 2 my $maxlen = 0;
978 2 for( @row ) {
979 18 ▶ substr $_, 0, 0, $maxlen ? ' ' : '- '; # 1st field if no maxlen yet
Branch: 1 branch
BranchTrueFalseTotal
$maxlen ? : 16 2 18
980 18 my $length = 0;
981 18 ▶ $length += $1 ? $tabsize - $length % $tabsize : length $2
Branch: 2 branches
BranchTrueFalseTotal
/\G(?:(\t)|([^\t]+))/cgu and do { $length += $1 ? $tabsize - $length % $tabsize : length $2 } 20 18 38
$1 ? : 1 19 20
982 while /\G(?:(\t)|([^\t]+))/gc;
983 18 $_ .= ": $length";
984 18 ▶ $maxlen = $length if $maxlen < $length;
Branch: 1 branch
BranchTrueFalseTotal
if $maxlen < $length 7 11 18
985 }
986 18 s/(\d+)\Z/' ' x ($maxlen - $1)/e
987 2 for @label = @row;
988 }
989 7 ▶ FETCH:
Branch: 1 branch
BranchTrueFalseTotal
@row = $sth->fetchrow_array or last 5 2 7
990 @row = $sth->fetchrow_array
991 or last;
992 5 ▶ $filter->( $sth->{NAME}, @row ) or goto FETCH if $filter;
Branch: 1 branch
BranchTrueFalseTotal
if $filter 2 3 5
Condition80%4/5
$filter && (&$filter($sth->{'NAME'}, @row) || (goto FETCH))
!ll&&!rl&&r
320
&$filter($sth->{"NAME"}, @row) or goto FETCH
l!l
11
MC/DC0%0/2
$filter && (&$filter($sth->{'NAME'}, @row) || (goto FETCH))
$filter &$filter($sth->{"NAME"}, @row)
Truth table66%2/3
A && B
A= $filterB= &$filter($sth->{"NAME"}, @row)
ABresult
0X0
100
111
993 }
994 }
995  
996 0 ▶sub render__create($;$$) {
Subroutine render__create: not called CC=5 SCAR=34.0
Pod undocumented
997 0 ▶ my @row = $_[0]->fetchrow_array
Branch: 1 branch
BranchTrueFalseTotal
my(@row) = $_[0]->fetchrow_array or return 0 0 0
998 or return;
999 0 ▶ my $col = $_[0]{NAME}[0] =~ /Function|Procedure/i ? 2 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'NAME'}[0] =~ /Function|Procedure/iu ? : 0 0 0
1000 0 ▶ if( @row > $col ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@row > $col) 0 0 0
1001 0 $col = $row[$col];
1002 0 ▶ $col =~ s/,/,\n/g if $_[0]{NAME}[0] =~ /View/i;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]{"NAME"}[0] =~ /View/iu 0 0 0
1003 0 say $col;
1004 }
1005 }
1006  
1007  
1008  
1009 4 my $lasttime = time;
1010 13 ▶sub run($;$\%) {
Subroutine run: called CC=8 SCAR=23.9
Pod undocumented
1011 13 my( $sql, $filter, $opt ) = @_;
1012 13 my $t0 = [gettimeofday];
1013 13 ▶ if( $DBI::err || $t0->[0] - $lasttime > 3600 and !$dbh->ping ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DBI::err || $t0->[0] - $lasttime > 3600 and not $SQL::Steno::dbh->ping) 0 13 13
Condition33%2/6
$DBI::err || $t0->[0] - $lasttime > 3600 and not $SQL::Steno::dbh->ping
!ll&&!rl&&r
1300
$DBI::err or $t0->[0] - $lasttime > 3600
l!l&&r!l&&!r
0013
MC/DC0%0/3
$DBI::err || $t0->[0] - $lasttime > 3600 and not $SQL::Steno::dbh->ping
$DBI::err $t0->[0] - $lasttime > 3600 not $SQL::Steno::dbh->ping
Truth table20%1/5
A or B and not(C)
A= $DBI::errB= $t0->[0] - $lasttime > 3600C= not $SQL::Steno::dbh->ping
ABCresult
00X0
1X00
0100
1X11
0111
1014 0 printf STDOUT "Inactive for %ds, ping failed after %.03fs, your session variables are lost.\n",
1015 $t0->[0] - $lasttime, tv_interval $t0;
1016 #$dbh->disconnect;
1017 0 $dbh = $dbh->clone; # reconnect
1018 0 $t0 = [gettimeofday];
1019 }
1020 13 $lasttime = $t0->[0];
1021 13 ▶ if( my $sth = UNIVERSAL::isa( $sql, 'DBI::st' ) ? $sql : $dbh->prepare( $sql )) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $sth = UNIVERSAL::isa($sql, "DBI::st") ? $sql : $SQL::Steno::dbh->prepare($sql)) 13 0 13
UNIVERSAL::isa($sql, 'DBI::st') ? : 0 13 13
1022 13 my $t1 = [gettimeofday];
1023 13 $sth->execute;
1024 13 printf STDOUT "prepare: %.03fs execute: %.03fs rows: %d\n",
1025 tv_interval( $t0, $t1 ), tv_interval( $t1 ), $DBI::rows;
1026 13 ▶ if( $sth->{Active} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->{"Active"}) 13 0 13
1027 13 ▶ if( $render ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($render) { } 4 9 13
1028 4 &$render( $sth, $filter, $opt );
1029 } else {
1030 9 render_table $sth, $filter, $opt;
1031 }
1032 }
1033 }
1034 }
1035  
1036  
1037 =head2 shell
1038  
1039 This function reads, converts and (if C<$dbh> is set) runs in an end-less loop
1040 (i.e. till end of file or C<^D>). Reading is a single line affair, unless you
1041 request otherwise. This can happen either, as in Unix Shell, by using
1042 continuation lines as long as you put a backslash at the end of your lines.
1043 Or there is a special case, if the 1st line starts with C<\\>, then everything
1044 up to C<\\> at the end of one of the next lines, constitutes one entry.
1045  
1046 In addition to converting, it offers a few extra features, performed in this
1047 order (i.e. C<&I<xyz>> can return C</I<regexp>/=I<literal sql>> etc.):
1048  
1049 =head3 C<&{I<Perl code>} I<following text>>
1050  
1051 Run I<Perl code>. It sees the optional I<following text> in C<$_> and may
1052 modify it. If it returns C<undef>, this statement is skipped. If it returns
1053 a DBI statement handle, run that instead of this statement. Else replace with
1054 what it returns.
1055  
1056 Reprocess result as a shell entry (i.e. it may return another C<&I<query>>).
1057  
1058 =head3 C<&I<query arg>; ...> E<nbsp> or E<nbsp> C<&I<query>( I<arg>; ... ) I<following text>>
1059  
1060 These allow canned entries and are more complex than macros, in that they take
1061 arguments and replacement can depend on the argument.
1062  
1063 Reprocess result as a shell entry (i.e. it may return another C<&I<query>>).
1064  
1065 You can define your own canned queries with:
1066  
1067 C< &{ Query I<name> =E<gt> 'I<doc>', 'I<query>' }>
1068  
1069 Here C<query> becomes the replacement string for C<&name>. It may contain
1070 arguments a bit like the Shell: C<$0> (I<name>), C<$*> (all arguments), C<$1,
1071 $2, ..., $10, ...> (individual arguments) and C<$E<gt>> (all arguments not
1072 adressed individually). They can become quoted like
1073 L<C<:\>|/namespec-strings-or-:-namespec-join-strings> as
1074 C<$\I<namespec>I<arg>> or C<$\I<namespec>%I<join>I<arg>>. Here I<arg> is
1075 C<*>, C<E<gt>> or a number directly tacked on to I<spec> or I<join>. E.g.:
1076 C<$\-"1> splits the 1st (semi-colon separated from the 2nd) argument itself on
1077 C<-> (minus), quotes the pieces with C<"> (double quote) and joins them with
1078 C<,> (comma). The two list variables C<$\*> & C<$\E<gt>> don't get split
1079 individually unless explicitly specified, e.g. C<$\,*>. Putting the quotes
1080 inside the argument like this, eliminates them, if no argument is given.
1081  
1082 =head3 C</I<regexp>/ I<statement>> E<nbsp> or E<nbsp> C</I<regexp>/i I<statement>> E<nbsp> or E<nbsp> C<!/I<regexp>/ I<statement>> E<nbsp> or E<nbsp> C<!/I<regexp>/i I<statement>>
1083  
1084 This will treat the I<statement> normally, but will join each output row into
1085 a C<~> (tilde) separated string for matching. NULL fields are rendered as
1086 that string. E.g. to return only rows starting with a number 1-5, followed by
1087 a NULL field, you could write: C</^[1-5]~NULL~/>.
1088  
1089 With a suffix C<i>, matching becomes case insensitive. This is why the mostly
1090 optional space before I<statement> is shown above. Without an C<i>, but if
1091 the statement starts with the word C<i> (e.g. your first column name), you
1092 must separate it with a space. With an C<i>, if the statement starts with an
1093 alphanumeric caracter, you must separate it with a space.
1094  
1095 Only matching rows are considered unless there is a preceding C<!>
1096 (exclamation mark), in which case only non-matching rows are considered.
1097  
1098 You can provide your own formatting of the row by setting C<$regexp_fail> to a
1099 Perl sub that returns a Perl expression as a string. That expression takes
1100 the row in C<@_> and shall be true if the row fails to match.
1101  
1102 Caveat: the whole result set of the I<statement> gets generated and
1103 transferred to the client. This is definitely much more expensive than doing
1104 the equivalent filtering in the where clause. But it is not a big deal for
1105 tens or maybe hundreds of thousands or rows, probably still faster than
1106 writing the corresponding SQL. And Perl's regexps are so much more powerful.
1107  
1108 =head3 C<{I<Perl code>}I<statement>>
1109  
1110 Call I<Perl code> for every output row returned by the I<statement> with the
1111 array of column names as zeroth argument and the values after that (i.e.
1112 numbered from 1 like in SQL). It may modify individual values. If it returns
1113 false, the row is skipped.
1114  
1115 You may combine S<C</I<regexp>/{I<Perl code>}>> in any order and as many of them as
1116 you want.
1117  
1118 The same caveat as for regexps applies here. But again Perl is far more
1119 powerful than any SQL functions.
1120  
1121 =head3 C<=I<literal sql>>
1122  
1123 A preceding C<=> prevents conversion, useful for hitherto untreated keywords
1124 or where the conversion doesn't play well with your intention.
1125  
1126 =head3 C<?>
1127  
1128 Help prefix. Alone it will give an overview. You can follow up with any of
1129 the special syntaxes, with or without an abbreviation. E.g. C<?(> will show
1130 all function abbreviations, whereas C<?I<abbrev>(> will show only those functions
1131 matching I<abbrev> or C<?#I<abbrev>> only those tables matching I<abbrev>.
1132  
1133 =head3 C<??I<statement>>
1134  
1135 Will convert and show, but not perform I<statement>. If C<$dbh> is not set, this
1136 is the default behaviour.
1137  
1138 =head3 C<!I<System Shell code>>
1139  
1140 Run I<System Shell code>.
1141  
1142 =head3 C<E<gt>I<filename>> E<nbsp> or E<nbsp> C<E<gt>E<gt>I<filename>>
1143  
1144 Redirect or append next statement's output to I<filename>. For known
1145 suffixes and options, see the L<next section|/Output Formats>.
1146  
1147 =head3 C<|I<System Shell code>>
1148  
1149 Pipe next statement's output through I<System Shell code>.
1150  
1151 =head2 Output Formats
1152  
1153 The output format for the next SQL statement that is run, is chosen from the
1154 suffix of a redirection or a special suffix query. In both cases
1155 comma-separated options may be passed:
1156  
1157 =over
1158  
1159 =item >I<filename>.I<suffix>
1160  
1161 =item >I<filename>.I<suffix>( I<opt>; ... )
1162  
1163 =item >>I<filename>.I<suffix>
1164  
1165 =item >>I<filename>.I<suffix>( I<opt>; ... )
1166  
1167 =item &.I<suffix opt>; ...
1168  
1169 =item &.I<suffix>( I<opt>; ... ) following text
1170  
1171 =back
1172  
1173 The known suffixes and their respective options are:
1174  
1175 =over
1176  
1177 =item C<.csv>
1178  
1179 This writes Comma Separated Values with one subtle trick: NULL and empty
1180 strings are distinguished by quoting the latter. Some tools like Perl's file
1181 DB L<DBD::CSV> or rather its underlying L<Text::CSV_XS> can pick that up. CSV
1182 can take one of these options:
1183  
1184 =over
1185  
1186 =item semi
1187  
1188 Use a semicolon as a separator. This is a common format in environments where
1189 the comma is the decimal separator. However if you want decimal commas, you must
1190 provide such formatting yourself.
1191  
1192 =item tab
1193  
1194 Use tabulators as column separators. Apart from that you get the full CSV
1195 formatting, so this is not the primitive F<.tsv> format some tools may have.
1196  
1197 =back
1198  
1199  
1200 =item C<.table>
1201  
1202 This is the default table format. But you need to name it, if you want to set
1203 options.
1204  
1205 =over
1206  
1207 =item all
1208  
1209 This is a shorthand for outputting everything in the long form, equivalent to
1210 C<( NULL, crlf, date )>.
1211  
1212 =item crlf
1213  
1214 Do not shorten C<\r\n> to C<\R>.
1215  
1216 =item date
1217  
1218 Output ISO dates fully instead of shortening 0000-00-00 to 0000- and
1219 yyyy-01-01 to yyyy- or yyyy-mm-01 to yyyy-mm-.
1220  
1221 =item time
1222  
1223 Output times fully instead of shortening 23:59(:59) to 24: and hh:00(:00) to
1224 hh: or hh:mm(:00) to hh:mm.
1225  
1226 =item NULL
1227  
1228 =item null
1229  
1230 Output this keyword instead of the shorter C<ω> from DB theory (or whatever
1231 you assigned to C<$NULL>).
1232  
1233 =back
1234  
1235  
1236 =item C<.yaml>
1237  
1238 =item C<.yml>
1239  
1240 Format output as YAML. This format has no options. Because its every value
1241 on a new line format can be more readable, there is a shorthand query C<&->
1242 for it.
1243  
1244 =back
1245  
1246 =cut
1247  
1248 4 our $prompt = 'steno> ';
1249 4 our $contprompt = '...> ';
1250 4 our $echo;
1251 # Called for every leading re, 1st arg is the optional '!', 2nd arg '/re/' or '/re/i'. Expression shall be true for non-matching lines.
1252 3 ▶our $regexp_fail = sub($$) { 'join( "~", map ref() ? () : $_ // q!NULL!, @_ )' . ($_[0] ? '=~' : '!~') . $_[1] };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] ? : 1 2 3
1253 1 ▶sub shell() {
Subroutine shell: called CC=35 SCAR=42.4
Pod documented
1254 1 print STDERR $prompt;
1255 1 my $fh;
1256 1 ▶ while( <> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline ARGV)) 22 1 23
1257 22 undef $error;
1258 22 ▶ goto NEXT unless /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless /\S/u 2 20 22
1259 20 ▶ if( s/^\s*\\\\\s*// ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^\s*\\\\\s*//u) { } 1 19 20
1260 1 s/\s*\Z/\n/s;
1261 1 local $/ = "\\\\\n"; # leading \n gets chopped below
1262 1 $_ .= <>;
1263 1 chomp;
1264 } else {
1265 19 ▶ while( s/(?<!\\)((?:\\\\)*)\\(?=\n\Z)/$1/ ) { # join continuation lines
Branch: 1 branch
BranchTrueFalseTotal
if (s/(?<!\\)((?:\\\\)*)\\(?=\n\Z)/$1/u) 1 19 20
1266 1 print STDERR $contprompt;
1267 1 $_ .= <>;
1268 }
1269 19 s/\A\s+//;
1270 }
1271 20 s/\s+\Z//;
1272 20 ▶ say if $echo;
Branch: 1 branch
BranchTrueFalseTotal
if $SQL::Steno::echo 20 0 20
1273 20 ▶ until( $error ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error) 36 0 36
1274 36 ▶ if( s!^&$perl_re!! ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^&$SQL::Steno::perl_re//u) { } 3 33 36
1275 3 my $perl = eval $1;
1276 3 local $| = 1; # flush to avoid stderr prompt overtaking last output line.
1277 3 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 3 3
1278 3 ▶ if( UNIVERSAL::isa $perl, 'DBI::st' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (UNIVERSAL::isa($perl, 'DBI::st')) { } 0 3 3
elsif (defined $perl) { } 1 2 3
1279 0 $_ = $perl;
1280 0 goto RUN;
1281 } elsif( defined $perl ) {
1282 1 substr $_, 0, 0, $perl;
1283 } else {
1284 2 goto NEXT;
1285 }
1286 } else {
1287 last unless
1288 33 ▶ s!^&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))!convert_Query $1, $3!e
Branch: 1 branch
BranchTrueFalseTotal
unless s/^&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Query($1, $3);/eu or s/^&(\.?\w+|-) *(.*)/&convert_Query($1, $2);/eu 18 15 33
Condition100%3/3
s/^&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Query($1, $3);/eu or s/^&(\.?\w+|-) *(.*)/&convert_Query($1, $2);/eu
l!l&&r!l&&!r
31218
MC/DC100%2/2
s/^&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Query($1, $3);/eu or s/^&(\.?\w+|-) *(.*)/&convert_Query($1, $2);/eu
s/^&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Query($1, $3);/eu s/^&(\.?\w+|-) *(.*)/&convert_Query($1, $2);/eu
Truth table100%3/3
A or B
A= s/^&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Query($1, $3);/euB= s/^&(\.?\w+|-) *(.*)/&convert_Query($1, $2);/eu
ABresult
1X1
011
000
1289 12 or s!^&(\.?\w+|-) *(.*)!convert_Query $1, $2!e;
1290 }
1291 }
1292  
1293 18 my $filter = '';
1294 18 ▶ while( s/^\s*$perl_re// || s%^\s*(!?)(/.+?/(?:i\b)?)\s*%% ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^\s*$SQL::Steno::perl_re//u or s[^\s*(!?)(/.+?/(?:i\b)?)\s*][]u) 9 18 27
Condition100%3/3
s/^\s*$SQL::Steno::perl_re//u or s[^\s*(!?)(/.+?/(?:i\b)?)\s*][]u
l!l&&r!l&&!r
6318
MC/DC100%2/2
s/^\s*$SQL::Steno::perl_re//u or s[^\s*(!?)(/.+?/(?:i\b)?)\s*][]u
s/^\s*$SQL::Steno::perl_re//u s[^\s*(!?)(/.+?/(?:i\b)?)\s*][]u
Truth table100%3/3
A or B
A= s/^\s*$SQL::Steno::perl_re//uB= s[^\s*(!?)(/.+?/(?:i\b)?)\s*][]u
ABresult
1X1
011
000
1295 9 ▶ if( defined $2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $2) { } 3 6 9
1296 3 $filter .= 'return if ' . $regexp_fail->( $1, $2 ) . ";\n";
1297 } else {
1298 6 $filter .= "return unless eval $1;\n";
1299 }
1300 }
1301 18 ▶ if( $filter ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filter) 7 11 18
1302 7 $filter = eval "sub {\n$filter 1; }";
1303 7 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
1304 }
1305 18 ▶ goto RUN if s/^\s*=//; # run literally
Branch: 1 branch
BranchTrueFalseTotal
if s/^\s*=//u 5 13 18
1306  
1307 13 my $skip = 0;
1308 13 ▶ if( /^\s*\?\s*(?:([?&#.:\\])(\w*)|(\w*)\()?/ ) { # help
Branch: 1 branch
BranchTrueFalseTotal
if (/^\s*\?\s*(?:([?&#.:\\])(\w*)|(\w*)\()?/u) 3 10 13
1309 3 ▶ if( $1 && $1 eq '?' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 and $1 eq '?') { } 0 3 3
Condition33%1/3
$1 and $1 eq "?"
!ll&&!rl&&r
030
MC/DC0%0/2
$1 and $1 eq "?"
$1 $1 eq "?"
Truth table33%1/3
A and B
A= $1B= $1 eq "?"
ABresult
0X0
100
111
1310 0 s/^\s*\?\s*\?//;
1311 0 $skip = 1;
1312 } else {
1313 3 help( $1, $2, $3 );
1314 3 goto NEXT;
1315 }
1316 }
1317 10 ▶ if( s/^\s*!// ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^\s*!//u) 0 10 10
1318 0 system $_;
1319 0 ▶ if( $? == -1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($? == -1) { } 0 0 0
elsif (my $exit = $? & 127) { } 0 0 0
1320 0 print STDERR "failed to execute: $!\n";
1321 } elsif( my $exit = $? & 0b111_1111 ) {
1322 0 ▶ printf STDERR "child died with signal %d, with%s coredump\n",
Branch: 1 branch
BranchTrueFalseTotal
$? & 128 ? : 0 0 0
1323 $exit, ($? & 0b1000_0000) ? '' : 'out';
1324 } else {
1325 0 printf STDERR "child exited with value %d\n", $? >> 8;
1326 }
1327 0 goto NEXT;
1328 }
1329 10 s/^\s*()//; # dummy because $1 survives loop iterations :-o
1330 10 ▶ if( /\A(>{1,2})\s*(.+?(\.\w+)?)(?:\((.*)\))?\s*\Z/ ) { # redirect output
Branch: 2 branches
BranchTrueFalseTotal
if (/\A(>{1,2})\s*(.+?(\.\w+)?)(?:\((.*)\))?\s*\Z/u) { } 0 10 10
elsif (/\A\|(.+)\Z/u) { } 0 10 10
1331 0 ▶ set_render $3, $4 ? split ';', $4 : () if $3;
Branch: 2 branches
BranchTrueFalseTotal
if $3 0 0 0
$4 ? : 0 0 0
1332 0 ▶ open $fh, "$1:utf8", (glob $2)[0];
Subroutine BEGIN: called CC=1 SCAR=0.2
1333 0 select $fh;
1334 0 goto NEXT;
1335 } elsif( /\A\|(.+)\Z/ ) { # pipe output
1336 0 open $fh, '|-:utf8', $1;
1337 0 select $fh;
1338 0 goto NEXT;
1339 }
1340  
1341 10 undef $error;
1342  
1343 10 ▶ goto NEXT unless $_ && &convert;
Branch: 1 branch
BranchTrueFalseTotal
unless $_ and &convert 2 8 10
Condition66%2/3
$_ and &convert
!ll&&!rl&&r
208
MC/DC50%1/2
$_ and &convert
$_ &convert
Truth table66%2/3
A and B
A= $_B= &convert
ABresult
0X0
100
111
1344  
1345 8 print STDOUT "$_;\n";
1346 8 ▶ goto NEXT if $skip;
Branch: 1 branch
BranchTrueFalseTotal
if $skip 0 8 8
1347  
1348 13 ▶ RUN:
Branch: 1 branch
BranchTrueFalseTotal
if $SQL::Steno::dbh 13 0 13
1349 run $_, $filter, %opt if $dbh;
1350 13 ($render, %opt) = ();
1351 13 ▶ if( $fh ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fh) 0 13 13
1352 0 close;
1353 0 select STDOUT;
1354 0 undef $fh;
1355 }
1356 NEXT:
1357 22 print STDERR $prompt;
1358 }
1359 1 print STDERR "\n";
1360 }
1361  
1362  
1363  
1364 0 ▶sub helphashalt(\%@) {
Subroutine helphashalt: not called CC=5 SCAR=34.0
Pod undocumented
1365 0 my $hash = shift;
1366 0 ▶ if( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
1367 0 my $ret = $hash->{''};
1368 0 print "for *ptr, *cr, *cp, ...:\n";
1369 printf "%-5s %s\n", $_, &$ret( $_ )
1370 0 for @_;
1371 0 print "\n";
1372 }
1373 $_ eq '' or printf "%-5s %s\n", $_, $hash->{$_}
1374 0 ▶ for sort keys %$hash;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq "" or printf "%-5s %s\n", $_, $hash->{$_} 0 0 0
1375 }
1376 3 ▶sub helphash($$$\%;\@) {
Subroutine helphash: called CC=13 SCAR=47.8
Pod undocumented
1377 #my( $str, $prefix, $suffix, $hash, $list ) = @_;
1378 3 ▶ if( $_[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]) { } 3 0 3
1379 3 undef $error;
1380 3 ▶ $error or printf "%-7s %s\n", "$_[1]$_[0]$_[2]", $_ if $_ = &find;
Branch: 1 branch
BranchTrueFalseTotal
if $_ = &find 3 0 3
Condition33%2/6
($_ = &find) && ($error || printf("%-7s %s\n", "$_[1]$_[0]$_[2]", $_))
!ll&&!rl&&r
030
$error or printf "%-7s %s\n", "$_[1]$_[0]$_[2]", $_
l!l&&r!l&&!r
030
MC/DC0%0/3
($_ = &find) && ($error || printf("%-7s %s\n", "$_[1]$_[0]$_[2]", $_))
($_ = &find) $error printf "%-7s %s\n", "$_[1]$_[0]$_[2]", $_
Truth table0%0/4
A && B or C
A= ($_ = &find)B= $errorC= printf "%-7s %s\n", "$_[1]$_[0]$_[2]", $_
ABCresult
0XX0
1000
11X1
1011
1381 } else {
1382 0 my %hash = %{$_[3]};
1383 0 ▶ if( my $sub = delete $hash{''} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sub = delete $hash{""}) 0 0 0
1384 0 my @list = $sub->();
1385 0 for my $elt ( @list ) {
1386 0 $hash{$elt->[0]} = $sub->( my $name = $elt->[0] ) . ' ' . $elt->[1];
1387 }
1388 }
1389 0 chomp %hash;
1390 printf "%-7s %s\n", "$_[1]$_$_[2]", $hash{$_}
1391 0 ▶ for sort { lc( $a ) cmp lc( $b ) or $a cmp $b } keys %hash;
Condition0%0/3
lc $a cmp lc $b || $a cmp $b
l!l&&r!l&&!r
000
MC/DC0%0/2
lc $a cmp lc $b || $a cmp $b
lc $a cmp lc $b $a cmp $b
Truth table0%0/3
A || B
A= lc $a cmp lc $bB= $a cmp $b
ABresult
1X1
011
000
1392 0 ▶ return unless $_[4];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[4] 0 0 0
1393 0 my $i = 0;
1394 0 ▶ my @list = sort { lc( $a ) cmp lc( $b ) or $a cmp $b } @{$_[4]};
Condition0%0/3
lc $a cmp lc $b || $a cmp $b
l!l&&r!l&&!r
000
MC/DC0%0/2
lc $a cmp lc $b || $a cmp $b
lc $a cmp lc $b $a cmp $b
Truth table0%0/3
A || B
A= lc $a cmp lc $bB= $a cmp $b
ABresult
1X1
011
000
1395 0 ▶ while( @list ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@list) 0 0 0
1396 0 ▶ if( ($i += length $list[0]) < 80 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($i += length $list[0]) < 80) { } 0 0 0
1397 0 print ' ', shift @list;
1398 } else {
1399 0 $i = 0;
1400 0 print "\n";
1401 }
1402 }
1403 0 ▶ print "\n" if $i;
Branch: 1 branch
BranchTrueFalseTotal
if $i 0 0 0
1404 }
1405 }
1406  
1407 3 ▶sub help {
Subroutine help: called CC=15 SCAR=45.3
Pod undocumented
1408 3 ▶ if( defined $_[2] ) {
Branch: 6 branches
BranchTrueFalseTotal
if (defined $_[2]) { } 0 3 3
elsif (not $_[0]) { } 0 3 3
elsif ($_[0] eq '#') { } 0 3 3
elsif ($_[0] eq '.') { } 0 3 3
elsif ($_[0] eq '&') { } 2 1 3
elsif ($_[0] eq '\\') { } 1 0 1
1409 0 helphash $_[2], '', '(', %Functions, @Functions;
1410 } elsif( !$_[0] ) {
1411 0 print <<\HELP;
1412 All entries are single line unless \\wrapped at 1st bol and last eol\\ or continued.\
1413 Queries have the form: {{!}/regexp/{i}}{=}query
1414 The query has lots of short-hands expanded, unless it is prefixed by the optional =.
1415 The fields joined with '~' are grepped if regexp is given, case-insensitively if i is given.
1416  
1417 ??query Only shows massaged query.
1418 !perl-code Runs perl-code.
1419 >file Next query's output to file. In csv or yaml format if filename has that suffix.
1420  
1421 Query has the form {select|update|insert|delete}{fieldlist};tablelist{;clause} or set ...
1422 'select' is prepended if none of these initial keywords.
1423 fieldlist defaults to '*', also if Query starts with '#'.
1424 ';' is alternately replaced by 'from' and 'where'.
1425  
1426 Abbreviations, more help with ?&{abbrev}, ?:{abbrev}, ?\{abbrev}, ?#{abbrev}, ?.{abbrev}, ?{abbrev}(
1427 &{Perl code}... # only at bol, if it returns undef then skip, else prepend to ...
1428 &query $1;$2;... # only at bol
1429 &query($1;$2;...)... # only at bol, only replace upto )
1430 :macro
1431 :\quote(arg,...) # split, quote & join (?\ alone needs trailing space, because \ at end continues)
1432 :{Perl code} # dynamic macro
1433 #table #table#t
1434 .column .column.c # for any table recognized in statement
1435 function(
1436  
1437 Characters \t\n\r get masked in output, \r\n as \R.
1438 Date or time 0000-00-00 -> 0000- 1970-01-01 -> 1970- 00:00:00 -> 00: 23:59:59 -> 24:
1439 HELP
1440 } elsif( $_[0] eq '#' ) {
1441 0 ▶ @keys_Table_Columns = keys %Table_Columns unless @keys_Table_Columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @keys_Table_Columns 0 0 0
1442 0 helphash $_[1], '#', '', %Tables, @keys_Table_Columns;
1443 } elsif( $_[0] eq '.' ) {
1444 0 ▶ helphashalt %Columns, 'ptr' unless $_[1]; # \todo WIN@
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 0 0
1445 0 ▶ $error or print "$_\n" if
Branch: 1 branch
BranchTrueFalseTotal
if $_[1] and $_ = &find($_[1], ".", "", \%SQL::Steno::Columns) 0 0 0
Condition0%0/9
$_[1] && ($_ = &find($_[1], '.', '', \%SQL::Steno::Columns)) && ($error || print("$_\n"))
!ll&&!rl&&r
000
$_[1] and $_ = &find($_[1], ".", "", \%SQL::Steno::Columns)
!ll&&!rl&&r
000
$error or print "$_\n"
l!l&&r!l&&!r
000
MC/DC0%0/4
$_[1] && ($_ = &find($_[1], '.', '', \%SQL::Steno::Columns)) && ($error || print("$_\n"))
$_[1] $_ = &find($_[1], ".", "", \%SQL::Steno::Columns) $error print "$_\n"
Truth table0%0/5
A and B && C or D
A= $_[1]B= $_ = &find($_[1], ".", "", \%SQL::Steno::Columns)C= $errorD= print "$_\n"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
1446 $_[1] and $_ = find $_[1], '.', '', %Columns; # \todo, @column;
1447 } elsif( $_[0] eq '&' ) {
1448 2 ▶ print <<\HELP unless $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 2 2
1449 &{ Query name => 'doc', 'query' } define query &name on the fly
1450 query may contain arguments a bit like the Shell: $1, $2, ..., $*
1451 they can become quoted: $\1, $\"2, $\`*, $\[3, $\{}>
1452 $* means all args; $> the remaining args after using up the numbered ones
1453 if it is quoted, each arg gets quoted, separated by a comma
1454 $?arg?arg-replacement?no-arg-replacement? 1st if $arg has a value
1455 HELP
1456 2 helphash $_[1], '&', '', %Queries_help;
1457 } elsif( $_[0] eq '\\' ) {
1458 1 ▶ print <<\HELP unless $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 1 1
1459 :\namespec(arg,...) or func\namespec(arg,...) quotes args for you.
1460 &{ Quote name => 'doc', 'namespec' } define quote \name on the fly
1461 namespec may another name and/or any splitter chars (-,:;./ ),
1462 preventer chars (#?ω^\@!), quoting chars ('"`[]{}) and/or
1463 a string to join the results with after a %.
1464 HELP
1465 1 helphash $_[1], '\\', '', %Quotes_help;
1466 } else {
1467 0 ▶ print <<\HELP unless $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 0 0
1468 :\(...) split arguments and quote in many ways
1469 HELP
1470 0 local $Tables{TBL} = 'TABLE';
1471 0 helphash $_[1], ':', '', %Macros;
1472 }
1473 }
1474  
1475 4 1;
1476  
1477 =head1 YOUR SCRIPT
1478  
1479 package SQL::Steno; # doesn't export yet, so get the functions easily
1480 use SQL::Steno;
1481 use DBI;
1482 our $dbh = DBI->connect( ... ); # preferably mysql, but other DBs should work (with limitations).
1483 # If you want #tbl and .col to work, (only) one of:
1484 init_from_query; # fast, defaults to mysql information_schema, for which you need read permission
1485 init; # slow, using DBI dbh methods.
1486 # Set any of the variables mentioned above to get you favourite abbreviations.
1487 shell;
1488  
1489 =head1 LICENSE
1490  
1491 This program is free software; you may redistribute it and/or modify it under
1492 the same terms as Perl itself.
1493  
1494 =head1 SEE ALSO
1495  
1496 L<DBI>, L<SQL::Interp>, L<SQL::Preproc>, L<SQL::Yapp>, L<Jade|http://jade-lang.com/>
1497  
1498 =head1 AUTHOR
1499  
1500 (C) 2015, 2016 by Daniel Pfeiffer <occitan@esperanto.org>.
↑ Summary