#!/usr/local/bin/perl 

use DBI;
use strict;

MAIN: 
{
	my($key, $value, $addition);

	my($source, $TourId, $QId);

	print "Before connecting to the DB\n";
	
	my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
		or die "Can't connect to DB chgk\n";

	print "Connected successfully\n";

	while ($source = shift) {
		print "$source\n";
		
		my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments WHERE ParentId = $source");
		$sth->execute;

		while ($TourId = ($sth->fetchrow)[0]) {

			my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions 
                                WHERE ParentId = $TourId");
			$sth->execute;


			while ($QId = ($sth->fetchrow)[0]) {

				#my ($sth) = $dbh->prepare("DELETE FROM Lines WHERE Id = $QId");
				#$sth->execute;

				my ($sth) = $dbh->prepare("DELETE FROM Questions WHERE QuestionId = $QId");
				$sth->execute;



			}

			my ($sth) = $dbh->prepare("DELETE FROM Tournaments WHERE Id = $TourId");
			$sth->execute;

		}

		my ($sth) = $dbh->prepare("DELETE FROM Tournaments WHERE Id = $source");
		$sth->execute;
	}
	$dbh->disconnect;
}
