{{ message }}
Repository navigation
Expand file tree
/
Copy pathPostgresBulkSchemaTest.php
More file actions
818 lines (705 loc) · 34.1 KB
/
Copy pathPostgresBulkSchemaTest.php
File metadata and controls
818 lines (705 loc) · 34.1 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
<?php
declare(strict_types=1);
namespace Tests\Unit;
use DBDiff\DB\Adapters\BulkSchemaAdapterInterface;
use DBDiff\DB\Adapters\PostgresAdapter;
use DBDiff\DB\Support\PostgresSchemaHelper;
use DBDiff\DB\Support\PostgresColumnType;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the batch schema assembly introduced for issue #165.
*
* getBulkTableSchema() fetches every changed table in a fixed number of
* queries and then splits the flat result sets back out per table. The
* assembly step is where batching can go wrong, so these tests focus on it —
* especially cross-table isolation, which single-table fetching got for free.
*
* The assemble* helpers are private and take pre-fetched rows, so they are
* exercised through reflection with no database connection, matching the
* approach used by MySQLAdapterNormalizationTest.
*/
class PostgresBulkSchemaTest extends TestCase
{
private PostgresAdapter $adapter;
protected function setUp(): void
{
$this->adapter = new PostgresAdapter();
}
private function invoke(string $method, array $args)
{
$ref = new \ReflectionMethod(PostgresAdapter::class, $method);
$ref->setAccessible(true);
return $ref->invoke($this->adapter, ...$args);
}
/** Build an information_schema.columns row with sensible defaults. */
private static function colRow(string $table, string $name, array $overrides = []): array
{
return array_merge([
'table_name' => $table,
'column_name' => $name,
'data_type' => 'integer',
'character_maximum_length' => null,
'is_nullable' => 'YES',
'column_default' => null,
'numeric_precision' => null,
'numeric_scale' => null,
'udt_name' => 'int4',
'datetime_precision' => null,
'is_identity' => 'NO',
'identity_generation' => null,
'identity_start' => null,
'identity_increment' => null,
'identity_maximum' => null,
'identity_minimum' => null,
'identity_cycle' => null,
'explicit_collation' => null,
'att_storage' => null,
'type_storage' => null,
'att_compression' => null,
'is_generated' => 'NEVER',
'generation_expression' => null,
'domain_name' => null,
], $overrides);
}
/** Build a table_constraints row with sensible defaults. */
private static function conRow(string $table, string $name, array $overrides = []): array
{
return array_merge([
'table_name' => $table,
'constraint_name' => $name,
'constraint_type' => 'UNIQUE',
'is_deferrable' => 'NO',
'initially_deferred' => 'NO',
'column_name' => null,
'ordinal_position' => 1,
'foreign_table' => null,
'foreign_column' => null,
'update_rule' => null,
'delete_rule' => null,
'match_option' => 'NONE',
'convalidated' => true,
], $overrides);
}
/** Build a PG18+ named NOT NULL constraint row (pg_constraint contype='n'). */
private static function notNullRow(
string $table,
string $conname,
string $column,
bool $convalidated = true
): array {
return [
'table_name' => $table,
'conname' => $conname,
'column_name' => $column,
'convalidated' => $convalidated,
];
}
// ── Interface wiring ──────────────────────────────────────────────────
public function testPostgresAdapterDeclaresBulkCapability(): void
{
// DBSchema uses this instanceof check to decide whether to batch.
$this->assertInstanceOf(BulkSchemaAdapterInterface::class, $this->adapter);
}
// ── assembleColumns ───────────────────────────────────────────────────
public function testAssembleColumnsSplitsRowsAcrossTables(): void
{
$rows = [
self::colRow('users', 'id'),
self::colRow('users', 'email', ['data_type' => 'text']),
self::colRow('orders', 'id'),
];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame(['users', 'orders'], array_keys($result));
$this->assertSame(['id', 'email'], array_keys($result['users']));
$this->assertSame(['id'], array_keys($result['orders']));
}
public function testAssembleColumnsKeepsSameColumnNameSeparatePerTable(): void
{
// Two tables sharing a column name must not overwrite each other —
// the failure mode a flat, non-table-keyed result would produce.
$rows = [
self::colRow('users', 'name', ['data_type' => 'text']),
self::colRow('orders', 'name', ['data_type' => 'character varying',
'character_maximum_length' => 50]),
];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame('"name" text', $result['users']['name']);
$this->assertSame('"name" varchar(50)', $result['orders']['name']);
}
public function testAssembleColumnsEmitsNotNullAndDefault(): void
{
$rows = [self::colRow('t', 'status', [
'data_type' => 'text',
'is_nullable' => 'NO',
'column_default' => "'active'::text",
])];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame('"status" text NOT NULL DEFAULT \'active\'::text', $result['t']['status']);
}
public function testAssembleColumnsEmitsIdentity(): void
{
$rows = [self::colRow('t', 'id', [
'is_nullable' => 'NO',
'is_identity' => 'YES',
'identity_generation' => 'ALWAYS',
'column_default' => 'nextval(...)',
])];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
// Identity columns carry no DEFAULT clause even when one is reported.
$this->assertSame('"id" integer NOT NULL GENERATED ALWAYS AS IDENTITY', $result['t']['id']);
}
public function testAssembleColumnsDefaultsIdentityGenerationWhenNull(): void
{
$rows = [self::colRow('t', 'id', [
'is_identity' => 'YES',
'identity_generation' => null,
])];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame('"id" integer GENERATED BY DEFAULT AS IDENTITY', $result['t']['id']);
}
public function testAssembleColumnsEmitsNonDefaultIdentityOptions(): void
{
$rows = [self::colRow('t', 'id', [
'data_type' => 'bigint',
'is_identity' => 'YES',
'identity_generation' => 'ALWAYS',
'identity_increment' => '10',
'identity_start' => '100',
])];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame(
'"id" bigint GENERATED ALWAYS AS IDENTITY (INCREMENT BY 10 START WITH 100)',
$result['t']['id']
);
}
/**
* A column that simply inherits its type's sequence bounds must not have
* them spelled out, or an `integer` identity and a `bigint` one would
* differ by their MAXVALUE alone and a type change would read as two.
*/
public function testAssembleColumnsOmitsIdentityOptionsThatAreTypeDefaults(): void
{
$rows = [self::colRow('t', 'id', [
'data_type' => 'integer',
'is_identity' => 'YES',
'identity_generation' => 'ALWAYS',
'identity_increment' => '1',
'identity_start' => '1',
'identity_minimum' => '1',
'identity_maximum' => '2147483647',
'identity_cycle' => 'NO',
])];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame('"id" integer GENERATED ALWAYS AS IDENTITY', $result['t']['id']);
}
public function testAssembleColumnsEmitsIdentityCycle(): void
{
$rows = [self::colRow('t', 'id', [
'data_type' => 'smallint',
'is_identity' => 'YES',
'identity_generation' => 'BY DEFAULT',
'identity_maximum' => '999',
'identity_cycle' => 'YES',
])];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame(
'"id" smallint GENERATED BY DEFAULT AS IDENTITY (MAXVALUE 999 CYCLE)',
$result['t']['id']
);
}
/**
* COLLATE decides comparison and sort order, so a column rendered without
* it applies cleanly and then orders its rows differently — the quietest
* kind of wrong this renderer can produce.
*/
public function testAssembleColumnsEmitsExplicitCollation(): void
{
$rows = [self::colRow('t', 'name', [
'data_type' => 'text',
'udt_name' => 'text',
'explicit_collation' => 'C',
])];
$result = $this->invoke('assembleColumns', [$rows, [], [], []]);
$this->assertSame('"name" text COLLATE "C"', $result['t']['name']);
}
/** An inherited collation must not be spelled out, or nothing ever matches. */
public function testAssembleColumnsOmitsInheritedCollation(): void
{
$rows = [self::colRow('t', 'name', [
'data_type' => 'text',
'udt_name' => 'text',
'explicit_collation' => null,
])];
$result = $this->invoke('assembleColumns', [$rows, [], [], []]);
$this->assertSame('"name" text', $result['t']['name']);
}
public function testAssembleColumnsEmitsColumnCompression(): void
{
foreach (['l' => 'lz4', 'p' => 'pglz'] as $code => $word) {
$rows = [self::colRow('t', 'big', [
'data_type' => 'text',
'udt_name' => 'text',
'att_compression' => $code,
])];
$result = $this->invoke('assembleColumns', [$rows, [], [], []]);
$this->assertSame("\"big\" text COMPRESSION $word", $result['t']['big']);
}
}
public function testStorageStatementsOnlyCoverColumnsThatDifferFromTheirType(): void
{
$stmts = \DBDiff\DB\Support\PostgresSchemaHelper::storageStatements('"t"', [
'a' => ['att_storage' => 'p', 'type_storage' => 'x'],
'b' => ['att_storage' => 'x', 'type_storage' => 'x'],
'c' => ['att_storage' => 'e', 'type_storage' => 'x'],
]);
$this->assertSame([
'ALTER TABLE "t" ALTER COLUMN "a" SET STORAGE PLAIN',
'ALTER TABLE "t" ALTER COLUMN "c" SET STORAGE EXTERNAL',
], $stmts);
}
public function testAssembleColumnsEmitsStoredGeneratedColumn(): void
{
$rows = [self::colRow('t', 'total', [
'data_type' => 'numeric',
'numeric_precision' => 10,
'numeric_scale' => 2,
'is_generated' => 'ALWAYS',
'generation_expression' => '(qty * price)',
])];
$result = $this->invoke('assembleColumns', [$rows, [], []]);
$this->assertSame(
'"total" numeric(10,2) GENERATED ALWAYS AS ((qty * price)) STORED',
$result['t']['total']
);
}
public function testAssembleColumnsSuppressesNotNullEnforcedByDomain(): void
{
// The domain already carries NOT NULL, so repeating it inline would
// make the source and target DDL disagree spuriously.
$rows = [self::colRow('t', 'code', [
'data_type' => 'text',
'domain_name' => 'nonempty_text',
'is_nullable' => 'NO',
])];
$result = $this->invoke('assembleColumns', [$rows, ['nonempty_text' => true], []]);
$this->assertSame('"code" nonempty_text', $result['t']['code']);
}
public function testAssembleColumnsKeepsNotNullWhenDomainIsNullable(): void
{
$rows = [self::colRow('t', 'code', [
'data_type' => 'text',
'domain_name' => 'loose_text',
'is_nullable' => 'NO',
])];
$result = $this->invoke('assembleColumns', [$rows, ['loose_text' => false], []]);
$this->assertSame('"code" loose_text NOT NULL', $result['t']['code']);
}
public function testAssembleColumnsSuppressesNotNullCarriedByNamedConstraint(): void
{
// PG18+ named NOT NULL constraints are emitted as constraints instead,
// so the inline NOT NULL must be dropped to avoid a duplicate.
$rows = [self::colRow('t', 'email', ['data_type' => 'text', 'is_nullable' => 'NO'])];
$nnCols = ['t' => ['email' => true]];
$result = $this->invoke('assembleColumns', [$rows, [], $nnCols]);
$this->assertSame('"email" text', $result['t']['email']);
}
public function testAssembleColumnsNamedNotNullSuppressionIsPerTable(): void
{
// A named NOT NULL on users.email must not suppress orders.email.
$rows = [
self::colRow('users', 'email', ['data_type' => 'text', 'is_nullable' => 'NO']),
self::colRow('orders', 'email', ['data_type' => 'text', 'is_nullable' => 'NO']),
];
$result = $this->invoke('assembleColumns', [$rows, [], ['users' => ['email' => true]]]);
$this->assertSame('"email" text', $result['users']['email']);
$this->assertSame('"email" text NOT NULL', $result['orders']['email']);
}
public function testAssembleColumnsWithNoRows(): void
{
$this->assertSame([], $this->invoke('assembleColumns', [[], [], []]));
}
// ── assembleIndexes ───────────────────────────────────────────────────
public function testAssembleIndexesSplitsRowsAcrossTables(): void
{
$rows = [
['table_name' => 'users', 'indexname' => 'users_email_idx', 'indexdef' => 'CREATE INDEX users_email_idx ON users (email)'],
['table_name' => 'orders', 'indexname' => 'orders_user_idx', 'indexdef' => 'CREATE INDEX orders_user_idx ON orders (user_id)'],
];
$result = $this->invoke('assembleIndexes', [$rows, []]);
$this->assertSame(['users_email_idx'], array_keys($result['users']));
$this->assertSame(['orders_user_idx'], array_keys($result['orders']));
}
public function testAssembleIndexesSkipsConstraintBackedIndexes(): void
{
// PK/UNIQUE/EXCLUDE indexes are rendered as constraints instead.
$rows = [
['table_name' => 'users', 'indexname' => 'users_pkey', 'indexdef' => 'CREATE UNIQUE INDEX users_pkey ON users (id)'],
['table_name' => 'users', 'indexname' => 'users_email_idx', 'indexdef' => 'CREATE INDEX users_email_idx ON users (email)'],
];
$result = $this->invoke('assembleIndexes', [$rows, ['users' => ['users_pkey' => true]]]);
$this->assertSame(['users_email_idx'], array_keys($result['users']));
}
public function testAssembleIndexesSkipListIsScopedPerTable(): void
{
// Index names are only unique per schema in practice, but the skip list
// is keyed by table: a constraint index on one table must never hide a
// same-named plain index on another.
$rows = [
['table_name' => 'users', 'indexname' => 'shared_name', 'indexdef' => 'CREATE UNIQUE INDEX shared_name ON users (id)'],
['table_name' => 'orders', 'indexname' => 'shared_name', 'indexdef' => 'CREATE INDEX shared_name ON orders (ref)'],
];
$result = $this->invoke('assembleIndexes', [$rows, ['users' => ['shared_name' => true]]]);
$this->assertSame([], $result['users']);
$this->assertSame(
['shared_name' => 'CREATE INDEX shared_name ON orders (ref)'],
$result['orders']
);
}
public function testAssembleIndexesKeepsTableWithOnlySkippedIndexes(): void
{
$rows = [
['table_name' => 'users', 'indexname' => 'users_pkey', 'indexdef' => 'CREATE UNIQUE INDEX users_pkey ON users (id)'],
];
$result = $this->invoke('assembleIndexes', [$rows, ['users' => ['users_pkey' => true]]]);
$this->assertSame(['users' => []], $result);
}
// ── assembleConstraints ───────────────────────────────────────────────
public function testAssembleConstraintsSplitsRowsAcrossTables(): void
{
$rows = [
self::conRow('users', 'users_email_key', ['column_name' => 'email']),
self::conRow('orders', 'orders_ref_key', ['column_name' => 'ref']),
];
$result = $this->invoke('assembleConstraints', [$rows, [], []]);
$this->assertSame(['users_email_key'], array_keys($result['users']));
$this->assertSame(['orders_ref_key'], array_keys($result['orders']));
}
public function testAssembleConstraintsKeepsSameConstraintNameSeparatePerTable(): void
{
// Postgres scopes constraint names per table, not per schema, so two
// tables may legitimately share one. Batching must not merge them.
$rows = [
self::conRow('users', 'uniq_code', ['column_name' => 'code']),
self::conRow('orders', 'uniq_code', ['column_name' => 'ref']),
];
$result = $this->invoke('assembleConstraints', [$rows, [], []]);
$this->assertSame('CONSTRAINT "uniq_code" UNIQUE ("code")', $result['users']['uniq_code']);
$this->assertSame('CONSTRAINT "uniq_code" UNIQUE ("ref")', $result['orders']['uniq_code']);
}
public function testAssembleConstraintsGroupsMultiColumnConstraint(): void
{
$rows = [
self::conRow('t', 'uniq_ab', ['column_name' => 'a', 'ordinal_position' => 1]),
self::conRow('t', 'uniq_ab', ['column_name' => 'b', 'ordinal_position' => 2]),
];
$result = $this->invoke('assembleConstraints', [$rows, [], []]);
$this->assertSame('CONSTRAINT "uniq_ab" UNIQUE ("a", "b")', $result['t']['uniq_ab']);
}
public function testAssembleConstraintsCollapsesJoinFanOut(): void
{
// A 2-column FK referencing a 2-column key produces 2x2 rows because
// key_column_usage and constraint_column_usage are joined together.
// Each column must still appear exactly once in the emitted DDL.
$base = [
'constraint_type' => 'FOREIGN KEY',
'foreign_table' => 'parent',
'update_rule' => 'NO ACTION',
'delete_rule' => 'CASCADE',
];
$rows = [
self::conRow('child', 'fk_ab', $base + ['column_name' => 'a', 'ordinal_position' => 1, 'foreign_column' => 'x']),
self::conRow('child', 'fk_ab', $base + ['column_name' => 'a', 'ordinal_position' => 1, 'foreign_column' => 'y']),
self::conRow('child', 'fk_ab', $base + ['column_name' => 'b', 'ordinal_position' => 2, 'foreign_column' => 'x']),
self::conRow('child', 'fk_ab', $base + ['column_name' => 'b', 'ordinal_position' => 2, 'foreign_column' => 'y']),
];
$result = $this->invoke('assembleConstraints', [$rows, [], []]);
$this->assertStringContainsString('FOREIGN KEY ("a", "b")', $result['child']['fk_ab']);
}
public function testAssembleConstraintsAppendsCheckConstraints(): void
{
$checks = [
['table_name' => 't', 'constraint_name' => 'chk_pos', 'definition' => 'CHECK ((qty > 0))'],
];
$result = $this->invoke('assembleConstraints', [[], $checks, []]);
$this->assertSame('CONSTRAINT "chk_pos" CHECK ((qty > 0))', $result['t']['chk_pos']);
}
public function testAssembleConstraintsAppendsNamedNotNull(): void
{
$nn = [self::notNullRow('t', 'email_required', 'email')];
$result = $this->invoke('assembleConstraints', [[], [], $nn]);
$this->assertSame('CONSTRAINT "email_required" NOT NULL "email"', $result['t']['email_required']);
}
public function testAssembleConstraintsMarksUnvalidatedNamedNotNull(): void
{
$nn = [self::notNullRow('t', 'email_required', 'email', false)];
$result = $this->invoke('assembleConstraints', [[], [], $nn]);
$this->assertSame('CONSTRAINT "email_required" NOT NULL "email" NOT VALID', $result['t']['email_required']);
}
public function testAssembleConstraintsKeepsNamedNotNullScopedPerTable(): void
{
$nn = [
self::notNullRow('users', 'nn_shared', 'email'),
self::notNullRow('orders', 'nn_shared', 'ref'),
];
$result = $this->invoke('assembleConstraints', [[], [], $nn]);
$this->assertSame('CONSTRAINT "nn_shared" NOT NULL "email"', $result['users']['nn_shared']);
$this->assertSame('CONSTRAINT "nn_shared" NOT NULL "ref"', $result['orders']['nn_shared']);
}
public function testAssembleConstraintsCombinesAllThreeSources(): void
{
$rows = [self::conRow('t', 'uniq_a', ['column_name' => 'a'])];
$checks = [['table_name' => 't', 'constraint_name' => 'chk_a', 'definition' => 'CHECK ((a > 0))']];
$nn = [self::notNullRow('t', 'nn_a', 'a')];
$result = $this->invoke('assembleConstraints', [$rows, $checks, $nn]);
$this->assertSame(['uniq_a', 'chk_a', 'nn_a'], array_keys($result['t']));
}
public function testAssembleConstraintsDropsUnrenderableTypes(): void
{
// constraintDefinition returns null for types it does not render; a null
// must never reach the diff map, where it would be compared as a value.
$rows = [self::conRow('t', 'weird', ['constraint_type' => 'SOMETHING ELSE', 'column_name' => 'a'])];
$result = $this->invoke('assembleConstraints', [$rows, [], []]);
$this->assertArrayNotHasKey('weird', $result['t'] ?? []);
}
// ── PostgresSchemaHelper::constraintDefinition ────────────────────────
public function testBuildConstraintDefForeignKey(): void
{
$c = self::conRow('t', 'fk', [
'constraint_type' => 'FOREIGN KEY',
'foreign_table' => 'parent',
'foreign_column' => 'id',
'update_rule' => 'NO ACTION',
'delete_rule' => 'CASCADE',
]);
$c['columns'] = ['parent_id'];
$this->assertSame(
'CONSTRAINT "fk" FOREIGN KEY ("parent_id") REFERENCES "parent" ("id")'
. ' ON UPDATE NO ACTION ON DELETE CASCADE',
PostgresSchemaHelper::constraintDefinition('fk', $c)
);
}
public function testAForeignKeyOutsidePublicIsQualifiedAndKeepsEveryColumn(): void
{
// A key onto auth.users rendered as REFERENCES "users", and a
// two-column key as REFERENCES "p" ("a"): neither could be applied.
$c = self::conRow('t', 'fk', [
'constraint_type' => 'FOREIGN KEY',
'foreign_table' => 'users',
'foreign_schema' => 'auth',
'foreign_columns' => '["id", "tenant"]',
'update_rule' => 'NO ACTION',
'delete_rule' => 'CASCADE',
]);
$c['columns'] = ['user_id', 'tenant_id'];
$this->assertSame(
'CONSTRAINT "fk" FOREIGN KEY ("user_id", "tenant_id") REFERENCES "auth"."users" ("id", "tenant")'
. ' ON UPDATE NO ACTION ON DELETE CASCADE',
PostgresSchemaHelper::constraintDefinition('fk', $c)
);
}
/** @dataProvider matchOptionProvider */
public function testBuildConstraintDefMatchOptions(?string $option, string $expected): void
{
$c = self::conRow('t', 'fk', [
'constraint_type' => 'FOREIGN KEY',
'foreign_table' => 'parent',
'foreign_column' => 'id',
'update_rule' => 'NO ACTION',
'delete_rule' => 'NO ACTION',
'match_option' => $option,
]);
$c['columns'] = ['parent_id'];
$def = PostgresSchemaHelper::constraintDefinition('fk', $c);
$this->assertStringContainsString($expected, $def);
}
public static function matchOptionProvider(): array
{
return [
'MATCH FULL' => ['FULL', '("id") MATCH FULL ON UPDATE'],
'MATCH PARTIAL' => ['PARTIAL', '("id") MATCH PARTIAL ON UPDATE'],
'NONE emits nothing' => ['NONE', '("id") ON UPDATE'],
'SIMPLE emits nothing'=> ['SIMPLE', '("id") ON UPDATE'],
];
}
public function testBuildConstraintDefDeferrable(): void
{
$c = self::conRow('t', 'uq', ['is_deferrable' => 'YES', 'initially_deferred' => 'YES']);
$c['columns'] = ['a'];
$this->assertSame(
'CONSTRAINT "uq" UNIQUE ("a") DEFERRABLE INITIALLY DEFERRED',
PostgresSchemaHelper::constraintDefinition('uq', $c)
);
}
public function testBuildConstraintDefDeferrableInitiallyImmediate(): void
{
$c = self::conRow('t', 'uq', ['is_deferrable' => 'YES', 'initially_deferred' => 'NO']);
$c['columns'] = ['a'];
$this->assertSame(
'CONSTRAINT "uq" UNIQUE ("a") DEFERRABLE INITIALLY IMMEDIATE',
PostgresSchemaHelper::constraintDefinition('uq', $c)
);
}
public function testBuildConstraintDefNotValidForeignKey(): void
{
$c = self::conRow('t', 'fk', [
'constraint_type' => 'FOREIGN KEY',
'foreign_table' => 'parent',
'foreign_column' => 'id',
'update_rule' => 'NO ACTION',
'delete_rule' => 'NO ACTION',
'convalidated' => false,
]);
$c['columns'] = ['parent_id'];
$this->assertStringEndsWith(' NOT VALID', PostgresSchemaHelper::constraintDefinition('fk', $c));
}
public function testBuildConstraintDefPrimaryKey(): void
{
$c = self::conRow('t', 'pk', ['constraint_type' => 'PRIMARY KEY']);
$c['columns'] = ['a', 'b'];
$this->assertSame(
'CONSTRAINT "pk" PRIMARY KEY ("a", "b")',
PostgresSchemaHelper::constraintDefinition('pk', $c)
);
}
// PostgreSQL 15+: what the built-in renderer dropped, so the copy held a
// key that set every column null, and a unique that treated nulls apart.
public function testAForeignKeySettingSomeColumnsNullNamesThem(): void
{
$c = self::conRow('h', 'fk', [
'constraint_type' => 'FOREIGN KEY',
'foreign_table' => 'p',
'foreign_columns' => '["a", "b"]',
'update_rule' => 'NO ACTION',
'delete_rule' => 'SET NULL',
'delete_set_columns' => '["b"]',
]);
$c['columns'] = ['a', 'b'];
$this->assertStringContainsString(
'ON UPDATE NO ACTION ON DELETE SET NULL ("b")',
PostgresSchemaHelper::constraintDefinition('fk', $c)
);
}
public function testAUniqueTreatingNullsAsEqualSaysSo(): void
{
$c = self::conRow('h', 'u', ['constraint_type' => 'UNIQUE', 'nulls_not_distinct' => true]);
$c['columns'] = ['a', 'b'];
$this->assertSame('CONSTRAINT "u" UNIQUE NULLS NOT DISTINCT ("a", "b")', PostgresSchemaHelper::constraintDefinition('u', $c));
$c['nulls_not_distinct'] = false;
$this->assertSame('CONSTRAINT "u" UNIQUE ("a", "b")', PostgresSchemaHelper::constraintDefinition('u', $c));
}
public function testBuildConstraintDefReturnsNullForUnknownType(): void
{
$c = self::conRow('t', 'x', ['constraint_type' => 'CHECK']);
$c['columns'] = ['a'];
$this->assertNull(PostgresSchemaHelper::constraintDefinition('x', $c));
}
// ── buildColumnType ───────────────────────────────────────────────────
/**
* @dataProvider columnTypeProvider
*
* Calls PostgresColumnType directly — the type spelling moved there out of
* the adapter, so this no longer needs reflection to reach a private method.
*/
public function testBuildColumnType(array $col, string $expected): void
{
$row = self::colRow('t', 'c', $col);
$this->assertSame($expected, PostgresColumnType::render($row));
}
public static function columnTypeProvider(): array
{
return [
'domain wins over data_type' => [
['data_type' => 'text', 'domain_name' => 'email_address'], 'email_address',
],
'time without time zone' => [['data_type' => 'time without time zone'], 'time'],
'time with time zone' => [['data_type' => 'time with time zone'], 'timetz'],
'double precision' => [['data_type' => 'double precision'], 'double precision'],
'array uses udt_name' => [['data_type' => 'ARRAY', 'udt_name' => '_int4'], '_int4'],
'varchar with length' => [
['data_type' => 'character varying', 'character_maximum_length' => 255], 'varchar(255)',
],
// The length was dropped: bit(8) became bit(1), bit varying(64) unbounded.
'bit with length' => [['data_type' => 'bit', 'character_maximum_length' => 8], 'bit(8)'],
'bit varying with length' => [
['data_type' => 'bit varying', 'character_maximum_length' => 64], 'bit varying(64)',
],
'bit varying unbounded' => [['data_type' => 'bit varying', 'character_maximum_length' => null], 'bit varying'],
'varchar without length' => [
['data_type' => 'character varying', 'character_maximum_length' => null], 'varchar',
],
'char with length' => [
['data_type' => 'character', 'character_maximum_length' => 10], 'char(10)',
],
'numeric with precision' => [
['data_type' => 'numeric', 'numeric_precision' => 10, 'numeric_scale' => 2], 'numeric(10,2)',
],
'numeric without precision' => [
['data_type' => 'numeric', 'numeric_precision' => null], 'numeric',
],
// The precision comes from atttypmod, not from
// information_schema.datetime_precision, which reports the default
// rather than the absence of a modifier: a bare timestamptz and a
// timestamptz(6) are both 6 there, so a precision nobody declared was
// emitted and the column did not reproduce (issue #215). -1 is the
// catalog's way of saying no modifier was given.
'timestamptz no precision' => [
['data_type' => 'timestamp with time zone', 'atttypmod' => -1], 'timestamptz',
],
'timestamptz with precision' => [
['data_type' => 'timestamp with time zone', 'atttypmod' => 3], 'timestamptz(3)',
],
'timestamptz ignores datetime_precision' => [
// What the reported bug looked like at this level: the lossy
// column says 6, the catalog says no modifier was given.
[
'data_type' => 'timestamp with time zone',
'datetime_precision' => 6,
'atttypmod' => -1,
],
'timestamptz',
],
'timestamp no precision' => [
['data_type' => 'timestamp without time zone', 'atttypmod' => -1], 'timestamp',
],
'timestamp with precision' => [
['data_type' => 'timestamp without time zone', 'atttypmod' => 6], 'timestamp(6)',
],
'timestamp keeps a precision of zero' => [
// The old test was `datetime_precision > 0`, which discarded it.
['data_type' => 'timestamp without time zone', 'atttypmod' => 0], 'timestamp(0)',
],
'time with precision' => [
// Previously returned from the alias map before any precision was
// considered, so a declared one was lost.
['data_type' => 'time without time zone', 'atttypmod' => 3], 'time(3)',
],
'timetz with precision' => [
['data_type' => 'time with time zone', 'atttypmod' => 2], 'timetz(2)',
],
'interval uses the server rendering' => [
// interval's modifier carries a field range as well as a
// precision, which no single number can express.
[
'data_type' => 'interval',
'formatted_type' => 'interval day to second(3)',
'atttypmod' => 2147418115,
],
'interval day to second(3)',
],
'interval without a modifier' => [
['data_type' => 'interval', 'formatted_type' => 'interval', 'atttypmod' => -1], 'interval',
],
'passthrough integer' => [['data_type' => 'integer'], 'integer'],
'passthrough jsonb' => [['data_type' => 'jsonb'], 'jsonb'],
];
}
// ── getBulkTableSchema guard ──────────────────────────────────────────
public function testGetBulkTableSchemaShortCircuitsOnEmptyList(): void
{
// Must return before touching the connection — an IN () clause built
// from an empty list would be a syntax error on every driver.
$connection = $this->createMock(\Illuminate\Database\Connection::class);
$connection->expects($this->never())->method('select');
$this->assertSame([], $this->adapter->getBulkTableSchema($connection, []));
}
}
You can’t perform that action at this time.
