Skip to content

Commit

Permalink
patch
Browse files Browse the repository at this point in the history
  • Loading branch information
AnourValar committed Apr 22, 2023
1 parent 8459ec7 commit 9320f1d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Service.php
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,10 @@ protected function canonizeArgs($value)
*/
protected function cleanUp(\Illuminate\Database\Connection $connection, string $table): void
{
if (! mt_rand(0, 10)) {
if (! mt_rand(0, 50)) {
$connection
->table($table)
->where('updated_at', '<=', date('Y-m-d H:i:s', strtotime('-1 day')))
->where('updated_at', '<=', date('Y-m-d H:i:s', strtotime('-5 days')))
->delete();
}
}
Expand Down
45 changes: 45 additions & 0 deletions src/Strategies/OptimisticTransactionStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,51 @@ public function lock(string $sha1, Connection $connection, string $table): void
}
}

/**
* @param string $sha1
* @param \Illuminate\Database\Connection $connection
* @param string $table
* @param bool $reTry
* @throws \Exception
* @return void
*/
protected function apply(string $sha1, Connection $connection, string $table, bool $reTry = true): void
{
$connection->beginTransaction();

try {
$record = $connection->table($table)->lock($this->getLock())->where('sha1', '=', $sha1)->first();
} catch (\Illuminate\Database\QueryException $e) {
$connection->rollBack();
throw $e;
}

if ($record) {
$connection->table($table)->where('sha1', '=', $sha1)->update(['updated_at' => date('Y-m-d H:i:s')]);

$connection->commit();
return;
}

if (! $reTry) {
$connection->rollBack();
throw new \Exception('Something went wrong.');
}

try {
$connection->table($table)->insert(['sha1' => $sha1, 'updated_at' => date('Y-m-d H:i:s')]);
$connection->commit();
} catch (\Illuminate\Database\QueryException $e) {
$connection->rollBack();
} catch (\Throwable $e) {
$connection->rollBack();

throw $e;
}

$this->apply($sha1, $connection, $table, false);
}

/**
* {@inheritDoc}
* @see \AnourValar\LaravelAtom\Strategies\TransactionStrategy::getLock()
Expand Down

0 comments on commit 9320f1d

Please sign in to comment.