PartitionQuery.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\DB\QueryBuilder\Partitioned;
  8. use OCP\DB\QueryBuilder\IQueryBuilder;
  9. /**
  10. * A sub-query from a partitioned join
  11. */
  12. class PartitionQuery {
  13. public const JOIN_MODE_INNER = 'inner';
  14. public const JOIN_MODE_LEFT = 'left';
  15. // left-join where the left side IS NULL
  16. public const JOIN_MODE_LEFT_NULL = 'left_null';
  17. public const JOIN_MODE_RIGHT = 'right';
  18. public function __construct(
  19. public IQueryBuilder $query,
  20. public string $joinFromColumn,
  21. public string $joinToColumn,
  22. public string $joinMode,
  23. ) {
  24. if ($joinMode !== self::JOIN_MODE_LEFT && $joinMode !== self::JOIN_MODE_INNER) {
  25. throw new InvalidPartitionedQueryException("$joinMode joins aren't allowed in partitioned queries");
  26. }
  27. }
  28. public function mergeWith(array $rows): array {
  29. if (empty($rows)) {
  30. return [];
  31. }
  32. // strip table/alias from column names
  33. $joinFromColumn = preg_replace('/\w+\./', '', $this->joinFromColumn);
  34. $joinToColumn = preg_replace('/\w+\./', '', $this->joinToColumn);
  35. $joinFromValues = array_map(function (array $row) use ($joinFromColumn) {
  36. return $row[$joinFromColumn];
  37. }, $rows);
  38. $joinFromValues = array_filter($joinFromValues, function ($value) {
  39. return $value !== null;
  40. });
  41. $this->query->andWhere($this->query->expr()->in($this->joinToColumn, $this->query->createNamedParameter($joinFromValues, IQueryBuilder::PARAM_STR_ARRAY, ':' . uniqid())));
  42. $s = $this->query->getSQL();
  43. $partitionedRows = $this->query->executeQuery()->fetchAll();
  44. $columns = $this->query->getOutputColumns();
  45. $nullResult = array_combine($columns, array_fill(0, count($columns), null));
  46. $partitionedRowsByKey = [];
  47. foreach ($partitionedRows as $partitionedRow) {
  48. $partitionedRowsByKey[$partitionedRow[$joinToColumn]][] = $partitionedRow;
  49. }
  50. $result = [];
  51. foreach ($rows as $row) {
  52. if (isset($partitionedRowsByKey[$row[$joinFromColumn]])) {
  53. if ($this->joinMode !== self::JOIN_MODE_LEFT_NULL) {
  54. foreach ($partitionedRowsByKey[$row[$joinFromColumn]] as $partitionedRow) {
  55. $result[] = array_merge($row, $partitionedRow);
  56. }
  57. }
  58. } elseif ($this->joinMode === self::JOIN_MODE_LEFT || $this->joinMode === self::JOIN_MODE_LEFT_NULL) {
  59. $result[] = array_merge($nullResult, $row);
  60. }
  61. }
  62. return $result;
  63. }
  64. }