Perl和Rose :: DB Postgres交易

时间:2013-02-14 05:26:57

标签: perl postgresql transactions rose-db-object

我整天都在为这个问题苦苦挣扎..以为我会问这里,在我脱掉所有头发之前。

描述

我使用Perl 5.10.1与Rose :: DB和PostgreSQL 8.4(在Debian Linux上)。

我需要对我的" trans"进行一些更改。对象在单个事务块中(即更改全部写入或回滚)。但是,我无法让它发挥作用。

我已尝试使用AutoCommit ON和OFF。

在下面的示例代码中,$ db是在脚本开头建立的Rose :: DB连接(使用:my $ db = My :: DB-> new;)。所有Rose :: DB对象都从基类(My :: Base)继承。此基类具有DB连接的可继承子:

sub init_db
{
    My::DB->new_or_cached
}

数据库连接对象(My :: DB)包含连接字符串和设置:

_ _PACKAGE_ _->use_private_registry;

_ _PACKAGE_ _->register_db(
    driver          => 'pg',

database        => 'xx',
host            => 'localhost',
username        => 'xx',
password        => 'xx',

    connect_options => {
        AutoCommit      => 0,  -- changed to suit SCENARIO 1 and 2 below
        RaiseError      => 1,
    }
);

SCENARIO 1:AutoCommit OFF

AutoCommit 0和RaiseError 1

my $trans = shift;

eval {
    $trans->...        -- Make changes to object
    $trans->save;

    # die "testing";   -- Cause a rollback using "die"

    $db->commit or die $db->error;
};

if ($@)
{
    warn "aborted: $@";

    eval {
        $db->rollback;
    };
}

回滚案例:​​正常工作(没有写入数据库的更改)

提交案例:失败(没有写入数据库的更改)

SCENARIO 2:AutoCommit ON

AutoCommit 1和RaiseError 1

my $trans = shift;

eval {
    $db->begin_work or die $db->error;

    $trans->...        -- Make changes to object
    $trans->save;

    # die "testing";   -- Cause a rollback using "die"

    $db->commit or die $db->error;
};

if ($@)
{
    warn "aborted: $@";

    eval {
        $db->rollback;
    };
}

回滚案例:​​失败(写入数据库的更改)

提交案例:Works(写入DB的更改)

我们非常感谢您提供的任何帮助或建议。

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可能正在打开多个数据库连接。如果您提交的连接与具有事务的连接不同,则行为正是人们所期望的。

我建议你重新检查你的程序流程,以确保你只有一个连接。

相关问题