Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
DeadlockResolver.php
1<?php
2
3namespace Bitrix\Im\V2\Common;
4
8
10{
11 protected static int $defaultMaxTryCount = 3;
12
13 protected static function executeDeadlockSafeQuery(string $sql, ?int $maxRetryCount = null): void
14 {
15 $maxRetryCount ??= self::$defaultMaxTryCount;
16
17 try
18 {
19 Application::getConnection()->queryExecute($sql);
20 }
21 catch (SqlQueryException $e)
22 {
23 if (self::isDeadlock($e))
24 {
25 Application::getInstance()->addBackgroundJob(static fn () => self::retryQuery($sql, $maxRetryCount));
26 }
27 }
28 }
29
30 protected static function retryQuery(string $sql, ?int $maxRetryCount = null): void
31 {
32 $maxRetryCount ??= self::$defaultMaxTryCount;
33 $retryCount = 1;
34 $isSuccess = false;
35
36 while (!$isSuccess)
37 {
38 $isSuccess = true;
39 try
40 {
41 Application::getConnection()->queryExecute($sql);
42 }
43 catch (SqlQueryException $e)
44 {
45 if (self::isDeadlock($e))
46 {
47 $isSuccess = false;
48 if ($retryCount >= $maxRetryCount)
49 {
50 throw $e;
51 }
52 $retryCount++;
53 usleep(500000); // 0.5 sec
54 }
55 }
56 }
57 }
58
59 protected static function prepareFieldsToMinimizeDeadlocks(array $insert, array $uniqueKeys): array
60 {
61 $sortBy = [];
62
63 foreach ($uniqueKeys as $key)
64 {
65 $sortBy[$key] = SORT_ASC;
66 }
67
68 Collection::sortByColumn($insert, $sortBy);
69
70 return $insert;
71 }
72
73 protected static function getIndexKey(array $row, array $uniqueKeys): string
74 {
75 $values = [];
76 foreach ($uniqueKeys as $uniqueKey)
77 {
78 $values[] = $row[$uniqueKey];
79 }
80
81 return implode('|', $values);
82 }
83
84 protected static function isDeadlock(SqlQueryException $exception): bool
85 {
86 return mb_stripos($exception->getMessage(), '1213') !== false;
87 }
88}
static getConnection($name="")