
use strict;
use warnings;
use Sleepycat::DbXml;

#
# Example 10
#
# Create two XML Containers within a Berkeley DB environment,
# configure default deadlock detection, then within a Berkeley
# DB transaction add a document to each container. If a
# deadlock occurs then retry the transaction.
#

eval
{
	my $dbenv = new DbEnv ;
	$dbenv->set_lk_detect(Db::DB_LOCK_DEFAULT);
	$dbenv->open(undef, Db::DB_CREATE | Db::DB_INIT_LOCK | Db::DB_INIT_LOG |
			    Db::DB_INIT_MPOOL | Db::DB_INIT_TXN);
	my $container1 = new XmlContainer($dbenv, "test1.dbxml");
	my $container2 = new XmlContainer($dbenv, "test2.dbxml");
	my $retry = 1;

	while($retry)
	{
		eval
		{
			my $txn = $dbenv->txn_begin;
			$container1->open($txn, Db::DB_CREATE);
			$container2->open($txn, Db::DB_CREATE);
			my $document = new XmlDocument ;
			$document->setContent(
			    "<book><title>Knowledge Discovery in Databases.</title></book>");
			$container1->putDocument($txn, $document);
			$container2->putDocument($txn, $document);
			$txn->commit;
			$container1->close;
			$container2->close;
			$container1->remove;
			$container2->remove;
			$retry = 0;
		};
		my $e ;
		if ($e = catch DbDeadlockException)
		{
			# do nothing
		}
		elsif ($e = catch DbException or
		       $e = catch std::exception)
		{
			warn $e->what() . "\n";
			$retry = 0;
		}
	}

	$dbenv->close;
};

if (my $e = catch std::exception)
{
	warn $e->what() . "\n";
}
elsif($@)
{
	warn $@;
}
