#!/usr/bin/env perl
# vim: set tabstop=2 smartindent shiftwidth=2 expandtab:
#
# Name: yasql - Yet Another SQL*Plus replacement
#
# See POD documentation at end
#
# $Id: yasql,v 1.66 2001/03/13 21:34:58 nshafer Exp nshafer $
#
# Copyright (C) 2000 Ephibian, 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.
#
# email: nshafer@ephibian.com
#

use strict;
use DBI;
use Term::ReadLine;
use Data::Dumper;
use Benchmark;
use Getopt::Long;

use vars qw($dbh $term $tcap $attribs $history_file $cursth @dbparams $dbuser
            $num_connects $connect_in_progress $connected $running_query
            $pager @completion_list @completion_possibles
            $break_timeout $connection_timeout $max_connection_attempts
            $opt_host $opt_sid $opt_port $opt_debug $opt_bench $opt_nocomp
            $qbuffer $last_qbuffer $inquotes $quote $fbuffer $last_fbuffer
            $nohires $version $Id $breakhit $quitting
            $sigintcaught %conf $autocommit
            $prompt_host $prompt_user $prompt_length
            $stty
           );

#Globals
$Id = '$Id: yasql,v 1.66 2001/03/13 21:34:58 nshafer Exp nshafer $';
$Id =~ /v \d+\.(\d+)/;
$version = "1." . $1;

# try to include Time::HiRes for fine grained benchmarking
eval q{
  use Time::HiRes qw (gettimeofday tv_interval);
};
if($@) {
  wrn("Time::HiRes not installed.  Please install if you want benchmark times "
     ."to include milliseconds.");
  $nohires = 1;
}

# install signal handlers
sub setup_sigs() {
  $SIG{INT} = \&sighandle;
  $SIG{TSTP} = \&sighandle;
  $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();

$connected = 1;

# start the interface
interface();

# end



sub init() {
  debugmsg(2, "init called", @_);
  # This reads the command line then initializes the DBI and Term::Readline
  # packages

  $sigintcaught = 0;

  # 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
  );

  usage(1) if $opt_help;

  # 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;

  # 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',
    AutoCommit              => 0,
    CommitOnExit            => 1,
    LongTruncOk             => 1,
    LongReadLen             => 80,
    edit_history            => 1,
    auto_complete           => 1,
    extended_benchmarks     => 0,
    prompt                  => '%U%H',
    column_wildcards        => 1,
    extended_tab_list       => 0,
    sql_query_in_error      => 0
  );

  my $config_file;
  if(-e "$ENV{HOME}/.yasqlrc") {
    $config_file = "$ENV{HOME}/.yasqlrc";
  } elsif(-e "/etc/yasql.conf") {
    $config_file = "/etc/yasql.conf";
  }
  
  if($config_file) {
    debugmsg(3, "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);
      $conf{$var} = $value;
      debugmsg(3, "Setting option [$var] to [$value]");
    }
  }

  ($conf{history_file}) = glob($conf{history_file});

  debugmsg(3,"Conf: [" . Dumper(\%conf) . "]");

  # Output startup string
  print "\nYASQL version $version Copyright (c) 2000 Ephibian, Inc.\n";
  print $Id . "\n";
  print "Please type 'help' for usage instructions\n";
  print "\n";
  
  # Get the output of 'stty -g' so that we can restore the terminal when we
  # exit.  If the command fails then we will just ignore it and hope that the
  # ReadLine library can restore the settings
  $stty = `stty -g`;
  debugmsg(2, "stty: [$stty]");

  # set up the Term::ReadLine
  $term = new Term::ReadLine('YASQL');
  $term->ornaments(0);

  if ($term->ReadLine eq "Term::ReadLine::Gnu") {
    $attribs = $term->Attribs();
    $attribs->{history_length} = '500';
    $attribs->{completion_entry_function} = \&complete_entry_function;

    if($opt_debug >= 4) {
      foreach(sort keys(%$attribs)) {
        debugmsg(4,"[term-attrib] $_: $attribs->{$_}");
      }
      foreach(sort keys(%{$term->Features()})) {
        debugmsg(4,"[term-feature] $_: $attribs->{$_}");
      }
    }
    
    # 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 "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);
    }

  } else {
    wrn("Term::Readline::Gnu not installed.  Please install from CPAN for \n"
       ."advanced functionality.  Until then I will run crippled. (like \n"
       ."possibly not having command history or line editing...\n");
  }
  
  # output info about the options given  
  print "Debugging is on\n" if $opt_debug;
  DBI->trace(1) if $opt_debug > 3;

  # 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;

  # set up the pager
  $conf{pager} = $ENV{PAGER} if $ENV{PAGER};

  # set up DBI
  if(@ARGV == 0) {
    # nothing was provided
    $dbh = db_connect(1);
  } else {
    # an argument was given!

    # sort the arguments so that any script parameters are processed last, after
    # we connect to the DB.
    @ARGV = sort argv_sort @ARGV;
    debugmsg(2, "a argv: [" . join(", ", @ARGV) . "]");

    # check the format of the provided argument
    my $script = 0;
    while( my $arg = shift @ARGV ) {
      if( $arg =~ /^\@/ ) {
        # connect to DB if we haven't already
        unless(defined $dbh) {
          $dbh = db_connect(1);
        }

        # Script file specified on command-line, process it.
        last unless run_script($arg);
        last if( $sigintcaught );
        $script = 1;
      } else {
        my($username, $password, $connect_string) = parse_connect_string($arg);
    
        $dbh = db_connect(1, $username, $password, $connect_string);
      }
    }
    # Quit if one or more scripts were given on the command-line
    quit(0,0) if( $script );
  }

  unless($opt_nocomp || !$conf{auto_complete}) {
    populate_completion_list();
  }
}

sub argv_sort() {
  if($a =~ /^\@/ && $b !~ /^\@/) {
    return 1;
  } elsif($a !~ /^\@/ && $b =~ /^\@/) {
    return -1;
  } else {
    return 0;
  }
}

sub parse_connect_string($) {
  debugmsg(2, "parse_connect_string called", @_);

  my($arg) = @_;
  my($username, $password, $connect_string);

  if($arg =~ /^([^\/]+)\/([^\@]+)\@(.*)$/) {
    #username/password@connect_string
    $username = $1;
    $password = $2;
    $connect_string = $3;
    return($username, $password, $connect_string);
  } elsif($arg =~ /^([^\@]+)\@(.*)$/) {
    # username@connect_string
    $username = $1;
    $password = '';
    $connect_string = $2;
    return($username, $password, $connect_string);
  } elsif($arg =~ /^([^\/]+)\/([^\@]+)$/) {
    # username/password
    $username = $1;
    $password = $2;
    $connect_string = '';
    return($username, $password, $connect_string);
  } elsif($arg =~ /^([^\/\@]+)$/) {
    # username
    $username = $1;
    $password = $2;
    $connect_string = '';
    return($username, $password, $connect_string);
  } elsif($arg =~ /^\@(.*)$/) {
    # @connect_string
    $username = '';
    $password = '';
    $connect_string = $1;
    return($username, $password, $connect_string);
  } else {
    return(undef,undef,undef);
  }
}

sub populate_completion_list() {
  debugmsg(2, "populate_completion_list called", @_);

  # grab all the table and column names and put them in @completion_list
  print "Generating auto-complete list...\n";
  
  if($conf{extended_tab_list}) {
    my $sqlstr = 'select table_name from all_tables';
    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);
    }

    $sqlstr = 'select column_name from all_tab_columns';
    $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);
    }
  
    $sqlstr = 'select object_name from all_objects';
    $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 $sqlstr = 'select table_name from all_tables where owner = ?';
    my $sth = $dbh->prepare($sqlstr)
      or query_err('prepare', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
    $sth->execute(uc($dbuser))
      or query_err('execute', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
    while(my $res = $sth->fetchrow_array()) {
      push(@completion_list, $res);
    }
  
    $sqlstr = 'select column_name from all_tab_columns where owner = ?';
    $sth = $dbh->prepare($sqlstr)
      or query_err('prepare', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
    $sth->execute(uc($dbuser))
      or query_err('execute', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
    while(my $res = $sth->fetchrow_array()) {
      push(@completion_list, $res);
    }
  
    $sqlstr = 'select object_name from all_objects where owner = ?';
    $sth = $dbh->prepare($sqlstr)
      or query_err('prepare', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
    $sth->execute(uc($dbuser))
      or query_err('execute', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
    while(my $res = $sth->fetchrow_array()) {
      push(@completion_list, $res);
    }
  }

  setup_sigs();
}

sub complete_entry_function($$) {
  debugmsg(2, "complete 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.

  my($word, $state) = @_;

  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(3,"last_char: [$last_char]");
    my $use_lower;
    if($last_char =~ /^[A-Z]$/) {
      $use_lower = 0;
    } else {
      $use_lower = 1;
    }
    foreach my $list_item (@completion_list) {
      eval { #Trap errors
        if($list_item =~ /^$word/i) {
          push(@completion_possibles, 
            ($use_lower ? lc($list_item) : uc($list_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(2, "db_reconnect called", @_);
  # This first disconnects the database, then tries to reconnect

  print "Reconnecting...\n";

  # Commit... or not
  if($conf{CommitOnExit}) {
    print "Committing any outstanding transaction...\n";
    $dbh->commit() if defined $dbh && !$dbh->{AutoCommit};
  } else {
    print "Rolling back any outstanding transaction...\n";
    $dbh->rollback() if defined $dbh && !$dbh->{AutoCommit};
  }

  $dbh->disconnect() if defined $dbh;

  $dbh = db_connect(1, @dbparams);
}

sub db_connect($;$$$) {
  debugmsg(2, "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($die_on_error, $username, $password, $connect_string) = @_;
  my($dbhandle, $dberr, $dberrstr);

  debugmsg(1,"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) {
    err("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{AutoCommit}, 
    LongReadLen => $conf{LongReadLen}, LongTruncOk => $conf{LongTruncOk}
  };
  $autocommit = $conf{AutoCommit}; #set the global

  # install alarm signal handle
  $SIG{ALRM} = \&sighandle;

  # set the alarm
  alarm($conf{connection_timeout});
  
  if($connect_string) {
    # We were provided with a connect string, so we can use the TNS method

    check_oracle_home();
    ($username, $password) = get_up($username, $password);

    my $userstring;
    if($username) {
      $userstring = $username . '@' . $connect_string;
    } else {
      $userstring = $connect_string;
    }
    
    print "Attempting connection to $userstring\n";
    $connect_in_progress = 1;
    $dbhandle = DBI->connect('dbi:Oracle:',$userstring,$password,$attributes)
      or do {
        $dberr = $DBI::err;
        $dberrstr = $DBI::errstr;
      };

    $prompt_host = $connect_string;
    $prompt_user = $username;
    $connect_in_progress = 0;
  } 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;

    ($username, $password) = get_up($username, $password);

    print "Attempting connection to $opt_host\n";
    debugmsg(1,"dsn: [$dsn]");
    $connect_in_progress = 1;
    $dbhandle = DBI->connect("dbi:Oracle:$dsn",$username,$password,
                             $attributes)
      or do {
        $dberr = $DBI::err;
        $dberrstr = $DBI::errstr;
      };

    $prompt_host = $opt_host;
    $prompt_host = "$opt_sid!" . $prompt_host if $opt_sid;
    $prompt_user = $username;
    $connect_in_progress = 0;
  } else {
    # attempt a connection without specifying a hostname or anything

    check_oracle_home();
    ($username, $password) = get_up($username, $password);

    print "Attempting connection to default database\n";
    $connect_in_progress = 1;
    $dbhandle = DBI->connect('dbi:Oracle:',$username,$password,$attributes)
      or do {
        $dberr = $DBI::err;
        $dberrstr = $DBI::errstr;
      };

    $prompt_host = $ENV{ORACLE_SID};
    $prompt_user = $username;
    $connect_in_progress = 0;
  }

  if($dbhandle) {
    # Save the parameters for reconnecting
    @dbparams = ($username, $password, $connect_string);

    # set the $dbuser global for use elsewhere
    $dbuser = $username;
    $num_connects = 0;
    print "Connection successful!\n";

    # Issue a warning about autocommit.  It's nice to know...
    print "AutoCommit is " . ($conf{AutoCommit} ? "ON" : "OFF")
        . ", CommitOnExit is " . ($conf{CommitOnExit} ? "ON" : "OFF") . "\n";
  } elsif( ($dberr eq '1017' || $dberr eq '1005') 
      && ++$num_connects < $conf{max_connection_attempts}) {
    wrn("Could not connect to database: $dberrstr");
    #@dbparams = (undef,undef,$connect_string);
    $dbhandle = db_connect($die_on_error,undef,undef,$connect_string);
  } elsif($die_on_error) {
    err("Could not connect to database: $dberrstr [$dberr]");
  } else {
    wrn("Could not connect to database: $dberrstr [$dberr]");
    return(0);
  }
  
  # set the signal handle to 'ignore'
  $SIG{ALRM} = 'IGNORE';
  
  return($dbhandle);
}

sub get_prompt(;$) {
  debugmsg(2, "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
  my $prompt_string = shift;

  $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($$) {
  debugmsg(2, "get_up called", @_);
  # Get username/password

  my($username, $password) = @_;

  unless($username) {
    # prompt for the username
    $username = $term->readline('Username: ');

    # Take that entry off of the history list
    if ($term->ReadLine eq "Term::ReadLine::Gnu") {
      $term->remove_history($term->where_history());
    }
  }
  unless($password) {
    # prompt for the password, and disable echo
    unless ($term->ReadLine eq "Term::ReadLine::Gnu") {
      # Turn off local echo if we don't have the advanced readline library
      `stty -echo`;
    }
    my $orig_redisplay= $attribs->{redisplay_function};
#    if(lc($ENV{TERM}) eq "xterm") {
#      # a workaround for the broken xterm type.  Why it's broken is beyond me,
#      # but it doesn't have the cr (carriage return) and le (cursor left)
#      # entries, which REALLY doesn't make sense to me... I've provided a
#      # yucky workaround so we use that instead of the builtin one.
      $attribs->{redisplay_function} = \&shadow_redisplay;
#    } else {
#      # Use the normal shadow_redisplay that's part of Term::Readline::Gnu
#      $attribs->{redisplay_function} = $attribs->{shadow_redisplay};
#    }
    
    $password = $term->readline('Password: ');
    $attribs->{redisplay_function} = $orig_redisplay;
    unless ($term->ReadLine eq "Term::ReadLine::Gnu") {
      # Turn on local echo
      `stty echo`;
    }

    # Take that entry off of the history list
    if ($term->ReadLine eq "Term::ReadLine::Gnu") {
      $term->remove_history($term->where_history());
    }
  }

  return($username, $password);
}

sub check_oracle_home() {
  # This checks for the ORACLE_HOME environment variable and dies if it's
  # not set
  err("Please set your ORACLE_HOME environment variable!") 
    unless $ENV{ORACLE_HOME};
  return(1);
}

# my own shadow_redisplay, which seems to work on linux and solaris platforms.
# The one provided in Term::ReadLine::Gnu was broken
sub shadow_redisplay {
#  debugmsg(2, "shadow_redisplay called", @_);
  my $OUT = $attribs->{outstream};
  my $oldfh = select($OUT); $| = 1; select($oldfh);
  print $OUT ("\r", $attribs->{prompt});
#  print $OUT ($tcap->Tputs('le') # cursor left
#              x (length($attribs->{line_buffer}) - $attribs->{point}));
  $oldfh = select($OUT); $| = 0; select($oldfh);
}

sub print_non_print {
  my $string = shift;
  my @string = unpack("C*", $string);
  my $ret_string;
  foreach(@string) {
    if($_ >= 40 && $_ <= 176) {
      $ret_string .= chr($_);
    } else {
      $ret_string .= "<$_>";
    }
  }
  return($ret_string);
}

sub interface() {
  debugmsg(2, "interface called", @_);
  # this is the main program loop that handles all the user input.

  my $input;
  my $prompt = get_prompt();
  
  while(defined($input = $term->readline($prompt))) {
    $sigintcaught = 0;
    $prompt = process_input($input, $prompt) || get_prompt();
  }

  quit(0,0);
}

sub process_input($;$) {
  debugmsg(2, "process_input called", @_);

  my $input = shift;
  my $prompt = shift;
  my $nprompt;
  SWITCH: {
    $input =~ /^\s*\\a\s*$/i  and populate_completion_list(),   last SWITCH;
    $input =~ /^\s*help\s*$/i and help(),                       last SWITCH;
    $input =~ /^\s*\?\s*$/i   and help(),                       last SWITCH;
    $input =~ /^\s*quit\s*$/i and quit(0,1),                    last SWITCH;
    $input =~ /^\s*exit\s*$/i and quit(0,1),                    last SWITCH;
    $input =~ /^\s*\\q\s*$/i  and quit(0,1),                    last SWITCH;
    $input =~ /^\s*reconnect\s*$/i and db_reconnect(),          last SWITCH;
    $input =~ /^\s*\\r\s*$/i  and db_reconnect(),               last SWITCH;
    $input =~ /^\s*connect\s*(.*)$/i and connect_cmd($1),       last SWITCH;
    $input =~ /^\s*\\l\s*$/i  and show_qbuffer(),               last SWITCH;
    $input =~ /^\s*l\s*$/i    and show_qbuffer(),               last SWITCH;
    $input =~ /^\s*list\s*$/i and show_qbuffer(),               last SWITCH;
    $input =~ /^\s*\\c\s*$/i  and $nprompt = clear_qbuffer(),   last SWITCH;
    $input =~ /^\s*clear\s*$/i and $nprompt = clear_qbuffer(),  last SWITCH;
    $input =~ /^\s*clear buffer\s*$/i and $nprompt = clear_qbuffer(), 
                                                                last SWITCH;
    $input =~ /^\s*\\e\s*(.*)$/i  and $nprompt = edit($1),      last SWITCH;
    $input =~ /^\s*edit\s*(.*)$/i and $nprompt = edit($1),      last SWITCH;
    $input =~ /^\s*\@\S+$/i   and $nprompt = run_script($input),last SWITCH;
    $input =~ /^\s*debug\s*(.*)$/i and debug_toggle($1),        last SWITCH;
    $input =~ /^\s*autocommit\s*(.*)$/i and autocommit_toggle(),last SWITCH;
    $input =~ /^\s*commit/i and commit_cmd(),                   last SWITCH;
    $input =~ /^\s*rollback/i and rollback_cmd(),               last SWITCH;
    $input =~ /[^\s]/         and $nprompt = parse_input($input) 
                                  || last,                      last SWITCH;
    # default
    $nprompt = $prompt; # use last prompt if nothing caught (blank line)
  }
  return($nprompt);
}

sub parse_input($) {
  debugmsg(2, "parse_input called", @_);
  # this takes input and parses it.  It looks for single quotes (') and double
  # quotes (") and presents prompts accordingly.  It also looks for query 
  # terminators, such as semicolon (;), forward-slash (/) and back-slash-g (\g).
  # If it finds a query terminator, then it pushes any text onto the query
  # buffer ($qbuffer) and then passes the entire query buffer, as well as the
  # format type, determined by the terminator type, to the query() function.  It
  # also wipes out the qbuffer at this time.
  #
  # It returns a prompt (like 'SQL> ' or '  -> ') if successfull, 0 otherwise
  
  my $input = shift;

  my $inputcp = $input;
  while($inputcp =~ s/('|")//) {
    if(!$quote || $quote eq $1) {
      $inquotes = ($inquotes ? 0 : 1);
      if($inquotes) {
        $quote = $1;
      } else {
        undef($quote);
      }
    }
  }
  debugmsg(4,"inquotes: [$inquotes] quote: [$quote]\n");

  # now we need to check for a terminator, if we're not inquotes
  unless($inquotes) {
    if($input =~ s/\s*(;)(\d*)\s*$// || $input =~ s/\s*(\/)(\d*)\s*$// 
       || $input =~ s/\s*(\\[Gg])(\d*)\s*$// 
       || ($input =~ /^\s*(desc|show)\s*\S+/ && !$qbuffer)) {
      $qbuffer .= $input;
      debugmsg(4,"qbuffer: [$qbuffer]\n");

      # deduce the format from the terminator type
      my($format, $num_rows);
      if($1 eq ';' || $1 eq '/') {
        $format = 'table';
        $num_rows = $2;
        $fbuffer = $1;
      } elsif($1 eq '\g') {
        $format = 'list';
        $num_rows = $2;
        $fbuffer = $1;
      } elsif($1 eq '\G') {
        $format = 'list_aligned';
        $num_rows = $2;
        $fbuffer = $1;
      } elsif($1 =~ /^(desc|show)/) {
        $format = 'table';
        $num_rows = undef;
        $fbuffer = undef;
      }
      $num_rows ||= 0;

      debugmsg(4,"fbuffer: [$fbuffer]\n");

      # if there is nothing in the buffer, then we assume that the user just 
      # wants to reexecute the last query, which we have saved in $last_qbuffer
      if($qbuffer) {
        query($qbuffer, $format, $num_rows);
        # copy the current qbuffer to old_qbuffer
        $last_qbuffer = $qbuffer;
        $last_fbuffer = $fbuffer;
      } elsif($last_qbuffer) {
        query($last_qbuffer, $format, $num_rows);
      } else {
        query_err('Query', 'No current query in buffer');
      }

      undef($qbuffer);
      undef($fbuffer);

      # return a 'new' prompt
      return(get_prompt());
    }
  }

  $qbuffer .= $input . "\n";

  debugmsg(4,"qbuffer: [$qbuffer]\n");

  if($inquotes) {
    return(get_prompt($quote));
  } else {
    return(get_prompt('-'));
  }
}

sub connect_cmd($) {
  debugmsg(2, "connect_cmd called", @_);

  my($arg) = @_;

  unless($arg) {
    wrn("Invalid connect syntax.  See help");
    return(0);
  }

  my($username, $password, $connect_string) = parse_connect_string($arg);
  
  my $new_dbh = db_connect(0, $username, $password, $connect_string);
  if($new_dbh) {
    print "Closing last connection...\n";
    # Commit... or not
    if($conf{CommitOnExit}) {
      print "Committing any outstanding transaction...\n";
      $dbh->commit() if defined $dbh && !$dbh->{AutoCommit};
    } else {
      print "Rolling back any outstanding transaction...\n";
      $dbh->rollback() if defined $dbh && !$dbh->{AutoCommit};
    }

    $dbh->disconnect() if defined $dbh;
    $dbh = $new_dbh;
    unless($opt_nocomp || !$conf{auto_complete}) {
      populate_completion_list();
    }
  }
  
}

sub commit_cmd() {
  debugmsg(2, "commit_cmd called", @_);
  # this just called commit

  if(defined $dbh) {
    if($dbh->{AutoCommit}) {
      wrn("commit ineffective with AutoCommit enabled");
    } else {
      $dbh->commit();
      print "Transaction committed\n";
    }
  } else {
    print "No connection\n";
  }
}

sub rollback_cmd() {
  debugmsg(2, "rollback_cmd called", @_);
  # this just called commit

  if(defined $dbh) {
    if($dbh->{AutoCommit}) {
      wrn("rollback ineffective with AutoCommit enabled");
    } else {
      $dbh->rollback();
      print "Transaction rolled back\n";
    }
  } else {
    print "No connection\n";
  }
}

sub edit() {
  debugmsg(2, "edit called", @_);
  # This writes the current qbuffer to a file then opens up an editor on that 
  # file... when the editor returns, we read in the file and overwrite the 
  # qbuffer with it.  If there is nothing in the qbuffer, and there is
  # something in the last_qbuffer, then we use the last_qbuffer.  If nothing
  # is in either, then we just open the editor with a blank file.

  my $filename = shift;
  my $passed_file = 1 if $filename;
  my $filecontents;
  my $prompt = get_prompt();

  debugmsg(2, "passed_file: [$passed_file]");

  if($qbuffer) {
    debugmsg(2, "Using current qbuffer for contents");
    $filecontents = $qbuffer;
  } elsif($last_qbuffer) {
    debugmsg(2, "Using last_qbuffer for contents");
    $filecontents = $last_qbuffer . $last_fbuffer;
  } else {
    debugmsg(2, "Using blank contents");
    $filecontents = "";
  }

  debugmsg(3, "filecontents: [$filecontents]");

  # determine the tmp directory
  my $tmpdir;
  if($ENV{TMP}) {
    $tmpdir = $ENV{TMP};
  } elsif($ENV{TEMP}) {
    $tmpdir = $ENV{TEMP};
  } elsif(-d "/tmp") {
    $tmpdir = "/tmp";
  } else {
    $tmpdir = ".";
  }

  # determine the preferred editor
  my $editor;
  if($ENV{EDITOR}) {
    $editor = $ENV{EDITOR};
  } else {
    $editor = "vi";
  }

  # create the filename, if not given one
  $filename ||= "$tmpdir/yasql_" . int(rand(1000)) . "_$$";

  # expand the filename
  ($filename) = glob($filename);

  debugmsg(1, "Editing $filename with $editor");

  # check for file existance.  If it exists, then we open it up but don't
  # write the buffer to it
  my $file_exists;
  if($passed_file) {
    # if the file was passed, then check for it's existance
    if(-e $filename) {
      # The file was found
      $file_exists = 1;
    } else {
      wrn("$filename was not found, creating new file, which will not be ".
          "deleted");
    }
  } else {
    # no file was specified, so just write to the the temp file, and we
    # don't care if it exists, since there's no way another process could
    # write to the same file at the same time since we use the PID in the
    # filename.
    my $ret = open(TMPFILE, ">$filename");
    if(!$ret) { #if file was NOT opened successfully
      wrn("Could not write to $filename: $!");
    } else {
      print TMPFILE $filecontents;
      close(TMPFILE);
    }
  }

  # now spawn the editor
  my $ret = system($editor, "$filename");
  if($ret) { #if the editor or system returned a positive return value
    wrn("Editor exited with $ret");
  } else {
    # read in the tmp file and apply it's contents to the buffer
    my $ret = open(TMPFILE, "$filename");
    if(!$ret) { # if file was NOT opened successfully
      wrn("Could not read $filename: $!");
    } else {
      # delete our qbuffer and reset the inquotes var
      $qbuffer = "";
      $inquotes = 0;
      while(<TMPFILE>) {
        # chomp off newlines
        chomp;
        
        last if $sigintcaught;
        # now send it in to process_input
        $prompt = process_input($_);
        if ($term->ReadLine eq "Term::ReadLine::Gnu" && $conf{edit_history}) {
          $term->AddHistory($_);
        }
      }
      close(TMPFILE);
    }
  }

  unless($passed_file) {
    # delete the tmp file
    debugmsg(1, "Deleting $filename");
    unlink("$filename") ||
      wrn("Could not unlink $filename: $!");
  }

  # print the buffer
  print "\n";
  print $qbuffer;
  print "\n";

  return($prompt);
}

sub run_script($) {
  debugmsg(2, "run_script called", @_);
  # This reads in the given script and executes it's lines as if they were typed
  # in directly.  It will NOT erase the current buffer before it runs.  It
  # will append the contents of the file to the current buffer, basicly
  my $input = shift;
  my $prompt;

  # parse input
  $input =~ /^\@(.*)$/;
  my $file = $1;
  $file = glob($file);

  # read in the tmp file and apply it's contents to the buffer
  my $ret = open(SCRIPT, $file);
  if(!$ret) { # if file was NOT opened successfully
    wrn("Could not read $file: $!");
    $prompt = get_prompt();
  } else {
    # read in the script
    while(<SCRIPT>) {
      # chomp off newlines
      chomp;

      last if $sigintcaught;
      
      # now send it in to process_input
      $prompt = process_input($_);
    }
    close(SCRIPT);
  }

  return($prompt);
}

sub show_qbuffer() {
  debugmsg(2, "show_qbuffer called", @_);
  # This outputs the current buffer

  #print "\nBuffer:\n";
  print $qbuffer;
  print "\n";
}

sub clear_qbuffer() {
  debugmsg(2, "clear_qbuffer called", @_);
  # This clears the current buffer

  $qbuffer = '';
  $inquotes = 0;
  print "Buffer cleared\n";
  return(get_prompt());
}

sub debug_toggle(;$) {
  debugmsg(2, "debug_toggle called", @_);
  # If nothing is passed, then debugging is turned off if on, on if off.  If
  # a number is passed, then we explicitly set debugging to that number

  my $debuglevel = shift;

  if(length($debuglevel) > 0) {
    unless($debuglevel =~ /^\d+$/) {
      wrn('Debug level must be an integer');
      return(1);
    }

    $opt_debug = $debuglevel;
  } else {
    if($opt_debug) {
      $opt_debug = 0;
    } else {
      $opt_debug = 1;
    }
  }
  $opt_debug > 3 ? DBI->trace(1) : DBI->trace(0);
  print "** debug is now " . ($opt_debug ? "level $opt_debug" : 'off') . "\n";
}

sub autocommit_toggle() {
  debugmsg(2, "autocommit_toggle called", @_);
  # autocommit is turned off if on on if off

  if($dbh->{AutoCommit}) {
    $dbh->{AutoCommit} = 0;
  } else {
    $dbh->{AutoCommit} = 1;
  }

  print "AutoCommit is now " . ($dbh->{AutoCommit} ? 'on' : 'off') . "\n";
}

sub show($$) {
  debugmsg(2, "show called", @_);
  # Can 'show thing'.  Possible things:
  #   tables    - outputs all of the tables that the current user owns
  #   sequences - outputs all of the sequences that the current user owns
  #   
  # Can also 'show thing on table'.  Possible things:
  #   constraints - Shows constraints on the 'table', like Check, Primary Key, 
  #                 Unique, and Foreign Key
  #   indexes     - Shows indexes on the 'table'
  #   triggers    - Shows triggers on the 'table'

  my $input = shift;
  my $format = shift;

  # convert to lowercase for comparison operations
  $input = lc($input);

  # parse the input to find out what 'thing' has been requested
  if($input =~ /^\s*show\s+(\w+)\s*$/) {
    if($1 eq 'tables') {
      my $sqlstr = q{
        select table_name "Table Name"
        from user_tables
      };
      query($sqlstr, $format);
    } elsif($1 eq 'sequences') {
      my $sqlstr = q{
        select sequence_name "Sequence Name"
        from user_sequences
      };
      query($sqlstr, $format);
    } elsif($1 eq 'processes') {
      my $sqlstr = q{
        select sid, 
               username "User", 
               status "Status", 
               schemaname "Schema", 
               osuser || '@' || machine "From", 
               to_char(logon_time, 'Mon DD YYYY HH:MI:SS') "Logon Time" 
          from v$session 
         where username is not null
      };
      query($sqlstr, $format);
    } else {
      query_err("show", "Unsupported show type", $input);
    }
  } elsif($input =~ /^\s*show\s+(\w+)\s+on\s+(\w+)/) {
    # this is a thing on a table
    if($1 eq 'indexes') {
      my $sqlstr = q{
        select ai.index_name "Index Name",
          ai.index_type "Type",
          ai.uniqueness "Unique?",
          aic.column_name "Column Name"
        from all_indexes ai, all_ind_columns aic
        where ai.index_name = aic.index_name
          and ai.table_name = ?
      };
      query($sqlstr, $format, undef, uc($2));
    } elsif($1 eq 'constraints') {
      my $sqlstr = q{
        select constraint_name "Constraint Name",
          decode(constraint_type, 
            'C', 'Check', 
            'P', 'Primary Key', 
            'R', 'Foreign Key', 
            'U', 'Unique', 
            '') "Type",
            search_condition "Search Condition"
        from all_constraints
        where table_name = ?
        order by constraint_name
      };
      query($sqlstr, $format, undef, uc($2));
    } elsif($1 eq 'keys') {
      my $sqlstr = q{
        select ac.constraint_name "Name", 
               decode(ac.constraint_type, 
                 'R', 'Foreign Key',
                 'U', 'Unique',
                 'P', 'Primary Key',
                 ac.constraint_type) "Type",
               ac.table_name "Table Name", 
               acc.column_name "Column", 
               r_ac.table_name "Parent Table", 
               r_acc.column_name "Parent Column"
          from all_constraints ac, all_cons_columns acc,
               all_constraints r_ac, all_cons_columns r_acc
         where ac.constraint_name = acc.constraint_name
           and ac.constraint_type in ('R','U','P')
           and ac.r_constraint_name = r_ac.constraint_name(+)
           and r_ac.constraint_name = r_acc.constraint_name(+)
           and ac.table_name = ?
         order by ac.constraint_name, acc.position
      };
      query($sqlstr, $format, undef, uc($2));
    } elsif($1 eq 'checks') {
      my $sqlstr = q{
        select ac.constraint_name "Name", 
               decode(ac.constraint_type, 
                 'C', 'Check',
                 ac.constraint_type) "Type",
               ac.table_name "Table Name", 
               ac.search_condition "Search Condition"
          from all_constraints ac
         where ac.table_name = ?
           and ac.constraint_type = 'C'
         order by ac.constraint_name
      };
      query($sqlstr, $format, undef, uc($2));
    } elsif($1 eq 'triggers') {
      my $sqlstr = q{
        select trigger_name "Trigger Name",
          trigger_type "Type",
          when_clause "When",
          triggering_event "Event"
        from all_triggers 
        where table_name = ?
      };
      query($sqlstr, $format, undef, uc($2));
    } else {
      query_err("show", "Unsupported show type", $input);
    }
  } else {
    query_err("show", "Unsupported show type", $input);
  }
  
      
}

sub describe($$;$) {
  debugmsg(2, "describe called", @_);
  # This describes a table, view, sequence, or synonym  by listing it's 
  # columns and their attributes

  my $input = shift;
  my $format = shift;
  my $nosynonym = shift; # If this is true then we won't look for synonyms

  # convert to lowercase for comparison operations
  $input = lc($input);

  # make sure we're still connected to the database
  unless($dbh->ping()) {
    wrn("Database connection died");
    db_reconnect();
  }
    
  # parse the query to find the table that was requested to be described
  if($input =~ /^\s*desc\w*\s*([\w\.]+)/) {
    my $object = $1;
    my $sqlstr;
    my $type;
    my @ret;

    my $schema;
    if($object =~ /^(\w+)\.(\w+)$/) {
      $schema = $1;
      $object = $2;
    } else {
      $schema = $dbuser;
    }

    debugmsg(1,"object: [$object] schema: [$schema]");

    # look in all_constraints for the object first.  This is because oracle
    # stores information about primary keys in the all_objects table as "index"s
    # but it doesn't have foreign keys or constraints.  So we want to match
    # there here first
    @ret = $dbh->selectrow_array(
      "select constraint_type, constraint_name from all_constraints where "
        ."constraint_name = ?",
      undef, uc($object)
    );

    unless(@ret) {
      # now look in all_objects
      my $all_object_cols = 'object_type,owner,object_name,subobject_name,'
                          . 'object_id,data_object_id,created,last_ddl_time,'
                          . 'timestamp,status,temporary,generated';

      @ret = $dbh->selectrow_array(
        "select $all_object_cols from all_objects where object_name = ? "
          ."and owner = ?"
          .($nosynonym ? " and object_type != 'SYNONYM'" : ""), 
          undef, uc($object), uc($schema)
      ) or
      @ret = $dbh->selectrow_array(
        "select $all_object_cols from all_objects where object_name = ? "
          ."and owner = 'PUBLIC'" 
          .($nosynonym ? " and object_type != 'SYNONYM'" : ""), 
          undef, uc($object)
      );
    }


    $type = $ret[0];
    debugmsg(1,"type: [$type] ret: [@ret]");

    if($type eq 'SYNONYM') {
      # Find what this is a synonym to, then recursively call this function
      # again to describe whatever it points to
      my($table_name, $table_owner) = $dbh->selectrow_array(
        'select table_name, table_owner from all_synonyms '
        .'where synonym_name = ? and owner = ?',
        undef, uc($ret[2]), uc($ret[1])
      );
      
      describe("desc $table_owner.$table_name", $format, 1);
    } elsif($type eq 'SEQUENCE') {
      my $sqlstr = q{
        select sequence_name "Name", 
          min_value "Min", 
          max_value "Max", 
          increment_by "Inc", 
          cycle_flag "Cycle", 
          order_flag "Order", 
          last_number "Last"
        from all_sequences
        where sequence_name = ?
          and sequence_owner = ?
      };
      query($sqlstr, $format, undef, uc($ret[2]), uc($ret[1]));
    } elsif($type eq 'TABLE' || $type eq 'VIEW') {
      my $sqlstr = q{
        select column_name "Name",   
               decode(nullable,
                 'N','NOT NULL'
                 ) "Null?",
               decode(data_type,
                 'VARCHAR2','VARCHAR2(' || TO_CHAR(data_length) || ')',
                 'NVARCHAR2','NVARCHAR2(' || TO_CHAR(data_length) || ')',
                 'CHAR','CHAR(' || TO_CHAR(data_length) || ')',
                 'NCHAR','NCHAR(' || TO_CHAR(data_length) || ')',
                 'NUMBER',
                   decode(data_precision,
                     NULL, 'NUMBER',
                     'NUMBER(' || TO_CHAR(data_precision)
                                || ',' || TO_CHAR(data_scale) || ')'
                   ),
                 'FLOAT',
                   decode(data_precision,
                     NULL, 'FLOAT', 'FLOAT(' || TO_CHAR(data_precision) || ')'
                   ),
                 'DATE','DATE',
                 'LONG','LONG',
                 'LONG RAW','LONG RAW',
                 'RAW','RAW(' || TO_CHAR(data_length) || ')',
                 'MLSLABEL','MLSLABEL',
                 'ROWID','ROWID',
                 'CLOB','CLOB',
                 'NCLOB','NCLOB',
                 'BLOB','BLOB',
                 'BFILE','BFILE',
                 data_type || ' ???'
               ) "Type",
               data_default "Default"
          from all_tab_columns
         where table_name = ?
           and owner = ?
         order by column_id
      };
      query($sqlstr, $format, undef, uc($ret[2]), uc($ret[1]));
    } elsif($type eq 'R') {
      my $sqlstr = q{
        select ac.constraint_name "Name", 
               decode(ac.constraint_type, 
                 'R', 'Foreign Key',
                 'C', 'Check',
                 'U', 'Unique',
                 'P', 'Primary Key',
                 ac.constraint_type) "Type",
               ac.table_name "Table Name", 
               acc.column_name "Column Name", 
               r_ac.table_name "Parent Table", 
               r_acc.column_name "Parent Column",
               ac.delete_rule "Delete Rule"
          from all_constraints ac, all_cons_columns acc,
               all_constraints r_ac, all_cons_columns r_acc
         where ac.constraint_name = acc.constraint_name
           and ac.r_constraint_name = r_ac.constraint_name
           and r_ac.constraint_name = r_acc.constraint_name
           and ac.constraint_type = 'R'
           and ac.constraint_name = ?
         order by ac.constraint_name, acc.position
      };
      query($sqlstr, 'list_aligned', undef, uc($ret[1]));
    } elsif($type eq 'P' || $type eq 'U') {
      my $sqlstr = q{
        select ac.constraint_name "Name", 
               decode(ac.constraint_type, 
                 'R', 'Foreign Key',
                 'C', 'Check',
                 'U', 'Unique',
                 'P', 'Primary Key',
                 ac.constraint_type) "Type",
               ac.table_name "Table Name", 
               acc.column_name "Column Name" 
          from all_constraints ac, all_cons_columns acc
         where ac.constraint_name = acc.constraint_name
           and ac.constraint_name = ?
         order by ac.constraint_name, acc.position
      };
      query($sqlstr, $format, undef, uc($ret[1]));
    } elsif($type eq 'C') {
      my $sqlstr = q{
        select ac.constraint_name "Name", 
               decode(ac.constraint_type, 
                 'R', 'Foreign Key',
                 'C', 'Check',
                 'U', 'Unique',
                 'P', 'Primary Key',
                 ac.constraint_type) "Type",
               ac.table_name "Table Name", 
               ac.search_condition "Search Condition"
          from all_constraints ac
         where ac.constraint_name = ?
         order by ac.constraint_name
      };
      query($sqlstr, $format, undef, uc($ret[1]));
    } elsif($type eq 'INDEX') {
      my $sqlstr = q{
        select ai.index_name "Index Name",
               ai.index_type "Type",
               ai.table_name "Table Name",
               ai.uniqueness "Unique?",
               aic.column_name "Column Name"
          from all_indexes ai, all_ind_columns aic
         where ai.index_name = aic.index_name(+)
           and ai.index_name = ?
      };
      query($sqlstr, $format, undef, uc($ret[2]));
    } elsif($type eq 'TRIGGER') {
      my $sqlstr = q{
        select trigger_name "Trigger Name",
               trigger_type "Type",
               triggering_event "Event",
               table_name "Table",
               when_clause "When",
               description "Description",
               trigger_body "Body"
          from all_triggers
         where trigger_name = ?
      };
      query($sqlstr, 'list_aligned', undef, uc($ret[2]));
    } elsif($type eq 'PACKAGE') {
      wrn("Not implemented (yet)");
    } elsif($type eq 'PROCEDURE') {
      wrn("Not implemented (yet)");
    } elsif($type eq 'CLUSTER') {
      wrn("Not implemented (yet)");
    } elsif($type eq 'TRIGGER') {
      wrn("Not implemented (yet)");
    } else {
      query_err('describe', "Object $object not found");
    }
  }
}

sub query($$;$@) {
  debugmsg(2, "query called", @_);
  # this runs the provided query and calls format_display to display the results

  my $sqlstr = shift;
  my $format = shift;
  my $num_rows = shift;
  my @bind_vars = @_;

  my(@querybench, @formatbench);

  # Look for special query types, such as "show" and "desc" that we handle
  # and don't send to the database at all, since they're not really valid SQL.

  if($sqlstr =~ /^\s*desc/i) {
    describe($sqlstr, $format);
  } elsif($sqlstr =~ /^\s*show/i) {
    show($sqlstr, $format);
  } else {
    $running_query = 1;

    # make sure we're still connected to the database
    unless($dbh->ping()) {
      wrn("Database connection died");
      db_reconnect();
    }
    #wrn("Ping: [" . $dbh->ping() . "]");

    $sqlstr = wildcard_expand($sqlstr) if $conf{column_wildcards};

    # send the query on to the database 
    push(@querybench, get_bench());
    my $sth = $dbh->prepare($sqlstr) 
      or query_err('prepare', $DBI::errstr, $sqlstr), setup_sigs(), return(0);

    $cursth = $sth;

    finish_query($sth), return(0) if $sigintcaught; #pseudo sig handle

    $sth->execute(@bind_vars) 
      or query_err('execute', $DBI::errstr, $sqlstr), setup_sigs(), return(0);
    push(@querybench, get_bench());

    finish_query($sth), return(0) if $sigintcaught; #pseudo sig handle

    debugmsg(1, "rows returned: [" . $sth->rows() . "]");

    push(@formatbench, get_bench());
    format_output($sth, $format, $num_rows, $sqlstr);
    push(@formatbench, get_bench());
 
    finish_query($sth), return(0) if $sigintcaught; #pseudo sig handle

    if($opt_bench || $conf{extended_benchmarks}) {
      print "\n\n";
      print ('-' x 80);
      print "\n";
      output_benchmark("Query: ", @querybench, "\n");
      output_benchmark("Format:", @formatbench, "\n");
    } else {
      output_benchmark(" (", @querybench, " sec)");
      print "\n";
    }
    print "\n";

    finish_query($sth);

    undef($sth);
    undef($cursth);
  }

  return(1);
}

sub wildcard_expand($) {
  debugmsg(2, "wildcard_expand called", @_);
  my $sql = shift;
  my $newsql = $sql;
  my $fromstuff;
  my $wheregrouporder = $sql;
  $wheregrouporder =~ s/.*(where|order|group).*/\1/;
  if ($wheregrouporder eq $sql) {
    $wheregrouporder = "";
  }
  ($sql,$fromstuff) = split(/order|group|where/i,$sql,2);
  if ($sql =~ /^select\s+(.+?)\*\s+from\s+(.+)/i) {
    debugmsg(1, "Match made: ($1) ($2)");
    my $wildcardstring = uc($1);
    my $tablename = uc($2);
    my @tlist = split(/,/,$tablename);
    my $tablelist = "";
    my %column_prefix;
    foreach my $table (@tlist) {
      $table =~ s/^ *//;
      $table =~ s/([^ ]+)\s+(.*)/\1/;
      $column_prefix{$table} = $2 ? $2 : $table;
      $tablelist .= ($tablelist ? "," : "") . $table;
    }
    $tablelist =~ s/,/' or table_name='/g;
    my $qstr = "select table_name||'.'||column_name from all_tab_columns where (table_name='$tablelist') and column_name like '$wildcardstring%' escape '\\'";
    debugmsg(1, "qstr: [$qstr]");
    my $sth = $dbh->prepare($qstr);
    $sth->execute();
    setup_sigs();
    my $colname;
    my $collist;
    while ( ($colname) = $sth->fetchrow_array() ) {
      foreach my $table (keys %column_prefix) {
        $colname =~ s/$table\./$column_prefix{$table}\./;
        $colname =~ s/ //g;
      }
      $collist .= ($collist ? "," : "") . $colname;
    }
    $collist = $collist ? $collist : "*";
    $newsql = "select " . $collist . " from " . $tablename . " "
            . $wheregrouporder . " " . $fromstuff;
    debugmsg(1, "newsql: [$newsql]");
  }
  $newsql;
}

sub finish_query($) {
  # This just finishes the query and cleans up the state info
  my $sth = shift;

  $sth->finish;
  undef($cursth);
  $running_query = 0;
  setup_sigs();
}

sub get_bench() {
  debugmsg(2, "get_bench called", @_);
  # returns benchmark info
  
  my($benchmark, $hires);
  $benchmark = new Benchmark; 

  if($nohires) {
    $hires = time;
  } else {
    # use an eval to keep perl from syntax checking it unless we have the
    # Time::HiRes module loaded
    eval q{
      $hires = [gettimeofday]
    };
  }

  return($benchmark, $hires);
}

sub output_benchmark() {
  debugmsg(2, "output_benchmark called", @_);
  # This just outputs the benchmark info
  my($string, $bstart, $hrstart, $bend, $hrend, $string2) = @_;
  
  my $bench = timediff($bend, $bstart);
  
  my $time;
  if($nohires) {
    # the times will be seconds
    $time = $hrend - $hrstart;
  } else {
    eval q{$time = tv_interval($hrstart, $hrend)};
    $time = sprintf("%.2f", $time);
  }
  
  if($opt_bench || $conf{extended_benchmarks}) {
    print "$string\[$time\s] [" . timestr($bench) . " ]$string2";
  } else {
    print "$string$time$string2";
  }
}

sub format_output($$$$) {
  debugmsg(2, "format_output called", @_);
  # Formats the output according to the query terminator.  If it was a ';' or
  # a '/' then a normal table is output.  If it was a '\g' then all the columns   # and rows are output put line by line.
  # input:  $sth $format
  #         sth is the statement handler
  #         format can be either 'table', 'list', or 'list_aligned'
  # output: prints the results to the user

  my $sth = shift;
  my $format = shift;
  my $num_rows = shift;
  my $sqlstr = shift;

  debugmsg(3,"type: [" . Dumper($sth->{TYPE}) . "]");

  # Is this query a select?
  my $isselect = 1 if $sqlstr =~ /^\s*select/;

  if($format eq 'table') {
    #my $res = $sth->fetchall_arrayref();

    my $count = 0;
    my $res = [];
    while(my @res = $sth->fetchrow_array()) {
      push(@$res, \@res);
      $count++;
      debugmsg(1,"num_rows hit on fetch") if $num_rows && $count >= $num_rows;
      last if $num_rows && $count >= $num_rows;
      return(0) if $sigintcaught; #pseudo sig handle
    }

    # If we didn't get any rows back, then the query was probably an insert or 
    # update, so we call format_affected
    if(@$res <= 0 && !$isselect) {
      format_affected($sth->rows());
      return(1);
    }
    
    return(0) if $sigintcaught; #pseudo sig handle

    # First go through all the return data to determine column widths
    my @widths;
    for( my $i = 0; $i < @{$res}; $i++ ) {
      for( my $j = 0; $j < @{$res->[$i]}; $j++ ) {
        if(length($res->[$i]->[$j]) > $widths[$j]) {
          $widths[$j] = length($res->[$i]->[$j]);
        }
      }
      return(0) if $sigintcaught; #pseudo sig handle
      debugmsg(1,"num_rows hit on calc") if $num_rows && $i >= $num_rows-1;
      last if $num_rows && $i >= $num_rows-1;
    }

    return(0) if $sigintcaught; #pseudo sig handle

    my $fields = $sth->{NAME};
    my $types = $sth->{TYPE};
    
    return(0) if $sigintcaught; #pseudo sig handle

    # Extend the column widths if the column name is longer than any of the
    # data, so that it doesn't truncate the column name
    for( my $i = 0; $i < @$fields; $i++ ) {
      if(length($fields->[$i]) > $widths[$i]) {
        $widths[$i] = length($fields->[$i]);
      }
      return(0) if $sigintcaught; #pseudo sig handle
    }

    return(0) if $sigintcaught; #pseudo sig handle

    my $sumwidths;
    foreach(@widths) {
      $sumwidths += $_;
    }

    return(0) if $sigintcaught; #pseudo sig handle

    debugmsg(1,"fields: [" . join("|", @$fields) . "] sumwidths: [$sumwidths] widths: [" . join("|", @widths) . "]\n");

    return(0) if $sigintcaught; #pseudo sig handle

    # now do the actual outputting, starting with the header
    my $rows_selected = 0;
    if(@$res) {
      print "\n";
      for( my $i = 0; $i < @$fields; $i++ ) {
        print " " if $i > 0;
        if($types->[$i] == 3) {
          printf("%$widths[$i]s", $fields->[$i]);
        } else {
          printf("%-$widths[$i]s", $fields->[$i]);
        }
      }
      print "\n";
      
      for( my $i = 0; $i < @$fields; $i++ ) {
        print " " if $i > 0;
        print '-' x $widths[$i];
      }
      print "\n";
    
      return(0) if $sigintcaught; #pseudo sig handle

      # now print the actual data rows
      for( my $j = 0; $j < @$res; $j++ ) {
        for( my $i = 0; $i < @$fields; $i++ ) {
          print " " if $i > 0;
          my $data = $res->[$j]->[$i];
          # Strip out plain ole \r's since SQL*Plus seems to...
          $data =~ s/\r//g;
          $data = 'NULL' unless defined $data;
            if($types->[$i] == 3) {
              printf("%$widths[$i]s", $data);
            } else {
              printf("%-$widths[$i]s", $data);
            }
        }
        print "\n";
    
        $rows_selected++;
        debugmsg(2,"num_rows hit on output") if $num_rows && $j >= $num_rows-1;
        last if $num_rows && $j >= $num_rows-1;
        return(0) if $sigintcaught; #pseudo sig handle
      }
    }

    print "\n";
    print "$rows_selected rows selected.";
        
  } elsif($format eq 'list') {
    # output in a nice list format, which is where we print each row in turn,
    # with each column on it's own line
    
    my $fields = $sth->{NAME};
    
    my $count = 0;
    while(my $res = $sth->fetch()) {
      print "\n**** Row: " . ($count+1) . "\n";
      for( my $i = 0; $i < @$fields; $i++ ) {
        my $data = $res->[$i];
        $data = 'NULL' unless defined $data;
        print $fields->[$i] . ": " . $data . "\n";
      }
      $count++;
      last if $num_rows && $count >= $num_rows;
      return(0) if $sigintcaught; #pseudo sig handle
    }

    return(0) if $sigintcaught; #pseudo sig handle

    # If we didn't get any rows back, then the query was probably an insert or 
    # update, so we call format_affected
    if($count <= 0 && !$isselect) {
      format_affected($sth->rows());
      return(1);
    }
    
    print "\n";
    print $count . " rows selected.";
    
  } elsif($format eq 'list_aligned') {
    # output in a nice list format, which is where we print each row in turn,
    # with each column on it's own line.  The column names are aligned in this
    # one (so that the data all starts on the same column)
    
    my $fields = $sth->{NAME};

    my $maxwidth = 0;
    for( my $i = 0; $i < @$fields; $i++ ) {
      my $len = length($fields->[$i]) + 1; # +1 for the colon
      $maxwidth = $len if $len >= $maxwidth;
    }
    
    return(0) if $sigintcaught; #pseudo sig handle

    my $count = 0;
    while(my $res = $sth->fetch()) {
      print "\n**** Row: " . ($count+1) . "\n";
      for( my $i = 0; $i < @$fields; $i++ ) {
        my $data = $res->[$i];
        $data = 'NULL' unless defined $data;
        printf("%-" . $maxwidth . "s", $fields->[$i] . ":");
        print " " . $data . "\n";
      }
      $count++;
      last if $num_rows && $count >= $num_rows;
      return(0) if $sigintcaught; #pseudo sig handle
    }

    return(0) if $sigintcaught; #pseudo sig handle

    # If we didn't get any rows back, then the query was probably an insert or 
    # update, so we call format_affected
    if($count <= 0 && !$isselect) {
      format_affected($sth->rows());
      return(1);
    }
    
    print "\n";
    print $count . " rows selected.";
    
  } else {
    die("Invalid format: $format");
  }
}    

sub format_affected($) {
  debugmsg(2, "format_affected called", @_);
  # This just outputs the given number

  my $affected = shift;

  print "\n";
  print "$affected row" . ($affected == 1 ? '' : 's') . " affected";
}


sub query_err($$) {
  debugmsg(2, "query_err called", @_);
  # outputs a standard query error.  does not exit
  # input: $query_type, $msg

  my $query_type = shift;
  my $msg = shift;
  my $query = shift;
  chomp($query_type);
  chomp($msg);
  chomp($query);

  print "\n";
  #print "Query Error: ";
  #print "$query_type failed: $msg\n";
  print "$msg\n";
  print "Query: $query\n" if $query && $conf{sql_query_in_error};
  print "\n";
}

sub err($) {
  debugmsg(2, "err called", @_);
  # outputs an error message and exits
  my $msg = shift;

  print "Error: $msg\n";
  quit(1);
}

sub wrn($) {
  debugmsg(2, "wrn called", @_);
  # outputs a warning
  my $msg = shift;

  print "Warning: $msg\n";
}

sub quit(;$$$) {
  debugmsg(2, "quit called", @_);
  # just quits

  setup_sigs();

  my $exitcode = shift || 0;
  my $erase_last_line_in_buffer = shift || 0;
  my $force_quit = shift || 0; # Set this to 1 to try a smoother force quit

  print "Quitting...\n";
  $quitting = 1;

  if($force_quit) {
    exit($exitcode);
  }
  
  # Commit... or not
  if($conf{CommitOnExit} && defined $dbh && !$dbh->{AutoCommit}) {
    print "Committing any outstanding transaction...\n";
    $dbh->commit();
  } elsif(defined $dbh && !$dbh->{AutoCommit}) {
    print "Rolling back any outstanding transaction...\n";
    $dbh->rollback();
  }

  # disconnect the database
  debugmsg(1, "disconnecting from database");
  #$cursth->finish() if defined $cursth;
  $dbh->disconnect() if defined $dbh;

  if ($term->ReadLine eq "Term::ReadLine::Gnu") {
    if($erase_last_line_in_buffer) {
      # delete the quit command from the history list
      debugmsg(1, "removing last history line");
      $term->remove_history($term->where_history());
    }

    # save the history buffera
    debugmsg(1, "Writing history");
    unless($term->WriteHistory($conf{history_file})) {
      wrn("Could not write history file to $conf{history_file}.  "
         ."History not saved");
    }

    # try to reset the terminal
    debugmsg(1, "cleaning up terminal");
    if ($term->ReadLine eq "Term::ReadLine::Gnu") {
      $term->cleanup_after_signal();
    }

    # if $stty has something then pass it's contents to stty again to restore
    # the terminal for sure
    if($stty) {
      `stty $stty`;
    }

  }
  
  debugmsg(1, "exiting with exitcode: [$exitcode]");
  exit($exitcode);
}

sub END {
  debugmsg(2, "END called", @_);

  # try to reset the terminal
  debugmsg(1, "cleaning up terminal");
  if ($term->ReadLine eq "Term::ReadLine::Gnu") {
    $term->cleanup_after_signal();
  }
}

sub sighandle {
  debugmsg(1, "sighandle called", @_);
  my $sig = shift;

  $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 "Attempting to force exit...\n";
      exit();
    }
    
    if($sigintcaught) {
      # the user has alrady hit INT and so we now force an exit
      print "Caught another SIG$sig\n";
      quit(undef, undef, 1);
    } else {
      $sigintcaught = 1;
    }
    
    if($running_query) {
      if(defined $cursth) {
        print "Attempting to cancel query...\n";
        debugmsg(1, "canceling statement handle");
        my $ret = $cursth->cancel();
        $cursth->finish;
      }
    } elsif(!$connected) {
      quit();
    
      if(defined $cursth) {
        print "Attempting to cancel query...\n";
        debugmsg(1, "canceling statement handle");
        my $ret = $cursth->cancel();
        $cursth->finish;
      }
    }

  } elsif($sig eq 'ALRM') {
    err("Could not connect to database, timed out. (timeout: "
       ."$conf{connection_timeout})") if $connect_in_progress;
  }
}

sub debugmsg($;@) {
  my $debuglevel = shift;
  my @msgs = @_;
  if($opt_debug >= $debuglevel ) {
    print STDERR "[" . localtime() . "] [$debuglevel] [" . join("] [", @msgs) . "]\n";
  }
}

sub usage(;$) {
  debugmsg(2, "usage called", @_);
  my $exit = shift;
  $exit ||= 0;

  print qq(Usage: yasql [options] )
      . qq([ [<username>[/<password>]][@<connect_string>] ]

Options:
  -d <debug_level>, --debug=<debug_level>
    Turn debugging on to <debug_level>

  -H <host_address>, --host=<host_address>
    Host to connect to
  
  -p <host_port>, --port=<host_port>
    Host port to connect to
  
  -s <SID>, --sid=<SID>
    Oracle SID to connect to

  -h, -?, --help
    This help information

  -b, --bench, --benchmark
    Display extra benchmarking info

  -A
    Turn off the generation of the auto-completion list at startup.  Use
    This if it takes too long to generate the list with a large database.

);
  
  exit(1) if $exit;
}

sub help() {
  debugmsg(2, "help called", @_);
  # This just outputs online help
  
  my $help = q{
Commands:
  help
    This screen

  quit | exit | \q
    Exit the program.

  \A
    Regenerate the auto-completion list.  Run this if you update the database
    schema and the changes don't appear when you hit tab.

  connect <connect_string>
    Drop the current connection and open a new one.  Syntax of connect_string:
      [<username>[/<password>]][@<connection_descriptor>]

  reconnect | \r
    Reconnect to the database

  desc[ribe] [<user>.]<object>
    Describe object.  Synonyms will be resolved.
    Supported objects: table, view, sequence, primary key, foreign key, check,
                       unique index

  show <object_type>
    Show all the objects owned by you of a certain type.
    Supported types: tables, sequences, constraints, keys, checks, processes

  show <object_type> on <table>
    Show all the objects of a certain type on a certain table.
    Supported types: indexes, constraints, triggers

  list | l | \l
    List the contents of the current buffer

  clear | clear buffer | \c
    Clear the current buffer

  edit [<file>] | \e [<file>]
    Will open a text editor as defined by the EDITOR environment variable.  If
    a file is given as the argument, then the editor will be opened with that
    file.  If the given file does not exist then it will be created.  In both
    cases the file will not be deleted, and the current buffer will be 
    overwritten by the contents of the file.  If no file is given, then the
    editor will be opened with a temporary file, which will contain the current
    contents of the buffer, or the last execute query if the buffer is empty.
    After the editor quits, the file will be read into the buffer.  The contents
    will be parsed and executed just as if you had typed them all in by hand.
    You can have multiple commands and/or queries.  If the last command is not
    terminated them you will be able to add furthur lines or input a terminator
    to execute the query.

  @<filename>
    Execute all the commands in <filename> as if they were typed in directly.
    All CLI commands and queries are supported.  yasql will quit after running
    all commands in the script.

  debug [<num>]
    Toggle debuggin on/off or if <num> is specified, then set debugging to that
    level

  autocommit
    Toggle AutoCommit on/off

Queries:
  All other input is treated as a query, and is sent straight to the database.

  All queries must be terminated by one of the following characters:
    ;  - Returns data in table form
    /  - Returns data in table form
    \g - Returns data in non-aligned list form
    \G - Returns data in aligned list form

  You may re-run the last query by typing the terminator by itself.

  You may add a number after the terminator, which will cause only the
  first <num> rows to be returned.  e.g. 'select * from table;10' will run
  the query and return the first 10 rows in table format.  This will also work
  if you just type the terminator to rerun the last query.

Please see 'perldoc yasql' for more help
};
 
  my $ret = open(PAGER, "|$conf{pager}");
  if($ret) {
    print PAGER $help;
    close(PAGER);
  } else {
    print $help;
  }
}

__END__

=head1 NAME

yasql - Yet Another SQL*Plus replacement

=head1 SYNOPSIS

B<yasql> [options] [connect_string]

=over 4

=item connect_string

[I<username>[/I<password>]][@I<connection_descriptor>]

=item options

=over 4

=item -d I<debuglevel>, --debug=I<debuglevel>

Turn debuggin on to I<debuglevel> level.  Valid levels: 1,2,3,4

=item -H I<hostaddress>, --host=I<hostaddress>

Host to connect to

=item -p I<hostport>, --port=I<hostport>

Host port to connect to

=item -s I<SID>, --sid=I<SID>

Oracle SID to connect to

=item -h, -?, --help

Output usage information and quit.

=item -b, --bench, --benchmark

Turn on extended benchmark info, which includes times and CPU usages for both
queries and formatting.

=item -A

Turn off the generation of the auto-completion list at startup.  Use This if 
it takes too long to generate the list with a large database.

=back

=item Examples

=over 4

=item Connect to local database

=over 4

=item yasql

=item yasql user

=item yasql user/password

=item yasql @LOCAL

=item yasql user@LOCAL

=item yasql user/password@LOCAL

=item yasql -h localhost

=item yasql -h localhost -p 1521

=item yasql -h localhost -p 1521 -s ORCL

=back

=item Connect to remote host

=over 4

=item yasql @REMOTE

=item yasql user@REMOTE

=item yasql user/password@REMOTE

=item yasql -h remote.domain.com

=item yasql -h remote.domain.com -p 1512

=item yasql -h remote.domain.com -p 1512 -s ORCL

=back

=back

=back

If no connect_string or a hostaddress is given, then will attempt to connect to
the local default database.

=head1 DESCRIPTION

YASQL is an open Oracle command line interface.  YASQL features a much
kinder alternative to SQL*Plus's user interface. This does not provide every
feature that SQL*Plus does, only the ones needed for general ad hoc queries.
The main intent of this program is for viewing data in the database, or testing
queries.  It is not intended to create fancy reports, such as those featured in SQL*Plus.  It also does not have any sort of scripting language such as PL/SQL.
It has a few native commands, such as describe, show, quit, and everything
else is passed through to the Oracle server.  The main things it provides are:

=over 4

=item Full ReadLine support

Allows the same command line style editing as other ReadLine enabled programs
such as BASH and the Perl Debugger.  You can edit the command line as well as
browse your command history.  The command 
history is saved in your home directory in a file called .yasql_history.  You 
can also use tab completion on all table and column names.

=item Alternate output methods

A different style of output suited to each type of need.  There is currently
a table and list output style.  Table style outputs in the same manner as 
SQL*Plus, except the column widths are set based on the width of the data in 
the column, and not the column length defined in the table schema.  List outputs
each row on it's own line, column after column for easier viewing of wide return
results.

=item Tab completion

All tables, columns, and other misc objects can be completed using tab, much
like you can with bash.

=item Easy top row_num listings

You can easily put a number after a terminator, which will only output those
number of lines.  No more typing "where row_num < 10" after every query.  Now
you can type 'select * from table;10' instead.

=item Enhanced Data Dictionary commands

Special commands like 'show tables', 'desc <table>', 'show indexes on <table>',
'desc <sequence>', and many many more so that you can easily see your schema.

=item Query editing

You can open and edit queries in your favorite text editor.

=item Basic scripting

You can put basic SQL queries in a script and execute them from YASQL.

=item Config file

You can create a config file of options so that you don't have to set them
everytime you run it.

=item Future extensibility

We, the community, can modify and add to this whatever we want, we can't do that
with SQL*Plus.

=back

=head1 REQUIREMENTS

=over 4

=item Perl 5

This was developed with Perl 5.6, but is known to work on 5.005_03 and above.
Any earlier version of Perl 5 may or may not work.  Perl 4 will definately not
work.

=item Unix environment

YASQL was developed under linux, and aimed at as many Unix installations as 
possible.  Known to be compatible with RedHat Linux as well as Sun Solaris.
Please send me an email (nshafer@ephibian.com) if it works for other platforms.
I'd be especially interested if it worked on Win32.

=item DBD::Oracle

DBD::Oracle must be installed since this uses DBI for database connections.

=item Oracle client libraries

The Oracle client libraries must be installed for DBD::Oracle.  Of course you
can't install DBD::Oracle without them...

=item Term::Readline

Term::Readline must be installed (it is with most Perl installations), but more 
importantly, installing Term::Readline:Gnu from CPAN will greatly enhance the 
usability.

=item ORACLE_HOME

The ORACLE_HOME environment variable must be set if you use a connection 
descriptor to connect so that YASQL can translate the descriptor into 
usefull connection information to make the actual connection.

=item ORACLE_SID

The ORACLE_SID environment variable must be set unless you specify one with the 
-s option (see options above).

=back

=head1 CONFIG

YASQL will look for a config file first in ~/.yasqlrc then 
/etc/yasql.conf.  The following options are available:

=over 4

=item connection_timeout = <seconds>

Timeout for connection attempts

Default: 20

=item max_connection_attempts = <num>

The amount of times to attempt the connection if the username/password are wrong

Default: 3

=item history_file = <file>

Where to save the history file.  Shell metachars will be globbed (expanded)

Default: ~/.yasql_history

=item pager = <file>

Your favorite pager for extended output. (right now only the help command)

Default: /bin/more

=item AutoCommit = [0/1]

Autocommit any updates/inserts etc

Default: 0

=item CommitOnExit = [0/1]

Commit any pending transactions on exit.  Errors or crashes will still cause
the current transaction to rollback.  But with this on a commit will occur
when you explicitly exit.

Default: 0

=item LongTruncOk = [0/1]

Long truncation OK.  If set to 1 then when a row contains a field that is
set to a LONG time, such as BLOB, CLOB, etc will be truncated to LongReadLen
length.  If 0, then the row will be skipped and not outputted.

Default: 1

=item LongReadLen = <num_chars>

Long Read Length.  This is the length of characters to truncate to if 
LongTruncOk is on

Default: 80

=item edit_history = [0/1]

Whether or not to put the query edited from the 'edit' command into the
command history.

Default: 1

=item auto_complete = [0/1]

Whether or not to generate the autocompletion list on connection.  If connecting
to a large database (in number of tables/columns sense), the generation process
could take a bit. For most databases it shouldn't take long at all though.

Default: 1

=item extended_benchmarks = [0/1]

Whether or not to include extended benchmarking info after queries.  Will 
include both execution times and CPU loads for both the query and formatting
parts of the process.

Default: 0

=item column_wildcards = [0/1]

Column wildcards is an extremely experimental feature that is still being
hashed out due to the complex nature of it.  This should affect only select
statements and expands any wildcards (*) in the column list.  such as
'select col* from table;'.

Default: 0

=item extended_tab_list = [0/1]

extended tab list will cause the possible matches list to be filled by basicly
any and all objects.  With it off the tab list will be restricted to only
tables, columns, and objects owned by the current user.

Default: 0

=back

=head1 AUTHOR

Written by Nathan Shafer (B<nshafer@ephibian.com>) with support from Ephibian,
Inc.  http://www.ephibian.com

=head1 THANKS

Thanks to everyone at Ephibian that helped with testing, and a special thanks
to Tom Renfro at Ephibian who did a lot of testing and found quite a few 
doozies.

The following people have also contributed to help make YASQL what it is:
Allan Peda
Lance Klein

=head1 COPYRIGHT

Copyright (C) 2000 Ephibian, Inc.

=head1 LICENSE

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.

=head1 TODO

=over 4

=item When the given terminal type is not in the termcap readline will die with
a nasty error message.  Possibly try to catch it before, or even specify a
default term-type (vt100).

=item Add smarter tables and wrapping in columns.  Also add configurable max
column widths and max table width.

=item Add a curses interface option for easy viewing and scrolling, etc.  This
will require some research to determine if it's even worth it.

=item Add HTML and CSV output options

=item Add support for MySQL and PostgreSQL

=back

=head1 CHANGELOG

$Log: yasql,v $
Revision 1.66  2001/03/13 21:34:58  nshafer
There are no longer any references to termcap, so yasql should now work on
termcap-less systems such as Debian Linux and AIX

Revision 1.65  2001/03/12 17:44:31  nshafer
Restoring the terminal is hopefully more robust and better now.  YASQL now
tries to use the 'stty' program to dump the settings of the terminal on
startup so that it can restore it back to those settings.  It requires that
stty is installed in the path, but that should be the case with most systems.
Also made the output of the query in the error message an option that is off
by default.  I had never meant to include that in the final release, but kept
on forgetting to take it out.

Revision 1.64  2001/03/06 16:00:33  nshafer
Fixed bug where desc would match anytime, even in middle of query, which is
bad.

Revision 1.63  2001/03/01 17:30:26  nshafer
Refined the ctrl-c process for not-so-linuxy OS's, namely solaris.  Now
stripping out Dos carriage returns since SQL*Plus seems to.

Revision 1.62  2001/02/26 22:39:12  nshafer
Fixed bug where prompt would reset itself when a blank line was entered.
Added script argument on command line (Lance Klein)
Added support for any command line commands in the script (Lance Klein)
The 'desc' and 'show' commands no longer require a terminator (like ;) as long as the whole statement is on one line (Lance Klein)
Added option 'extended_tab_list' for a much bigger, more complete tab listing (Lance Klein)
The edit command is no longer limited to 1 query at a time.  You can now put any valid command or query, and as many of them as you want.  The parsing rules for the edit command is exactly identical to the script parsing.
cleaned up documentation a bit

Revision 1.61  2001/01/31 19:56:22  nshafer
changed CommitOnExit to be 1 by default, to emulate SQL*Plus behavior, and
at popular request

Revision 1.60  2001/01/29 16:38:17  nshafer
got rid of (tm)

Revision 1.59  2001/01/29 16:28:22  nshafer
Modified docs a little with the new scope of open source now in the mix.

Revision 1.58  2001/01/24 15:27:00  nshafer
cleanup_after_signals is not in the Term::ReadLine::Stub, so it would
output error messages on systems without Term::ReadLine::Gnu.  Fixed

Revision 1.57  2001/01/17 23:26:53  nshafer
Added Tom Renfro's column_wildcard expansion code.  New conf variable:
column_wildcards.  0 by default until this code is expanded on a bit more.

Revision 1.56  2001/01/17 23:00:25  nshafer
Added CommitOnExit config, 0 by default.  Added info output at startup and
when a new connection is initiated about the state of AutoCommit and
CommitOnExit.  Also added statement about explicit rollback or commit when
disconnecting.  Added warning message to commit_cmd and rollback_cmd if
AutoCommit is on.  Now explicitly committing or rolling back on disconnect,
it is no longer left up to the DBI's discretion... except in abnormal
termination.

Revision 1.55  2001/01/11 18:05:12  nshafer
 Added trap for regex errors in tab completion (like if you put 'blah[' then
hit tab)

Revision 1.54  2001/01/10 17:07:22  nshafer
added output to those last 2 commands

Revision 1.53  2001/01/10 17:03:58  nshafer
added commit and rollback commands so that you don't have to send them to the
backend

Revision 1.52  2001/01/10 16:00:08  nshafer
fixed bug with prompt where on each call get_prompt would add another '@'.
Thanks Tom

Revision 1.51  2001/01/09 21:16:12  nshafer
dar... fixed another bug where the %H would stay if there was no prompt_host

Revision 1.50  2001/01/09 21:12:13  nshafer
fixed bug with that last update.  Now it only interpolates the %H variable
if there is something to interpolate it with

Revision 1.49  2001/01/09 21:09:56  nshafer
changed the %H variable to be prefixed with a @

Revision 1.48  2001/01/09 21:04:36  nshafer
changed 'default' to '' for the prompt's hostname when no connect_string is
used

Revision 1.47  2001/01/09 20:55:11  nshafer
added configurable prompt and changed the default prompt

Revision 1.46  2001/01/09 18:50:50  nshafer
updated todo list

Revision 1.45  2001/01/09 18:32:35  nshafer
Added 'connect <connect_string>' command.  I may add the ability to specify
options like on the command line (like '-H blah.com')

Revision 1.44  2001/01/08 22:08:49  nshafer
more documentation changes

Revision 1.43  2001/01/08 20:51:31  nshafer
added some documentation

Revision 1.42  2001/01/08 20:09:35  nshafer
Added debug and autocommit commands

Revision 1.41  2001/01/08 18:12:43  nshafer
added END handler to hopefully clean up the terminal better

Revision 1.40  2001/01/05 23:29:38  nshafer
new name!

Revision 1.39  2001/01/05 18:00:16  nshafer
Added config file options for auto completion generation and extended
benchmark info

Revision 1.38  2001/01/05 16:39:47  nshafer
Fixed error where calling edit a second time would not open the file properly
because of the way glob() works.

Revision 1.37  2001/01/04 23:52:30  nshafer
changed the version string to parse it out of the revision string (duh...)
moved the prompting of username and password so that the check for the
oracle_home variable happens before.  Before if you didn't have the environment
variable set then it will prompt you for username and password, then die
with the error, which is annoying
fixed the quit calls so taht they properly erase the quit line from the
history.  I had broken this a long time ago when I added the exit status
param to the quit function
Outputting in full table format (';' terminator) with a num_rows number
(like ';100') would still cause the entire result set to be pulled into
memory, which was really slow and could take a lot of memory if the table
was large.  Fixed it so that it only pulls in num_rows number of rows when
using the digit option

Revision 1.36  2000/12/22 22:12:18  nshafer
fixed a wrong-quote-type in the debug messages

Revision 1.35  2000/12/22 22:07:06  nshafer
forgot version... you know the drill...

Revision 1.34  2000/12/22 21:57:01  nshafer
Added config file support, queries from the 'edit' command are now entered
into the command history (configurable), cleaned up the SIGINT actions quite
a bit so they should work better now, added LongReadLen and LongTruncOk
options so that LONG columns types won't mess up, added the number after terminator
feature to limit how many rows are returned.

Revision 1.33  2000/12/20 22:56:03  nshafer
version number.... again.... sigh

Revision 1.32  2000/12/20 22:55:32  nshafer
added todo item, now in rpms

Revision 1.31  2000/12/20 17:07:52  nshafer
added the reprompt for username/password on error 1005 null password given

Revision 1.30  2000/12/20 17:04:18  nshafer
Refined the shadow_redisplay stuff.  Now I will only use my builtin function
if the terminal type is set to "xterm" because that terminal type has a
broken termcap entry.  Also set it to not echo when entering password if
Term::ReadLine::Gnu is not installed

Revision 1.29  2000/12/20 15:47:56  nshafer
trying a new scheme for the shadow_redisplay.  Clear to EOL wasn't working
Also fixed a few problems in the documentation
.,

Revision 1.28  2000/12/19 23:55:03  nshafer
I need to stop forgetting the revision number...

Revision 1.27  2000/12/19 23:48:49  nshafer
cleaned up debugging

Revision 1.26  2000/12/19 23:10:18  nshafer
Lotsa new stuff... tab completion of table, column, and object names,
improved signal handling, the edit command now accepts a filename parameter,
new command 'show processes' which shows you info on who's connected,
improved benchmark info, and a lot of other cleanup/tweaks

Revision 1.25  2000/12/13 16:58:26  nshafer
oops forgot documentation again

Revision 1.24  2000/12/13 16:54:42  nshafer
added desc <trigger>

Revision 1.23  2000/12/12 17:52:15  nshafer
updated todo list (oops, forgot)

Revision 1.22  2000/12/12 17:51:39  nshafer
added desc <index>

Revision 1.21  2000/12/12 17:15:28  nshafer
fixed bug when connecting using a host string (-H option)
added a few more types to the 'show' and 'desc' commands

Revision 1.20  2000/12/08 22:13:43  nshafer
many little fixes and tweaks here and there

Revision 1.19  2000/12/06 20:50:03  nshafer
added scripting ability with "@<filename>" command
changed all tabs to spaces!

Revision 1.18  2000/12/06 19:30:38  nshafer
added clear command
refined connection process.  if invalid username/password entered then prompt again

Revision 1.17  2000/12/05 22:20:58  nshafer
Tightened up outputs.  Doesn't show column names if no rows selected, if
it's not a select, then show number of rows affected

Revision 1.16  2000/12/04 18:04:53  nshafer
*** empty log message ***

Revision 1.15  2000/12/04 18:03:14  nshafer
fixed bug where the -H option was interpreted as -h or help.  All command
line options are now case sensitive

Revision 1.14  2000/12/04 17:54:38  nshafer
Added list command (and \l and l)

Revision 1.13  2000/12/04 17:34:18  nshafer
fixed a formatting issue if Time::HiRes isn't installed

Revision 1.12  2000/12/04 17:29:41  nshafer
Added benchmark options to view the extended benchmark info.  Now it displays
just the time in a more friendly format.  The old style is only active if the
benchmark option is specified.
Cleaned up some formatting issues
Brought the usage and POD documentation up to date
Added some items to the TODO

Revision 1.11  2000/11/30 22:54:38  nshafer
Fixed bug with the edit command where if you were 'inquotes' then you would
stay in quotes even after editing the file

Revision 1.10  2000/11/30 22:01:38  nshafer
Fixed bug where username and password were added to the command history.
Set it so that the quit commands are not added to the command history either.
Added the 'edit' command and modified it's todo list item, as well as added
it to the 'help' command

Revision 1.9  2000/11/29 17:55:35  nshafer
changed version from .21 to 1.0 beta 9.  I'll follow the revision numbers now

Revision 1.8  2000/11/29 17:46:31  nshafer
added a few items to the todo list

Revision 1.7  2000/11/29 15:50:56  nshafer
got rid of SID output at startup

Revision 1.6  2000/11/29 15:49:51  nshafer
moved revision info to $revision and added Id output

Revision 1.5  2000/11/29 15:46:41  nshafer
fixed revision number

Revision 1.4  2000/11/29 15:44:23  nshafer
fixed issue where environment variable ORACLE_SID overwrote explicit set
on the command line.  now whatever you put on the command line will overwrite
the environment variable

=cut

