testsuite: Make some tests more stable.
[parallel.git] / src / sql
blob4444ea54841a002dbbba2f9d2e6d7bfbc62540b4
1 #!/usr/bin/perl -w
3 =head1 NAME
5 sql - execute a command on a database determined by a dburl
7 =head1 SYNOPSIS
9 B<sql> [options] I<dburl> [I<commands>]
11 B<sql> [options] I<dburl> < commandfile
13 B<#!/usr/bin/sql> B<--shebang> [options] I<dburl>
15 =head1 DESCRIPTION
17 GNU B<sql> aims to give a simple, unified interface for accessing
18 databases through all the different databases' command line
19 clients. So far the focus has been on giving a common way to specify
20 login information (protocol, username, password, hostname, and port
21 number), size (database and table size), and running queries.
23 The database is addressed using a DBURL. If I<commands> are left out
24 you will get that database's interactive shell.
26 GNU B<sql> is often used in combination with GNU B<parallel>.
28 =over 9
30 =item I<dburl>
32 A DBURL has the following syntax:
33 [sql:]vendor://
34 [[user][:password]@][host][:port]/[database][?sqlquery]
36 See the section DBURL below.
38 =item I<commands>
40 The SQL commands to run. Each argument will have a newline
41 appended.
43 Example: "SELECT * FROM foo;" "SELECT * FROM bar;"
45 If the arguments contain '\n' or '\x0a' this will be replaced with a
46 newline:
48 Example: "SELECT * FROM foo;\n SELECT * FROM bar;"
50 If no commands are given SQL is read from the keyboard or STDIN.
52 Example: echo 'SELECT * FROM foo;' | sql mysql:///
55 =item B<--db-size>
57 =item B<--dbsize>
59 Size of database. Show the size of the database on disk. For Oracle
60 this requires access to read the table I<dba_data_files> - the user
61 I<system> has that.
64 =item B<--help>
66 =item B<-h>
68 Print a summary of the options to GNU B<sql> and exit.
71 =item B<--html>
73 HTML output. Turn on HTML tabular output.
76 =item B<--show-processlist>
78 =item B<--proclist>
80 =item B<--listproc>
82 Show the list of running queries.
85 =item B<--show-databases>
87 =item B<--showdbs>
89 =item B<--list-databases>
91 =item B<--listdbs>
93 List the databases (table spaces) in the database.
96 =item B<--show-tables>
98 =item B<--list-tables>
100 =item B<--table-list>
102 List the tables in the database.
105 =item B<--noheaders>
107 =item B<--no-headers>
109 =item B<-n>
111 Remove headers and footers and print only tuples. Bug in Oracle: it
112 still prints number of rows found.
115 =item B<-p> I<pass-through>
117 The string following -p will be given to the database connection
118 program as arguments. Multiple -p's will be joined with
119 space. Example: pass '-U' and the user name to the program:
121 I<-p "-U scott"> can also be written I<-p -U -p scott>.
124 =item B<-r>
126 Try 3 times. Short version of I<--retries 3>.
129 =item B<--retries> I<ntimes>
131 Try I<ntimes> times. If the client program returns with an error,
132 retry the command. Default is I<--retries 1>.
135 =item B<--sep> I<string>
137 =item B<-s> I<string>
139 Field separator. Use I<string> as separator between columns.
142 =item B<--skip-first-line>
144 Do not use the first line of input (used by GNU B<sql> itself
145 when called with B<--shebang>).
148 =item B<--table-size>
150 =item B<--tablesize>
152 Size of tables. Show the size of the tables in the database.
155 =item B<--verbose>
157 =item B<-v>
159 Print which command is sent.
162 =item B<--version>
164 =item B<-V>
166 Print the version GNU B<sql> and exit.
169 =item B<--shebang>
171 =item B<-Y>
173 GNU B<sql> can be called as a shebang (#!) command as the first line of a script. Like this:
175 #!/usr/bin/sql -Y mysql:///
177 SELECT * FROM foo;
179 For this to work B<--shebang> or B<-Y> must be set as the first option.
181 =back
183 =head1 DBURL
185 A DBURL has the following syntax:
186 [sql:]vendor://
187 [[user][:password]@][host][:port]/[database][?sqlquery]
189 To quote special characters use %-encoding specified in
190 http://tools.ietf.org/html/rfc3986#section-2.1 (E.g. a password
191 containing '/' would contain '%2F').
193 Examples:
194 mysql://scott:tiger@my.example.com/mydb
195 sql:oracle://scott:tiger@ora.example.com/xe
196 postgresql://scott:tiger@pg.example.com/pgdb
197 pg:///
198 postgresqlssl://scott@pg.example.com:3333/pgdb
199 sql:sqlite2:////tmp/db.sqlite?SELECT * FROM foo;
200 sqlite3:///../db.sqlite3?SELECT%20*%20FROM%20foo;
202 Currently supported vendors: MySQL (mysql), MySQL with SSL (mysqls,
203 mysqlssl), Oracle (oracle, ora), PostgreSQL (postgresql, pg, pgsql,
204 postgres), PostgreSQL with SSL (postgresqlssl, pgs, pgsqlssl,
205 postgresssl, pgssl, postgresqls, pgsqls, postgress), SQLite2 (sqlite,
206 sqlite2), SQLite3 (sqlite3).
208 Aliases must start with ':' and are read from
209 /etc/sql/aliases and ~/.sql/aliases. The user's own
210 ~/.sql/aliases should only be readable by the user.
212 Example of aliases:
214 :myalias1 pg://scott:tiger@pg.example.com/pgdb
215 :myalias2 ora://scott:tiger@ora.example.com/xe
216 # Short form of mysql://`whoami`:nopassword@localhost:3306/`whoami`
217 :myalias3 mysql:///
218 # Short form of mysql://`whoami`:nopassword@localhost:33333/mydb
219 :myalias4 mysql://:33333/mydb
220 # Alias for an alias
221 :m :myalias4
222 # the sortest alias possible
223 : sqlite2:////tmp/db.sqlite
224 # Including an SQL query
225 :query sqlite:////tmp/db.sqlite?SELECT * FROM foo;
227 =head1 EXAMPLES
229 =head2 Get an interactive prompt
231 The most basic use of GNU B<sql> is to get an interactive prompt:
233 B<sql sql:oracle://scott:tiger@ora.example.com/xe>
235 If you have setup an alias you can do:
237 B<sql :myora>
240 =head2 Run a query
242 To run a query directly from the command line:
244 B<sql :myalias "SELECT * FROM foo;">
246 Oracle requires newlines after each statement. This can be done like
247 this:
249 B<sql :myora "SELECT * FROM foo;" "SELECT * FROM bar;">
251 Or this:
253 B<sql :myora "SELECT * FROM foo;\nSELECT * FROM bar;">
256 =head2 Copy a PostgreSQL database
258 To copy a PostgreSQL database use pg_dump to generate the dump and GNU
259 B<sql> to import it:
261 B<pg_dump pg_database | sql pg://scott:tiger@pg.example.com/pgdb>
264 =head2 Empty all tables in a MySQL database
266 Using GNU B<parallel> it is easy to empty all tables without dropping them:
268 B<sql -n mysql:/// 'show tables' | parallel sql mysql:/// DELETE FROM {};>
271 =head2 Drop all tables in a PostgreSQL database
273 To drop all tables in a PostgreSQL database do:
275 B<sql -n pg:/// '\dt' | parallel --colsep '\|' -r sql pg:/// DROP TABLE {2};>
278 =head2 Run as a script
280 Instead of doing:
282 B<sql mysql:/// < sqlfile>
284 you can combine the sqlfile with the DBURL to make a
285 UNIX-script. Create a script called I<demosql>:
287 B<#!/usr/bin/sql -Y mysql:///>
289 B<SELECT * FROM foo;>
291 Then do:
293 B<chmod +x demosql; ./demosql>
296 =head2 Use --colsep to process multiple columns
298 Use GNU B<parallel>'s B<--colsep> to separate columns:
300 B<sql -s '\t' :myalias 'SELECT * FROM foo;' | parallel --colsep '\t' do_stuff {4} {1}>
303 =head2 Retry if the connection fails
305 If the access to the database fails occasionally B<--retries> can help
306 make sure the query succeeds:
308 B<sql --retries 5 :myalias 'SELECT * FROM really_big_foo;'>
311 =head2 Get info about the running database system
313 Show how big the database is:
315 B<sql --db-size :myalias>
317 List the tables:
319 B<sql --list-tables :myalias>
321 List the size of the tables:
323 B<sql --table-size :myalias>
325 List the running processes:
327 B<sql --show-processlist :myalias>
330 =head1 REPORTING BUGS
332 GNU B<sql> is part of GNU B<parallel>. Report bugs to <bug-parallel@gnu.org>.
335 =head1 AUTHOR
337 When using GNU B<sql> for a publication please cite:
339 O. Tange (2011): GNU SQL - A Command Line Tool for Accessing Different
340 Databases Using DBURLs, ;login: The USENIX Magazine, April 2011:29-32.
342 Copyright (C) 2008-2010 Ole Tange http://ole.tange.dk
344 Copyright (C) 2010-2019 Ole Tange, http://ole.tange.dk and Free
345 Software Foundation, Inc.
347 =head1 LICENSE
349 This program is free software; you can redistribute it and/or modify
350 it under the terms of the GNU General Public License as published by
351 the Free Software Foundation; either version 3 of the License, or
352 at your option any later version.
354 This program is distributed in the hope that it will be useful,
355 but WITHOUT ANY WARRANTY; without even the implied warranty of
356 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
357 GNU General Public License for more details.
359 You should have received a copy of the GNU General Public License
360 along with this program. If not, see <http://www.gnu.org/licenses/>.
362 =head2 Documentation license I
364 Permission is granted to copy, distribute and/or modify this documentation
365 under the terms of the GNU Free Documentation License, Version 1.3 or
366 any later version published by the Free Software Foundation; with no
367 Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
368 Texts. A copy of the license is included in the file fdl.txt.
370 =head2 Documentation license II
372 You are free:
374 =over 9
376 =item B<to Share>
378 to copy, distribute and transmit the work
380 =item B<to Remix>
382 to adapt the work
384 =back
386 Under the following conditions:
388 =over 9
390 =item B<Attribution>
392 You must attribute the work in the manner specified by the author or
393 licensor (but not in any way that suggests that they endorse you or
394 your use of the work).
396 =item B<Share Alike>
398 If you alter, transform, or build upon this work, you may distribute
399 the resulting work only under the same, similar or a compatible
400 license.
402 =back
404 With the understanding that:
406 =over 9
408 =item B<Waiver>
410 Any of the above conditions can be waived if you get permission from
411 the copyright holder.
413 =item B<Public Domain>
415 Where the work or any of its elements is in the public domain under
416 applicable law, that status is in no way affected by the license.
418 =item B<Other Rights>
420 In no way are any of the following rights affected by the license:
422 =over 9
424 =item *
426 Your fair dealing or fair use rights, or other applicable
427 copyright exceptions and limitations;
429 =item *
431 The author's moral rights;
433 =item *
435 Rights other persons may have either in the work itself or in
436 how the work is used, such as publicity or privacy rights.
438 =back
440 =item B<Notice>
442 For any reuse or distribution, you must make clear to others the
443 license terms of this work.
445 =back
447 A copy of the full license is included in the file as cc-by-sa.txt.
449 =head1 DEPENDENCIES
451 GNU B<sql> uses Perl. If B<mysql> is installed, MySQL dburls will
452 work. If B<psql> is installed, PostgreSQL dburls will work. If
453 B<sqlite> is installed, SQLite2 dburls will work. If B<sqlite3> is
454 installed, SQLite3 dburls will work. If B<sqlplus> is installed,
455 Oracle dburls will work. If B<rlwrap> is installed, GNU B<sql> will
456 have a command history for Oracle.
459 =head1 FILES
461 ~/.sql/aliases - user's own aliases with DBURLs
463 /etc/sql/aliases - common aliases with DBURLs
466 =head1 SEE ALSO
468 B<mysql>(1), B<psql>(1), B<rlwrap>(1), B<sqlite>(1), B<sqlite3>(1), B<sqlplus>(1)
470 =cut
472 use Getopt::Long;
473 use strict;
474 use File::Temp qw/tempfile tempdir/;
476 parse_options();
478 my $pass_through_options = (defined $::opt_p) ? join(" ",@{$::opt_p}) : "";
479 my $dburl_or_alias = shift;
480 if (not defined $dburl_or_alias) {
481 Usage("No DBURL given");
482 exit -1;
484 my %dburl = parse_dburl(get_alias($dburl_or_alias));
486 my $interactive_command;
487 my $batch_command;
489 my $database_driver = database_driver_alias($dburl{'databasedriver'});
490 if($database_driver eq "mysql" or
491 $database_driver eq "mysqlssl") {
492 ($batch_command,$interactive_command) = mysql_commands($database_driver,%dburl);
493 } elsif($database_driver eq "postgresql" or
494 $database_driver eq "postgresqlssl") {
495 ($batch_command,$interactive_command) = postgresql_commands($database_driver,%dburl);
496 } elsif($database_driver eq "oracle") {
497 ($batch_command,$interactive_command) = oracle_commands($database_driver,%dburl);
498 } elsif($database_driver eq "sqlite" or
499 $database_driver eq "sqlite3") {
500 ($batch_command,$interactive_command) = sqlite_commands($database_driver,%dburl);
503 my $err;
504 my $retries;
505 $retries ||= defined $::opt_retries ? $::opt_retries : undef;
506 $retries ||= defined $::opt_retry ? $::opt_retry * 3 : undef;
507 $retries ||= 1;
509 if(defined $::opt_processlist) {
510 unshift @ARGV, processlist($database_driver,%dburl);
513 if(defined $::opt_tablelist) {
514 unshift @ARGV, tablelist($database_driver,%dburl);
517 if(defined $::opt_dblist) {
518 unshift @ARGV, dblist($database_driver,%dburl);
521 if(defined $::opt_dbsize) {
522 unshift @ARGV, dbsize($database_driver,%dburl);
525 if(defined $::opt_tablesize) {
526 unshift @ARGV, tablesize($database_driver,%dburl);
529 my $queryfile = "";
530 if($dburl{'query'}) {
531 my $fh;
532 ($fh,$queryfile) = tempfile(SUFFIX => ".sql");
533 print $fh $dburl{'query'},"\n";
534 close $fh;
535 $batch_command = "(cat $queryfile;rm $queryfile; cat) | $batch_command";
538 do {
539 if (is_stdin_terminal()) {
540 if(@ARGV) {
541 open(M,"| $batch_command") || die("mysql/psql/sqlplus not in path");
542 for(@ARGV) {
543 s/\\n/\n/g;
544 s/\\x0a/\n/gi;
545 print M "$_\n";
547 close M;
548 } else {
549 $::opt_debug and print "$interactive_command\n";
550 $::opt_verbose and print "$interactive_command\n";
551 system("$interactive_command");
553 } else {
554 if(@ARGV) {
555 open(M,"| $batch_command") || die("mysql/psql/sqlplus not in path");
556 for(@ARGV) {
557 s/\\n/\n/g;
558 s/\\x0a/\n/gi;
559 print M "$_\n";
561 close M;
562 } else {
563 $::opt_debug and print "$batch_command\n";
564 $::opt_verbose and print "$batch_command\n";
565 system("$batch_command");
568 $err = $?>>8;
569 } while (--$retries and $err);
571 $queryfile and unlink $queryfile;
573 $Global::Initfile && unlink $Global::Initfile;
574 exit ($err);
576 sub parse_options {
577 $Global::version = 20181223;
578 $Global::progname = 'sql';
580 # This must be done first as this may exec myself
581 if(defined $ARGV[0] and ($ARGV[0]=~/^-Y/ or $ARGV[0]=~/^--shebang /)) {
582 # Program is called from #! line in script
583 $ARGV[0]=~s/^-Y //; # remove -Y if on its own
584 $ARGV[0]=~s/^-Y/-/; # remove -Y if bundled with other options
585 $ARGV[0]=~s/^--shebang //; # remove --shebang if it is set
586 my $argfile = pop @ARGV;
587 # exec myself to split @ARGV into separate fields
588 exec "$0 --skip-first-line < $argfile @ARGV";
590 Getopt::Long::Configure ("bundling","require_order");
591 GetOptions("passthrough|p=s@" => \$::opt_p,
592 "sep|s=s" => \$::opt_s,
593 "html" => \$::opt_html,
594 "show-processlist|proclist|listproc" => \$::opt_processlist,
595 "show-tables|showtables|listtables|list-tables|tablelist|table-list"
596 => \$::opt_tablelist,
597 "dblist|".
598 "listdb|listdbs|list-db|list-dbs|list-database|".
599 "list-databases|listdatabases|listdatabase|showdb|".
600 "showdbs|show-db|show-dbs|show-database|show-databases|".
601 "showdatabases|showdatabase" => \$::opt_dblist,
602 "db-size|dbsize" => \$::opt_dbsize,
603 "table-size|tablesize" => \$::opt_tablesize,
604 "noheaders|no-headers|n" => \$::opt_n,
605 "r" => \$::opt_retry,
606 "retries=s" => \$::opt_retries,
607 "debug|D" => \$::opt_debug,
608 # Shebang #!/usr/bin/parallel -Yotheroptions
609 "Y|shebang" => \$::opt_shebang,
610 "skip-first-line" => \$::opt_skip_first_line,
611 # GNU requirements
612 "help|h" => \$::opt_help,
613 "version|V" => \$::opt_version,
614 "verbose|v" => \$::opt_verbose,
615 ) || die_usage();
617 if(defined $::opt_help) { die_usage(); }
618 if(defined $::opt_version) { version(); exit(0); }
619 $Global::debug = $::opt_debug;
622 sub database_driver_alias {
623 my $driver = shift;
624 my %database_driver_alias = ("mysql" => "mysql",
625 "mysqls" => "mysqlssl",
626 "mysqlssl" => "mysqlssl",
627 "oracle" => "oracle",
628 "ora" => "oracle",
629 "oracles" => "oraclessl",
630 "oras" => "oraclessl",
631 "oraclessl" => "oraclessl",
632 "orassl" => "oraclessl",
633 "postgresql" => "postgresql",
634 "pgsql" => "postgresql",
635 "postgres" => "postgresql",
636 "pg" => "postgresql",
637 "postgresqlssl" => "postgresqlssl",
638 "pgsqlssl" => "postgresqlssl",
639 "postgresssl" => "postgresqlssl",
640 "pgssl" => "postgresqlssl",
641 "postgresqls" => "postgresqlssl",
642 "pgsqls" => "postgresqlssl",
643 "postgress" => "postgresqlssl",
644 "pgs" => "postgresqlssl",
645 "sqlite" => "sqlite",
646 "sqlite2" => "sqlite",
647 "sqlite3" => "sqlite3",
649 return $database_driver_alias{$driver};
652 sub mysql_commands {
653 my ($database_driver,%opt) = (@_);
654 find_command_in_path("mysql") || die ("mysql not in path");
655 if(defined($::opt_s)) { die "Field separator not implemented for mysql" }
656 my $password = defined($opt{'password'}) ? "--password=".$opt{'password'} : "";
657 my $host = defined($opt{'host'}) ? "--host=".$opt{'host'} : "";
658 my $port = defined($opt{'port'}) ? "--port=".$opt{'port'} : "";
659 my $user = defined($opt{'user'}) ? "--user=".$opt{'user'} : "";
660 my $database = defined($opt{'database'}) ? $opt{'database'} : $ENV{'USER'};
661 my $html = defined($::opt_html) ? "--html" : "";
662 my $no_headers = defined($::opt_n) ? "--skip-column-names" : "";
663 my $ssl = "";
664 if ($database_driver eq "mysqlssl") {
665 $ssl="--ssl";
667 my($credential_fh,$tmp) = tempfile(SUFFIX => ".sql");
668 chmod (0600,$tmp);
669 print $credential_fh ("[client]\n",
670 $user && "user=$opt{'user'}\n",
671 $password && "password=$opt{'password'}\n",
672 $host && "host=$opt{'host'}\n");
673 close $credential_fh;
675 # Prepend with a remover of the credential tempfile
676 # -C: Compression if both ends support it
677 $batch_command =
678 "((sleep 1; rm $tmp) & ".
679 "mysql --defaults-extra-file=$tmp -C $pass_through_options $no_headers $html $ssl $host $user $port $database)";
680 $interactive_command = $batch_command;
681 return($batch_command,$interactive_command);
684 sub postgresql_commands {
685 my ($database_driver,%opt) = (@_);
686 find_command_in_path("psql") || die ("psql not in path");
687 my $sep = ($::opt_s) ? "-A --field-separator '$::opt_s'" : "";
688 my $password = defined($opt{'password'}) ? "PGPASSWORD=".$opt{'password'} : "";
689 my $host = defined($opt{'host'}) ? "-h ".$opt{'host'} : "";
690 my $port = defined($opt{'port'}) ? "-p ".$opt{'port'} : "";
691 my $user = defined($opt{'user'}) ? "-U ".$opt{'user'} : "";
692 my $database = defined($opt{'database'}) ? "-d ".$opt{'database'} : "";
693 my $html = defined($::opt_html) ? "--html" : "";
694 my $no_headers = defined($::opt_n) ? "--tuples-only" : "";
695 my $ssl = "";
696 if ($database_driver eq "postgresqlssl") {
697 $ssl="PGSSLMODE=require";
699 $batch_command =
700 "$ssl $password psql $pass_through_options $sep $no_headers $html $host $user $port $database";
701 $interactive_command = $batch_command;
703 return($batch_command,$interactive_command);
706 sub oracle_commands {
707 my ($database_driver,%opt) = (@_);
708 # oracle://user:pass@grum:1521/XE becomes:
709 # sqlplus 'user/pass@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = grum)(PORT = 1521)) (CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = XE) ))'
710 my $sqlplus = find_command_in_path("sqlplus") ||
711 find_command_in_path("sqlplus64") or
712 die ("sqlplus/sqlplus64 not in path");
714 # Readline support: if rlwrap installed run rlwrap sqlplus
715 my $rlwrap = find_command_in_path("rlwrap");
717 # Set good defaults in the inifile
718 $Global::Initfile = "/tmp/$$.sql.init";
719 open(INIT,">".$Global::Initfile) || die;
720 print INIT "SET LINESIZE 32767\n";
721 $::opt_debug and print "SET LINESIZE 32767\n";
722 print INIT "SET WRAP OFF\n";
723 $::opt_debug and print "SET WRAP OFF\n";
724 if(defined($::opt_html)) {
725 print INIT "SET MARK HTML ON\n";
726 $::opt_debug and print "SET MARK HTML ON\n";
728 if(defined($::opt_n)) {
729 print INIT "SET PAGES 0\n";
730 $::opt_debug and print "SET PAGES 0\n";
731 } else {
732 print INIT "SET PAGES 50000\n";
733 $::opt_debug and print "SET PAGES 50000\n";
735 if(defined($::opt_s)) {
736 print INIT "SET COLSEP $::opt_s\n";
737 $::opt_debug and print "SET COLSEP $::opt_s\n";
739 close INIT;
741 my $password = defined($opt{'password'}) ? "/".$opt{'password'} : "";
742 my $host = defined($opt{'host'}) ? $opt{'host'} : "localhost";
743 my $port = defined($opt{'port'}) ? $opt{'port'} : "1521";
744 my $user = defined($opt{'user'}) ? $opt{'user'} : "";
745 # Database is called service in Oracle lingo
746 my $service = defined($opt{'database'}) ? "(SERVICE_NAME = ".$opt{'database'}.")" : "";
747 my $tns = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = $host)(PORT = $port)) ".
748 "(CONNECT_DATA =(SERVER = DEDICATED)$service ))";
749 my $ssl = "";
750 # -L: Do not re-ask for password if it is wrong
751 my $common_options = "-L $pass_through_options '$user$password\@$tns' \@$Global::Initfile";
752 my $batch_command = "$sqlplus -S ".$common_options;
753 my $interactive_command = "$rlwrap $sqlplus ".$common_options;
754 return($batch_command,$interactive_command);
757 sub sqlite_commands {
758 my ($database_driver,%opt) = (@_);
759 if(not find_command_in_path($database_driver)) {
760 print STDERR "Database driver '$database_driver' not supported\n";
761 exit -1;
763 my $sep = defined($::opt_s) ? "-separator '$::opt_s'" : "";
764 my $password = defined($opt{'password'}) ? "--password=".$opt{'password'} : "";
765 my $host = defined($opt{'host'}) ? "--host=".$opt{'host'} : "";
766 my $port = defined($opt{'port'}) ? "--port=".$opt{'port'} : "";
767 my $user = defined($opt{'user'}) ? "--user=".$opt{'user'} : "";
768 my $database = defined($opt{'database'}) ? $opt{'database'} : "";
769 my $html = defined($::opt_html) ? "-html" : "";
770 my $no_headers = defined($::opt_n) ? "-noheader" : "-header";
771 my $ssl = "";
772 $batch_command =
773 "$database_driver $pass_through_options $sep $no_headers $html $database";
774 $interactive_command = $batch_command;
775 return($batch_command,$interactive_command);
779 # Return the code for 'show processlist' in the chosen database dialect
780 sub processlist {
781 my $dbdriver = shift;
782 my %dburl = @_;
783 my %statement =
784 ("mysql" => "show processlist;",
785 "postgresql" => ("SELECT ".
786 " datname AS database,".
787 " usename AS username,".
788 " now()-xact_start AS runtime,".
789 " current_query ".
790 "FROM pg_stat_activity ".
791 "ORDER BY runtime DESC;"),
792 "oracle" => ("SELECT ".
793 ' CPU_TIME/100000, SYS.V_$SQL.SQL_TEXT, USERNAME '.
794 "FROM ".
795 ' SYS.V_$SQL, SYS.V_$SESSION '.
796 "WHERE ".
797 ' SYS.V_$SQL.SQL_ID = SYS.V_$SESSION.SQL_ID(+) '.
798 "AND username IS NOT NULL ".
799 "ORDER BY CPU_TIME DESC;"),
801 if($statement{$dbdriver}) {
802 return $statement{$dbdriver};
803 } else {
804 print STDERR "processlist is not implemented for $dbdriver\n";
805 exit 1;
809 # Return the code for 'show tables' in the chosen database dialect
810 sub tablelist {
811 my $dbdriver = shift;
812 my %dburl = @_;
813 my %statement =
814 ("mysql" => "show tables;",
815 "postgresql" => '\dt',
816 "oracle" => ("SELECT object_name FROM user_objects WHERE object_type = 'TABLE';"),
817 "sqlite" => ".tables",
818 "sqlite3" => ".tables",
820 if($statement{$dbdriver}) {
821 return $statement{$dbdriver};
822 } else {
823 print STDERR "tablelist is not implemented for $dbdriver\n";
824 exit 1;
828 # Return the code for 'show databases' in the chosen database dialect
829 sub dblist {
830 my $dbdriver = shift;
831 my %dburl = @_;
832 my %statement =
833 ("mysql" => "show databases;",
834 "postgresql" => ("SELECT datname FROM pg_database ".
835 "WHERE datname NOT IN ('template0','template1','postgres') ".
836 "ORDER BY datname ASC;"),
837 "oracle" => ("select * from user_tablespaces;"),
839 if($statement{$dbdriver}) {
840 return $statement{$dbdriver};
841 } else {
842 print STDERR "dblist is not implemented for $dbdriver\n";
843 exit 1;
847 # Return the code for 'show database size' in the chosen database dialect
848 sub dbsize {
849 my $dbdriver = shift;
850 my %dburl = @_;
851 my %statement;
852 if(defined $dburl{'database'}) {
853 %statement =
854 ("mysql" => (
855 'SELECT '.
856 ' table_schema "database", '.
857 ' SUM(data_length+index_length) "bytes", '.
858 ' SUM(data_length+index_length)/1024/1024 "megabytes" '.
859 'FROM information_schema.TABLES '.
860 "WHERE table_schema = '$dburl{'database'}'".
861 'GROUP BY table_schema;'),
862 "postgresql" => (
863 "SELECT '$dburl{'database'}' AS database, ".
864 "pg_database_size('$dburl{'database'}') AS bytes, ".
865 "pg_size_pretty(pg_database_size('$dburl{'database'}')) AS human_readabable "),
866 "sqlite" => (
867 "SELECT ".(undef_as_zero(-s $dburl{'database'}))." AS bytes;"),
868 "sqlite3" => (
869 "SELECT ".(undef_as_zero(-s $dburl{'database'}))." AS bytes;"),
871 } else {
872 %statement =
873 ("mysql" => (
874 'SELECT '.
875 ' table_schema "database", '.
876 ' SUM(data_length+index_length) "bytes", '.
877 ' SUM(data_length+index_length)/1024/1024 "megabytes" '.
878 'FROM information_schema.TABLES '.
879 'GROUP BY table_schema;'),
880 "postgresql" => (
881 'SELECT datname AS database, pg_database_size(datname) AS bytes, '.
882 'pg_size_pretty(pg_database_size(datname)) AS human_readabable '.
883 'FROM (SELECT datname FROM pg_database) a;'),
884 "sqlite" => (
885 "SELECT 0 AS bytes;"),
886 "sqlite3" => (
887 "SELECT 0 AS bytes;"),
890 if($statement{$dbdriver}) {
891 return $statement{$dbdriver};
892 } else {
893 print STDERR "dbsize is not implemented for $dbdriver\n";
894 exit 1;
899 # Return the code for 'show table size' in the chosen database dialect
900 sub tablesize {
901 my $dbdriver = shift;
902 my $database = shift;
903 my %statement =
904 ("postgresql" => (
905 "SELECT relname, relpages*8 AS kb, reltuples::int AS \"live+dead rows\" ".
906 "FROM pg_class c ".
907 "ORDER BY relpages DESC;"),
908 "mysql" => (
909 "select table_name, TABLE_ROWS, DATA_LENGTH,INDEX_LENGTH from INFORMATION_SCHEMA.tables;"),
911 if($statement{$dbdriver}) {
912 return $statement{$dbdriver};
913 } else {
914 print STDERR "table size is not implemented for $dbdriver\n";
915 exit 1;
919 sub is_stdin_terminal {
920 return (-t STDIN);
923 sub find_command_in_path {
924 # Find the command if it exists in the current path
925 my $command = shift;
926 my $path = `which $command`;
927 chomp $path;
928 return $path;
931 sub Usage {
932 if(@_) {
933 print "Error:\n";
934 print map{ "$_\n" } @_;
935 print "\n";
937 print "sql [-hnr] [--table-size] [--db-size] [-p pass-through] [-s string] dburl [command]\n";
940 sub get_alias {
941 my $alias = shift;
942 $alias =~ s/^(sql:)*//; # Accept aliases prepended with sql:
943 if ($alias !~ /^:/) {
944 return $alias;
947 # Find the alias
948 my $path;
949 if (-l $0) {
950 ($path) = readlink($0) =~ m|^(.*)/|;
951 } else {
952 ($path) = $0 =~ m|^(.*)/|;
955 my @deprecated = ("$ENV{HOME}/.dburl.aliases",
956 "$path/dburl.aliases", "$path/dburl.aliases.dist");
957 for (@deprecated) {
958 if(-r $_) {
959 print STDERR "$_ is deprecated. Use .sql/aliases instead (read man sql)\n";
962 my @urlalias=();
963 check_permissions("$ENV{HOME}/.sql/aliases");
964 check_permissions("$ENV{HOME}/.dburl.aliases");
965 my @search = ("$ENV{HOME}/.sql/aliases",
966 "$ENV{HOME}/.dburl.aliases", "/etc/sql/aliases",
967 "$path/dburl.aliases", "$path/dburl.aliases.dist");
968 for my $alias_file (@search) {
969 if(-r $alias_file) {
970 push @urlalias, `cat "$alias_file"`;
973 my ($alias_part,$rest) = $alias=~/(:\w*)(.*)/;
974 # If we saw this before: we have an alias loop
975 if(grep {$_ eq $alias_part } @Private::seen_aliases) {
976 print STDERR "$alias_part is a cyclic alias\n";
977 exit -1;
978 } else {
979 push @Private::seen_aliases, $alias_part;
982 my $dburl;
983 for (@urlalias) {
984 /^$alias_part\s+(\S+.*)/ and do { $dburl = $1; last; }
987 if($dburl) {
988 return get_alias($dburl.$rest);
989 } else {
990 Usage("$alias is not defined in @search");
991 exit(-1);
995 sub check_permissions {
996 my $file = shift;
998 if(-e $file) {
999 if(not -o $file) {
1000 my $username = (getpwuid($<))[0];
1001 print STDERR "$file should be owned by $username: chown $username $file\n";
1003 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
1004 $atime,$mtime,$ctime,$blksize,$blocks) = stat($file);
1005 if($mode & 077) {
1006 my $username = (getpwuid($<))[0];
1007 print STDERR "$file should be only be readable by $username: chmod 600 $file\n";
1012 sub parse_dburl {
1013 my $url = shift;
1014 my %options = ();
1015 # sql:mysql://[[user][:password]@][host][:port]/[database[?sql query]]
1017 if($url=~m!(?:sql:)? # You can prefix with 'sql:'
1018 ((?:oracle|ora|mysql|pg|postgres|postgresql)(?:s|ssl|)|
1019 (?:sqlite|sqlite2|sqlite3)):// # Databasedriver ($1)
1021 ([^:@/][^:@]*|) # Username ($2)
1023 :([^@]*) # Password ($3)
1026 ([^:/]*)? # Hostname ($4)
1029 ([^/]*)? # Port ($5)
1033 ([^?/]*)? # Database ($6)
1038 (.*)? # Query ($7)
1040 !x) {
1041 $options{databasedriver} = undef_if_empty(uri_unescape($1));
1042 $options{user} = undef_if_empty(uri_unescape($2));
1043 $options{password} = undef_if_empty(uri_unescape($3));
1044 $options{host} = undef_if_empty(uri_unescape($4));
1045 $options{port} = undef_if_empty(uri_unescape($5));
1046 $options{database} = undef_if_empty(uri_unescape($6))
1047 || $options{user};
1048 $options{query} = undef_if_empty(uri_unescape($7));
1049 debug("dburl $url\n");
1050 debug("databasedriver ",$options{databasedriver}, " user ", $options{user},
1051 " password ", $options{password}, " host ", $options{host},
1052 " port ", $options{port}, " database ", $options{database},
1053 " query ",$options{query}, "\n");
1054 } else {
1055 Usage("$url is not a valid DBURL");
1056 exit -1;
1058 return %options;
1061 sub uri_unescape {
1062 # Copied from http://cpansearch.perl.org/src/GAAS/URI-1.55/URI/Escape.pm
1063 # to avoid depending on URI::Escape
1064 # This section is (C) Gisle Aas.
1065 # Note from RFC1630: "Sequences which start with a percent sign
1066 # but are not followed by two hexadecimal characters are reserved
1067 # for future extension"
1068 my $str = shift;
1069 if (@_ && wantarray) {
1070 # not executed for the common case of a single argument
1071 my @str = ($str, @_); # need to copy
1072 foreach (@str) {
1073 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
1075 return @str;
1077 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if defined $str;
1078 $str;
1081 sub undef_if_empty {
1082 if(defined($_[0]) and $_[0] eq "") {
1083 return undef;
1085 return $_[0];
1088 sub undef_as_zero {
1089 my $a = shift;
1090 return $a ? $a : 0;
1093 sub version {
1094 # Returns: N/A
1095 print join("\n",
1096 "GNU $Global::progname $Global::version",
1097 "Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016,2017",
1098 "Ole Tange and Free Software Foundation, Inc.",
1099 "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>",
1100 "This is free software: you are free to change and redistribute it.",
1101 "GNU $Global::progname comes with no warranty.",
1103 "Web site: http://www.gnu.org/software/${Global::progname}\n",
1104 "When using GNU $Global::progname for a publication please cite:\n",
1105 "O. Tange (2011): GNU SQL - A Command Line Tool for Accessing Different",
1106 "Databases Using DBURLs, ;login: The USENIX Magazine, April 2011:29-32.\n"
1110 sub die_usage {
1111 # Returns: N/A
1112 usage();
1113 exit(255);
1116 sub usage {
1117 # Returns: N/A
1118 print "Usage:\n";
1119 print "$Global::progname [options] dburl [sqlcommand]\n";
1120 print "$Global::progname [options] dburl < sql_command_file\n";
1121 print "\n";
1122 print "See 'man $Global::progname' for the options\n";
1125 sub debug {
1126 # Returns: N/A
1127 $Global::debug or return;
1128 @_ = grep { defined $_ ? $_ : "" } @_;
1129 print @_;
1132 $::opt_skip_first_line = $::opt_shebang = 0;