lib/DBIx/RunSQL.pm

filter: Statementstmt 36.2% 58 / 160 Branchbran 18.1% 16 / 88 Conditioncond 24.3% 9 / 37 MC/DCmcdc 21.7% 5 / 23 Subroutinesub 63.1% 12 / 19 Podpod 87.5% 7 / 8 totaltotal 31.9% 107 / 335 CC 59 SCAR 46.6
CC
59
Cov
29%
run_sql
240.0
format_results
240.0
split_sql
49.2
CRAP 105.8
↑ Summary script/run-sql.pl »
1 package DBIx::RunSQL;
2 11 ▶use 5.020;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 11 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 11 ▶use stable 'postderef';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 11 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 11 ▶use Module::Load 'load';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 11 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 11 our $VERSION = '0.27';
10  
11 =encoding utf8
12  
13 =head1 NAME
14  
15 DBIx::RunSQL - run SQL from a file
16  
17 =cut
18  
19 =head1 SYNOPSIS
20  
21 #!/usr/bin/perl -w
22 use strict;
23 use DBIx::RunSQL;
24  
25 my $test_dbh = DBIx::RunSQL->create(
26 dsn => 'dbi:SQLite:dbname=:memory:',
27 sql => 'sql/create.sql',
28 options => { PrintError => 0, RaiseError => 1 },
29 force => 1,
30 verbose => 1,
31 formatter => 'Text::Table',
32 rotate => 1,
33 null => '(Null)',
34 );
35  
36 # now run your tests with a DB setup fresh from setup.sql
37  
38 =head1 METHODS
39  
40 =head2 C<< DBIx::RunSQL->create ARGS >>
41  
42 =head2 C<< DBIx::RunSQL->run ARGS >>
43  
44 Runs the SQL commands and returns the database handle.
45 In list context, it returns the database handle and the
46 suggested exit code.
47  
48 =over 4
49  
50 =item *
51  
52 C<sql> - name of the file containing the SQL statements
53  
54 The default is C<sql/create.sql>
55  
56 If C<sql> is a reference to a glob or a filehandle,
57 the SQL will be read from that. B<not implemented>
58  
59 If C<sql> is undefined, the C<$::DATA> or the C<0> filehandle will
60 be read until exhaustion. B<not implemented>
61  
62 This allows one to create SQL-as-programs as follows:
63  
64 #!/usr/bin/perl -w -MDBIx::RunSQL -e 'create()'
65 create table ...
66  
67 If you want to run SQL statements from a scalar,
68 you can simply pass in a reference to a scalar containing the SQL:
69  
70 sql => \"update mytable set foo='bar';",
71  
72 =item *
73  
74 C<dsn>, C<user>, C<password>, C<options> - DBI parameters for connecting to the DB
75  
76 =item *
77  
78 C<dbh> - a premade database handle to be used instead of C<dsn>
79  
80 =item *
81  
82 C<force> - continue even if errors are encountered
83  
84 =item *
85  
86 C<verbose> - print each SQL statement as it is run
87  
88 =item *
89  
90 C<verbose_handler> - callback to call with each SQL statement instead of C<print>
91  
92 =item *
93  
94 C<verbose_fh> - filehandle to write to instead of C<STDOUT>
95  
96 =back
97  
98 =cut
99  
100 sub create {
101 0 ▶ my ($self,%args) = @_;
Subroutine create: not called CC=6 SCAR=37.4
Pod documented
102 0 ▶ $args{sql} ||= 'sql/create.sql';
Condition0%0/2
$args{"sql"} ||= "sql/create.sql"
l!l
00
MC/DC0%0/1
$args{"sql"} ||= "sql/create.sql"
$args{"sql"}
Truth table0%0/2
A
A= $args{"sql"}
Aresult
11
00
103  
104 0 ▶ $args{options} ||= {};
Condition0%0/2
$args{"options"} ||= {}
l!l
00
MC/DC0%0/1
$args{"options"} ||= {}
$args{"options"}
Truth table0%0/2
A
A= $args{"options"}
Aresult
11
00
105  
106 0 my $dbh = delete $args{ dbh };
107 0 ▶ if (! $dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbh) 0 0 0
108 $dbh = DBI->connect($args{dsn}, $args{user}, $args{password}, $args{options})
109 0 ▶ or die "Couldn't connect to DSN '$args{dsn}' : " . DBI->errstr;
Branch: 1 branch
BranchTrueFalseTotal
$dbh = "DBI"->connect($args{"dsn"}, $args{"user"}, $args{"password"}, $args{"options"}) or die qq[Couldn't connect to DSN '$args{"dsn"}' : ] . "DBI"->errstr 0 0 0
110 };
111  
112 0 my $errors = $self->run_sql_file(
113 dbh => $dbh,
114 %args,
115 );
116 0 ▶ return wantarray ? ($dbh, $errors) : $dbh;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
117 };
118 11 *run = *run = \&create;
119  
120 =head2 C<< DBIx::RunSQL->run_sql_file ARGS >>
121  
122 my $dbh = DBI->connect(...)
123  
124 for my $file (sort glob '*.sql') {
125 DBIx::RunSQL->run_sql_file(
126 verbose => 1,
127 dbh => $dbh,
128 sql => $file,
129 );
130 };
131  
132 Runs an SQL file on a prepared database handle.
133 Returns the number of errors encountered.
134  
135 If the statement returns rows, these are printed
136 separated with tabs.
137  
138 =over 4
139  
140 =item *
141  
142 C<dbh> - a premade database handle
143  
144 =item *
145  
146 C<sql> - name of the file containing the SQL statements
147  
148 =item *
149  
150 C<fh> - filehandle to the file containing the SQL statements
151  
152 =item *
153  
154 C<force> - continue even if errors are encountered
155  
156 =item *
157  
158 C<verbose> - print each SQL statement as it is run
159  
160 =item *
161  
162 C<verbose_handler> - callback to call with each SQL statement instead of
163 C<print>
164  
165 =item *
166  
167 C<verbose_fh> - filehandle to write to instead of C<STDOUT>
168  
169 =item *
170  
171 C<output_bool> - whether to exit with a nonzero exit code if any row is found
172  
173 This makes the function return a nonzero value even if there is no error
174 but a row was found.
175  
176 =item *
177  
178 C<output_string> - whether to output the (one) row and column, without any
179 headers
180  
181 =item *
182  
183 C<formatter> - see the C<<formatter>> option of C<< ->format_results >>
184  
185 =item *
186  
187 C<rotate> - rotate the table by 90° , outputting columns as rows
188  
189 =item *
190  
191 C<null> - string to replace SQL C<NULL> columns by
192  
193 =back
194  
195 =cut
196  
197 sub run_sql_file {
198 0 ▶ my ($self,%args) = @_;
Subroutine run_sql_file: not called CC=3 SCAR=24.8
Pod documented
199 0 ▶ if( ! $args{ fh }) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"fh"}) 0 0 0
200 open $args{ fh }, "<:crlf", $args{sql}
201 0 ▶ or die "Couldn't read '$args{sql}' : $!";
Branch: 1 branch
BranchTrueFalseTotal
open $args{"fh"}, "<:crlf", $args{"sql"} or die qq[Couldn't read '$args{"sql"}' : $!] 0 0 0
202 0 delete $args{ sql };
203 };
204 0 $self->run_sql(
205 %args,
206 );
207 }
208  
209 =head2 C<< DBIx::RunSQL->run_sql ARGS >>
210  
211 my $dbh = DBI->connect(...)
212  
213 DBIx::RunSQL->run_sql(
214 verbose => 1,
215 dbh => $dbh,
216 sql => \@sql_statements,
217 );
218  
219 Runs an SQL string on a prepared database handle.
220 Returns the number of errors encountered.
221  
222 If the statement returns rows, these are printed
223 separated with tabs, but see the C<output_bool> and C<output_string> options.
224  
225 =over 4
226  
227 =item *
228  
229 C<dbh> - a premade database handle
230  
231 =item *
232  
233 C<sql> - string or array reference containing the SQL statements
234  
235 =item *
236  
237 C<force> - continue even if errors are encountered
238  
239 =item *
240  
241 C<verbose> - print each SQL statement as it is run
242  
243 =item *
244  
245 C<verbose_handler> - callback to call with each SQL statement instead of C<print>
246  
247 =item *
248  
249 C<verbose_fh> - filehandle to write to instead of C<STDOUT>
250  
251 =item *
252  
253 C<output_bool> - whether to exit with a nonzero exit code if any row is found
254  
255 This makes the function return a nonzero value even if there is no error
256 but a row was found.
257  
258 =item *
259  
260 C<output_string> - whether to output the (one) row and column, without any headers
261  
262 =item *
263  
264 C<formatter> - see the C<<formatter>> option of C<< ->format_results >>
265  
266 =item *
267  
268 C<rotate> - rotate the table by 90° , outputting columns as rows
269  
270 =item *
271  
272 C<null> - string to replace SQL C<NULL> columns by
273  
274 =back
275  
276 =cut
277  
278 sub run_sql {
279 0 ▶ my ($self,%args) = @_;
Subroutine run_sql: not called CC=15 SCAR=54.8
Pod documented
280 0 my $errors = 0;
281  
282 0 ▶ if( ! $args{ verbose_handler }) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"verbose_handler"}) 0 0 0
283 0 ▶ $args{ verbose_fh } //= \*main::STDOUT;
Condition0%0/2
$args{"verbose_fh"} //= \*STDOUT
l!l
00
MC/DC0%0/1
$args{"verbose_fh"} //= \*STDOUT
$args{"verbose_fh"}
Truth table0%0/2
A
A= $args{"verbose_fh"}
Aresult
11
00
284 $args{ verbose_handler } = sub {
285 0 ▶ print { $args{ verbose_fh } } "$_[0]\n";
Subroutine __ANON__: not called CC=1 SCAR=6.9
286 }
287 0 };
288 0 my $status = delete $args{ verbose_handler };
289  
290 0 ▶ if( $args{ fh }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"fh"}) 0 0 0
291 0 $args{ sql } = delete $args{ fh };
292 };
293  
294 0 ▶ while( defined(my $statement = $self->split_sql($args{ sql }))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $statement = $self->split_sql($args{"sql"}))) 0 0 0
295 # skip "statements" that consist only of comments
296 0 ▶ next unless $statement =~ /^\s*[A-Z][A-Z]/mi;
Branch: 1 branch
BranchTrueFalseTotal
unless $statement =~ /^\s*[A-Z][A-Z]/imu 0 0 0
297 0 ▶ $status->($statement) if $args{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"verbose"} 0 0 0
298  
299 0 my $sth = $args{dbh}->prepare($statement);
300 0 ▶ if(! $sth) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $sth) { } 0 0 0
301 0 ▶ if (!$args{force}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $args{'force'}) { } 0 0 0
302 0 die "[SQL ERROR]: $statement\n";
303 } else {
304 0 warn "[SQL ERROR]: $statement\n";
305 };
306 } else {
307 0 my $status= $sth->execute();
308 0 ▶ if(! $status) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $status) { } 0 0 0
elsif (defined $sth->{'NUM_OF_FIELDS'} and 0 < $sth->{'NUM_OF_FIELDS'}) { } 0 0 0
309 0 ▶ if (!$args{force}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $args{'force'}) { } 0 0 0
310 0 die "[SQL ERROR]: $statement\n";
311 } else {
312 0 warn "[SQL ERROR]: $statement\n";
313 };
314 ▶ } elsif( defined $sth->{NUM_OF_FIELDS} and 0 < $sth->{NUM_OF_FIELDS} ) {
Condition0%0/3
defined $sth->{"NUM_OF_FIELDS"} and 0 < $sth->{"NUM_OF_FIELDS"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $sth->{"NUM_OF_FIELDS"} and 0 < $sth->{"NUM_OF_FIELDS"}
defined $sth->{"NUM_OF_FIELDS"} 0 < $sth->{"NUM_OF_FIELDS"}
Truth table0%0/3
A and B
A= defined $sth->{"NUM_OF_FIELDS"}B= 0 < $sth->{"NUM_OF_FIELDS"}
ABresult
0X0
100
111
315 # SELECT statement, output results
316 0 ▶ if( $args{ output_bool }) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'output_bool'}) { } 0 0 0
elsif ($args{'output_string'}) { } 0 0 0
317 0 my $res = $self->format_results(
318 sth => $sth,
319 no_header_when_empty => 1,
320 %args
321 );
322 0 print $res;
323 # Set the exit code depending on the length of $res because
324 # we lost the information on how many rows the result
325 # set had ...
326 0 $errors = length $res > 0;
327  
328 } elsif( $args{ output_string }) {
329 0 local $args{formatter} = 'tab';
330 0 print $self->format_results(
331 sth => $sth,
332 no_header_when_empty => 1,
333 %args
334 );
335  
336 } else {
337 0 print $self->format_results( sth => $sth, %args );
338 };
339 };
340 };
341 };
342 0 $errors
343 }
344  
345 =head2 C<< DBIx::RunSQL->format_results %options >>
346  
347 my $sth= $dbh->prepare( 'select * from foo' );
348 $sth->execute();
349 print DBIx::RunSQL->format_results( sth => $sth );
350  
351 Executes C<< $sth->fetchall_arrayref >> and returns
352 the results either as tab separated string
353 or formatted using L<Text::Table> if the module is available.
354  
355 If you find yourself using this often to create reports,
356 you may really want to look at L<Querylet> instead.
357  
358 =over 4
359  
360 =item *
361  
362 C<sth> - the executed statement handle
363  
364 =item *
365  
366 C<formatter> - if you want to force C<tab> or C<Text::Table>
367 usage, you can do it through that parameter.
368 In fact, the module will use anything other than C<tab>
369 as the class name and assume that the interface is compatible
370 to C<Text::Table>.
371  
372 =item *
373  
374 C<no_header_when_empty> - don't print anything if there are no results
375  
376 =item *
377  
378 C<rotate> - rotate the table by 90° , outputting columns as rows
379  
380 =item *
381  
382 C<null> - string to replace SQL C<NULL> columns by
383  
384 =back
385  
386 Note that the query results are returned as one large string,
387 so you really do not want to run this for large(r) result
388 sets.
389  
390 =cut
391  
392 sub _nullstr {
393 0 ▶ my $str = shift;
Subroutine _nullstr: not called CC=2 SCAR=17.9
394 0 ▶ map { defined $_ ? $_ : $str } @_
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 0 0 0
395 }
396  
397 sub format_results {
398 0 ▶ my( $self, %options )= @_;
Subroutine format_results: not called CC=15 SCAR=54.8
Pod documented
399 0 my $sth= delete $options{ sth };
400  
401 0 ▶ if( ! $options{ formatter }) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options{"formatter"}) 0 0 0
402 0 ▶ if( eval { require "Text/Table.pm" }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require 'Text/Table.pm' } }) { } 0 0 0
403 0 $options{ formatter }= 'Text::Table';
404 } else {
405 0 $options{ formatter }= 'tab';
406 };
407 };
408  
409 0 ▶ my $nullstr = $options{ null } // ''; # / , for Filter::Simple
Condition0%0/2
$options{"null"} // ""
l!l
00
MC/DC0%0/1
$options{"null"} // ""
$options{"null"}
Truth table0%0/2
A
A= $options{"null"}
Aresult
11
00
410  
411 0 my @columns= @{ $sth->{NAME} };
412 0 my $res= $sth->fetchall_arrayref();
413 0 my @rows = map { [ _nullstr( $nullstr, @$_ ) ] } @$res;
414  
415 0 my $no_header_when_empty = $options{ no_header_when_empty };
416 0 ▶ my $print_header = not exists $options{ header } || $options{ header };
Condition0%0/3
exists $options{'header'} || $options{'header'}
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $options{'header'} || $options{'header'}
exists $options{'header'} $options{'header'}
Truth table0%0/3
A || B
A= exists $options{'header'}B= $options{'header'}
ABresult
1X1
011
000
417 0 my $rotate = $options{ rotate };
418  
419 0 ▶ if( $rotate ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rotate) 0 0 0
420 # Rotate our output
421 my @new_rows = map {
422 0 my $i = $_;
423 0 [$columns[$i], map { $_->[$i] } @rows]
424 } (0..$#columns);
425 0 @rows = @new_rows;
426 0 @columns = @{shift @rows};
427 }
428  
429 0 my $result='';
430 0 ▶ if( @columns ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@columns) 0 0 0
431 # Output as print statement
432 0 ▶ if( $no_header_when_empty and ! @$res ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($no_header_when_empty and not @$res) { } 0 0 0
elsif ('tab' eq $options{'formatter'}) { } 0 0 0
Condition0%0/3
$no_header_when_empty and not @$res
!ll&&!rl&&r
000
MC/DC0%0/2
$no_header_when_empty and not @$res
$no_header_when_empty not @$res
Truth table0%0/3
A and not(B)
A= $no_header_when_emptyB= not @$res
ABresult
0X0
100
111
433 # Nothing to do
434  
435 } elsif( 'tab' eq $options{ formatter } ) {
436 $result = join "\n",
437 $print_header ? join( "\t", @columns ) : (),
438 0 ▶ map { join( "\t", @$_ ) } @rows
Branch: 1 branch
BranchTrueFalseTotal
$print_header ? : 0 0 0
439 ;
440  
441 } else {
442 0 my $class = $options{ formatter };
443  
444 0 ▶ if( !( $class->can('table') || $class->can('new'))) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class->can("table") or $class->can("new")) 0 0 0
Condition0%0/3
$class->can("table") or $class->can("new")
l!l&&r!l&&!r
000
MC/DC0%0/2
$class->can("table") or $class->can("new")
$class->can("table") $class->can("new")
Truth table0%0/3
A or B
A= $class->can("table")B= $class->can("new")
ABresult
1X1
011
000
445 # Try to load the module, just in case it isn't present in
446 # memory already
447  
448 0 eval { load $class; };
449 };
450  
451 # Now dispatch according to the apparent type
452 0 ▶ if( !$class->isa('Text::Table') and my $table = $class->can('table') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $class->isa('Text::Table') and my $table = $class->can('table')) { } 0 0 0
Condition0%0/3
not $class->isa("Text::Table") and my $table = $class->can("table")
!ll&&!rl&&r
000
MC/DC0%0/2
not $class->isa("Text::Table") and my $table = $class->can("table")
not $class->isa("Text::Table") my $table = $class->can("table")
Truth table0%0/3
not(A) and B
A= not $class->isa("Text::Table")B= my $table = $class->can("table")
ABresult
0X0
100
111
453 # Text::Table::Any interface
454 0 $result = $table->( header_row => $print_header,
455 rows => [\@columns, @rows ],
456 );
457 } else {;
458 # Text::Table interface
459 0 my $t= $options{formatter}->new(@columns);
460 0 $t->load( @rows );
461 0 $result= $t;
462 };
463 };
464 };
465 0 "$result"; # Yes, sorry - we stringify everything
466 }
467  
468 =head2 C<< DBIx::RunSQL->split_sql ARGS >>
469  
470 my $sql = <<'SQL';
471 create table foo (name varchar(64));
472 create trigger foo_insert on foo before insert;
473 new.name= 'foo-'||old.name;
474 end;
475 insert into foo name values ('bar');
476 SQL
477 while( defined( my $s = DBIx::RunSQL->split_sql( $sql ))) {
478 push @statements, $s;
479 }
480 # @statements has three elements
481  
482 This is a helper subroutine to split a sequence of (semicolon-newline-delimited)
483 SQL statements into separate statements. It is documented because
484 it is not a very smart subroutine and you might want to
485 override or replace it. It might also be useful outside the context
486 of L<DBIx::RunSQL> if you need to split up a large blob
487 of SQL statements into smaller pieces.
488  
489 This routine takes a string, filehandle or an iterator as its parameter.
490 This iterator should return the next statement.
491 A filehandle or a string will be split at C< ;\n >.
492  
493 C<split_sql> will try to reassemble C<CREATE TRIGGER>
494 statements from the list of statements.
495  
496 =cut
497  
498 sub next_sql {
499 3 ▶ $_[1] =~ /\G\s*(\S.*?)(?:;[ \t]*\r?\n|\s*;?\s*\z)/sg
Subroutine next_sql: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$_[1] =~ /\G\s*(\S.*?)(?:;[ \t]*\r?\n|\s*;?\s*\z)/gsu or return undef 1 2 3
500 or return undef;
501 2 return "$1";
502 }
503  
504 sub split_sql {
505 3 ▶ my $self = shift;
Subroutine split_sql: called CC=11 SCAR=39.0
Pod documented
506 3 my $iterator;
507  
508 3 ▶ if( ! ref $_[0] ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $_[0]) { } 3 0 3
elsif (ref $_[0] eq 'CODE') { } 0 0 0
elsif (ref $_[0] eq 'GLOB') { } 0 0 0
509 # We got an SQL string, make up an iterator
510 3 my $s = \$_[0];
511 3 ▶ $iterator = sub { $self->next_sql($$s) };
Subroutine __ANON__: called CC=1 SCAR=0.0
512 } elsif( ref $_[0] eq 'CODE' ) {
513 0 $iterator = $_[0]
514 } elsif( ref $_[0] eq 'GLOB' ) {
515 0 my $fh = $_[0];
516 0 ▶ $iterator = sub { local $/ = ";\n"; <$fh> }
Subroutine __ANON__: not called CC=1 SCAR=6.9
517 0 } else {
518 0 croak "Don't know how to handle reference type " . ref $_[0];
519 }
520  
521 3 my $statement = $iterator->();
522 return undef
523 3 ▶ if not defined $statement;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $statement 1 2 3
524 2 my $trigger;
525  
526 2 ▶ if( $statement =~ /^\s*CREATE\s+TRIGGER\b/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($statement =~ /^\s*CREATE\s+TRIGGER\b/iu) 0 2 2
527 0 ▶ if( $statement !~ /END$/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $statement =~ /END$/iu) { } 0 0 0
528 # Multiline CREATE TRIGGER statement
529 0 $trigger = $statement;
530  
531 0 my $next;
532 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
(not defined $next or $next =~ /END$/iu) or do { do { $next = &$iterator(); $trigger .= ';' unless $trigger =~ /;$/u; $trigger .= "\n$next" if defined $next } } 0 0 0
Condition0%0/3
not defined $next or $next =~ /END$/iu
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $next or $next =~ /END$/iu
not defined $next $next =~ /END$/iu
Truth table0%0/3
not(A) or B
A= not defined $nextB= $next =~ /END$/iu
ABresult
1X1
011
000
533 0 $next = $iterator->();
534 0 ▶ $trigger .= ";" if $trigger !~ /;$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $trigger =~ /;$/u 0 0 0
535 0 ▶ $trigger .= "\n$next"
Branch: 1 branch
BranchTrueFalseTotal
if defined $next 0 0 0
536 if defined $next;
537 } until (! defined $next or $next =~ /END$/i);
538 } else {
539 # Single-line CREATE TRIGGER statement
540 0 $trigger = $statement;
541 }
542 0 $statement = $trigger;
543 };
544  
545 2 return $statement
546 }
547  
548 11 1;
549  
550 =head2 C<< DBIx::RunSQL->parse_command_line >>
551  
552 my $options = DBIx::RunSQL->parse_command_line( 'my_application', \@ARGV );
553  
554 Helper function to turn a command line array into options for DBIx::RunSQL
555 invocations. The array of command line items is modified in-place.
556  
557 If the reference to the array of command line items is missing, C<@ARGV>
558 will be modified instead.
559  
560 =cut
561  
562 sub parse_command_line {
563 4 ▶ my ($package,$appname,$argv) = @_;
Subroutine parse_command_line: called CC=8 SCAR=20.9
Pod documented
564 4 require Getopt::Long; Getopt::Long->import('GetOptionsFromArray');
565  
566 4 ▶ if (! $argv) { $argv = \@ARGV };
Branch: 1 branch
BranchTrueFalseTotal
unless ($argv) 1 3 4
567  
568 4 ▶ if (GetOptionsFromArray( $argv,
Branch: 1 branch
BranchTrueFalseTotal
if (GetOptionsFromArray($argv, 'user=s', \my $user, 'password=s', \my $password, 'dsn=s', \my $dsn, 'verbose', \my $verbose, 'force|f', \my $force, 'sql=s', \my $sql, 'bool', \my $output_bool, 'string', \my $output_string, 'quiet', \my $no_header_when_empty, 'format=s', \my $formatter_class, 'rotate', \my $rotate, 'null=s', \my $nullstr, 'help|h', \my $help, 'man', \my $man)) { } 4 0 4
569 'user=s' => \my $user,
570 'password=s' => \my $password,
571 'dsn=s' => \my $dsn,
572 'verbose' => \my $verbose,
573 'force|f' => \my $force,
574 'sql=s' => \my $sql,
575 'bool' => \my $output_bool,
576 'string' => \my $output_string,
577 'quiet' => \my $no_header_when_empty,
578 'format=s' => \my $formatter_class,
579 'rotate' => \my $rotate,
580 'null=s' => \my $nullstr,
581 'help|h' => \my $help,
582 'man' => \my $man,
583 )) {
584 11 ▶ no warnings 'newline';
Subroutine BEGIN: called CC=1 SCAR=0.0
585 4 ▶ $sql ||= join " ", @$argv;
Condition100%3/3
$sql ||= join(" ", @$argv)
l!l&&r!l&&!r
112
MC/DC100%2/2
$sql ||= join(" ", @$argv)
$sql join(" ", @$argv)
Truth table100%3/3
A ||= B
A= $sqlB= join(" ", @$argv)
ABresult
1X1
011
000
586 4 ▶ if( $sql and ! -f $sql ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql and not -f $sql) 2 2 4
Condition66%2/3
$sql and not -f $sql
!ll&&!rl&&r
202
MC/DC50%1/2
$sql and not -f $sql
$sql not -f $sql
Truth table66%2/3
A and not(B)
A= $sqlB= not -f $sql
ABresult
0X0
100
111
587 2 $sql = \"$sql",
588 };
589 4 my $fh;
590 4 ▶ if( ! $sql and not @$argv) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sql or @$argv) 2 2 4
Condition66%2/3
$sql or @$argv
l!l&&r!l&&!r
202
MC/DC50%1/2
$sql or @$argv
$sql @$argv
Truth table66%2/3
A or B
A= $sqlB= @$argv
ABresult
1X1
011
000
591 # Assume we'll read the SQL from stdin
592 2 $fh = \*STDIN;
593 };
594 return {
595 4 user => $user,
596 password => $password,
597 dsn => $dsn,
598 verbose => $verbose,
599 force => $force,
600 sql => $sql,
601 fh => $fh,
602 no_header_when_empty => $no_header_when_empty,
603 output_bool => $output_bool,
604 output_string => $output_string,
605 formatter => $formatter_class,
606 rotate => $rotate,
607 null => $nullstr,
608 help => $help,
609 man => $man,
610 };
611 } else {
612 0 return undef;
613 };
614 }
615  
616 sub handle_command_line {
617 4 ▶ my ($package,$appname,$argv) = @_;
Subroutine handle_command_line: called CC=5 SCAR=16.4
Pod documented
618 4 require Pod::Usage; Pod::Usage->import();
619  
620 4 ▶ my $opts = $package->parse_command_line($appname,$argv)
Branch: 1 branch
BranchTrueFalseTotal
my $opts = $package->parse_command_line($appname, $argv) or pod2usage(2) 0 4 4
621 or pod2usage(2);
622 4 ▶ pod2usage(1) if $opts->{help};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"help"} 0 4 4
623 4 ▶ pod2usage(-verbose => 2) if $opts->{man};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"man"} 0 4 4
624  
625 4 ▶ $opts->{dsn} ||= sprintf 'dbi:SQLite:dbname=db/%s.sqlite', $appname;
Condition100%2/2
$opts->{"dsn"} ||= sprintf('dbi:SQLite:dbname=db/%s.sqlite', $appname)
l!l
13
MC/DC100%1/1
$opts->{"dsn"} ||= sprintf('dbi:SQLite:dbname=db/%s.sqlite', $appname)
$opts->{"dsn"}
Truth table100%2/2
A
A= $opts->{"dsn"}
Aresult
11
00
626 4 my( $dbh, $exitcode) = $package->create(
627 %$opts
628 );
629 4 return $exitcode
630 }
631  
632 =head2 C<< DBIx::RunSQL->handle_command_line >>
633  
634 DBIx::RunSQL->handle_command_line( 'my_application', \@ARGV );
635  
636 Helper function to run the module functionality from the command line. See below
637 how to use this function in a good self-contained script.
638 This function
639 passes the following command line arguments and options to C<< ->create >>:
640  
641 --user
642 --password
643 --dsn
644 --sql
645 --quiet
646 --format
647 --force
648 --verbose
649 --bool
650 --string
651 --rotate
652 --null
653  
654 In addition, it handles the following switches through L<Pod::Usage>:
655  
656 --help
657 --man
658  
659 If no SQL is given, this function will read the SQL from STDIN.
660  
661 If no dsn is given, this function will use
662 C< dbi:SQLite:dbname=db/$appname.sqlite >
663 as the default database.
664  
665 See also the section PROGRAMMER USAGE for a sample program to set
666 up a database from an SQL file.
667  
668 =head1 PROGRAMMER USAGE
669  
670 This module abstracts away the "run these SQL statements to set up
671 your database" into a module. In some situations you want to give the
672 setup SQL to a database admin, but in other situations, for example testing,
673 you want to run the SQL statements against an in-memory database. This
674 module abstracts away the reading of SQL from a file and allows for various
675 command line parameters to be passed in. A skeleton C<create-db.pl>
676 looks like this:
677  
678 #!/usr/bin/perl -w
679 use strict;
680 use DBIx::RunSQL;
681  
682 my $exitcode = DBIx::RunSQL->handle_command_line('myapp', \@ARGV);
683 exit $exitcode;
684  
685 =head1 NAME
686  
687 create-db.pl - Create the database
688  
689 =head1 SYNOPSIS
690  
691 create-db.pl "select * from mytable where 1=0"
692  
693 =head1 ABSTRACT
694  
695 This sets up the database. The following
696 options are recognized:
697  
698 =head1 OPTIONS
699  
700 =over 4
701  
702 =item C<--user> USERNAME
703  
704 =item C<--password> PASSWORD
705  
706 =item C<--dsn> DSN
707  
708 The DBI DSN to use for connecting to
709 the database
710  
711 =item C<--sql> SQLFILE
712  
713 The alternative SQL file to use
714 instead of C<sql/create.sql>.
715  
716 =item C<--quiet>
717  
718 Output no headers for empty SELECT resultsets
719  
720 =item C<--bool>
721  
722 Set the exit code to 1 if at least one result row was found
723  
724 =item C<--string>
725  
726 Output the (single) column that the query returns as a string without
727 any headers
728  
729 =item C<--format> formatter
730  
731 Use a different formatter for table output. Supported formatters are
732  
733 tab - output results as tab delimited columns
734  
735 Text::Table - output results as ASCII table
736  
737 =item C<--force>
738  
739 Don't stop on errors
740  
741 =item C<--help>
742  
743 Show this message.
744  
745 =back
746  
747 =cut
748  
749 =head1 NOTES
750  
751 =head2 COMMENT FILTERING
752  
753 The module tries to keep the SQL as much verbatim as possible. It
754 filters all lines that end in semicolons but contain only SQL comments. All
755 other comments are passed through to the database with the next statement.
756  
757 =head2 TRIGGER HANDLING
758  
759 This module uses a very simplicistic approach to recognize triggers.
760 Triggers are problematic because they consist of multiple SQL statements
761 and this module does not implement a full SQL parser. An trigger is
762 recognized by the following sequence of lines
763  
764 CREATE TRIGGER
765 ...
766 END;
767  
768 If your SQL dialect uses a different syntax, it might still work to put
769 the whole trigger on a single line in the input file.
770  
771 =head2 OTHER APPROACHES
772  
773 If you find yourself wanting to write SELECT statements,
774 consider looking at L<Querylet> instead, which is geared towards that
775 and even has an interface for Excel or HTML output.
776  
777 If you find yourself wanting to write parametrized queries as
778 C<.sql> files, consider looking at L<Data::Phrasebook::SQL>
779 or potentially L<DBIx::SQLHandler>.
780  
781 =head1 SEE ALSO
782  
783 L<ORLite::Migrate>
784  
785 L<Test::SQLite> - SQLite setup/teardown for tests, mostly geared towards
786 testing, not general database setup
787  
788 =head1 REPOSITORY
789  
790 The public repository of this module is
791 L<https://github.com/Corion/DBIx--RunSQL>.
792  
793 =head1 SUPPORT
794  
795 The public support forum of this module is
796 L<https://perlmonks.org/>.
797  
798 =head1 BUG TRACKER
799  
800 Please report bugs in this module via the RT CPAN bug queue at
801 L<https://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-RunSQL>
802 or via mail to L<bug-dbix-runsql@rt.cpan.org>.
803  
804 =head1 AUTHOR
805  
806 Max Maischein C<corion@cpan.org>
807  
808 =head1 COPYRIGHT (c)
809  
810 Copyright 2009-2021 by Max Maischein C<corion@cpan.org>.
811  
812 =head1 LICENSE
813  
814 This module is released under the same terms as Perl itself.
815  
816 =cut
↑ Summary script/run-sql.pl »