1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Pgsql; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use LogicException; |
9
|
|
|
use Yiisoft\Db\Driver\Pdo\AbstractPdoCommand; |
10
|
|
|
|
11
|
|
|
use function sprintf; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Implements a database command that can be executed with a PDO (PHP Data Object) database connection for PostgreSQL |
15
|
|
|
* Server. |
16
|
|
|
*/ |
17
|
|
|
final class Command extends AbstractPdoCommand |
18
|
|
|
{ |
19
|
1 |
|
public function showDatabases(): array |
20
|
|
|
{ |
21
|
1 |
|
$sql = <<<SQL |
22
|
|
|
SELECT datname FROM pg_database WHERE datistemplate = false AND datname NOT IN ('postgres', 'template0', 'template1') |
23
|
1 |
|
SQL; |
24
|
|
|
|
25
|
1 |
|
return $this->setSql($sql)->queryColumn(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @see {https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html} |
30
|
|
|
* |
31
|
|
|
* @param string $viewName |
32
|
|
|
* @param bool|null $concurrently Add [ CONCURRENTLY ] to refresh command |
33
|
|
|
* @param bool|null $withData Add [ WITH [ NO ] DATA ] to refresh command |
34
|
|
|
* @return bool |
35
|
|
|
* @throws \Throwable |
36
|
|
|
* @throws \Yiisoft\Db\Exception\Exception |
37
|
|
|
* @throws \Yiisoft\Db\Exception\InvalidConfigException |
38
|
|
|
*/ |
39
|
5 |
|
public function refreshMaterializedView(string $viewName, ?bool $concurrently = null, ?bool $withData = null): bool |
40
|
|
|
{ |
41
|
5 |
|
if ($concurrently || ($concurrently === null || $withData === null)) { |
42
|
|
|
|
43
|
5 |
|
$tableSchema = $this->db->getTableSchema($viewName); |
44
|
|
|
|
45
|
5 |
|
if ($tableSchema) { |
46
|
4 |
|
$hasUnique = count($this->db->getSchema()->findUniqueIndexes($tableSchema)) > 0; |
47
|
|
|
} else { |
48
|
1 |
|
throw new InvalidArgumentException( |
49
|
1 |
|
sprintf('"%s" not found in DB', $viewName) |
50
|
1 |
|
); |
51
|
|
|
} |
52
|
|
|
|
53
|
4 |
|
if ($concurrently && !$hasUnique) { |
54
|
1 |
|
throw new LogicException('CONCURRENTLY refresh is not allowed without unique index.'); |
55
|
|
|
} |
56
|
|
|
|
57
|
3 |
|
$concurrently = $hasUnique; |
58
|
|
|
} |
59
|
|
|
|
60
|
3 |
|
$sql = 'REFRESH MATERIALIZED VIEW'; |
61
|
|
|
|
62
|
3 |
|
if ($concurrently) { |
63
|
|
|
|
64
|
2 |
|
if ($withData === false) { |
65
|
2 |
|
throw new LogicException('CONCURRENTLY and WITH NO DATA may not be specified together.'); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$sql .= ' CONCURRENTLY'; |
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
$sql .= ' ' . $this->db->getQuoter()->quoteTableName($viewName); |
72
|
|
|
|
73
|
1 |
|
if (is_bool($withData)) { |
74
|
1 |
|
$sql .= ' WITH ' . ($withData ? 'DATA' : 'NO DATA'); |
75
|
|
|
} |
76
|
|
|
|
77
|
1 |
|
return $this->setSql($sql)->execute() === 0; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|