#!/usr/bin/perl

# RUN AS:
#
# ORACLE_HOME=/nfs/nikam/sw/oracle-10.2/ora_home_10.2/ LC_ALL=C AESOP_PASSWD=<password-of-MAMOPER> perl oracle_dump
#

use strict;
use warnings;
use utf8;

use lib '/nfs/nikam/sw/oracle-10.2/perl/lib/perl';
use DBI;
use DBD::Oracle qw(:ora_types);
$ENV{'NLS_LANG'}='CZECH.UTF8';


my $pass = $ENV{'AESOP_PASSWD'} // die "You must set AESOP_PASSWD\n";
my $dbh = DBI->connect('dbi:Oracle:host=mffout.karlov.mff.cuni.cz;service_name=mffout.karlov.mff.cuni.cz;port=1521',
  'mamoper', $pass, {ora_connect_with_default_signals => [ 'INT' ], 'LongReadLen' => 1000000 }) or die;

$, = "\t";
$\ = "\n";
my $dump_directory = "oracle_dks_dump";
mkdir $dump_directory unless -d $dump_directory;

sub dump_table($){
	my $name = shift;
	print $name;
	my $filename = $dump_directory."/".$name.".csv";
	open(my $fh, ">:encoding(UTF-8)", $filename);
	select $fh;
	my $query = $dbh->prepare("SELECT * FROM $name");
	$query->execute;
	print @{$query->{NAME}};
	print @{$query->{TYPE}};
	while (my @row = $query->fetchrow_array()) {
		$_//='' for @row;
		s/\t/\\t/g for @row;
		s/\n/\\n/g for @row;
		print @row;
	}
	select STDOUT;
	close $fh;
}

# my $query = $dbh->prepare("SELECT table_name, TABLESPACE_NAME FROM all_tables WHERE owner='MAMOPER'");
my $query = $dbh->prepare("SELECT table_name, owner FROM all_tables");
$query->execute;
while (my @row = $query->fetchrow_array()) {
	if (!( $row[1] eq 'SYS')) {
		dump_table "$row[1].$row[0]"; 
	}
}