55namespace Enqueue \Dbal ;
66
77use Doctrine \DBAL \Connection ;
8+ use Doctrine \DBAL \ParameterType ;
89use Doctrine \DBAL \Types \Type ;
910
1011trait DbalConsumerHelperTrait
@@ -20,20 +21,22 @@ protected function fetchMessage(array $queues, string $deliveryId, int $redelive
2021
2122 $ this ->getConnection ()->beginTransaction ();
2223
23- $ message = $ this ->getConnection ()->createQueryBuilder ()
24+ $ query = $ this ->getConnection ()->createQueryBuilder ()
2425 ->select ('* ' )
2526 ->from ($ this ->getContext ()->getTableName ())
2627 ->andWhere ('delivery_id IS NULL ' )
2728 ->andWhere ('delayed_until IS NULL OR delayed_until <= :delayedUntil ' )
2829 ->andWhere ('queue IN (:queues) ' )
2930 ->addOrderBy ('priority ' , 'desc ' )
3031 ->addOrderBy ('published_at ' , 'asc ' )
31- ->setParameter ('delayedUntil ' , $ now , \Doctrine \DBAL \ParameterType::INTEGER )
32- ->setParameter ('queues ' , array_values ($ queues ), \Doctrine \DBAL \Connection::PARAM_STR_ARRAY )
33- ->setMaxResults (1 )
34- ->execute ()
35- ->fetch ()
36- ;
32+ ->setMaxResults (1 );
33+
34+ // select for update
35+ $ message = $ this ->getConnection ()->executeQuery (
36+ $ query ->getSQL ().' ' .$ this ->getConnection ()->getDatabasePlatform ()->getWriteLockSQL (),
37+ ['delayedUntil ' => $ now , 'queues ' => array_values ($ queues )],
38+ ['delayedUntil ' => ParameterType::INTEGER , 'queues ' => Connection::PARAM_STR_ARRAY ]
39+ )->fetch ();
3740
3841 if (!$ message ) {
3942 $ this ->getConnection ()->commit ();
@@ -50,7 +53,8 @@ protected function fetchMessage(array $queues, string $deliveryId, int $redelive
5053 ->setParameter ('id ' , $ message ['id ' ], Type::GUID )
5154 ->setParameter ('deliveryId ' , $ deliveryId , Type::STRING )
5255 ->setParameter ('redeliverAfter ' , $ now + $ redeliveryDelay , Type::BIGINT )
53- ->execute ();
56+ ->execute ()
57+ ;
5458
5559 $ this ->getConnection ()->commit ();
5660
@@ -61,7 +65,8 @@ protected function fetchMessage(array $queues, string $deliveryId, int $redelive
6165 ->setParameter ('deliveryId ' , $ deliveryId , Type::STRING )
6266 ->setMaxResults (1 )
6367 ->execute ()
64- ->fetch ();
68+ ->fetch ()
69+ ;
6570
6671 return $ deliveredMessage ?: null ;
6772 } catch (\Exception $ e ) {
0 commit comments