aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/SQLUnionQuery.php
diff options
context:
space:
mode:
authorJan-Hendrik Willms <tleilax+studip@gmail.com>2025-06-06 13:01:38 +0200
committerJan-Hendrik Willms <tleilax+studip@gmail.com>2025-06-06 13:31:01 +0200
commit358428ebcd727c908c3367451373942d63009085 (patch)
treeb7b381c61fd3fa6fc5ba64c869ea4f1979c57a26 /lib/classes/SQLUnionQuery.php
parent538ea8b4871e0933d59c57393912ef1fe0737528 (diff)
restructure the query in BlubberThread::findMyGlobalThreads() by using UNION...
Closes #5628 Merge request studip/studip!4245
Diffstat (limited to 'lib/classes/SQLUnionQuery.php')
-rw-r--r--lib/classes/SQLUnionQuery.php87
1 files changed, 87 insertions, 0 deletions
diff --git a/lib/classes/SQLUnionQuery.php b/lib/classes/SQLUnionQuery.php
new file mode 100644
index 0000000..6254b78
--- /dev/null
+++ b/lib/classes/SQLUnionQuery.php
@@ -0,0 +1,87 @@
+<?php
+/**
+ * This class is to be used in combination with SQLQuery if you need to
+ * combine many SQLQuery objets into one single query using UNION.
+ */
+class SQLUnionQuery
+{
+ /**
+ * @var SQLQuery[]
+ */
+ protected array $queries;
+ protected bool $unionAll = false;
+
+ public function __construct(SQLQuery ...$queries)
+ {
+ $this->queries = $queries;
+ }
+
+ /**
+ * Adds a query to the union.
+ */
+ public function add(SQLQuery $query): void
+ {
+ $this->queries[] = $query;
+ }
+
+ /**
+ * Whether UNION ALL should be used or not
+ */
+ public function setUnionAll(bool $unionAll): void
+ {
+ $this->unionAll = $unionAll;
+ }
+
+ /**
+ * Returns the combined query
+ */
+ public function getQuery(): string
+ {
+ $queries = [];
+ foreach ($this->queries as $query) {
+ $queries[] = $query->show();
+ }
+
+ $query = implode(
+ $this->unionAll ? ' UNION ALL ' : ' UNION ',
+ $queries
+ );
+
+ return $query;
+ }
+
+ /**
+ * Returns the used parameters
+ */
+ public function getParameters(): array
+ {
+ $parameters = [];
+ foreach ($this->queries as $query) {
+ $parameters = array_merge($parameters, $query->settings['parameter'] ?? []);
+ }
+
+ return $parameters;
+ }
+
+ /**
+ * Fetches all rows from the combined query
+ */
+ public function fetchAll(callable $callable = null): array
+ {
+ return DBManager::get()->fetchAll(
+ $this->getQuery(),
+ $this->getParameters(),
+ $callable
+ );
+ }
+
+ /**
+ * Fetches a single column from all rows of the combined query
+ */
+ public function fetchFirst(int $columnNumber = 0): array
+ {
+ return $this->fetchAll(function ($row) use ($columnNumber) {
+ return array_values($row)[$columnNumber];
+ });
+ }
+}