如何在 DBIx:Class 中锁定 table?

How can I lock a table in DBIx:Class?

我正在用

编写一个小应用程序

在我的应用程序中,我需要执行以下操作;

  1. 做一些复杂的处理(需要一分钟才能完成)
  2. 将上述处理的结果数据插入 tables
  3. 获取最后的自增部分table,再做一些处理。
  4. 使用 (3) 中的值作为插入另一个 table(结点 table)的一部分

这是从第 2 步开始的一些示例代码

#step 2
my $device = $device_rs->create(
 {
  devicename      => $deviceName,
  objects         => \@objects
  object_groups   => \@objectgroups,

}
);

#step 3
my $lastogid  = $db->resultset('ObjectGroup')->get_column('objectgroupid')->max;
my $lastobid  = $db->resultset('Object')->get_column('objectid')->max;

my $obgcount = scalar(@objectgroups);
my $objcount = scalar(@objects);

my $ogoffset = $lastogid - $obgcount;
my $oboffset = $lastobid - $objcount;

#now increment the object/group ids by the offset which will be inserted into the many-  many table
foreach my $hash (@childobjects) {
 $hash->{'objectgroup_objectgroupid'} += $ogoffset;
 $hash->{'object_objectid'}           += $oboffset;
}

#step 4  - populate the junction table
$db->resultset('ObjectGroupHasObjects’)->populate(\@childobjects);

现在由于有多个线程运行一次,从第 3 步获得的值可能不正确(对于当前的“设备”)。

我正在尝试找到解决此问题的方法。我目前唯一能想到的就是在步骤 2) 之前锁定数据库 tables 并在步骤 4) 之后解锁。

我如何在 DBIx::Class 中执行此操作,这是否可以解决我的问题?

谢谢。

类似

$schema->dbh_do("LOCK TABLES names");
...
...
$schema->dbh_do("UNLOCK TABLES");

来源:http://www.perlmonks.org/?node_id=854538

另见:How to avoid race conditions when using the find_or_create method of DBIx::Class::ResultSet?

SQLHackers::SELECT#SELECT_..._FOR_UPDATE