PreparedStatement.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\DB;
  8. use Doctrine\DBAL\Exception;
  9. use Doctrine\DBAL\ParameterType;
  10. use Doctrine\DBAL\Statement;
  11. use OCP\DB\IPreparedStatement;
  12. use OCP\DB\IResult;
  13. use PDO;
  14. /**
  15. * Adapts our public API to what doctrine/dbal exposed with 2.6
  16. *
  17. * The old dbal statement had stateful methods e.g. to fetch data from an executed
  18. * prepared statement. To provide backwards compatibility to apps we need to make
  19. * this class stateful. As soon as those now deprecated exposed methods are gone,
  20. * we can limit the API of this adapter to the methods that map to the direct dbal
  21. * methods without much magic.
  22. */
  23. class PreparedStatement implements IPreparedStatement {
  24. /** @var Statement */
  25. private $statement;
  26. /** @var IResult|null */
  27. private $result;
  28. public function __construct(Statement $statement) {
  29. $this->statement = $statement;
  30. }
  31. public function closeCursor(): bool {
  32. $this->getResult()->closeCursor();
  33. return true;
  34. }
  35. public function fetch(int $fetchMode = PDO::FETCH_ASSOC) {
  36. return $this->getResult()->fetch($fetchMode);
  37. }
  38. public function fetchAll(int $fetchMode = PDO::FETCH_ASSOC): array {
  39. return $this->getResult()->fetchAll($fetchMode);
  40. }
  41. public function fetchColumn() {
  42. return $this->getResult()->fetchOne();
  43. }
  44. public function fetchOne() {
  45. return $this->getResult()->fetchOne();
  46. }
  47. public function bindValue($param, $value, $type = ParameterType::STRING): bool {
  48. return $this->statement->bindValue($param, $value, $type);
  49. }
  50. public function bindParam($param, &$variable, $type = ParameterType::STRING, $length = null): bool {
  51. return $this->statement->bindParam($param, $variable, $type, $length);
  52. }
  53. public function execute($params = null): IResult {
  54. return ($this->result = new ResultAdapter($this->statement->execute($params)));
  55. }
  56. public function rowCount(): int {
  57. return $this->getResult()->rowCount();
  58. }
  59. private function getResult(): IResult {
  60. if ($this->result !== null) {
  61. return $this->result;
  62. }
  63. throw new Exception("You have to execute the prepared statement before accessing the results");
  64. }
  65. }