lib/DBIx/RunSQL.pm

filter: Statementstmt 35.1% 57 / 162 Branchbran 17.7% 16 / 90 Conditioncond 24.3% 9 / 37 MC/DCmcdc 21.7% 5 / 23 Subroutinesub 63.1% 12 / 19 Podpod 87.5% 7 / 8 totaltotal 31.2% 106 / 339 CC 60 SCAR 46.8
CC
60
Cov
28%
run_sql
240.0
format_results
240.0
split_sql
67.0
CRAP 107.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.28';
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 0 ▶sub create {
Subroutine create: not called CC=6 SCAR=37.4
Pod documented
101 0 my ($self,%args) = @_;
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 0 ▶sub run_sql_file {
Subroutine run_sql_file: not called CC=3 SCAR=24.8
Pod documented
198 0 my ($self,%args) = @_;
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 0 ▶sub run_sql {
Subroutine run_sql: not called CC=15 SCAR=54.8
Pod documented
279 0 my ($self,%args) = @_;
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 0 ▶ $args{ verbose_handler } = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
285 0 print { $args{ verbose_fh } } "$_[0]\n";
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 0 ▶sub _nullstr {
Subroutine _nullstr: not called CC=2 SCAR=17.9
393 0 my $str = shift;
394 0 ▶ map { defined $_ ? $_ : $str } @_
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 0 0 0
395 }
396  
397 0 ▶sub format_results {
Subroutine format_results: not called CC=15 SCAR=54.8
Pod documented
398 0 my( $self, %options )= @_;
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 3 ▶sub next_sql {
Subroutine next_sql: called CC=2 SCAR=6.9
Pod undocumented
499 3 ▶ $_[1] =~ /\G\s*(\S.*?)(?:;[ \t]*\r?\n|\s*;?\s*\z)/sg
Branch: 1 branch
BranchTrueFalseTotal
$_[1] =~ /\G\s*(\S.*?)(?:;[ \t]*\r?\n|\s*;?\s*\z)/gsu or return undef 2 1 3
500 or return undef;
501 2 return "$1";
502 }
503  
504 3 ▶sub split_sql {
Subroutine split_sql: called CC=12 SCAR=42.0
Pod documented
505 3 my $self = shift;
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  
525 2 ▶ if( $statement =~ /^\s*CREATE\s+TRIGGER\b/mi ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($statement =~ /^\s*CREATE\s+TRIGGER\b/imu) 0 2 2
526 0 my $trigger;
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; if (defined $next) { $trigger .= "\n" unless $trigger =~ /\n\z/u; $trigger .= $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 ▶ if( defined $next ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $next) 0 0 0
536 0 ▶ $trigger .= "\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $trigger =~ /\n\z/u 0 0 0
537 unless $trigger =~ /\n\z/;
538 0 $trigger .= $next
539 };
540 } until ((! defined $next) or ($next =~ /END;?$/i));
541 } else {
542 # Single-line CREATE TRIGGER statement
543 0 $trigger = $statement;
544 }
545 0 $statement = $trigger;
546 };
547  
548 2 return $statement
549 }
550  
551 11 1;
552  
553 =head2 C<< DBIx::RunSQL->parse_command_line >>
554  
555 my $options = DBIx::RunSQL->parse_command_line( 'my_application', \@ARGV );
556  
557 Helper function to turn a command line array into options for DBIx::RunSQL
558 invocations. The array of command line items is modified in-place.
559  
560 If the reference to the array of command line items is missing, C<@ARGV>
561 will be modified instead.
562  
563 =cut
564  
565 4 ▶sub parse_command_line {
Subroutine parse_command_line: called CC=8 SCAR=20.9
Pod documented
566 4 my ($package,$appname,$argv) = @_;
567 4 require Getopt::Long; Getopt::Long->import('GetOptionsFromArray');
568  
569 4 ▶ if (! $argv) { $argv = \@ARGV };
Branch: 1 branch
BranchTrueFalseTotal
unless ($argv) 1 3 4
570  
571 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
572 'user=s' => \my $user,
573 'password=s' => \my $password,
574 'dsn=s' => \my $dsn,
575 'verbose' => \my $verbose,
576 'force|f' => \my $force,
577 'sql=s' => \my $sql,
578 'bool' => \my $output_bool,
579 'string' => \my $output_string,
580 'quiet' => \my $no_header_when_empty,
581 'format=s' => \my $formatter_class,
582 'rotate' => \my $rotate,
583 'null=s' => \my $nullstr,
584 'help|h' => \my $help,
585 'man' => \my $man,
586 )) {
587 11 ▶ no warnings 'newline';
Subroutine BEGIN: called CC=1 SCAR=0.0
588 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
589 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
590 2 $sql = \"$sql",
591 };
592 4 my $fh;
593 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
594 # Assume we'll read the SQL from stdin
595 2 $fh = \*STDIN;
596 };
597 return {
598 4 user => $user,
599 password => $password,
600 dsn => $dsn,
601 verbose => $verbose,
602 force => $force,
603 sql => $sql,
604 fh => $fh,
605 no_header_when_empty => $no_header_when_empty,
606 output_bool => $output_bool,
607 output_string => $output_string,
608 formatter => $formatter_class,
609 rotate => $rotate,
610 null => $nullstr,
611 help => $help,
612 man => $man,
613 };
614 } else {
615 0 return undef;
616 };
617 }
618  
619 4 ▶sub handle_command_line {
Subroutine handle_command_line: called CC=5 SCAR=16.4
Pod documented
620 4 my ($package,$appname,$argv) = @_;
621 4 require Pod::Usage; Pod::Usage->import();
622  
623 4 ▶ my $opts = $package->parse_command_line($appname,$argv)
Branch: 1 branch
BranchTrueFalseTotal
my $opts = $package->parse_command_line($appname, $argv) or pod2usage(2) 4 0 4
624 or pod2usage(2);
625 4 ▶ pod2usage(1) if $opts->{help};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"help"} 0 4 4
626 4 ▶ pod2usage(-verbose => 2) if $opts->{man};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"man"} 0 4 4
627  
628 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
629 4 my( $dbh, $exitcode) = $package->create(
630 %$opts
631 );
632 4 return $exitcode
633 }
634  
635 =head2 C<< DBIx::RunSQL->handle_command_line >>
636  
637 DBIx::RunSQL->handle_command_line( 'my_application', \@ARGV );
638  
639 Helper function to run the module functionality from the command line. See below
640 how to use this function in a good self-contained script.
641 This function
642 passes the following command line arguments and options to C<< ->create >>:
643  
644 --user
645 --password
646 --dsn
647 --sql
648 --quiet
649 --format
650 --force
651 --verbose
652 --bool
653 --string
654 --rotate
655 --null
656  
657 In addition, it handles the following switches through L<Pod::Usage>:
658  
659 --help
660 --man
661  
662 If no SQL is given, this function will read the SQL from STDIN.
663  
664 If no dsn is given, this function will use
665 C< dbi:SQLite:dbname=db/$appname.sqlite >
666 as the default database.
667  
668 See also the section PROGRAMMER USAGE for a sample program to set
669 up a database from an SQL file.
670  
671 =head1 PROGRAMMER USAGE
672  
673 This module abstracts away the "run these SQL statements to set up
674 your database" into a module. In some situations you want to give the
675 setup SQL to a database admin, but in other situations, for example testing,
676 you want to run the SQL statements against an in-memory database. This
677 module abstracts away the reading of SQL from a file and allows for various
678 command line parameters to be passed in. A skeleton C<create-db.pl>
679 looks like this:
680  
681 #!/usr/bin/perl -w
682 use strict;
683 use DBIx::RunSQL;
684  
685 my $exitcode = DBIx::RunSQL->handle_command_line('myapp', \@ARGV);
686 exit $exitcode;
687  
688 =head1 NAME
689  
690 create-db.pl - Create the database
691  
692 =head1 SYNOPSIS
693  
694 create-db.pl "select * from mytable where 1=0"
695  
696 =head1 ABSTRACT
697  
698 This sets up the database. The following
699 options are recognized:
700  
701 =head1 OPTIONS
702  
703 =over 4
704  
705 =item C<--user> USERNAME
706  
707 =item C<--password> PASSWORD
708  
709 =item C<--dsn> DSN
710  
711 The DBI DSN to use for connecting to
712 the database
713  
714 =item C<--sql> SQLFILE
715  
716 The alternative SQL file to use
717 instead of C<sql/create.sql>.
718  
719 =item C<--quiet>
720  
721 Output no headers for empty SELECT resultsets
722  
723 =item C<--bool>
724  
725 Set the exit code to 1 if at least one result row was found
726  
727 =item C<--string>
728  
729 Output the (single) column that the query returns as a string without
730 any headers
731  
732 =item C<--format> formatter
733  
734 Use a different formatter for table output. Supported formatters are
735  
736 tab - output results as tab delimited columns
737  
738 Text::Table - output results as ASCII table
739  
740 =item C<--force>
741  
742 Don't stop on errors
743  
744 =item C<--help>
745  
746 Show this message.
747  
748 =back
749  
750 =cut
751  
752 =head1 NOTES
753  
754 =head2 COMMENT FILTERING
755  
756 The module tries to keep the SQL as much verbatim as possible. It
757 filters all lines that end in semicolons but contain only SQL comments. All
758 other comments are passed through to the database with the next statement.
759  
760 =head2 TRIGGER HANDLING
761  
762 This module uses a very simplicistic approach to recognize triggers.
763 Triggers are problematic because they consist of multiple SQL statements
764 and this module does not implement a full SQL parser. An trigger is
765 recognized by the following sequence of lines
766  
767 CREATE TRIGGER
768 ...
769 END;
770  
771 If your SQL dialect uses a different syntax, it might still work to put
772 the whole trigger on a single line in the input file.
773  
774 =head2 OTHER APPROACHES
775  
776 If you find yourself wanting to write SELECT statements,
777 consider looking at L<Querylet> instead, which is geared towards that
778 and even has an interface for Excel or HTML output.
779  
780 If you find yourself wanting to write parametrized queries as
781 C<.sql> files, consider looking at L<Data::Phrasebook::SQL>
782 or potentially L<DBIx::SQLHandler>.
783  
784 =head1 SEE ALSO
785  
786 L<ORLite::Migrate>
787  
788 L<Test::SQLite> - SQLite setup/teardown for tests, mostly geared towards
789 testing, not general database setup
790  
791 =head1 REPOSITORY
792  
793 The public repository of this module is
794 L<https://github.com/Corion/DBIx--RunSQL>.
795  
796 =head1 SUPPORT
797  
798 The public support forum of this module is
799 L<https://perlmonks.org/>.
800  
801 =head1 BUG TRACKER
802  
803 Please report bugs in this module via the RT CPAN bug queue at
804 L<https://rt.cpan.org/Public/Dist/Display.html?Name=DBIx-RunSQL>
805 or via mail to L<bug-dbix-runsql@rt.cpan.org>.
806  
807 =head1 AUTHOR
808  
809 Max Maischein C<corion@cpan.org>
810  
811 =head1 COPYRIGHT (c)
812  
813 Copyright 2009-2021 by Max Maischein C<corion@cpan.org>.
814  
815 =head1 LICENSE
816  
817 This module is released under the same terms as Perl itself.
818  
819 =cut
↑ Summary script/run-sql.pl »