#----------------------------------------------------------------------
# Log into the Oracle database
#

sub DBLogin {
    $DB = &ora_login('', $DBUser, $DBPassword);
    
    print "Logging in as $DBUser, $DBPassword\n" if ($DEBUG);

    die "$ora_errstr\n" if ($ora_errno != 0);
}

sub DBLogoff {
    &ora_logoff($DB);
}

sub DBinit {
    $ENV{'ORACLE_HOME'} = "/cosmic/oracle";
    $ENV{'ORACLE_SID'} = "oracle";
    $ENV{'TWO_TASK'} = "T:$DBServer:$DBDatabase";
}

#----------------------------------------------------------------------
# Used everywhere, sql--> table builder..
#

sub sql {
    local($db,$sql,$sep)=@_;			# local copy parameters
    
    @res = ();

    $sep = '~' unless $sep;			# provide default for sep

    $csr = &ora_open($db, $sql);
    die "$ora_errstr $sql\n" if ($ora_errno != 0);

    if (($nfields = &ora_fetch($csr)) > 0) { # does the statement return data?
	while (@data = &ora_fetch($csr)) {
	    die "$ora_errstr $sql\n" if ($ora_errno != 0);
	    push(@res,join($sep,@data));
	}
    }
    die "$ora_errstr\n" if ($ora_errno != 0);

    &ora_close($csr);
    @res;
}

sub DBcolumnList {
    local ($table,$search) = @_;
    local ($where);
    local (@cols);
	
    $where  =  "cols.column_name like \'$search\' and" if ($search);
    
    @cols = &sql($DB, 
	       "SELECT column_name from ACCESSIBLE_COLUMNS cols
                WHERE $where cols.table_name = '$table'
    ");

    return(@cols);
}

#
# Oracle list of tables
#
    
sub DBtableList {
    local (@tables) = ("");
    local ($search) = @_;
	
    $DBUser =~ tr/a-z/A-Z/;
    $where  =  "and o.table_name like \'$search\'" if ($search);
    @tables =  &sql($DB, 
		   "SELECT o.table_name
                    FROM accessible_tables o
                    WHERE (o.table_type = 'VIEW' or o.table_type = 'TABLE')
                          and o.owner = '$DBUser'
                    order by o.table_name");

    return(@tables);
}

#--------------------------------------------------------------------
# type of the column..  (CHAR, etc..)
#

sub DBcolumnType {
    local($tablecol) = @_;
    local ($table,$column) = split(/\./, $tablecol);
    local ($where);

    @cols = &sql($DB, 
	       "SELECT data_type from ACCESSIBLE_COLUMNS cols
                WHERE $where cols.table_name = '$table'
    ");

    return (shift(@cols));
}


1; # for require
