-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgreSQL.php
More file actions
86 lines (72 loc) · 2.58 KB
/
PostgreSQL.php
File metadata and controls
86 lines (72 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
declare(strict_types=1);
namespace CakeDumpSql\Sql;
use CakeDumpSql\Error\BinaryNotFoundException;
use CakeDumpSql\Error\VersionMismatchException;
use Symfony\Component\Process\Process;
class PostgreSQL extends SqlBase
{
protected string $command = 'pg_dump';
/**
* @return string
* @throws \CakeDumpSql\Error\BinaryNotFoundException
* @throws \CakeDumpSql\Error\VersionMismatchException
*/
public function dump(): string
{
if (!$this->checkBinary($this->command)) {
throw new BinaryNotFoundException($this->command . ' was not found');
}
$passFile = $this->writePassFile();
$command = [
'PGPASSFILE=' . $passFile,
$this->command,
'--host=' . ($this->config['host'] ?? 'localhost'),
'--port=' . ($this->config['port'] ?? 5432),
'--username=' . ($this->config['username'] ?? ''),
'--dbname="' . ($this->config['database'] ?? '') . '"',
];
if ($this->isDataOnly()) {
$command[] = '--data-only';
}
$process = Process::fromShellCommandline(implode(' ', $command));
$process->run();
$output = $process->getOutput();
$error = $process->getErrorOutput();
if (str_contains($error, 'server version mismatch')) {
throw new VersionMismatchException();
}
if (!empty($error)) {
$this->io->warning($error);
}
return $output;
}
/**
* Write a .pgpass file containing the login data
*
* @return string The absolute path to the file
*/
private function writePassFile(): string
{
$passwordParts = [
empty($this->config['host']) ? 'localhost' : $this->config['host'],
empty($this->config['port']) ? '5432' : $this->config['port'],
// Database
'*',
$this->config['username'],
$this->config['password'],
];
// Escape colon and backslash characters in entries.
// @see http://www.postgresql.org/docs/9.1/static/libpq-pgpass.html
array_walk($passwordParts, function (string &$part): void {
// The order of the replacements is important so that backslashes are
// not replaced twice.
$part = str_replace(['\\', ':'], ['\\\\', '\:'], $part);
});
$pgpassContents = implode(':', $passwordParts);
$pgPassPath = TMP . 'psql.pgpass';
file_put_contents($pgPassPath, $pgpassContents);
chmod($pgPassPath, 0600);
return $pgPassPath;
}
}