#!/usr/bin/perl

# $Id: mysql2dia,v 1.3 2004/12/29 19:41:21 itamarc Exp $

use strict;
use DBI;
use Getopt::Mixed "nextOption";
use GenDia;

my $debug = 0;
my ($banco,$host,$outfile,$username,$password) = &getParams();
my $dbh = DBI->connect("dbi:mysql:".$banco.":".$host, $username, $password) or die "Error with DB connection.";

# Get database data
my %data;
my $sql = "SHOW TABLES";
my $tables = &runSql($sql);
foreach my $table (@{$tables}) {
	$sql = "DESCRIBE ".$table->[0];
	my $fields = &runSql($sql);
	foreach my $field (@{$fields}) {
		$data{$table->[0]}{FIELDS}{$field->[0]} = $field->[1];
	}
}

# Generate file
my $generator = new GenDia(debug=>$debug);
$generator->setOutfile($outfile);
$generator->setData(\%data);
$generator->store();

#############################################################
sub runSql {
	my $sql = shift;
	my $rows = undef;
	my $sth = $dbh->prepare($sql);
	$sth->execute();
	if ($sth->rows) {
		$rows = $sth->fetchall_arrayref;
	}
	$sth->finish();
	return $rows;
}

sub usage {
	print qq|Usage:
$0 -d database [-h host] [-o outputfile] [-D] [-u user] [-p password]
	-d	database is mandatory.
	-h	host default is "localhost".
	-o	outputfile default is "[database].dia".
	-D	activate debug mode.
	-u	database user name.
	-p	database password.

|;
}

sub getParams {
	my ($db,$host,$file,$username,$password) = ("","localhost","","root","");
	Getopt::Mixed::init("d=s h=s o=s D u=s p=s");
	while (my ($option, $value) = nextOption()) {
		if($option eq "d") {
			$db = $value;
		} elsif ($option eq "h") {
			$host = $value;
		} elsif ($option eq "o") {
			$file = $value;
		} elsif ($option eq "D") {
			print "Debug mode activated.\n";
			$debug++;
		} elsif ($option eq "u") {
			$username = $value
		} elsif ($option eq "p") {
			$password = $value
		}
	}
	Getopt::Mixed::cleanup();
	if(!$db) {
		&usage();
		exit(1);
	} else {
		if(!$file) {
			$file = $db.'.dia';
		}
	}
	return ($db,$host,$file,$username,$password);
}

1;

