Skip to content

Commit

Permalink
chore(db): Apply query prepared statements
Browse files Browse the repository at this point in the history
  • Loading branch information
solracsf committed Oct 17, 2024
1 parent 40fd76f commit 955aa2e
Show file tree
Hide file tree
Showing 10 changed files with 88 additions and 110 deletions.
28 changes: 11 additions & 17 deletions apps/dav/lib/CalDAV/Reminder/Backend.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,16 @@
*/
class Backend {

/** @var IDBConnection */
protected $db;

/** @var ITimeFactory */
private $timeFactory;

/**
* Backend constructor.
*
* @param IDBConnection $db
* @param ITimeFactory $timeFactory

Check failure on line 25 in apps/dav/lib/CalDAV/Reminder/Backend.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

MismatchingDocblockParamType

apps/dav/lib/CalDAV/Reminder/Backend.php:25:12: MismatchingDocblockParamType: Parameter $timeFactory has wrong type 'OCP\AppFramework\Utility\ITimeFactory', should be 'OCA\DAV\CalDAV\Reminder\protectedITimeFactory' (see https://psalm.dev/141)

Check failure on line 25 in apps/dav/lib/CalDAV/Reminder/Backend.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

UndefinedClass

apps/dav/lib/CalDAV/Reminder/Backend.php:25:12: UndefinedClass: Class, interface or enum named OCA\DAV\CalDAV\Reminder\protectedITimeFactory does not exist (see https://psalm.dev/019)
*/
public function __construct(IDBConnection $db,
ITimeFactory $timeFactory) {
$this->db = $db;
$this->timeFactory = $timeFactory;
public function __construct(
protected IDBConnection $db,
protectedITimeFactory $timeFactory,
) {
}

/**
Expand All @@ -50,7 +44,7 @@ public function getRemindersToProcess():array {
->join('cr', 'calendarobjects', 'co', $query->expr()->eq('cr.object_id', 'co.id'))
->join('cr', 'calendars', 'c', $query->expr()->eq('cr.calendar_id', 'c.id'))
->groupBy('cr.event_hash', 'cr.notification_date', 'cr.type', 'cr.id', 'cr.calendar_id', 'cr.object_id', 'cr.is_recurring', 'cr.uid', 'cr.recurrence_id', 'cr.is_recurrence_exception', 'cr.alarm_hash', 'cr.is_relative', 'cr.is_repeat_based', 'co.calendardata', 'c.displayname', 'c.principaluri');
$stmt = $query->execute();
$stmt = $query->executeQuery();

return array_map(
[$this, 'fixRowTyping'],
Expand All @@ -69,7 +63,7 @@ public function getAllScheduledRemindersForEvent(int $objectId):array {
$query->select('*')
->from('calendar_reminders')
->where($query->expr()->eq('object_id', $query->createNamedParameter($objectId)));
$stmt = $query->execute();
$stmt = $query->executeQuery();

return array_map(
[$this, 'fixRowTyping'],
Expand Down Expand Up @@ -122,7 +116,7 @@ public function insertReminder(int $calendarId,
'notification_date' => $query->createNamedParameter($notificationDate),
'is_repeat_based' => $query->createNamedParameter($isRepeatBased ? 1 : 0),
])
->execute();
->executeStatement();

return $query->getLastInsertId();
}
Expand All @@ -139,7 +133,7 @@ public function updateReminder(int $reminderId,
$query->update('calendar_reminders')
->set('notification_date', $query->createNamedParameter($newNotificationDate))
->where($query->expr()->eq('id', $query->createNamedParameter($reminderId)))
->execute();
->executeStatement();
}

/**
Expand All @@ -153,7 +147,7 @@ public function removeReminder(int $reminderId):void {

$query->delete('calendar_reminders')
->where($query->expr()->eq('id', $query->createNamedParameter($reminderId)))
->execute();
->executeStatement();
}

/**
Expand All @@ -166,7 +160,7 @@ public function cleanRemindersForEvent(int $objectId):void {

$query->delete('calendar_reminders')
->where($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
->execute();
->executeStatement();
}

/**
Expand All @@ -180,7 +174,7 @@ public function cleanRemindersForCalendar(int $calendarId):void {

$query->delete('calendar_reminders')
->where($query->expr()->eq('calendar_id', $query->createNamedParameter($calendarId)))
->execute();
->executeStatement();
}

/**
Expand Down
15 changes: 5 additions & 10 deletions apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,16 @@

class RefreshWebcalJobRegistrar implements IRepairStep {

/** @var IDBConnection */
private $connection;

/** @var IJobList */
private $jobList;

/**
* FixBirthdayCalendarComponent constructor.
*
* @param IDBConnection $connection
* @param IJobList $jobList
*/
public function __construct(IDBConnection $connection, IJobList $jobList) {
$this->connection = $connection;
$this->jobList = $jobList;
public function __construct(
private IDBConnection $connection,
private IJobList $jobList,
) {
}

/**
Expand All @@ -47,7 +42,7 @@ public function run(IOutput $output) {
$query = $this->connection->getQueryBuilder();
$query->select(['principaluri', 'uri'])
->from('calendarsubscriptions');
$stmt = $query->execute();
$stmt = $query->executeQuery();

$count = 0;
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
Expand Down
16 changes: 7 additions & 9 deletions apps/dav/lib/Migration/RemoveClassifiedEventActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@

class RemoveClassifiedEventActivity implements IRepairStep {

/** @var IDBConnection */
private $connection;

public function __construct(IDBConnection $connection) {
$this->connection = $connection;
public function __construct(
private IDBConnection $connection,
) {
}

/**
Expand Down Expand Up @@ -58,7 +56,7 @@ protected function removePrivateEventActivity(): int {
->from('calendarobjects', 'o')
->leftJoin('o', 'calendars', 'c', $query->expr()->eq('c.id', 'o.calendarid'))
->where($query->expr()->eq('o.classification', $query->createNamedParameter(CalDavBackend::CLASSIFICATION_PRIVATE)));
$result = $query->execute();
$result = $query->executeQuery();

while ($row = $result->fetch()) {
if ($row['principaluri'] === null) {
Expand All @@ -69,7 +67,7 @@ protected function removePrivateEventActivity(): int {
->setParameter('type', 'calendar')
->setParameter('calendar_id', $row['calendarid'])
->setParameter('event_uid', '%' . $this->connection->escapeLikeParameter('{"id":"' . $row['uid'] . '"') . '%');
$deletedEvents += $delete->execute();
$deletedEvents += $delete->executeStatement();
}
$result->closeCursor();

Expand All @@ -92,7 +90,7 @@ protected function removeConfidentialUncensoredEventActivity(): int {
->from('calendarobjects', 'o')
->leftJoin('o', 'calendars', 'c', $query->expr()->eq('c.id', 'o.calendarid'))
->where($query->expr()->eq('o.classification', $query->createNamedParameter(CalDavBackend::CLASSIFICATION_CONFIDENTIAL)));
$result = $query->execute();
$result = $query->executeQuery();

while ($row = $result->fetch()) {
if ($row['principaluri'] === null) {
Expand All @@ -104,7 +102,7 @@ protected function removeConfidentialUncensoredEventActivity(): int {
->setParameter('calendar_id', $row['calendarid'])
->setParameter('event_uid', '%' . $this->connection->escapeLikeParameter('{"id":"' . $row['uid'] . '"') . '%')
->setParameter('filtered_name', '%' . $this->connection->escapeLikeParameter('{"id":"' . $row['uid'] . '","name":"Busy"') . '%');
$deletedEvents += $delete->execute();
$deletedEvents += $delete->executeStatement();
}
$result->closeCursor();

Expand Down
14 changes: 8 additions & 6 deletions apps/files_sharing/lib/ShareBackend/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
use OC\Files\View;
use OCA\FederatedFileSharing\FederatedShareProvider;
use OCA\Files_Sharing\Helper;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Files\NotFoundException;
use OCP\IDBConnection;
use OCP\Server;
use OCP\Share\IShare;
use OCP\Share_Backend_File_Dependent;
Expand All @@ -27,10 +29,10 @@ class File implements Share_Backend_File_Dependent {

private $path;

/** @var FederatedShareProvider */
private $federatedShareProvider;

public function __construct(?FederatedShareProvider $federatedShareProvider = null) {
public function __construct(
private ?FederatedShareProvider $federatedShareProvider = null,
protected IDBConnection $connection,
) {
if ($federatedShareProvider) {
$this->federatedShareProvider = $federatedShareProvider;
} else {
Expand Down Expand Up @@ -183,13 +185,13 @@ protected static function resolveReshares($source) {
if (isset($source['parent'])) {
$parent = $source['parent'];
while (isset($parent)) {
$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$qb = $this->connection->getQueryBuilder();

Check failure on line 188 in apps/files_sharing/lib/ShareBackend/File.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

InvalidScope

apps/files_sharing/lib/ShareBackend/File.php:188:11: InvalidScope: Invalid reference to $this in a static context (see https://psalm.dev/013)
$qb->select('parent', 'uid_owner')
->from('share')
->where(
$qb->expr()->eq('id', $qb->createNamedParameter($parent))
);
$result = $qb->execute();
$result = $qb->executeQuery();
$item = $result->fetch();
$result->closeCursor();
if (isset($item['parent'])) {
Expand Down
4 changes: 2 additions & 2 deletions apps/user_status/lib/Db/UserStatusMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public function clearStatusesOlderThan(int $olderThan, int $now): void {
$qb->expr()->eq('status', $qb->createNamedParameter(IUserStatus::ONLINE))
));

$qb->execute();
$qb->executeStatement();
}

/**
Expand All @@ -140,7 +140,7 @@ public function clearOlderThanClearAt(int $timestamp): void {
->where($qb->expr()->isNotNull('clear_at'))
->andWhere($qb->expr()->lte('clear_at', $qb->createNamedParameter($timestamp, IQueryBuilder::PARAM_INT)));

$qb->execute();
$qb->executeStatement();
}


Expand Down
2 changes: 1 addition & 1 deletion core/Db/LoginFlowV2Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public function cleanup(): void {
$qb->expr()->lt('timestamp', $qb->createNamedParameter($this->timeFactory->getTime() - self::lifetime))
);

$qb->execute();
$qb->executeStatement();
}

/**
Expand Down
28 changes: 15 additions & 13 deletions lib/private/Files/Cache/Storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ public static function getGlobalCache() {
* @param bool $isAvailable
* @throws \RuntimeException
*/
public function __construct($storage, $isAvailable, IDBConnection $connection) {
public function __construct(
$storage,
$isAvailable,
protected IDBConnection $connection,
) {
if ($storage instanceof IStorage) {
$this->storageId = $storage->getId();
} else {
Expand Down Expand Up @@ -149,15 +153,15 @@ public function getAvailability() {
public function setAvailability($isAvailable, int $delay = 0) {
$available = $isAvailable ? 1 : 0;
if (!$isAvailable) {
\OC::$server->get(LoggerInterface::class)->info('Storage with ' . $this->storageId . ' marked as unavailable', ['app' => 'lib']);
\OCP\Server::get(LoggerInterface::class)->info('Storage with ' . $this->storageId . ' marked as unavailable', ['app' => 'lib']);
}

$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = $this->connection->getQueryBuilder();
$query->update('storages')
->set('available', $query->createNamedParameter($available))
->set('last_checked', $query->createNamedParameter(time() + $delay))
->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
$query->execute();
$query->executeStatement();
}

/**
Expand All @@ -179,16 +183,16 @@ public static function remove($storageId) {
$storageId = self::adjustStorageId($storageId);
$numericId = self::getNumericStorageId($storageId);

$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = $this->connection->getQueryBuilder();
$query->delete('storages')
->where($query->expr()->eq('id', $query->createNamedParameter($storageId)));
$query->execute();
$query->executeStatement();

if (!is_null($numericId)) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = $this->connection->getQueryBuilder();
$query->delete('filecache')
->where($query->expr()->eq('storage', $query->createNamedParameter($numericId)));
$query->execute();
$query->executeStatement();
}
}

Expand All @@ -198,12 +202,10 @@ public static function remove($storageId) {
* @param int $mountId
*/
public static function cleanByMountId(int $mountId) {
$db = \OC::$server->getDatabaseConnection();

try {
$db->beginTransaction();
$this->connection->beginTransaction();

$query = $db->getQueryBuilder();
$query = $this->connection->getQueryBuilder();
$query->select('storage_id')
->from('mounts')
->where($query->expr()->eq('mount_id', $query->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
Expand All @@ -225,7 +227,7 @@ public static function cleanByMountId(int $mountId) {
->where($query->expr()->eq('mount_id', $query->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
$query->executeStatement();

$db->commit();
$this->connection->commit();
} catch (\Exception $e) {
$db->rollBack();
throw $e;
Expand Down
24 changes: 6 additions & 18 deletions lib/private/Repair/RepairDavShares.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,27 +23,15 @@
class RepairDavShares implements IRepairStep {
protected const GROUP_PRINCIPAL_PREFIX = 'principals/groups/';

/** @var IConfig */
private $config;
/** @var IDBConnection */
private $dbc;
/** @var IGroupManager */
private $groupManager;
/** @var LoggerInterface */
private $logger;
/** @var bool */
private $hintInvalidShares = false;

public function __construct(
IConfig $config,
IDBConnection $dbc,
IGroupManager $groupManager,
LoggerInterface $logger,
private IConfig $config,
private IDBConnection $dbc,
private IGroupManager $groupManager,
private LoggerInterface $logger,
) {
$this->config = $config;
$this->dbc = $dbc;
$this->groupManager = $groupManager;
$this->logger = $logger;
}

/**
Expand All @@ -64,7 +52,7 @@ protected function repairUnencodedGroupShares() {
->set('principaluri', $updateQuery->createParameter('updatedPrincipalUri'))
->where($updateQuery->expr()->eq('id', $updateQuery->createParameter('shareId')));

$statement = $qb->execute();
$statement = $qb->executeQuery();
while ($share = $statement->fetch()) {
$gid = substr($share['principaluri'], strlen(self::GROUP_PRINCIPAL_PREFIX));
$decodedGid = urldecode($gid);
Expand Down Expand Up @@ -93,7 +81,7 @@ protected function repairUnencodedGroupShares() {
$updateQuery
->setParameter('updatedPrincipalUri', $fixedPrincipal)
->setParameter('shareId', $share['id'])
->execute();
->executeStatement();
$this->logger->info('Repaired principal for dav share {id} from {old} to {new}', $logParameters);
} catch (Exception $e) {
$logParameters['message'] = $e->getMessage();
Expand Down
Loading

0 comments on commit 955aa2e

Please sign in to comment.