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