blib/lib/SQL/Steno.pm

filter: Statementstmt 70.4% 317 / 450 Branchbran 59.2% 211 / 356 Conditioncond 55.4% 77 / 139 MC/DCmcdc 30.4% 21 / 69 Subroutinesub 83.3% 20 / 24 Podpod 16.6% 3 / 18 totaltotal 61.4% 649 / 1056 CC 244 SCAR 38.7
CC
244
Cov
64%
helphash
117.2
shell
75.7
help
74.3
CRAP 48.0
↑ Summary
1 =head1 NAME
2  
3 SQL::Steno - Short hand for SQL and compact output
4  
5 =head1 SYNOPSIS
6  
7 Type some short-hand, see the corresponding SQL and its output:
8  
9 steno> TABLE1;somecolumn > 2 -- ; after tables means where
10 select * from TABLE1 where somecolumn > 2;
11 prepare: 0.000s execute: 0.073s rows: 14
12 id|column1 |column2
13 | | |column3
14 | | | |somecolumn
15 ----|-------------------------------------------|----|-|-|
16 27|foo | |a|7|
17 49|bar |abcd|a|3|
18 81|baz\nbazinga\nbazurka |jk |b|9|
19 1984|bla bla bla bla bla bla bla bla bla bla bla|xyz |c|5|
20 ...
21 steno> /abc|foo/#TBL1;.socol > 2 -- /regexp/ grep, #tableabbrev, .columnabbrev
22 select * from TABLE1 where somecolumn > 2;
23 prepare: 0.000s execute: 0.039s rows: 14
24 id|column1
25 | |column2
26 | | |[column3=a]
27 | | |somecolumn
28 --|---|----|-|
29 27|foo| |7|
30 49|bar|abcd|3|
31 steno> .c1,.c2,.some;#TE1#:ob2d3 -- ; before tables means from, 2nd # alias, :macro
32 select column1,column2,somecolumn from TABLE1 TE1 order by 2 desc, 3;
33 ...
34 steno> n(), yr(), cw(,1,2,3) -- functionabbrev before (, can have initial default arg
35 select count(*), year(now()), concat_ws(',',1,2,3);
36 ...
37 steno> .col1,.clm2,.sn;#TBL1:jTBL2 u(id);mydate :b :m+3d and :d-w -- :jTABLEABBREV and :+/- family
38 select column1,column2,somecolumn from TABLE1 join TABLE2 using(id) where mydate
39 between date_format(now(),"%Y-%m-01")+interval 3 day and curdate()-interval 1 week;
40 ...
41  
42 =head1 DESCRIPTION
43  
44 You're the command-line type, but are tired of typing C<select * from TABLE
45 where CONDITION>, always forgetting the final C<;>? Output always seems far
46 too wide and at least mysql cli messes up the format when it includes
47 newlines?
48  
49 This module consists of the function C<convert> which implements a
50 configurable ultra-compact language that maps to SQL. Then there is C<run>
51 which performs normal SQL queries but has various tricks for narrowing the
52 output. It can also grep on whole rows, rather than having to list all fields
53 that you expect to match. They get combined by the function C<shell> which
54 converts and runs in an endless loop.
55  
56 This is work in progress, only recently isolated from a monolithic script.
57 Language elements and API may change as the need arises, e.g. C<:macro> used
58 to be C<@macro>, till the day I wanted to use an SQL-variable and noticed the
59 collision. In this early stage, you are more than welcome to propose
60 ammendments, especially if they make the language more powerful and/or more
61 consistent. Defaults are for MariaDB/MySQL, though the mechanism also works
62 with other DBs.
63  
64 =cut
65  
66 4 ▶use v5.12;
Subroutine BEGIN: called CC=1 SCAR=0.0
67  
68 package SQL::Steno v0.2.4.1;
69  
70 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
71 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
72 4 ▶use Time::HiRes qw(gettimeofday tv_interval);
Subroutine BEGIN: called CC=1 SCAR=0.0
73  
74 4 binmode STDIN, ':utf8';
75 4 binmode STDOUT, ':utf8';
76  
77 4 our $dbh;
78 4 our $perl_re = qr/(\{(?:(?>[^{}]+)|(?-1))*\})/;
79 4 our( %Table_Columns, $table_re );
80 sub init {
81 0 ▶ die "\$dbh is undef\n" unless $dbh;
Subroutine init: not called CC=5 SCAR=34.0
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
unless $SQL::Steno::dbh 0 0 0
82 0 local @{$dbh}{qw(PrintWarn PrintError RaiseError)} = (0, 0, 0); # \todo is this right? views can barf because more restrictive.
83 0 for my $table ( @{$dbh->table_info->fetchall_arrayref} ) {
84 0 $Table_Columns{uc $table->[2]} = [];
85 0 splice @$table, 3, -1, '%';
86 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
87 0 for my $column ( @{$info->fetchall_arrayref} ) {
88 0 push @{$Table_Columns{$table->[2]}}, uc $column->[3];
89 }
90 }
91 0 undef $table_re; # (re)create below
92 }
93 4 our $init_from_query = <<\SQL;
94 select ucase(TABLE_NAME), ucase(COLUMN_NAME)
95 from information_schema.COLUMNS
96 where TABLE_SCHEMA = schema()
97 SQL
98 sub init_from_query {
99 0 ▶ die "\$dbh is undef\n" unless $dbh;
Subroutine init_from_query: not called CC=3 SCAR=24.8
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
unless $SQL::Steno::dbh 0 0 0
100 0 local @{$dbh}{qw(PrintWarn PrintError RaiseError)} = (0, 0, 0); # \todo is this right?
101 0 my $sth = $dbh->prepare( $init_from_query );
102 0 $sth->execute;
103 0 $sth->bind_columns( \my( $table, $column ));
104 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
105 0 undef $table_re; # (re)create below
106 }
107  
108  
109  
110 4 my %render =
111 (csv => \&render_csv,
112 table => \&render_table,
113 yaml => \&render_yaml,
114 yml => \&render_yaml);
115 4 my( $render, %opt );
116  
117 sub set_render($@) {
118 4 ▶ ($render, %opt) = ();
Subroutine set_render: called CC=3 SCAR=11.0
Pod undocumented
119 4 for( @_ ) {
120 7 ▶ if( defined $render ) { # all further args are opts
Branch: 1 branch
BranchTrueFalseTotal
if (defined $render) { } 3 4 7
121 3 tr/ \t//d;
122 3 undef $opt{$_}; # make it exist
123 } else {
124 4 $render = substr $_, 1;
125 }
126 }
127 4 $render = $render{$render};
128 4 ''; # For use as a query
129 }
130 4 our( %Queries_help, %Queries );
131  
132 4 for my $fmt ( keys %render ) {
133 16 $Queries_help{".$fmt"} = " output '&.$fmt() this' or next query as \U$fmt";
134 16 $Queries{".$fmt"} = \&set_render;
135 }
136 sub Queries(@) {
137 4 ▶ for( @_ ) {
Subroutine Queries: called CC=2 SCAR=6.9
Pod undocumented
138 36 $Queries_help{$_->[0]} = $_->[1];
139 36 $Queries{$_->[0]} = $_->[2];
140 }
141 }
142 4 Queries
143 ['-' => " output next query as YAML",
144 '&.yaml'],
145  
146  
147 [ps => ' show processlist (without Sleep)',
148 '{($_[7] // "") ne "Sleep"}=show processlist'],
149  
150 [psf => ' show full processlist (without Sleep)',
151 '{($_[7] // "") ne "Sleep"}=show full processlist'],
152  
153  
154 [s => 'var;value set @var = value',
155 'set @$1=$2'],
156  
157 [ss => 'var;value set @var = "value"',
158 'set @$1=$"*"'],
159  
160 [sd => 'var;value set @var = cast("value" as date)',
161 'set @$1=cast($"*" as date)'],
162  
163 [sdt => 'var;value set @var = cast("value" as datetime)',
164 'set @$1=cast($"*" as datetime)'],
165  
166 [st => 'var;value set @var = cast("value" as time)',
167 'set @$1=cast($"*" as time)'],
168  
169 [sy => ' set @a, @z yesterday is between @a and @z (see :baz)',
170 #'set @a=date(now())-interval 1 day, @z=date(now())-interval 1 second',
171 'select @a:=date(now()-interval 1 day)`@a`, @z:=date(now())-interval 1 second`@z`'];
172  
173  
174 4 our $weekstart = 1;
175 4 my $timespec_re = qr/[yqmwdhMs]?/;
176 4 our %Join_clause;
177 our %Macros =
178 (
179 b => ' between',
180 baz => ' between @a and @z',
181 d => ' distinct',
182 h => ' having',
183 j => ' join',
184 l => ' like',
185 lj => ' left join',
186 n => ' is null',
187 nb => ' not between',
188 nc => ' sql_no_cache',
189 nl => ' not like',
190 nn => ' is not null',
191 nr => ' not rlike',
192 od => ' on duplicate key update',
193 odku => ' on duplicate key update',
194 r => ' rlike',
195 u => ' union select',
196 ua => ' union all select',
197 wr => ' with rollup',
198 '' => sub {
199 2 ▶ my $join = 'for all #TBL matching TABLE';
Subroutine __ANON__: called CC=17 SCAR=40.1
200 2 my $int = 'see :+ :- :y-m :q+0 :d+2h';
201 2 my $gob = 'for 0 or more digits, optionally followed by a or d';
202 2 ▶ return ([jTBL => $join], ['jTBL#' => $join], [ljTBL => $join], [1 => 'for all numbers'],
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 2 2
203 [gb147 => $gob], [ob2d5a9 => $gob],
204 ['+' => <<INT], ['-' => $int], ['d+2h' => $int], ['y-m' => $int], ['q+0' => $int])
205 :B+/-NO this B(ase) +/- N(umber, 0 for none, default 1 if O given) O(ffset)
206 optional B, O is y(ear), q(uarter), m(onth), w(eek), d(ay), h(our), M(inute), s(econd)
207 INT
208 unless @_; # help
209 2 for( $_[0] ) {
210 2 ▶ return " limit $_" if /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\d+$/u 0 2 2
211 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
212 1 s/(?<! )(?=\d)/, /g;
213 1 s/a/ asc/g; s/(?<!r)d/ desc/g;
214 1 return $_;
215 }
216 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
217 0 ▶ my $left = $1 ? ' left' : '';
Branch: 1 branch
BranchTrueFalseTotal
$1 ? : 0 0 0
218 0 &convert_table_column;
219 0 /^(\w+)/;
220 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
221 }
222 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
223 s(^($timespec_re)([+-])(\d*)($timespec_re)$) {
224 ({ y => ' date_format(now(),"%Y-01-01")',
225 q => ' date_format(now()-interval mod(month(now())+11,3) month,"%Y-%m-01")',
226 m => ' date_format(now(),"%Y-%m-01")',
227 w => ' curdate()-interval weekday(now())' . ($weekstart ? ' day' : '+1 day'),
228 d => ' curdate()',
229 h => ' date_format(now(),"%F %H:00")',
230 M => ' date_format(now(),"%F %H:%M")',
231 s => ' now()' }->{$1} || '') .
232 ($3 ne '0' &&
233 "$2interval" .
234 ($3 ? " $3" : $4 ? ' 1' : '') .
235 ({ y => ' year',
236 q => ' quarter',
237 m => ' month',
238 w => ' week',
239 d => ' day',
240 h => ' hour',
241 M => ' minute',
242 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
243 }eo;
244 }
245 4 });
246  
247 # \todo default arg n() -> n(*) time*(now())
248 4 our %Functions =
249 (
250 c => 'concat',
251 cw => 'concat_ws',
252 coa => 'coalesce',
253 gc => 'group_concat',
254 i => 'in', # not really fn, but ( follows
255 in => 'ifnull',
256 l => 'char_length',
257 lc => 'lcase',
258 m => 'min',
259 M => 'max',
260 n => 'count',
261 ni => 'not in', # -"-
262 s => 'substring',
263 u => 'using', # -"-
264 uc => 'ucase'
265 );
266  
267 # functions where the 1st argument can be now()
268 4 my @nowFunctions = qw(
269 adddate addtime convert_tz date date_add date_format date_sub datediff day
270 dayname dayofmonth dayofweek dayofyear hour last_day minute month
271 monthname quarter second subdate subtime time time_format time_to_sec
272 timediff timestamp to_days to_seconds week weekday weekofyear year
273 yearweek
274 );
275 4 our @Functions = sort @nowFunctions, qw(
276 abs acos aes_decrypt aes_encrypt ascii asin atan avg benchmark bin bit_and
277 bit_count bit_length bit_or bit_xor cast ceiling char_length char
278 character_length charset coalesce coercibility collation compress
279 concat_ws concat connection_id conv cos cot count crc32 curdate
280 current_date current_time current_timestamp current_user curtime database
281 decode default degrees des_decrypt des_encrypt elt encode encrypt exp
282 export_set field find_in_set floor format found_rows from_days
283 from_unixtime get_format get_lock greatest group_concat hex if ifnull
284 inet_aton inet_ntoa insert instr interval is_free_lock is_used_lock isnull
285 last_insert_id lcase least left length ln load_file localtime
286 localtimestamp locate log10 log2 log lower lpad ltrim make_set makedate
287 maketime master_pos_wait max md5 microsecond mid min mod name_const now
288 nullif oct octet_length old_password ord password period_add period_diff
289 pi position power quote radians rand release_lock repeat replace reverse
290 right round row_count rpad rtrim schema sec_to_time session_user sha1 sign
291 sin sleep soundex space sqrt stddev stddev_pop stddev_samp str_to_date
292 strcmp substring_index substring sum sysdate system_user tan timestampadd
293 timestampdiff trim truncate ucase uncompress uncompressed_length unhex
294 unix_timestamp upper user utc_date utc_time utc_timestamp uuid values
295 var_pop var_samp variance
296 );
297  
298 4 our %DefaultArguments = (
299 count => '*',
300 concat_ws => "','"
301 );
302 4 $DefaultArguments{$_} = 'now()' for @nowFunctions;
303  
304  
305 4 our %Tables;
306 4 our %Columns;
307  
308 sub regexp($$) {
309 0 ▶ my( $str, $type ) = @_;
Subroutine regexp: not called CC=6 SCAR=37.4
Pod documented
310 0 ▶ if( $type < 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type < 2) 0 0 0
311 0 ▶ return if $str !~ /_/; # Otherwise same as find sprintf cases
Branch: 1 branch
BranchTrueFalseTotal
unless $str =~ /_/u 0 0 0
312 0 ▶ return ($type ? '' : '^') . join '.*?_', split /_/, $str; # 0 & 1
Branch: 1 branch
BranchTrueFalseTotal
$type ? : 0 0 0
313 }
314 0 my $expr = join '.*?', split //, $str; # 2, 3 & 4
315 0 ▶ if( $type < 4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type < 4) 0 0 0
316 0 substr $expr, 0, 0, '^'; # 2 & 3
317 0 ▶ $expr .= '$' if $type == 2; # 2
Branch: 1 branch
BranchTrueFalseTotal
if $type == 2 0 0 0
318 }
319 0 $expr;
320 }
321  
322 4 my $error;
323 4 my @simple = qw(^%s$ ^%s_ ^%s _%s$ _%s %s$ %s_ %s);
324 sub find($$$\%;\@) {
325 27 ▶ my( $str, $prefix, $suffix, $hash, $list ) = @_;
Subroutine find: called CC=12 SCAR=30.5
Pod undocumented
326 27 my $ret = $hash->{$str};
327 27 ▶ return $ret if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 15 12 27
328  
329 12 $ret = $hash->{''};
330 12 ▶ $ret = &$ret( $str ) if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 2 10 12
331 12 ▶ return $ret if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 2 10 12
332  
333 10 ▶ if( $list ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($list) 10 0 10
334 10 for my $type ( 0..@simple+4 ) { # Try to find a more and more fuzzy match.
335 10 ▶ my $expr = $type < @simple ?
Branch: 1 branch
BranchTrueFalseTotal
$type < @simple ? : 10 0 10
336 sprintf $simple[$type], $str :
337 regexp $str, $type - @simple;
338 10 ▶ next unless defined $expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expr 0 10 10
339 10 my @res = grep /$expr/i, @$list;
340 10 ▶ if( @res ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@res) 10 0 10
341 10 ▶ return $res[0] if @res == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @res == 1 10 0 10
342 0 warn "$prefix$str$suffix matches @res\n";
343 0 $error = 1;
344 0 return '';
345 }
346 }
347 }
348 # no special syntax for fields or functions, so don't fail on real one
349 0 ▶ return $str if ord $prefix == ord '.' or ord $suffix == ord '(';
Branch: 1 branch
BranchTrueFalseTotal
if ord $prefix == 46 or ord $suffix == 40 0 0 0
Condition0%0/3
ord $prefix == 46 or ord $suffix == 40
l!l&&r!l&&!r
000
MC/DC0%0/2
ord $prefix == 46 or ord $suffix == 40
ord $prefix == 46 ord $suffix == 40
Truth table0%0/3
A or B
A= ord $prefix == 46B= ord $suffix == 40
ABresult
1X1
011
000
350  
351 0 warn "$prefix$str$suffix doesn't match\n";
352 0 $error = 1;
353 }
354  
355 sub convert_Queries($$) {
356 13 ▶ my $res = find $_[0], '&', '', %Queries;
Subroutine convert_Queries: called CC=8 SCAR=21.6
Pod undocumented
357 13 local $_ = $_[1];
358 13 &convert_table_column;
359 13 my @arg = split ';';
360 13 ▶ return &$res( $_[0], @arg ) // '' if ref $res;
Branch: 1 branch
BranchTrueFalseTotal
if ref $res 4 9 13
Condition50%1/2
&$res($_[0], @arg) // ""
l!l
40
MC/DC0%0/1
&$res($_[0], @arg) // ""
&$res($_[0], @arg)
Truth table50%1/2
A
A= &$res($_[0], @arg)
Aresult
11
00
361 9 my @rest;
362 9 for my $i ( 1..@arg ) {
363 6 ▶ $res =~ s/\$$i/$arg[$i - 1]/g or $res =~ s/\$"$i"/"$arg[$i - 1]"/g or push @rest, $arg[$i - 1];
Branch: 1 branch
BranchTrueFalseTotal
$res =~ s/\$$i/$arg[$i - 1]/gu or $res =~ s/\$"$i"/"$arg[$i - 1]"/gu or push @rest, $arg[$i - 1] 2 4 6
Condition66%2/3
$res =~ s/\$$i/$arg[$i - 1]/gu or $res =~ s/\$"$i"/"$arg[$i - 1]"/gu
l!l&&r!l&&!r
402
MC/DC50%1/2
$res =~ s/\$$i/$arg[$i - 1]/gu or $res =~ s/\$"$i"/"$arg[$i - 1]"/gu
$res =~ s/\$$i/$arg[$i - 1]/gu $res =~ s/\$"$i"/"$arg[$i - 1]"/gu
Truth table66%2/3
A or B
A= $res =~ s/\$$i/$arg[$i - 1]/guB= $res =~ s/\$"$i"/"$arg[$i - 1]"/gu
ABresult
1X1
011
000
364 }
365 9 ▶ $res =~ s!\$\?(.*?)\?(.*?)\?!@rest ? $1 : $2!e;
Branch: 1 branch
BranchTrueFalseTotal
@rest ? : 0 0 0
366 9 ▶ $res =~ s!\$"\*"!'"' . join( '","', @rest ) . '"'!ge or
Branch: 1 branch
BranchTrueFalseTotal
$res =~ s/\$"\*"/'"' . join("\",\"", @rest) . '"';/egu or $res =~ s/\$\*/join ",", @rest;/egu 7 2 9
367 0 $res =~ s!\$\*!join( ',', @rest )!ge;
368 9 $res;
369 }
370  
371 4 my @keys_Table_Columns;
372 sub convert_table_column {
373 # \todo .col. or .col.alias like #tbl#
374 22 ▶ @keys_Table_Columns = keys %Table_Columns unless @keys_Table_Columns;
Subroutine convert_table_column: called CC=13 SCAR=36.4
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
unless @keys_Table_Columns 22 0 22
375 22 ▶ s&(?<!\\)#(\w+)(?:#(\w*))?&find( $1, '#', '', %Tables, @keys_Table_Columns ) . ($2 ? " $2" : defined $2 ? " $1" : '')&eg unless $error;
Branch: 3 branches
BranchTrueFalseTotal
unless $error 22 0 22
$2 ? : 0 0 0
defined $2 ? : 0 0 0
376  
377 22 ▶ unless( $table_re ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($SQL::Steno::table_re) 2 20 22
378 2 $table_re = join '|', keys %Table_Columns;
379 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
380 }
381 22 ▶ unless( $error ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error) 22 0 22
382 22 my %column;
383 22 for( grep /$table_re/io, split /\W+/ ) {
384 0 undef $column{$_} for @{$Table_Columns{$_}};
385 }
386 22 my @column = keys %column;
387 22 ▶ 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 0 0
$3 ? : 0 0 0
defined $3 ? : 0 0 0
388 }
389 }
390  
391  
392 =head2 convert
393  
394 This function takes a short-hand query in C<$_> and transforms it to SQL. See
395 L</shell> for more run time oriented features.
396  
397 First it looks for C<:macro>. These are mostly simple text-replacements
398 stored in C<%Macros>. There are also some dynamic macros. Those starting
399 with C<:j> (join) or C<:lj> (left join) may continue into a table spec without
400 the leading C<#>. E.g. C<:ljtbl#t> might expand to C<left join table t>.
401  
402 Those starting with C<:gb> (group by) or C<:ob> (order by) may be followed by
403 result columns numbers from 1-9, each optionally followed by a or d for asc or
404 desc. Macros can also be C<:{Perl code}>, which gets replaced by what it
405 returns.
406  
407 Then there are the time macros, where an optional leading letter indicates a
408 base time, and an optional trailing letter with an optional count means the
409 offset. The letters are:
410  
411 =over
412  
413 =item y
414  
415 (this) year. E.g. C<:y+2m> is march this year.
416  
417 =item q
418  
419 (this) quarter. E.g. C<:q+0> is this quarter, C<:q+q> is next quarter.
420  
421 =item m
422  
423 (this) month. E.g. C<:-3m> is whatever precedes, minus 3 months.
424  
425 =item w
426  
427 (this) week (starting on C<$weekstart>). E.g. C<:w+3d> is this week thursday (or wednesday).
428  
429 =item d
430  
431 (this) day. E.g. C<:d-w> is midnight one week ago.
432  
433 =item h
434  
435 (this) hour. E.g. C<:h+30M> is half past current hour.
436  
437 =item M
438  
439 (this) minute. E.g. C<:+10M> is whatever precedes, plus 10min.
440  
441 =item s
442  
443 (this) second. E.g. C<:s-2h> is exactly 2h ago.
444  
445 =back
446  
447 Then it looks for C<#tbl>, C<#tbl#> or C<#tbl#alias>. Here tbl is a key of
448 C<%Tables> or any abbreviation of known tables in C<@Tables>. If followed by
449 C<#>, the abbreviation is used as an alias, unless an alias directly follows,
450 in which case that is used.
451  
452 Then it looks for C<.col>, C<.col.> C<.col.alias>. Here col is a key of
453 C<%Columns> or any abbreviation of columns of any table recognized in the
454 query. If followed by C<.>, the abbreviation is used as an alias, unless an
455 alias directly follows, in which case that is used. It tries to be clever
456 about whether the 1st C<.> needs to be preserved, i.e. following a table name.
457  
458 Finally it looks for C<func(>. Here func is a key of C<%Functions> or any
459 abbreviation of known functions in C<@Functions>, which includes words
460 typically followed by an opening parenthesis, such as C<u(> for C<using(>.
461 C<i(> is C<in(>, so that C<in(> is free for matching C<ifnull(>, but more
462 importantly, because it has a smart brother: C<I(> is also C<in(>, where
463 quoting is applied as necessary, and unless you give an initial comma C<I(,>,
464 the elements are separated on space. E.g. C<I(a 3 a's q"q)> and
465 C<I(,a,3,a's,q"q)> both give C<in("a",3,"a's",'q"q')>. If the 1st argument of
466 a function is empty and the abbrev or function is found in
467 C<%DefaultArguments> the value becomes the 1st argument.
468  
469  
470 Finally it picks on the structure of the statement: These keywords can be
471 abbreviated: C<se(lect)>, C<ins(ert)>, C<upd(ate)> or C<del(ete)>. If none of
472 these or C<set> is present, C<select> is assumed as default (more keywords
473 need to be recognized in the future).
474  
475 For C<select>, semicolons are alternately replaced by C<from> (the 1st being
476 optional if it starts with a table name) and C<where>. If no result columns
477 are given, they default to C<*>, see L</SYNOPSIS>. For C<update>, semicolons
478 are frst replaced by C<set> and then C<where>.
479  
480 =cut
481  
482 sub convert {
483 # Handle I(str1 str2 str3)
484 9 ▶ s<\bI\((, ?)?(.+?)\)> { 'i('.join(',', map { /"/ ? "'$_'" : /^\d+$/ ? $_ : qq+"$_"+ } split $1||' +', $2, -1).')' }ge;
Subroutine convert: called CC=24 SCAR=41.9
Pod documented
Branch: 2 branches
BranchTrueFalseTotal
/"/u ? : 0 0 0
/^\d+$/u ? : 0 0 0
Condition0%0/2
$1 || ' +'
l!l
00
MC/DC0%0/1
$1 || ' +'
$1
Truth table0%0/2
A
A= $1
Aresult
11
00
485  
486 9 my @strings; # extract strings to prevent following replacements inside.
487 9 ▶ while( /\G.*?(['"])/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G.*?(['"])/cgu) 2 9 11
488 2 my $quote = $1;
489 2 my $pos = pos;
490 2 ▶ while( /\G.*?([\\$quote])/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G.*?([\\$quote])/cgu) 2 0 2
491 2 ▶ if( $1 eq '\\' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($1 eq '\\') { } 0 2 2
elsif (not /\G$quote/cgu) { } 2 0 2
492 0 ++pos; # skip next
493 } elsif( ! /\G$quote/gc ) { # skip double quote
494 2 push @strings, substr $_, $pos - 1, 1 - $pos + pos, # get string
495 "\cA".@strings."\cB"; # and replace with counter
496 2 last;
497 }
498 }
499 }
500  
501 9 ▶ until( $error ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error) 12 0 12
502 12 ▶ s&:$perl_re&my $ret = eval $1; warn $@ if $@; $ret // ' NULL '&ego or
Branch: 2 branches
BranchTrueFalseTotal
s[:$SQL::Steno::perl_re][my $ret = eval $1; warn $@ if $@; $ret // " NULL ";]egou or s/:(${timespec_re}[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)/&find($1, ":", "", \%SQL::Steno::Macros);/egou or last 9 3 12
if $@ 0 0 0
Condition40%2/5
s[:$SQL::Steno::perl_re][my $ret = eval $1; warn $@ if $@; $ret // " NULL ";]egou or s/:(${timespec_re}[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)/&find($1, ":", "", \%SQL::Steno::Macros);/egou
l!l&&r!l&&!r
039
$ret // " NULL "
l!l
00
MC/DC50%1/2
s[:$SQL::Steno::perl_re][my $ret = eval $1; warn $@ if $@; $ret // " NULL ";]egou or s/:(${timespec_re}[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)/&find($1, ":", "", \%SQL::Steno::Macros);/egou
s[:$SQL::Steno::perl_re][my $ret = eval $1; warn $@ if $@; $ret // " NULL ";]egou s/:(${timespec_re}[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)/&find($1, ":", "", \%SQL::Steno::Macros);/egou
MC/DC0%0/1
$ret // " NULL "
$ret
Truth table66%2/3
A or B
A= s[:$SQL::Steno::perl_re][my $ret = eval $1; warn $@ if $@; $ret // " NULL ";]egouB= s/:(${timespec_re}[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)/&find($1, ":", "", \%SQL::Steno::Macros);/egou
ABresult
1X1
011
000
Truth table0%0/2
A
A= $ret
Aresult
11
00
503 # \todo (?(?<=\w)\b)
504 3 s&:($timespec_re[+-]\d*$timespec_re(?(?<=\w)\b)|l?j\w+(?:#(\w*))|\w+)&find $1, ':', '', %Macros&ego or
505 last;
506 }
507  
508 9 s&^(?=#)&;&; # Assume empty fieldlist before table name
509 9 &convert_table_column;
510 9 s&^(?=$table_re)&;&; # Assume empty fieldlist before table name
511  
512 9 ▶ 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 9 0 9
Condition45%5/11
$fn || $1
l!l&&r!l&&!r
1000
$2 && ($SQL::Steno::DefaultArguments{$1} || $SQL::Steno::DefaultArguments{$fn}) || ''
l!l
010
$2 and $SQL::Steno::DefaultArguments{$1} || $SQL::Steno::DefaultArguments{$fn}
!ll&&!rl&&r
640
$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
513 #s&\b(\w+)(?=\()&find $1, '', '(', %Functions, @Functions or $1&eg unless $error;
514  
515 9 ▶ return if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 9 9
516 9 s/\A\s*;/*;/;
517 9 s/;\s*\Z//;
518 9 ▶ if( s/^upd(?:a(?:t(?:e)?)?)?\b/update/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^upd(?:a(?:t(?:e)?)?)?\b/update/iu) { } 0 9 9
519 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
520 } else {
521 9 ▶ 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 9 13
522 9 ▶ 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 9 0 9
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
009
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
523 s/^del(?:e(?:t(?:e)?)?)?\b/delete/i ||
524 s/^(?!se(?:lec)?t)/select /i;
525 }
526  
527 9 s/ $//mg;
528 9 s/ {2,}/ /g;
529 9 s/\cA(\d+)\cB/$strings[$1]/g; # put back the strings
530  
531 9 1;
532 }
533  
534  
535 # escape map for special replacement characters
536 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
537  
538 # With an argument of total number of rows, init output counting and return undef if it is to be skipped (not stdout).
539 # Without an argument, do the counting and return undef if no more rows wanted.
540 {
541 4 my( $total, $cnt, $i );
542 sub count(;$) {
543 16 ▶ if( @_ ) {
Subroutine count: called CC=9 SCAR=31.5
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 11 5 16
544 11 $total = $_[0];
545 11 $cnt = 0;
546 11 $i = 100;
547 11 ▶ return select eq 'main::STDOUT' ? 1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
select() eq 'main::STDOUT' ? : 2 9 11
548 }
549 5 ++$cnt;
550 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
551 0 printf STDERR "How many more, * for all, or q to quit? (%d of %d) [default: 100] ",
552 $cnt, $total;
553 0 $i = <>;
554 0 ▶ if( defined $i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $i) { } 0 0 0
555 0 $i =~ tr/qQxX \t\n\r/0000/d;
556 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
557 $i eq '*' ? ~0 :
558 $i == 0 ? return :
559 $i;
560 } else {
561 0 print "\n";
562 0 return;
563 }
564 }
565 5 1;
566 }
567 }
568  
569 4 sub render_csv($;$$) {
570 6 ▶ my( $sth, $filter ) = @_;
Subroutine render_csv: called CC=15 SCAR=27.1
Pod undocumented
571 my( $semi, $tab ) =
572 (exists $_[2]{semi},
573 exists $_[2]{tab})
574 6 ▶ if $_[2];
Branch: 1 branch
BranchTrueFalseTotal
if $_[2] 5 1 6
575 6 my $name = $sth->{NAME};
576 6 my @row = @$name;
577 6 while() {
578 18 for( @row ) {
579 162 ▶ if( defined ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_) { } 156 6 162
580 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 15 132 147
$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
581 /\A\Z/ or
582 s/"/""/g or
583 $semi ? tr/;\n// : $tab ? tr/\t\n// : tr/,\n// or
584 /\A=/;
585 } else {
586 6 $_ = '';
587 }
588 162 utf8::decode $_;
589 }
590 18 ▶ print join( $semi ? ';' : $tab ? "\t" : ',', @row ) . "\n";
Branch: 2 branches
BranchTrueFalseTotal
$semi ? : 6 12 18
$tab ? : 6 6 12
591  
592 21 ▶ FETCH:
Branch: 1 branch
BranchTrueFalseTotal
@row = $sth->fetchrow_array or last 6 15 21
593 @row = $sth->fetchrow_array
594 or last;
595 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
596 }
597 }
598  
599 4 my( $r1, $r2, $r3, $r5 ) = ('[01]\d', '[0-2]\d', '[0-3]\d', '[0-5]\d');
600 sub render_table($;$$) {
601 15 ▶ my( $sth, $filter ) = @_;
Subroutine render_table: called CC=49 SCAR=40.2
Pod undocumented
602 my( $null, $crlf, $date, $time ) =
603 exists $_[2]{all} ?
604 ('NULL', 1, 1, 1) :
605 (exists $_[2]{NULL} ? 'NULL' : exists $_[2]{null} ? 'null' : 0,
606 exists $_[2]{crlf},
607 exists $_[2]{date},
608 exists $_[2]{time})
609 15 ▶ if $_[2];
Branch: 4 branches
BranchTrueFalseTotal
if $_[2] 13 2 15
exists $_[2]{'all'} ? : 2 11 13
exists $_[2]{'NULL'} ? : 0 11 11
exists $_[2]{'null'} ? : 1 10 11
610 15 ▶ $null ||= '\@';
Condition100%2/2
$null ||= "\\\@"
l!l
312
MC/DC100%1/1
$null ||= "\\\@"
$null
Truth table100%2/2
A
A= $null
Aresult
11
00
611 15 my @name = @{$sth->{NAME}};
612 15 my @len = (0) x @name;
613 15 my( @txt, @res, @comp );
614 15 ▶ while( my @res1 = $sth->fetchrow_array ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@res1) = $sth->fetchrow_array) 80 15 95
615 80 ▶ next if $filter && !$filter->( \@name, @res1 );
Branch: 1 branch
BranchTrueFalseTotal
if $filter and not &$filter(\@name, @res1) 0 80 80
Condition66%2/3
$filter and not &$filter(\@name, @res1)
!ll&&!rl&&r
7910
MC/DC0%0/2
$filter and not &$filter(\@name, @res1)
$filter not &$filter(\@name, @res1)
Truth table66%2/3
A and not(B)
A= $filterB= not &$filter(\@name, @res1)
ABresult
0X0
100
111
616 80 for my $i ( 0..$#res1 ) {
617 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
618 4 $res1[$i] = $null;
619 } elsif( $res1[$i] !~ /^\d+(?:\.\d+)?$/ ) {
620 537 $txt[$i] = 1;
621 537 ▶ $res1[$i] =~ s/\r\n/\\R/g unless $crlf;
Branch: 1 branch
BranchTrueFalseTotal
unless $crlf 411 126 537
622 537 $res1[$i] =~ s/([\t\n\r])/$esc{$1}/g;
623 4 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
624 537 ▶ unless( $date ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($date) 215 322 537
625 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
626 109 ▶ $res1[$i] .= "$2-" if $2 > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $2 > 1 24 85 109
627 109 ▶ $res1[$i] .= $3 if $3;
Branch: 1 branch
BranchTrueFalseTotal
if $3 91 18 109
628 }
629 }
630 537 ▶ unless( $time ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($time) 215 322 537
631 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
632 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
633 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
3613
$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
634 49 $res1[$i] .= "24:";
635 } elsif( $6 > 0 ) {
636 24 $res1[$i] .= "$2:$3:$4$5$6";
637 } elsif( $4 > 0 ) {
638 12 $res1[$i] .= "$2:$3:$4";
639 } elsif( $3 > 0 ) {
640 12 $res1[$i] .= "$2:$3";
641 } else {
642 73 $res1[$i] .= "$2:";
643 }
644 170 ▶ ($res1[$i] .= $7) =~ s/:00$/:/
Branch: 1 branch
BranchTrueFalseTotal
if $7 84 86 170
645 if $7;
646 }
647 }
648 537 utf8::decode $res1[$i];
649 }
650 580 ▶ $txt[$i] = 0 if @txt < $i;
Branch: 1 branch
BranchTrueFalseTotal
if @txt < $i 10 570 580
651 580 my $len = length $res1[$i];
652 580 ▶ $len[$i] = $len if $len[$i] < $len;
Branch: 1 branch
BranchTrueFalseTotal
if $len[$i] < $len 184 396 580
653 }
654 80 ▶ if( @comp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@comp) { } 71 9 80
655 71 for my $i ( 0..$#comp ) {
656 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
657 }
658 } else {
659 9 @comp = @res1;
660 }
661 80 push @res, \@res1;
662 }
663 15 ▶ if( @res ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@res) 9 6 15
664 9 ▶ @comp = () if @res == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @res == 1 1 8 9
665 9 my $fmt = '';
666 9 ▶ for( my $i = 0; $i < @name; ++$i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @name) 71 9 80
667 71 $name[$i] =~ s/\r\n/\\R/g;
668 71 $name[$i] =~ s/([\t\n\r])/$esc{$1}/g;
669 71 ▶ if( defined $comp[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $comp[$i]) 0 71 71
670 0 my $more;
671 0 ▶ while( defined $comp[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $comp[$i]) 0 0 0
672 0 ▶ printf $fmt, @name[0..$i-1] unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 0 0 0
673 0 $more = 1;
674 0 printf "[%s=%s]", $name[$i], $comp[$i];
675 0 @name[0..$i] = ('') x ($i+1);
676 0 for my $row ( \@comp, \@name, \@len, \@txt, @res ) {
677 0 splice @$row, $i, 1;
678 }
679 }
680 0 print "\n";
681 0 --$i, next;
682 }
683 71 ▶ if( $len[$i] < length $name[$i] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len[$i] < length $name[$i]) 9 62 71
684 9 printf "$fmt%s\n", @name[0..$i];
685 9 @name[0..$i] = ('') x ($i+1);
686 }
687 71 ▶ $fmt .= '%' . ($txt[$i] ? -$len[$i] : $len[$i]) . 's|';
Branch: 1 branch
BranchTrueFalseTotal
$txt[$i] ? : 67 4 71
688 }
689 9 $fmt .= "\n";
690 9 ▶ printf $fmt, @name if $name[-1];
Branch: 1 branch
BranchTrueFalseTotal
if $name[-1] 8 1 9
691 9 printf $fmt, map '-'x$_, @len;
692 9 my $count = count @res; # init
693 9 for my $row ( @res ) {
694 80 printf $fmt, @$row;
695 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
696 }
697 }
698 }
699  
700 4 my $yaml_re = join '', sort keys %esc;
701 4 $yaml_re =~ s!\\!\\\\!;
702 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
703 sub render_yaml($;$$) {
704 2 ▶ my( $sth, $filter ) = @_;
Subroutine render_yaml: called CC=23 SCAR=31.7
Pod undocumented
705 2 my @label; # Fill on 0th round with same transformation as data (but \n inline)
706 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
707 2 my @row = @{$sth->{NAME}};
708 2 while() {
709 6 local $_;
710 6 my $i = 0;
711 6 for( @row ) {
712 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
713 2 $_ = '~';
714 } elsif( /^(?:y(?:es)?|no?|true|false|o(?:n|ff)|-?\.inf|\.nan)$/s ) { # can only be string in Perl or DB
715 0 $_ = "'$_'";
716 ▶ } 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
717 15 s/([$yaml_re])/$esc{$1}/go;
718 15 s/([\0-\010\013-\037\177-\237])/sprintf "\\x%02x", ord $1/ge;
719 15 $_ = qq!"$_"!;
720 } elsif( tr/\n// ) {
721 1 my $nl = chomp;
722 1 s/^/ /mg;
723 1 ▶ substr $_, 0, 0, $nl ? "|2\n" : "|2-\n";
Branch: 1 branch
BranchTrueFalseTotal
$nl ? : 0 1 1
724 }
725 54 ▶ printf "$label[$i++]$_\n" if @label;
Branch: 1 branch
BranchTrueFalseTotal
if @label 36 18 54
726 }
727 6 ▶ if( @label ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@label) { } 4 2 6
728 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
729 } else {
730 2 my $maxlen = 0;
731 2 for( @row ) {
732 18 ▶ substr $_, 0, 0, $maxlen ? ' ' : '- '; # 1st field if no maxlen yet
Branch: 1 branch
BranchTrueFalseTotal
$maxlen ? : 16 2 18
733 18 my $length = 0;
734 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
735 while /\G(?:(\t)|([^\t]+))/gc;
736 18 $_ .= ": $length";
737 18 ▶ $maxlen = $length if $maxlen < $length;
Branch: 1 branch
BranchTrueFalseTotal
if $maxlen < $length 7 11 18
738 }
739 18 s/(\d+)\Z/' ' x ($maxlen - $1)/e
740 2 for @label = @row;
741 }
742 7 ▶ FETCH:
Branch: 1 branch
BranchTrueFalseTotal
@row = $sth->fetchrow_array or last 2 5 7
743 @row = $sth->fetchrow_array
744 or last;
745 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
746 }
747 }
748  
749  
750  
751 4 my $lasttime = time;
752 sub run($;$\%) {
753 11 ▶ my( $sql, $filter, $opt ) = @_;
Subroutine run: called CC=8 SCAR=23.9
Pod undocumented
754 11 my $t0 = [gettimeofday];
755 11 ▶ 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 11 11
Condition33%2/6
$DBI::err || $t0->[0] - $lasttime > 3600 and not $SQL::Steno::dbh->ping
!ll&&!rl&&r
1100
$DBI::err or $t0->[0] - $lasttime > 3600
l!l&&r!l&&!r
0011
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
756 0 printf STDOUT "Inactive for %ds, ping failed after %.03fs, your session variables are lost.\n",
757 $t0->[0] - $lasttime, tv_interval $t0;
758 #$dbh->disconnect;
759 0 $dbh = $dbh->clone; # reconnect
760 0 $t0 = [gettimeofday];
761 }
762 11 $lasttime = $t0->[0];
763 11 ▶ 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)) 11 0 11
UNIVERSAL::isa($sql, 'DBI::st') ? : 0 11 11
764 11 my $t1 = [gettimeofday];
765 11 $sth->execute;
766 11 printf STDOUT "prepare: %.03fs execute: %.03fs rows: %d\n",
767 tv_interval( $t0, $t1 ), tv_interval( $t1 ), $DBI::rows;
768 11 ▶ if( $sth->{Active} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->{"Active"}) 11 0 11
769 11 ▶ if( $render ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($render) { } 4 7 11
770 4 &$render( $sth, $filter, $opt );
771 } else {
772 7 render_table $sth, $filter, $opt;
773 }
774 }
775 }
776 }
777  
778  
779 =head2 shell
780  
781 This function reads, converts and (if C<$dbh> is set) runs in an end-less loop
782 (i.e. till end of file or C<^D>). Reading is a single line affair, unless you
783 request otherwise. This can happen either, as in Unix Shell, by using
784 continuation lines as long as you put a backslash at the end of your lines.
785 Or there is a special case, if the 1st line starts with C<\\>, then everything
786 up to C<\\> at the end of one of the next lines, constitutes one entry.
787  
788 In addition to converting it offers a few extra features, performed in this
789 order (i.e. C<&xyz> can return C</regexp/=literal sql> etc.):
790  
791 =over
792  
793 =item &query arg; ...
794  
795 =item &query( arg; ... ) following text
796  
797 =item &{Perl code} following text
798  
799 These allow canned entries and are more complex than macros, in that they take
800 arguments and replacement can depend on the argument.
801  
802 Run I<Perl code>. It sees the I<following text> in C<$_> and may modify it.
803 If it returns undef this statement is skipped. If it returns a DBI statement
804 handle run that instead of this statement. Else replace with what it returns.
805  
806 Reprocess result as a shell entry (i.e. it may return another C<&>query).
807  
808 =item /regexp/ statement
809  
810 =item /regexp/i statement
811  
812 =item !/regexp/ statement
813  
814 =item !/regexp/i statement
815  
816 This will treat the I<statement> normally, but will join each output row for
817 matching as though it were the only row in default table format. That is
818 there is no space padding and the character '|' (which must be matched as
819 C<\|>) separates columns. At this stage no value rewriting has occured,
820 except NULL is already rendered as C<\@>.
821  
822 With a suffix C<i>, matching becomes case insensitive. This is why the mostly
823 optional space is shown above. Without an C<i>, but if the statement starts
824 with the word C<i> (e.g. your first column name), you must separate it with a
825 space. With an C<i>, if the statement starts with an alphanumeric caracter,
826 you must separate it with a space.
827  
828 Only matching rows are considered unless there is a preceding C<!>, in which
829 case only non-matching rows are considered.
830  
831 =item {Perl code}statement
832  
833 Call I<Perl code> for every output row returned by the I<statement> with the
834 array of column names as zeroth argument and the values after that (i.e.
835 numbered from 1 like in SQL). It may modify individual values. If it returns
836 false, the row is skipped.
837  
838 You may combine S<C</regexp/{Perl code}>> in any order and as many of them as
839 you want.
840  
841 =item =literal sql
842  
843 A preceding C<=> prevents conversion, useful for hitherto untreated keywords
844 or where the conversion doesn't play well with your intention.
845  
846 =item ?
847  
848 Help prefix. Alone it will give an overview. You can follow up with any of
849 the special syntaxes, with or without an abbreviation. E.g. C<?(> will show
850 all function abbreviations, whereas C<?abbrev(> will show only those functions
851 matching abbrev or C<?#abbrev> only those tables matching abbrev.
852  
853 =item ??statemment
854  
855 Will convert and show, but not perform statement. If C<$dbh> is not set, this
856 is the default behaviour.
857  
858 =item !System Shell code
859  
860 Run it.
861  
862 =item >filename
863  
864 =item >>filename
865  
866 Redirect or append next statement's output to I<filename>. For known
867 suffixes and options, see the L<next section|/Output formats>.
868  
869 =item |System Shell code
870  
871 Pipe next statement's output through I<System Shell code>.
872  
873 =back
874  
875  
876 =head2 Output formats
877  
878 The output format for the next SQL statement that is run, is chosen from the
879 suffix of a redirection or a special suffix query. In both cases
880 comma-separated options may be passed:
881  
882 =over
883  
884 =item >filename.suffix
885  
886 =item >filename.suffix( opt; ... )
887  
888 =item >>filename.suffix
889  
890 =item >>filename.suffix( opt; ... )
891  
892 =item &.suffix opt; ...
893  
894 =item &.suffix( opt; ... ) following text
895  
896 =back
897  
898 The known suffixes and their respective options are:
899  
900 =over
901  
902 =item C<.csv>
903  
904 This writes Comma Separated Values with one subtle trick: NULL and empty
905 strings are distinguished by quoting the latter. Some tools like Perl's file
906 DB L<DBD::CSV> or rather its underlying L<Text::CSV_XS> can pick that up. CSV
907 can take one of these options:
908  
909 =over
910  
911 =item semi
912  
913 Use a semicolon as a separator. This is a common format in environments where
914 the comma is the decimal separator. However if you want commas, you must
915 provide such formatting yourself.
916  
917 =item tab
918  
919 Use tabulators as column separators. Apart from that you get the full CSV
920 formatting, so this is not the primitive F<.tsv> format some tools may have.
921  
922 =back
923  
924  
925 =item C<.table>
926  
927 This is the default table format. But you need to name it, if you want to set
928 options.
929  
930 =over
931  
932 =item all
933  
934 This is a shorthand for outputting everything in the long form, equivalent to
935 C<( NULL, crlf, date )>.
936  
937 =item crlf
938  
939 Do not shorten C<\r\n> to C<\R>.
940  
941 =item date
942  
943 Output ISO dates fully instead of shortening 0000-00-00 to 0000- and
944 yyyy-01-01 to yyyy- or yyyy-mm-01 to yyyy-mm-.
945  
946 =item time
947  
948 Output times fully instead of shortening 23:59(:59) to 24: and hh:00(:00) to
949 hh: or hh:mm(:00) to hh:mm.
950  
951 =item NULL
952  
953 =item null
954  
955 Output this keywork instead of the shorter C<\@>.
956  
957 =back
958  
959  
960 =item C<.yaml>
961  
962 =item C<.yml>
963  
964 Format output as YAML. This format has no options. Because its every value
965 on a new line format can be more readable, there is a shorthand query C<&->
966 for it.
967  
968 =back
969  
970 =cut
971  
972 4 our $prompt = 'steno> ';
973 4 our $contprompt = '...> ';
974 sub shell() {
975 1 ▶ print STDERR $prompt;
Subroutine shell: called CC=36 SCAR=43.3
Pod documented
976 1 my $fh;
977 1 ▶ while( <> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline ARGV)) 16 1 17
978 16 undef $error;
979 16 ▶ goto NEXT unless /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless /\S/u 2 14 16
980 14 ▶ if( s/^\s*\\\\\s*// ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^\s*\\\\\s*//u) { } 1 13 14
981 1 s/\s*\Z/\n/s;
982 1 local $/ = "\\\\\n"; # leading \n gets chopped below
983 1 $_ .= <>;
984 1 chomp;
985 } else {
986 13 ▶ while( s/(?<!\\)((?:\\\\)*)\\(?=\n\Z)/$1/ ) { # join continuation lines
Branch: 1 branch
BranchTrueFalseTotal
if (s/(?<!\\)((?:\\\\)*)\\(?=\n\Z)/$1/u) 1 13 14
987 1 print STDERR $contprompt;
988 1 $_ .= <>;
989 }
990 13 s/\A\s+//;
991 }
992 14 s/\s+\Z//;
993 14 ▶ until( $error ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error) 28 0 28
994 last unless
995 28 ▶ s!^\&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))!convert_Queries $1, $3!e
Branch: 1 branch
BranchTrueFalseTotal
unless s/^\&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Queries($1, $3);/eu or s/^\&(\.?\w+|-) *(.*)/&convert_Queries($1, $2);/eu or my $perl = s/^\&$SQL::Steno::perl_re//u 14 14 28
Condition100%6/6
s/^\&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Queries($1, $3);/eu or s/^\&(\.?\w+|-) *(.*)/&convert_Queries($1, $2);/eu or my $perl = s/^\&$SQL::Steno::perl_re//u
l!l&&r!l&&!r
13114
s/^\&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Queries($1, $3);/eu or s/^\&(\.?\w+|-) *(.*)/&convert_Queries($1, $2);/eu
l!l&&r!l&&!r
31015
MC/DC100%3/3
s/^\&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Queries($1, $3);/eu or s/^\&(\.?\w+|-) *(.*)/&convert_Queries($1, $2);/eu or my $perl = s/^\&$SQL::Steno::perl_re//u
s/^\&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Queries($1, $3);/eu s/^\&(\.?\w+|-) *(.*)/&convert_Queries($1, $2);/eu my $perl = s/^\&$SQL::Steno::perl_re//u
Truth table100%4/4
A or B or C
A= s/^\&(\.?\w+|-)(\(((?:(?>[^()]+)|(?2))*)\))/&convert_Queries($1, $3);/euB= s/^\&(\.?\w+|-) *(.*)/&convert_Queries($1, $2);/euC= my $perl = s/^\&$SQL::Steno::perl_re//u
ABCresult
1XX1
01X1
0011
0000
996 10 or s!^\&(\.?\w+|-) *(.*)!convert_Queries $1, $2!e
997 or my $perl = s!^\&$perl_re!!;
998 14 ▶ if( $perl ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($perl) 1 13 14
999 1 $perl = eval $1;
1000 1 local $| = 1; # flush to avoid stderr prompt overtaking last output line.
1001 1 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
1002 1 ▶ if( UNIVERSAL::isa $perl, 'DBI::st' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (UNIVERSAL::isa($perl, 'DBI::st')) { } 0 1 1
elsif (defined $perl) { } 1 0 1
1003 0 $_ = $perl;
1004 0 goto RUN;
1005 } elsif( defined $perl ) {
1006 1 substr $_, 0, 0, $perl;
1007 } else {
1008 0 goto NEXT;
1009 }
1010 }
1011 }
1012  
1013 14 my $filter = '';
1014 14 ▶ 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 14 23
Condition100%3/3
s/^\s*$SQL::Steno::perl_re//u or s[^\s*(!?)(/.+?/(?:i\b)?)\s*][]u
l!l&&r!l&&!r
6314
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
1015 9 ▶ if( defined $2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $2) { } 3 6 9
1016 3 ▶ $filter .= 'return if join( "|", map ref() ? () : $_ // q!\@!, @_ ) ' . ($1 ? '=' : '!') . "~ $2;\n";
Branch: 1 branch
BranchTrueFalseTotal
$1 ? : 1 2 3
1017 } else {
1018 6 $filter .= "return unless eval $1;\n";
1019 }
1020 }
1021 14 ▶ if( $filter ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filter) 7 7 14
1022 7 $filter = eval "sub {\n$filter 1; }";
1023 7 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
1024 }
1025 14 ▶ goto RUN if s/^\s*=//; # run literally
Branch: 1 branch
BranchTrueFalseTotal
if s/^\s*=//u 5 9 14
1026  
1027 9 my $skip = 0;
1028 9 ▶ if( /^\s*\?\s*(?:([?&#.:])(\w*)|(\w*)\()?/ ) { # help
Branch: 1 branch
BranchTrueFalseTotal
if (/^\s*\?\s*(?:([?&#.:])(\w*)|(\w*)\()?/u) 1 8 9
1029 1 ▶ if( $1 && $1 eq '?' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 and $1 eq '?') { } 0 1 1
Condition33%1/3
$1 and $1 eq "?"
!ll&&!rl&&r
010
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
1030 0 s/^\s*\?\s*\?//;
1031 0 $skip = 1;
1032 } else {
1033 1 help( $1, $2, $3 );
1034 1 goto NEXT;
1035 }
1036 }
1037 8 ▶ if( s/^\s*!// ) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^\s*!//u) 0 8 8
1038 0 system $_;
1039 0 ▶ if( $? == -1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($? == -1) { } 0 0 0
elsif (my $exit = $? & 127) { } 0 0 0
1040 0 print STDERR "failed to execute: $!\n";
1041 } elsif( my $exit = $? & 0b111_1111 ) {
1042 0 ▶ printf STDERR "child died with signal %d, with%s coredump\n",
Branch: 1 branch
BranchTrueFalseTotal
$? & 128 ? : 0 0 0
1043 $exit, ($? & 0b1000_0000) ? '' : 'out';
1044 } else {
1045 0 printf STDERR "child exited with value %d\n", $? >> 8;
1046 }
1047 0 goto NEXT;
1048 }
1049 8 s/^\s*()//; # dummy because $1 survives loop iterations :-o
1050 8 ▶ if( /\A(>{1,2})\s*(.+?(\.\w+)?)(?:\((.*)\))?\s*\Z/ ) { # redirect output
Branch: 2 branches
BranchTrueFalseTotal
if (/\A(>{1,2})\s*(.+?(\.\w+)?)(?:\((.*)\))?\s*\Z/u) { } 0 8 8
elsif (/\A\|(.+)\Z/u) { } 0 8 8
1051 0 ▶ set_render $3, $4 ? split ';', $4 : () if $3;
Branch: 2 branches
BranchTrueFalseTotal
if $3 0 0 0
$4 ? : 0 0 0
1052 0 open $fh, "$1:utf8", (glob $2)[0];
1053 0 select $fh;
1054 0 goto NEXT;
1055 } elsif( /\A\|(.+)\Z/ ) { # pipe output
1056 0 open $fh, '|-:utf8', $1;
1057 0 select $fh;
1058 0 goto NEXT;
1059 }
1060  
1061 8 undef $error;
1062  
1063 8 ▶ goto NEXT unless $_ && &convert;
Branch: 1 branch
BranchTrueFalseTotal
unless $_ and &convert 2 6 8
Condition66%2/3
$_ and &convert
!ll&&!rl&&r
206
MC/DC50%1/2
$_ and &convert
$_ &convert
Truth table66%2/3
A and B
A= $_B= &convert
ABresult
0X0
100
111
1064  
1065 6 print STDOUT "$_;\n";
1066 6 ▶ goto NEXT if $skip;
Branch: 1 branch
BranchTrueFalseTotal
if $skip 0 6 6
1067  
1068 11 ▶ RUN:
Branch: 1 branch
BranchTrueFalseTotal
if $SQL::Steno::dbh 11 0 11
1069 run $_, $filter, %opt if $dbh;
1070 11 ($render, %opt) = ();
1071 11 ▶ if( $fh ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fh) 0 11 11
1072 0 close;
1073 0 select STDOUT;
1074 0 undef $fh;
1075 }
1076 NEXT:
1077 16 print STDERR $prompt;
1078 }
1079 1 print STDERR "\n";
1080 }
1081  
1082  
1083  
1084 sub helphashalt(\%@) {
1085 0 ▶ my $hash = shift;
Subroutine helphashalt: not called CC=5 SCAR=34.0
Pod undocumented
1086 0 ▶ if( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
1087 0 my $ret = $hash->{''};
1088 0 print "for *ptr, *cr, *cp, ...:\n";
1089 printf "%-5s %s\n", $_, &$ret( $_ )
1090 0 for @_;
1091 0 print "\n";
1092 }
1093 $_ eq '' or printf "%-5s %s\n", $_, $hash->{$_}
1094 0 ▶ for sort keys %$hash;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq "" or printf "%-5s %s\n", $_, $hash->{$_} 0 0 0
1095 }
1096 sub helphash($$$\%;\@) {
1097 #my( $str, $prefix, $suffix, $hash, $list ) = @_;
1098 1 ▶ if( $_[0] ) {
Subroutine helphash: called CC=13 SCAR=47.6
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]) { } 1 0 1
1099 1 undef $error;
1100 1 ▶ $error or printf "%-7s %s\n", "$_[1]$_[0]$_[2]", $_ if $_ = &find;
Branch: 1 branch
BranchTrueFalseTotal
if $_ = &find 1 0 1
Condition33%2/6
($_ = &find) && ($error || printf("%-7s %s\n", "$_[1]$_[0]$_[2]", $_))
!ll&&!rl&&r
010
$error or printf "%-7s %s\n", "$_[1]$_[0]$_[2]", $_
l!l&&r!l&&!r
010
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
1101 } else {
1102 0 my %hash = %{$_[3]};
1103 0 ▶ if( my $sub = delete $hash{''} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sub = delete $hash{""}) 0 0 0
1104 0 my @list = $sub->();
1105 0 for my $elt ( @list ) {
1106 0 $hash{$elt->[0]} = $sub->( my $name = $elt->[0] ) . ' ' . $elt->[1];
1107 }
1108 }
1109 0 chomp %hash;
1110 printf "%-7s %s\n", "$_[1]$_$_[2]", $hash{$_}
1111 0 ▶ for sort { lc( $a ) cmp lc( $b ) or $a cmp $b } keys %hash;
Branch: 1 branch
BranchTrueFalseTotal
lc $a cmp lc $b or $a cmp $b 0 0 0
1112 0 ▶ return unless $_[4];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[4] 0 0 0
1113 0 my $i = 0;
1114 0 ▶ my @list = sort { lc( $a ) cmp lc( $b ) or $a cmp $b } @{$_[4]};
Branch: 1 branch
BranchTrueFalseTotal
lc $a cmp lc $b or $a cmp $b 0 0 0
1115 0 ▶ while( @list ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@list) 0 0 0
1116 0 ▶ if( ($i += length $list[0]) < 80 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($i += length $list[0]) < 80) { } 0 0 0
1117 0 print ' ', shift @list;
1118 } else {
1119 0 $i = 0;
1120 0 print "\n";
1121 }
1122 }
1123 0 ▶ print "\n" if $i;
Branch: 1 branch
BranchTrueFalseTotal
if $i 0 0 0
1124 }
1125 }
1126  
1127 sub help {
1128 1 ▶ if( defined $_[2] ) {
Subroutine help: called CC=11 SCAR=43.1
Pod undocumented
Branch: 5 branches
BranchTrueFalseTotal
if (defined $_[2]) { } 0 1 1
elsif (not $_[0]) { } 0 1 1
elsif ($_[0] eq '#') { } 0 1 1
elsif ($_[0] eq '.') { } 0 1 1
elsif ($_[0] eq '&') { } 1 0 1
1129 0 local $Functions{I} = 'in but quotes strings itself, splits on space, or with beginning if I(, ... or I(,...';
1130 0 helphash $_[2], '', '(', %Functions, @Functions;
1131 } elsif( !$_[0] ) {
1132 0 print <<\HELP;
1133 All entries are single line unless \\wrapped at 1st bol and last eol\\ or continued.\
1134 Queries have the form: {{i}/regexp/}{=}query
1135 The query has lots of short-hands expanded, unless it is prefixed by the optional =.
1136 The fields joined with '|' are grepped if regexp is given, case-insensitively if i is given.
1137  
1138 ??query Only shows massaged query.
1139 !perl-code Runs perl-code.
1140 >file Next query's output to file. In csv or yaml format if filename has that suffix.
1141  
1142 Query has the form {select|update|insert|delete}{fieldlist};tablelist{;clause} or set ...
1143 'select' is prepended if none of these initial keywords.
1144 fieldlist defaults to '*', also if Query starts with '#'.
1145 ';' is alternately replaced by 'from' and 'where' except '\;'.
1146  
1147 Abbreviations, more help with ?&{abbrev}, ?#{abbrev}, ?.{abbrev}, ?{abbrev}(, ?:{abbrev}
1148 &query $1,$2,... # only at bol
1149 &query($1,$2,...)... # only at bol, only replace upto )
1150 &{Perl code}... # only at bol, if it return undef then skip, else prepend to ...
1151 #table
1152 .column # for any table recognized in statement
1153 function(
1154 :macro
1155 :{Perl code} # dynamic macro
1156  
1157 Characters \t\n\r get masked in output, \r\n as \R.
1158 Date or time 0000-00-00 -> 0000- 1970-01-01 -> 1970- 00:00:00 -> 00: 23:59:59 -> 24:
1159 HELP
1160 } elsif( $_[0] eq '#' ) {
1161 0 ▶ @keys_Table_Columns = keys %Table_Columns unless @keys_Table_Columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @keys_Table_Columns 0 0 0
1162 0 helphash $_[1], '#', '', %Tables, @keys_Table_Columns;
1163 } elsif( $_[0] eq '.' ) {
1164 0 ▶ helphashalt %Columns, 'ptr' unless $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 0 0
1165 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
1166 $_[1] and $_ = find $_[1], '.', '', %Columns; # \todo, @column;
1167 } elsif( $_[0] eq '&' ) {
1168 1 helphash $_[1], '&', '', %Queries_help;
1169 } else {
1170 0 local $Tables{TBL} = 'TABLE';
1171 0 helphash $_[1], ':', '', %Macros;
1172 }
1173 }
1174  
1175 =head1 YOUR SCRIPT
1176  
1177 package SQL::Steno; # doesn't export yet, so get the functions easily
1178 use SQL::Steno;
1179 use DBI;
1180 our $dbh = DBI->connect( ... ); # preferably mysql, but other DBs should work (with limitations).
1181 # If you want #tbl and .col to work, (only) one of:
1182 init_from_query; # fast, defaults to mysql information_schema, for which you need read permission
1183 init; # slow, using DBI dbh methods.
1184 # Set any of the variables mentioned above to get you favourite abbreviations.
1185 shell;
1186  
1187 =head1 LICENSE
1188  
1189 This program is free software; you may redistribute it and/or modify it under
1190 the same terms as Perl itself.
1191  
1192 =head1 SEE ALSO
1193  
1194 L<DBI>, L<SQL::Interp>, L<SQL::Preproc>, L<SQL::Yapp>, L<Jade|http://jade-lang.com/>
1195  
1196 =head1 AUTHOR
1197  
1198 (C) 2015 by Daniel Pfeiffer <occitan@esperanto.org>.
↑ Summary