{{ message }}
Repository navigation
Expand file tree
/
Copy pathPgDumpRendererPostgresTest.php
More file actions
338 lines (287 loc) · 13.4 KB
/
Copy pathPgDumpRendererPostgresTest.php
File metadata and controls
338 lines (287 loc) · 13.4 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
<?php
declare(strict_types=1);
namespace Tests;
use DBDiff\DB\Adapters\PostgresAdapter;
use DBDiff\DB\Support\PgDumpRenderer;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Events\StatementPrepared;
use Illuminate\Events\Dispatcher;
use PHPUnit\Framework\TestCase;
/**
* The pg_dump renderer, against a real database.
*
* These cannot be unit tests: the whole point is that PostgreSQL's own tooling
* produces the DDL, so a mocked pg_dump would only confirm the mock. Each case
* asserts on something the built-in renderer got wrong, since that is the
* reason this path exists.
*
* Skips when pg_dump is absent — which is the same condition under which the
* renderer itself steps aside, so a machine without it still runs the suite.
*/
class PgDumpRendererPostgresTest extends TestCase
{
private ?Capsule $capsule = null;
private PostgresAdapter $adapter;
private string $database = 'dbdiff_pgdump_test';
protected function setUp(): void
{
$host = getenv('DB_HOST_POSTGRES') ?: getenv('DB_HOST');
if (!$host) {
$this->markTestSkipped('DB_HOST_POSTGRES not set.');
}
if (!self::commandExists('pg_dump') || !self::commandExists('pg_restore')) {
// Legitimately absent: the renderer steps aside and so do these.
$this->markTestSkipped('pg_dump/pg_restore not on PATH.');
}
// The suite pins the renderer off for the fixture-based tests; this one
// is about the renderer, so it opts back in.
putenv('DBDIFF_PG_DUMP_RENDERER=');
$port = getenv('DB_PORT_POSTGRES') ?: '5432';
$user = getenv('DB_USER_POSTGRES') ?: 'dbdiff';
$pass = getenv('DB_PASSWORD_POSTGRES') ?: 'rootpass';
$admin = $this->connect($host, $port, $user, $pass, 'postgres');
// A connection left open by the previous case blocks DROP DATABASE.
$admin->statement(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = ? AND pid <> pg_backend_pid()",
[$this->database]
);
$admin->statement("DROP DATABASE IF EXISTS {$this->database}");
$admin->statement("CREATE DATABASE {$this->database}");
$admin->disconnect();
$this->capsule = null;
$this->connection = $this->connect($host, $port, $user, $pass, $this->database);
$this->adapter = new PostgresAdapter();
PgDumpRenderer::reset();
// Present but unusable is a misconfiguration, not a reason to skip. On
// CI, Debian's pg_wrapper resolved /usr/bin/pg_dump to 16 even with
// postgresql-client-18 installed, so against newer servers the guard
// declined and every case below silently ran on the built-in renderer
// — passing, because the two now agree on collation and identity.
$reason = PgDumpRenderer::unavailableReason($this->connection);
if ($reason !== null) {
$this->fail("pg_dump is installed but unusable, so this suite would test the wrong renderer: $reason");
}
// That check dumps the database to find out, and the archive is cached.
// Each case creates its table afterwards, so the cache has to go or the
// renderer would look for tables in a snapshot taken before they
// existed — and silently fall back.
PgDumpRenderer::reset();
}
protected function tearDown(): void
{
PgDumpRenderer::reset();
putenv('DBDIFF_PG_DUMP_RENDERER=off');
if (isset($this->connection)) {
$this->connection->disconnect();
}
}
private \Illuminate\Database\Connection $connection;
private function connect(string $host, string $port, string $user, string $pass, string $db): \Illuminate\Database\Connection
{
$capsule = new Capsule();
// DBDiff's own manager fetches associative rows; the adapters index
// into them by column name, so a test connection must match or it
// fails with "Cannot use object of type stdClass as array".
$dispatcher = new Dispatcher();
$dispatcher->listen(StatementPrepared::class, static function ($event): void {
$event->statement->setFetchMode(\PDO::FETCH_ASSOC);
});
$capsule->setEventDispatcher($dispatcher);
$capsule->addConnection([
'driver' => 'pgsql', 'host' => $host, 'port' => $port,
'database' => $db, 'username' => $user, 'password' => $pass,
'charset' => 'utf8', 'schema' => 'public',
], $db . '_' . spl_object_id($this));
return $capsule->getConnection($db . '_' . spl_object_id($this));
}
private static function commandExists(string $name): bool
{
$descriptors = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$process = @proc_open([$name, '--version'], $descriptors, $pipes);
if (!is_resource($process)) {
return false;
}
fclose($pipes[1]);
fclose($pipes[2]);
return proc_close($process) === 0;
}
/**
* Assert the DDL under test actually came from pg_dump.
*
* The built-in renderer now emits collations and identity options too, so
* an assertion on those alone passes either way and proves nothing about
* this path.
*/
private function assertCameFromPgDump(string $ddl): void
{
$this->assertTrue(PgDumpRenderer::wasUsed(), 'DDL did not come from pg_dump');
// pg_dump schema-qualifies; the built-in renderer emits bare quoted names.
$this->assertStringContainsString('public.', $ddl);
}
/** Collation decides sort order, and the built-in renderer dropped it. */
public function testRendersAnExplicitCollation(): void
{
$this->connection->statement('CREATE TABLE t (id int, name text COLLATE "C")');
$ddl = $this->adapter->getCreateStatement($this->connection, 't');
$this->assertCameFromPgDump($ddl);
$this->assertStringContainsString('COLLATE', $ddl);
$this->assertStringContainsString('"C"', $ddl);
}
/**
* An identity column's sequence options live in a separate table-of-contents
* entry named after the sequence, not the table. Matching on the table name
* alone silently produced a plain identity counting from one.
*/
public function testRendersIdentitySequenceOptions(): void
{
$this->connection->statement(
'CREATE TABLE t (id bigint GENERATED ALWAYS AS IDENTITY (INCREMENT 10 START 100), n text)'
);
$ddl = $this->adapter->getCreateStatement($this->connection, 't');
$this->assertCameFromPgDump($ddl);
$this->assertStringContainsString('GENERATED ALWAYS AS IDENTITY', $ddl);
$this->assertStringContainsString('INCREMENT BY 10', $ddl);
$this->assertStringContainsString('START WITH 100', $ddl);
}
/** Indexes are their own entries, under their own names. */
public function testRendersIndexesBelongingToTheTable(): void
{
$this->connection->statement('CREATE TABLE t (id int, b int)');
$this->connection->statement('CREATE INDEX t_b_idx ON t (b)');
$ddl = $this->adapter->getCreateStatement($this->connection, 't');
$this->assertCameFromPgDump($ddl);
$this->assertStringContainsString('CREATE INDEX t_b_idx', $ddl);
}
/** An unrelated table must not be dragged in by a shared listing. */
public function testRendersOnlyTheRequestedTable(): void
{
$this->connection->statement('CREATE TABLE wanted (id int)');
$this->connection->statement('CREATE TABLE other (id int)');
$ddl = $this->adapter->getCreateStatement($this->connection, 'wanted');
$this->assertStringContainsString('wanted', $ddl);
$this->assertStringNotContainsString('other', $ddl);
}
/**
* Callers append their own terminator, so the renderer must not leave one —
* this produced `PRIMARY KEY (id);;` before it was fixed.
*/
public function testDoesNotLeaveATrailingSemicolon(): void
{
$this->connection->statement('CREATE TABLE t (id int PRIMARY KEY)');
$ddl = $this->adapter->getCreateStatement($this->connection, 't');
$this->assertStringEndsNotWith(';', $ddl);
}
/** Ownership and psql meta-commands are not part of a migration. */
public function testStripsOwnershipAndMetaCommands(): void
{
$this->connection->statement('CREATE TABLE t (id int)');
$ddl = $this->adapter->getCreateStatement($this->connection, 't');
$this->assertStringNotContainsString('OWNER TO', $ddl);
$this->assertStringNotContainsString('\\restrict', $ddl);
$this->assertStringNotContainsString('SET statement_timeout', $ddl);
}
/**
* The off switch has to actually reach the built-in renderer, or the
* fixture-based suites would silently depend on the machine.
*/
public function testTheOffSwitchFallsBackToTheBuiltInRenderer(): void
{
$this->connection->statement('CREATE TABLE t (id int, name text COLLATE "C")');
putenv('DBDIFF_PG_DUMP_RENDERER=off');
PgDumpRenderer::reset();
$builtIn = $this->adapter->getCreateStatement($this->connection, 't');
// The built-in renderer quotes identifiers; pg_dump schema-qualifies them.
$this->assertStringContainsString('"t"', $builtIn);
$this->assertStringNotContainsString('public.t', $builtIn);
}
/**
* A pg_dump older than the server cannot read it, so the renderer must
* decline rather than emit a partial migration.
*/
public function testDeclinesWhenPgDumpIsOlderThanTheServer(): void
{
$stub = sys_get_temp_dir() . '/fake_pg_dump_' . getmypid();
file_put_contents($stub, "#!/bin/sh\necho 'pg_dump (PostgreSQL) 9.6.24'\n");
chmod($stub, 0755);
putenv('DBDIFF_PG_DUMP=' . $stub);
PgDumpRenderer::reset();
try {
$this->assertFalse(PgDumpRenderer::isActive($this->connection));
$this->assertStringContainsString('older than the server', (string) PgDumpRenderer::unavailableReason($this->connection));
} finally {
putenv('DBDIFF_PG_DUMP');
@unlink($stub);
}
}
/**
* A serial column's sequence has to come back owned by that column.
*
* PostgreSQL records the link as a dependency, and it is what makes the
* sequence part of the column rather than an object in its own right. The
* SEQUENCE and DEFAULT entries alone reproduce the column's behaviour but
* not the link, which leaves the copy holding a sequence owned by nothing.
*
* That was invisible until sequences became a modelled object kind. A diff
* between the original and the copy then found a standalone sequence on one
* side only and generated a DROP for it, which PostgreSQL refuses:
*
* cannot drop sequence t_id_seq because other objects depend on it
*
* So the property asserted here is the round trip, not the text: reproduce
* the table, and the sequence must be as invisible to the object-kind reader
* on the copy as it is on the original.
*/
public function testAReproducedSerialColumnKeepsItsSequenceOwnership(): void
{
$this->connection->statement('CREATE TABLE t (id serial PRIMARY KEY, n text)');
$ddl = $this->adapter->getCreateStatement($this->connection, 't');
$this->assertCameFromPgDump($ddl);
$this->assertStringContainsString(
'OWNED BY',
$ddl,
'without ALTER SEQUENCE ... OWNED BY the copy holds an unowned sequence'
);
// The original does not report it: it belongs to the column.
$this->assertSame(
[],
\DBDiff\DB\Support\PostgresObjectKinds::sequences($this->connection),
'a serial column\'s sequence is not a standalone object'
);
$replayDb = $this->database . '_replay';
$host = getenv('DB_HOST_POSTGRES') ?: getenv('DB_HOST');
$port = getenv('DB_PORT_POSTGRES') ?: '5432';
$user = getenv('DB_USER_POSTGRES') ?: 'dbdiff';
$pass = getenv('DB_PASSWORD_POSTGRES') ?: 'rootpass';
$admin = $this->connect($host, $port, $user, $pass, 'postgres');
$admin->statement("DROP DATABASE IF EXISTS $replayDb");
$admin->statement("CREATE DATABASE $replayDb");
$admin->disconnect();
$replay = $this->connect($host, $port, $user, $pass, $replayDb);
try {
foreach (explode(";\n", $ddl) as $stmt) {
$stmt = trim(rtrim(trim($stmt), ';'));
if ($stmt !== '') {
$replay->statement($stmt);
}
}
// And neither does the copy — which is the whole point. A mismatch
// here is a DROP SEQUENCE in the next migration.
$this->assertSame(
[],
\DBDiff\DB\Support\PostgresObjectKinds::sequences($replay),
'the reproduced sequence is unowned, so it reads as standalone'
);
} finally {
$replay->disconnect();
$admin = $this->connect($host, $port, $user, $pass, 'postgres');
$admin->statement(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = ? AND pid <> pg_backend_pid()",
[$replayDb]
);
$admin->statement("DROP DATABASE IF EXISTS $replayDb");
$admin->disconnect();
}
}
}
You can’t perform that action at this time.
