forked from datamuc/yasqlng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyasql.in
executable file
·5207 lines (4400 loc) · 167 KB
/
yasql.in
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env perl
# vim: set ts=8 smartindent shiftwidth=2 expandtab ai :
#
# Name: yasql - Yet Another SQL*Plus replacement
#
# See POD documentation at end
#
# $Id: yasql,v 1.83 2005/05/09 16:57:13 qzy Exp qzy $
#
# Copyright (C) 2000 Ephibian, Inc.
# Copyright (C) 2005 iMind.dev, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Yasql was originally developed by Nathan Shafer at Ephibian, Inc.
# Now it is mainly developed and maintained by Balint Kozman at iMind.dev, Inc.
#
# email: [email protected]
# email: [email protected]
# email: [email protected]
#
use strict;
use SelfLoader;
use DBI;
use Term::ReadLine;
use Data::Dumper;
use Benchmark;
use Getopt::Long;
# Load DBD::Oracle early to work around SunOS bug. See
# http://article.gmane.org/gmane.comp.lang.perl.modules.dbi.general/207
#
require DBD::Oracle;
#Globals
use vars qw(
$VERSION $Id $dbh $cursth @dbparams $dbuser $dbversion $term $term_type
$features $attribs $last_history $num_connects $connected $running_query
@completion_list @completion_possibles $completion_built $opt_host $opt_sid
$opt_port $opt_debug $opt_bench $opt_nocomp $opt_version $qbuffer
$last_qbuffer $fbuffer $last_fbuffer $quote $inquotes $inplsqlblock $increate
$incomment $csv_filehandle_open $csv_max_lines $nohires $notextcsv $csv
$sysconf $sysconfdir $quitting $sigintcaught %conf %prompt $prompt_length
@sqlpath %set $opt_batch $opt_notbatch $opt_headers
);
select((select(STDOUT), $| = 1)[0]); #unbuffer STDOUT
$sysconfdir = "/etc";
$sysconf = "$sysconfdir/yasql.conf";
# try to include Time::HiRes for fine grained benchmarking
eval q{
use Time::HiRes qw (gettimeofday tv_interval);
};
# try to include Text::CSV_XS for input and output of CSV data
eval q{
use Text::CSV_XS;
};
if($@) {
$notextcsv = 1;
}
# install signal handlers
sub setup_sigs {
$SIG{INT} = \&sighandle;
$SIG{TSTP} = 'DEFAULT';
$SIG{TERM} = \&sighandle;
}
setup_sigs();
# install a filter on the __WARN__ handler so that we can get rid of
# DBD::Oracle's stupid ORACLE_HOME warning. It would warn even if we don't
# connect using a TNS name, which doesn't require access to the ORACLE_HOME
$SIG{__WARN__} = sub{
warn(@_) unless $_[0] =~ /environment variable not set!/;
};
# initialize the whole thing
init();
if($@) {
if(!$opt_batch) {
wrn("Time::HiRes not installed. Please install if you want benchmark times "
."to include milliseconds.");
}
$nohires = 1;
}
$connected = 1;
# start the interface
interface();
# end
################################################################################
########### non-self-loaded functions ########################################
sub BEGIN {
$VERSION = 'unknown';
}
sub argv_sort {
if($a =~ /^\@/ && $b !~ /^\@/) {
return 1;
} elsif($a !~ /^\@/ && $b =~ /^\@/) {
return -1;
} else {
return 0;
}
}
sub sighandle {
my($sig) = @_;
debugmsg(3, "sighandle called", @_);
$SIG{$sig} = \&sighandle;
if($sig =~ /INT|TERM|TSTP/) {
if($quitting) {
# then we've already started quitting and so we just try to force exit
# without the graceful quit
print STDERR "Attempting to force exit...\n";
exit();
}
if($sigintcaught) {
# the user has alrady hit INT and so we now force an exit
print STDERR "Caught another SIG$sig\n";
quit(undef, 1);
} else {
$sigintcaught = 1;
}
if($running_query) {
if(defined $cursth) {
print STDERR "Attempting to cancel query...\n";
debugmsg(1, "canceling statement handle");
my $ret = $cursth->cancel();
$cursth->finish;
}
} elsif(!$connected) {
quit();
if(defined $cursth) {
print STDERR "Attempting to cancel query...\n";
debugmsg(1, "canceling statement handle");
my $ret = $cursth->cancel();
$cursth->finish;
}
}
} elsif($sig eq 'ALRM') {
if(defined $dbh) {
wrn("Connection lost (timeout: $conf{connection_timeout})");
quit(1);
} else {
lerr("Could not connect to database, timed out. (timeout: "
."$conf{connection_timeout})");
}
}
}
sub END {
debugmsg(3, "END called", @_);
# save the history buffer
if($term_type && $term_type eq 'gnu' && $term->history_total_bytes()) {
debugmsg(1, "Writing history");
unless($term->WriteHistory($conf{history_file})) {
wrn("Could not write history file to $conf{history_file}. "
."History not saved");
}
}
}
################################################################################
########### self-loaded functions ##############################################
#__DATA__
sub init {
# call GetOptions to parse the command line
my $opt_help;
Getopt::Long::Configure( qw(permute) );
$Getopt::Long::ignorecase = 0;
usage(1) unless GetOptions(
"debug|d:i" => \$opt_debug,
"host|H=s" => \$opt_host,
"port|p=s" => \$opt_port,
"sid|s=s" => \$opt_sid,
"help|h|?" => \$opt_help,
"nocomp|A" => \$opt_nocomp,
"bench|benchmark|b" => \$opt_bench,
"version|V" => \$opt_version,
"batch|B" => \$opt_batch,
"interactive|I" => \$opt_notbatch,
);
# set opt_debug to 1 if it's defined, which means the user just put -d or
# --debug without an integer argument
$opt_debug = 1 if !$opt_debug && defined $opt_debug;
$opt_batch = 0 if $opt_notbatch;
$opt_batch = 1 unless defined $opt_batch || -t STDIN;
debugmsg(3, "init called", @_);
# This reads the command line then initializes the DBI and Term::ReadLine
# packages
$sigintcaught = 0;
$completion_built = 0;
usage(0) if $opt_help;
# Output startup string
if(!$opt_batch) {
print STDERR "\n";
print STDERR "YASQL version $VERSION Copyright (c) 2000-2001 Ephibian, Inc, 2005 iMind.dev.\n";
print STDERR '$Id: yasql,v 1.83 2005/05/09 02:07:13 qzy Exp qzy $' . "\n";
}
if($opt_version) {
print STDERR "\n";
exit(0);
}
if(!$opt_batch) {
print STDERR "Please type 'help' for usage instructions\n";
print STDERR "\n";
}
# parse the config files. We first look for ~/.yasqlrc, then
# /etc/yasql.conf
# first set up the defaults
%conf = (
connection_timeout => 20,
max_connection_attempts => 3,
history_file => '~/.yasql_history',
pager => '/bin/more',
auto_commit => 0,
commit_on_exit => 1,
long_trunc_ok => 1,
long_read_len => 80,
edit_history => 1,
auto_complete => 1,
extended_benchmarks => 0,
prompt => '%U%H',
column_wildcards => 0,
extended_complete_list => 0,
command_complete_list => 1,
sql_query_in_error => 0,
nls_date_format => 'YYYY-MM-DD HH24:MI:SS',
complete_tables => 1,
complete_columns => 1,
complete_objects => 1,
fast_describe => 1,
server_output => 2000,
);
my $config_file;
if( -e $ENV{YASQLCONF} ) {
$config_file = $ENV{YASQLCONF};
} elsif(-e "$ENV{HOME}/.yasqlrc") {
$config_file = "$ENV{HOME}/.yasqlrc";
} elsif(-e $sysconf) {
$config_file = $sysconf;
}
if($config_file) {
debugmsg(2, "Reading config: $config_file");
open(CONFIG, "$config_file");
while(<CONFIG>) {
chomp;
s/#.*//;
s/^\s+//;
s/\s+$//;
next unless length;
my($var, $value) = split(/\s*=\s*/, $_, 2);
$var = 'auto_commit' if $var eq 'AutoCommit';
$var = 'commit_on_exit' if $var eq 'CommitOnExit';
$var = 'long_trunc_ok' if $var eq 'LongTruncOk';
$var = 'long_read_len' if $var eq 'LongReadLen';
$conf{$var} = $value;
debugmsg(3, "Setting option [$var] to [$value]");
}
}
if (($conf{server_output} > 0) && ($conf{server_output} < 2000)) {
$conf{server_output} = 2000;
}
if ($conf{server_output} > 1000000) {
$conf{server_output} = 1000000;
}
($conf{history_file}) = glob($conf{history_file});
debugmsg(3,"Conf: [" . Dumper(\%conf) . "]");
# Create a Text::CSV object
unless($notextcsv) {
$csv = new Text::CSV_XS( { binary => 1 } );
}
# Change the process name to just 'yasql' to somewhat help with security.
# This is not bullet proof, nor is it supported on all platforms. Those that
# don't support this will just fail silently.
debugmsg(2, "Process name: $0");
$0 = 'yasql';
# Parse the SQLPATH environment variable if it exists
if($ENV{SQLPATH}) {
@sqlpath = split(/;/, $ENV{SQLPATH});
}
# If the user set the SID on the command line, we'll overwrite the
# environment variable so that DBI sees it.
#print "Using SID $opt_sid\n" if $opt_sid;
$ENV{ORACLE_SID} = $opt_sid if $opt_sid;
# output info about the options given
print STDERR "Debugging is on\n" if $opt_debug;
DBI->trace(1) if $opt_debug > 3;
# Extending on from Oracle's conventions, try and obtain an early indication
# of ora_session_mode from AS SYSOPER, AS SYSDBA options. Be flexible :-)
my $ora_session_mode = 0;
my $osmp = '';
if (lc($ARGV[-2]) eq 'as') {
$ora_session_mode = 2 if lc($ARGV[-1]) eq 'sysdba';
$ora_session_mode = 4 if lc($ARGV[-1]) eq 'sysoper';
pop @ARGV;
pop @ARGV;
} elsif (lc($ARGV[1]) eq 'as') {
$ora_session_mode = 2 if lc($ARGV[2]) eq 'sysdba';
$ora_session_mode = 4 if lc($ARGV[2]) eq 'sysoper';
@ARGV = ($ARGV[0], @ARGV[3..$#ARGV]);
}
# set up DBI
if(@ARGV == 0) {
# nothing was provided
debugmsg(2, "No command line args were found");
$dbh = db_connect(1, $ora_session_mode);
} else {
debugmsg(2, "command line args found!");
debugmsg(2, @ARGV);
# an argument was given!
my $script = 0;
if(substr($ARGV[0], 0, 1) eq '@') {
# no logon string was given, must be a script
debugmsg(2, "Found: no logon, script name");
my($script_name, @script_params) = @ARGV;
$script = 1;
$dbh = db_connect(1, $ora_session_mode);
run_script($script_name);
} elsif(substr($ARGV[0], 0, 1) ne '@' && substr($ARGV[1], 0, 1) eq '@') {
# A logon string was given as well as a script file
debugmsg(2, "Found: login string, script name");
my($logon_string, $script_name, @script_params) = @ARGV;
$script = 1;
my($ora_session_mode2, $username, $password, $connect_string)
= parse_logon_string($logon_string);
$ora_session_mode = $ora_session_mode2 if $ora_session_mode2;
$dbh = db_connect(1, $ora_session_mode, $username, $password, $connect_string);
run_script($script_name);
} elsif(@ARGV == 1 && substr($ARGV[0], 0, 1) ne '@') {
# only a logon string was given
debugmsg(2, "Found: login string, no script name");
my($logon_string) = @ARGV;
my($ora_session_mode2, $username, $password, $connect_string)
= parse_logon_string($logon_string);
$ora_session_mode = $ora_session_mode2 if $ora_session_mode2;
$dbh = db_connect(1, $ora_session_mode, $username, $password, $connect_string);
} else {
usage(1);
}
if ($conf{server_output} > 0) {
$dbh->func( $conf{server_output}, 'dbms_output_enable' );
$set{serveroutput} = 1;
}
# Quit if one or more scripts were given on the command-line
quit(0) if $script;
}
if (!$opt_batch) {
setup_term() unless $term;
}
# set up the pager
$conf{pager} = $ENV{PAGER} if $ENV{PAGER};
}
sub setup_term {
# set up the Term::ReadLine
$term = new Term::ReadLine('YASQL');
$term->ornaments(0);
$term->MinLine(0);
debugmsg(1, "Using " . $term->ReadLine());
if($term->ReadLine eq 'Term::ReadLine::Gnu') {
# Term::ReadLine::Gnu specific setup
$term_type = 'gnu';
$attribs = $term->Attribs();
$features = $term->Features();
$term->stifle_history(500);
if($opt_debug >= 4) {
foreach(sort keys(%$attribs)) {
debugmsg(4,"[term-attrib] $_: $attribs->{$_}");
}
foreach(sort keys(%$features)) {
debugmsg(4,"[term-feature] $_: $features->{$_}");
}
}
# read in the ~/.yasql_history file
if(-e $conf{history_file}) {
unless($term->ReadHistory($conf{history_file})) {
wrn("Could not read $conf{history_file}. History not restored");
}
} else {
print STDERR "Creating $conf{history_file} to store your command line history\n";
open(HISTORY, ">$conf{history_file}")
or wrn("Could not create $conf{history_file}: $!");
close(HISTORY);
}
$last_history = $term->history_get($term->{history_length});
$attribs->{completion_entry_function} = \&complete_entry_function;
my $completer_word_break_characters
= $attribs->{completer_word_break_characters};
$completer_word_break_characters =~ s/[a-zA-Z0-9_\$\#]//g;
$attribs->{completer_word_break_characters}
= $completer_word_break_characters;
#$attribs->{catch_signals} = 0;
} elsif($term->ReadLine eq 'Term::ReadLine::Perl') {
# Term::ReadLine::Perl specific setup
$term_type = 'perl';
if($opt_debug >= 4) {
foreach(sort keys(%{$term->Features()})) {
debugmsg(4,"[term-feature] $_: $attribs->{$_}");
}
}
}
if ($term->ReadLine eq 'Term::ReadLine::Stub') {
wrn("Neither Term::ReadLine::Gnu or Term::ReadLine::Perl are installed.\n"
. "Please install from CPAN for advanced functionality. Until then "
. "YASQL will run\ncrippled. (like possibly not having command history "
. "or line editing...\n");
}
}
sub parse_logon_string {
debugmsg(3, "parse_logon_string called", @_);
my($arg) = @_;
my($ora_session_mode, $username, $password, $connect_string);
# strip off AS SYSDBA / AS SYSOPER first
if($arg =~ /^(.*)\s+as\s+sys(\w+)\s*$/i) {
$ora_session_mode = 2 if lc($2) eq 'dba';
$ora_session_mode = 4 if lc($2) eq 'oper';
$arg = $1 if $ora_session_mode;
$ora_session_mode = 0 unless $ora_session_mode;
}
if($arg =~ /^\/$/) {
$username = '';
$password = '';
$connect_string = 'external';
return($ora_session_mode, $username, $password, $connect_string);
} elsif($arg eq 'internal') {
$username = '';
$password = '';
$connect_string = 'external';
$ora_session_mode = 2;
return($ora_session_mode, $username, $password, $connect_string);
} elsif($arg =~ /^([^\/]+)\/([^\@]+)\@(.*)$/) {
#username/password@connect_string
$username = $1;
$password = $2;
$connect_string = $3;
return($ora_session_mode, $username, $password, $connect_string);
} elsif($arg =~ /^([^\@]+)\@(.*)$/) {
# username@connect_string
$username = $1;
$password = '';
$connect_string = $2;
return($ora_session_mode, $username, $password, $connect_string);
} elsif($arg =~ /^([^\/]+)\/([^\@]+)$/) {
# username/password
$username = $1;
$password = $2;
$connect_string = '';
return($ora_session_mode, $username, $password, $connect_string);
} elsif($arg =~ /^([^\/\@]+)$/) {
# username
$username = $1;
$password = $2;
$connect_string = '';
return($ora_session_mode, $username, $password, $connect_string);
} elsif($arg =~ /^\@(.*)$/) {
# @connect_string
$username = '';
$password = '';
$connect_string = $1;
return($ora_session_mode, $username, $password, $connect_string);
} else {
return(undef,undef,undef,undef);
}
}
sub populate_completion_list {
my($inline_print, $current_table_name) = @_;
debugmsg(3, "populate_completion_list called", @_);
# grab all the table and column names and put them in @completion_list
if($inline_print) {
$| = 1;
print STDERR "...";
} else {
print STDERR "Generating auto-complete list...\n";
}
if($conf{extended_complete_list}) {
my @queries;
if($conf{complete_tables}) {
push(@queries, '
select table_name x from all_tables union
select view_name x from all_views union
select synonym_name x from all_synonyms
');
}
if($conf{complete_columns}) {
push(@queries, 'select column_name from all_tab_columns');
}
if($conf{complete_objects}) {
push(@queries, 'select object_name from all_objects');
}
my $sqlstr = join(' union ', @queries);
debugmsg(3, "query: [$sqlstr]");
my $sth = $dbh->prepare($sqlstr)
or query_err('prepare', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
$sth->execute()
or query_err('execute', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
while(my $res = $sth->fetchrow_array()) {
push(@completion_list, $res);
}
} else {
my @queries;
if($conf{complete_tables}) {
push(@queries, "
select 'table-' || table_name x from user_tables union
select 'table-' || view_name x from user_views union
select 'table-' || synonym_name x from user_synonyms
");
}
if($conf{complete_columns}) {
push(@queries, "select 'column-' || column_name from user_tab_columns");
}
if($conf{complete_objects}) {
push(@queries, "select 'object-' || object_name from user_objects");
}
my $sqlstr = join(' union ', @queries);
debugmsg(3, "query: [$sqlstr]");
my $sth = $dbh->prepare($sqlstr)
or query_err('prepare', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
$sth->execute()
or query_err('execute', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
while(my $res = $sth->fetchrow_array()) {
push(@completion_list, $res);
}
}
if ($conf{command_complete_list}) {
push(@completion_list, qw{
command-create command-select command-insert command-update
command-delete from command-from command-execute command-show
command-describe command-drop
});
push(@completion_list, qw{
show-objects show-tables show-indexes show-sequences show-views
show-functions show-constraints show-keys show-checks show-triggers
show-query show-dimensions show-clusters show-procedures show-packages
show-indextypes show-libraries show-materialized views show-snapshots
show-synonyms show-waits show-processes show-errors show-user show-users
show-uid show-plan show-database links show-dblinksshow-recyclebin
show-dependencies
});
}
if ($current_table_name) {
my @queries;
push(@queries, "select 'current_column-$current_table_name.' || column_name from user_tab_columns where table_name=\'".uc($current_table_name)."\'");
my $sqlstr = join(' union ', @queries);
debugmsg(3, "query: [$sqlstr]");
my $sth = $dbh->prepare($sqlstr)
or query_err('prepare', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
$sth->execute()
or query_err('execute', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
while(my $res = $sth->fetchrow_array()) {
push(@completion_list, $res);
}
}
setup_sigs();
if($inline_print) {
print "\r";
print "[K";
$| = 0;
$term->forced_update_display();
}
}
sub complete_entry_function {
my($word, $state) = @_;
debugmsg(3, "complete_entry_function called", @_);
# This is called by Term::ReadLine::Gnu when a list of matches needs to
# be generated. It takes a string that is the word to be completed and
# a state number, which should increment every time it's called.
return unless $connected;
my $line_buffer = $attribs->{line_buffer};
debugmsg(4, "line_buffer: [$line_buffer]");
if($line_buffer =~ /^\s*\@/) {
return($term->filename_completion_function(@_));
}
unless($completion_built) {
unless($opt_nocomp || !$conf{auto_complete}) {
populate_completion_list(1);
}
$completion_built = 1;
}
if($state == 0) {
# compute all the possibilies and put them in @completion_possibles
@completion_possibles = ();
my $last_char = substr($word,length($word)-1,1);
debugmsg(2,"last_char: [$last_char]");
my @grep = ();
if ($line_buffer =~ /select(?!.*(?:from|where))[\s\w\$\#_,]*\.[\w_]*$/) {
# This case is for "select mytable.mycolumn" type lines
my $current_table_name = $line_buffer;
$current_table_name =~ s/(select.*)(\s)([\w_]+)(\.)([\w_]*)$/$3/;
debugmsg(3, "current table name: $current_table_name");
unless($opt_nocomp || !$conf{auto_complete}) {
populate_completion_list(1, $current_table_name);
}
debugmsg(4, "select table.column");
push(@grep, '^current_column-');
} elsif($line_buffer =~ /select(?!.*(?:from|where))[\s\w\$\#_,]+$/) {
debugmsg(4, "select ...");
push(@grep, '^column-', '^table-');
} elsif($line_buffer =~ /from(?!.*where)[\s\w\$\#_,]*$/) {
debugmsg(4, "from ...");
push(@grep, '^table-');
} elsif($line_buffer =~ /where[\s\w\$\#_,]*$/) {
debugmsg(4, "where ...");
push(@grep, '^column-');
} elsif($line_buffer =~ /update(?!.*set)[\s\w\$\#_,]*$/) {
debugmsg(4, "where ...");
push(@grep, '^table-');
} elsif($line_buffer =~ /set[\s\w\$\#_,]*$/) {
debugmsg(4, "where ...");
push(@grep, '^column-');
} elsif($line_buffer =~ /insert.*into(?!.*values)[\s\w\$\#_,]*$/) {
debugmsg(4, "where ...");
push(@grep, '^table-');
} elsif($line_buffer =~ /^\s*show\s+(deps|dependencies)\s+\w+/) {
push(@grep, 'table-');
} elsif($line_buffer =~ /^\s*show\s\w*/) {
push(@grep, 'show-');
} else {
push(@grep, '');
}
debugmsg(2,"grep: [@grep]");
my $use_lower;
if($last_char =~ /^[A-Z]$/) {
$use_lower = 0;
} else {
$use_lower = 1;
}
foreach my $grep (@grep) {
foreach my $list_item (grep(/$grep/, @completion_list)) {
my $item = $list_item;
$item =~ s/^\w*-//;
eval { #Trap errors
if($item =~ /^\Q$word\E/i) {
push(@completion_possibles,
($use_lower ? lc($item) : uc($item))
);
}
};
debugmsg(2, "Trapped error in complete_entry_function eval: $@") if $@;
}
}
debugmsg(3,"possibles: [@completion_possibles]");
}
# return the '$state'th element of the possibles
return($completion_possibles[$state] || undef);
}
sub db_reconnect {
debugmsg(3, "db_reconnect called", @_);
# This first disconnects the database, then tries to reconnect
print "Reconnecting...\n";
commit_on_exit();
if (defined $dbh) {
if (not $dbh->disconnect()) {
warn "Disconnect failed: $DBI::errstr\n";
return;
}
}
$dbh = db_connect(1, @dbparams);
}
sub db_connect {
my($die_on_error, $ora_session_mode, $username, $password, $connect_string) = @_;
debugmsg(3, "db_connect called", @_);
# Tries to connect to the database, prompting for username and password
# if not given. There are several cases that can happen:
# connect_string is present:
# ORACLE_HOME has to exist and the driver tries to make a connection to
# given connect_string.
# connect_string is not present:
# $opt_host is set:
# Connect to $opt_host on $opt_sid. Specify port only if $opt_port is
# set
# $opt_host is not set:
# Try to make connection to the default database by not specifying any
# host or connect string
my($dbhandle, $dberr, $dberrstr, $this_prompt_host, $this_prompt_user);
debugmsg(1,"ora_session_mode: [$ora_session_mode] username: [$username] password: [$password] connect_string: [$connect_string]");
# The first thing we're going to check is that the Oracle DBD is available
# since it's a sorta required element =)
my @drivers = DBI->available_drivers();
my $found = 0;
foreach(@drivers) {
if($_ eq "Oracle") {
$found = 1;
}
}
unless($found) {
lerr("Could not find DBD::Oracle... please install. Available drivers: "
.join(", ", @drivers) . ".\n");
}
#print "drivers: [" . join("|", @drivers) . "]\n";
# Now we can attempt a connection to the database
my $attributes = {
RaiseError => 0,
PrintError => 0,
AutoCommit => $conf{auto_commit},
LongReadLen => $conf{long_read_len},
LongTruncOk => $conf{long_trunc_ok},
ora_session_mode => $ora_session_mode
};
if($connect_string eq 'external') {
# the user wants to connect with external authentication
check_oracle_home();
# install alarm signal handle
$SIG{ALRM} = \&sighandle;
alarm($conf{connection_timeout});
if(!$opt_batch) {
print "Attempting connection to local database\n";
}
$dbhandle = DBI->connect('dbi:Oracle:',undef,undef,$attributes)
or do {
$dberr = $DBI::err;
$dberrstr = $DBI::errstr;
};
$this_prompt_host = $ENV{ORACLE_SID};
$this_prompt_user = $ENV{LOGNAME};
alarm(0); # cancel alarm
} elsif($connect_string) {
# We were provided with a connect string, so we can use the TNS method
check_oracle_home();
($ora_session_mode, $username, $password) = get_up($ora_session_mode, $username, $password);
$attributes->{ora_session_mode} = $ora_session_mode if $ora_session_mode;
my $userstring;
if($username) {
$userstring = $username . '@' . $connect_string;
} else {
$userstring = $connect_string;
}
# install alarm signal handle
$SIG{ALRM} = \&sighandle;
alarm($conf{connection_timeout});
if(!$opt_batch) {
print "Attempting connection to $userstring\n";
}
$dbhandle = DBI->connect('dbi:Oracle:',$userstring,$password,$attributes)
or do {
$dberr = $DBI::err;
$dberrstr = $DBI::errstr;
};
$this_prompt_host = $connect_string;
$this_prompt_user = $username;
alarm(0); # cancel alarm
} elsif($opt_host) {
# attempt a connection to $opt_host
my $dsn;
$dsn = "host=$opt_host";
$dsn .= ";sid=$opt_sid" if $opt_sid;
$dsn .= ";port=$opt_port" if $opt_port;
($ora_session_mode, $username, $password) = get_up($ora_session_mode, $username, $password);
$attributes->{ora_session_mode} = $ora_session_mode if $ora_session_mode;
# install alarm signal handle
$SIG{ALRM} = \&sighandle;
alarm($conf{connection_timeout});
print "Attempting connection to $opt_host\n";
debugmsg(1,"dsn: [$dsn]");
$dbhandle = DBI->connect("dbi:Oracle:$dsn",$username,$password,
$attributes)
or do {
$dberr = $DBI::err;
$dberrstr = $DBI::errstr;
};
$this_prompt_host = $opt_host;
$this_prompt_host = "$opt_sid!" . $this_prompt_host if $opt_sid;
$this_prompt_user = $username;
alarm(0); # cancel alarm
} else {
# attempt a connection without specifying a hostname or anything
check_oracle_home();
($ora_session_mode, $username, $password) = get_up($ora_session_mode, $username, $password);
$attributes->{ora_session_mode} = $ora_session_mode if $ora_session_mode;
# install alarm signal handle
$SIG{ALRM} = \&sighandle;
alarm($conf{connection_timeout});
print "Attempting connection to local database\n";
$dbhandle = DBI->connect('dbi:Oracle:',$username,$password,$attributes)
or do {
$dberr = $DBI::err;
$dberrstr = $DBI::errstr;
};
$this_prompt_host = $ENV{ORACLE_SID};
$this_prompt_user = $username;
alarm(0); # cancel alarm
}
if($dbhandle) {
# Save the parameters for reconnecting
@dbparams = ($ora_session_mode, $username, $password, $connect_string);
# set the $dbuser global for use elsewhere
$dbuser = $username;
$num_connects = 0;
$prompt{host} = $this_prompt_host;
$prompt{user} = $this_prompt_user;
# Get the version banner
debugmsg(2,"Fetching version banner");
my $banner = $dbhandle->selectrow_array(
"select banner from v\$version where banner like 'Oracle%'");
if(!$opt_batch) {
if($banner) {
print "Connected to: $banner\n\n";
} else {
print "Connection successful!\n";
}
}
if($banner =~ / (\d+)\.(\d+)\.([\d\.]+)/) {
my ($major, $minor, $other) = ($1, $2, $3);
$dbversion = $major || 8;
}
# Issue a warning about autocommit. It's nice to know...
print STDERR "auto_commit is " . ($conf{auto_commit} ? "ON" : "OFF")
. ", commit_on_exit is " . ($conf{commit_on_exit} ? "ON" : "OFF")
. "\n" unless $opt_batch;
} elsif( ($dberr eq '1017' || $dberr eq '1005')
&& ++$num_connects < $conf{max_connection_attempts}) {
$dberrstr =~ s/ \(DBD ERROR: OCISessionBegin\).*//;
print "Error: $dberrstr\n\n";
#@dbparams = (0,undef,undef,$connect_string);
$connect_string = '' if $connect_string eq 'external';
$dbhandle = db_connect($die_on_error,$ora_session_mode,undef,undef,$connect_string);
} elsif($die_on_error) {
lerr("Could not connect to database: $dberrstr [$dberr]");
} else {
wrn("Could not connect to database: $dberrstr [$dberr]");
return(0);
}
# set the NLS_DATE_FORMAT
if($conf{nls_date_format}) {
debugmsg(2, "setting NLS_DATE_FORMAT to $conf{nls_date_format}");
my $sqlstr = "alter session set nls_date_format = '"
. $conf{nls_date_format} . "'";
$dbhandle->do($sqlstr) or query_err('do', $DBI::errstr, $sqlstr);
}
$connected = 1;
return($dbhandle);
}
sub get_prompt {
my($prompt_string) = @_;
debugmsg(3, "get_prompt called", @_);
# This returns a prompt. It can be passed a string which will
# be manually put into the prompt. It will be padded on the left with
# white space
$prompt_length ||= 5; #just in case normal prompt hasn't been outputted
debugmsg(2, "prompt_length: [$prompt_length]");
if($prompt_string) {
my $temp_prompt = sprintf('%' . $prompt_length . 's', $prompt_string . '> ');
return($temp_prompt);
} else {
my $temp_prompt = $conf{prompt} . '> ';
my $temp_prompt_host = '@' . $prompt{host} if $prompt{host};
$temp_prompt =~ s/\%H/$temp_prompt_host/g;
$temp_prompt =~ s/\%U/$prompt{user}/g;
$prompt_length = length($temp_prompt);
return($temp_prompt);
}
}
sub get_up {