DBIx::Locker - locks for db resources that might not be totally insane


version 1.103


...and a warning.

DBIx::Locker was written to replace some lousy database resource locking code. The code would establish a MySQL lock with GET_LOCK to lock arbitrary resources. Unfortunately, the code would also silently reconnect in case of database connection failure, silently losing the connection-based lock. DBIx::Locker locks by creating a persistent row in a "locks" table.

Because DBIx::Locker locks are stored in a table, they won't go away. They have to be purged regularly. (A program for doing this, dbix_locker_purge, is included.) The locked resource is just a string. All records in the lock (or semaphore) table are unique on the lock string.

This is the entire mechanism. This is quick and dirty and quite effective, but it's not highly efficient. If you need high speed locks with multiple levels of resolution, or anything other than a quick and brutal solution, keep looking.


This library should run on perls released even a long time ago. It should work on any version of perl released in the last five years.

Although it may work on older versions of perl, no guarantee is made that the minimum required version will not be increased. The version may be increased for any reason, and there is no promise that patches will be accepted to lower the minimum required perl.



  my $locker = DBIx::Locker->new(\%arg);

This returns a new locker.

Valid arguments are:

  dbh      - a database handle to use for locking
  dbi_args - an arrayref of args to pass to DBI->connect to reconnect to db
  table    - the table for locks



These methods may be defined in subclasses to provide defaults to be used when constructing a new locker.


This method returns the locker's dbh.


This method returns the name of the table in the database in which locks are stored.


  my $lock = $locker->lock($lockstring, \%arg);

This method attempts to return a new DBIx::Locker::Lock.


This method deletes expired semaphores.


This method exists so that subclasses can do something else to support their DBD for getting the id of the created lock. For example, with DBD::ODBC and SQL Server it should be:

 sub last_insert_id { ($_[0]->dbh->selectrow_array('SELECT @@IDENTITY'))[0] }


To use this module you'll need to create the lock table, which should have five columns:

  • id Autoincrementing ID is recommended

  • lockstring varchar(128) with a unique constraint

  • created datetime

  • expires datetime

  • locked_by text

See the sql directory included in this dist for DDL for your database.


Ricardo SIGNES <>


  • Arthur Axel 'fREW' Schmidt <>

  • Chris Nehren <>

  • Hans Dieter Pearcey <>

  • Matthew Horsfall <>

  • Ricardo Signes <>

  • Rob N ★ <>

  • Sergiy Borodych <>


This software is copyright (c) 2022 by Ricardo SIGNES.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.