Files
Carl Schwan 0ff3de5ab2 fix(db): set a busy_timeout PRAGMA for SQLite connections
SQLite's default busy timeout is 0, so a connection that finds the
database locked by a concurrent writer fails immediately with
"database is locked" instead of waiting briefly for the lock to
clear. This is easy to hit even on small/single-user instances when
two requests (e.g. a background poll and a user action) touch the
DB at the same time.

Add a 'sqlite.busy_timeout' config option (default 30000ms) wired
through the same path as the existing 'sqlite.journal_mode' option,
and apply it via PRAGMA busy_timeout in SQLiteSessionInit.

Assisted-by: ClaudeCode:claude-sonnet-5
Signed-off-by: Carl Schwan <carl@carlschwan.eu>
2026-10-22 11:27:37 +02:00

67 lines
2.0 KiB
PHP

<?php
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OC\DB;
use Doctrine\Common\EventSubscriber;
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
class SQLiteSessionInit implements EventSubscriber {
/**
* Configure case-sensitive like for each connection
*/
public function __construct(
private readonly bool $caseSensitiveLike,
private readonly string $journalMode,
private readonly int $busyTimeout,
) {
}
public function postConnect(ConnectionEventArgs $args): void {
$sensitive = $this->caseSensitiveLike ? 'true' : 'false';
$args->getConnection()->executeStatement('PRAGMA case_sensitive_like = ' . $sensitive);
$args->getConnection()->executeStatement('PRAGMA journal_mode = ' . $this->journalMode);
$args->getConnection()->executeStatement('PRAGMA foreign_keys = true');
$args->getConnection()->executeStatement('PRAGMA busy_timeout = ' . $this->busyTimeout);
/** @var \Doctrine\DBAL\Driver\PDO\Connection $connection */
$connection = $args->getConnection()->getWrappedConnection();
$pdo = $connection->getWrappedConnection();
$regexSubstr = function ($string, $pattern): string {
if (is_null($string) || is_null($pattern)) {
return '';
} else {
$string = (string)$string;
$pattern = str_replace('#', '\#', (string)$pattern);
}
$matches = [];
$result = preg_match("#$pattern#", $string, $matches);
if ($result === 0 || $result === false) {
return '';
} else {
return $matches[0];
}
};
if (PHP_VERSION_ID >= 80500 && method_exists($pdo, 'createFunction')) {
$pdo->createFunction('md5', 'md5', 1);
$pdo->createFunction('regexp_substr', $regexSubstr, 2);
} else {
$pdo->sqliteCreateFunction('md5', 'md5', 1);
$pdo->sqliteCreateFunction('regexp_substr', $regexSubstr, 2);
}
}
#[\Override]
public function getSubscribedEvents(): array {
return [Events::postConnect];
}
}