aboutsummaryrefslogtreecommitdiff
path: root/src/test/regress/expected/constraints.out
blob: ad6aaab738538a1fec4c4d322a4688bdaa90f5ec (plain)
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
--
-- CONSTRAINTS
-- Constraints can be specified with:
--  - DEFAULT clause
--  - CHECK clauses
--  - PRIMARY KEY clauses
--  - UNIQUE clauses
--  - EXCLUDE clauses
--  - NOT NULL clauses
--
-- directory paths are passed to us in environment variables
\getenv abs_srcdir PG_ABS_SRCDIR
--
-- DEFAULT syntax
--
CREATE TABLE DEFAULT_TBL (i int DEFAULT 100,
	x text DEFAULT 'vadim', f float8 DEFAULT 123.456);
INSERT INTO DEFAULT_TBL VALUES (1, 'thomas', 57.0613);
INSERT INTO DEFAULT_TBL VALUES (1, 'bruce');
INSERT INTO DEFAULT_TBL (i, f) VALUES (2, 987.654);
INSERT INTO DEFAULT_TBL (x) VALUES ('marc');
INSERT INTO DEFAULT_TBL VALUES (3, null, 1.0);
SELECT * FROM DEFAULT_TBL;
  i  |   x    |    f    
-----+--------+---------
   1 | thomas | 57.0613
   1 | bruce  | 123.456
   2 | vadim  | 987.654
 100 | marc   | 123.456
   3 |        |       1
(5 rows)

CREATE SEQUENCE DEFAULT_SEQ;
CREATE TABLE DEFAULTEXPR_TBL (i1 int DEFAULT 100 + (200-199) * 2,
	i2 int DEFAULT nextval('default_seq'));
INSERT INTO DEFAULTEXPR_TBL VALUES (-1, -2);
INSERT INTO DEFAULTEXPR_TBL (i1) VALUES (-3);
INSERT INTO DEFAULTEXPR_TBL (i2) VALUES (-4);
INSERT INTO DEFAULTEXPR_TBL (i2) VALUES (NULL);
SELECT * FROM DEFAULTEXPR_TBL;
 i1  | i2 
-----+----
  -1 | -2
  -3 |  1
 102 | -4
 102 |   
(4 rows)

-- syntax errors
--  test for extraneous comma
CREATE TABLE error_tbl (i int DEFAULT (100, ));
ERROR:  syntax error at or near ")"
LINE 1: CREATE TABLE error_tbl (i int DEFAULT (100, ));
                                                    ^
--  this will fail because gram.y uses b_expr not a_expr for defaults,
--  to avoid a shift/reduce conflict that arises from NOT NULL being
--  part of the column definition syntax:
CREATE TABLE error_tbl (b1 bool DEFAULT 1 IN (1, 2));
ERROR:  syntax error at or near "IN"
LINE 1: CREATE TABLE error_tbl (b1 bool DEFAULT 1 IN (1, 2));
                                                  ^
--  this should work, however:
CREATE TABLE error_tbl (b1 bool DEFAULT (1 IN (1, 2)));
DROP TABLE error_tbl;
--
-- CHECK syntax
--
CREATE TABLE CHECK_TBL (x int,
	CONSTRAINT CHECK_CON CHECK (x > 3));
INSERT INTO CHECK_TBL VALUES (5);
INSERT INTO CHECK_TBL VALUES (4);
INSERT INTO CHECK_TBL VALUES (3);
ERROR:  new row for relation "check_tbl" violates check constraint "check_con"
DETAIL:  Failing row contains (3).
INSERT INTO CHECK_TBL VALUES (2);
ERROR:  new row for relation "check_tbl" violates check constraint "check_con"
DETAIL:  Failing row contains (2).
INSERT INTO CHECK_TBL VALUES (6);
INSERT INTO CHECK_TBL VALUES (1);
ERROR:  new row for relation "check_tbl" violates check constraint "check_con"
DETAIL:  Failing row contains (1).
SELECT * FROM CHECK_TBL;
 x 
---
 5
 4
 6
(3 rows)

CREATE TABLE NE_CHECK_TBL (x int,
	CONSTRAINT CHECK_CON CHECK (x > 3) NOT ENFORCED);
INSERT INTO NE_CHECK_TBL VALUES (5);
INSERT INTO NE_CHECK_TBL VALUES (4);
INSERT INTO NE_CHECK_TBL VALUES (3);
INSERT INTO NE_CHECK_TBL VALUES (2);
INSERT INTO NE_CHECK_TBL VALUES (6);
INSERT INTO NE_CHECK_TBL VALUES (1);
SELECT * FROM NE_CHECK_TBL;
 x 
---
 5
 4
 3
 2
 6
 1
(6 rows)

CREATE SEQUENCE CHECK_SEQ;
CREATE TABLE CHECK2_TBL (x int, y text, z int,
	CONSTRAINT SEQUENCE_CON
	CHECK (x > 3 and y <> 'check failed' and z < 8));
INSERT INTO CHECK2_TBL VALUES (4, 'check ok', -2);
INSERT INTO CHECK2_TBL VALUES (1, 'x check failed', -2);
ERROR:  new row for relation "check2_tbl" violates check constraint "sequence_con"
DETAIL:  Failing row contains (1, x check failed, -2).
INSERT INTO CHECK2_TBL VALUES (5, 'z check failed', 10);
ERROR:  new row for relation "check2_tbl" violates check constraint "sequence_con"
DETAIL:  Failing row contains (5, z check failed, 10).
INSERT INTO CHECK2_TBL VALUES (0, 'check failed', -2);
ERROR:  new row for relation "check2_tbl" violates check constraint "sequence_con"
DETAIL:  Failing row contains (0, check failed, -2).
INSERT INTO CHECK2_TBL VALUES (6, 'check failed', 11);
ERROR:  new row for relation "check2_tbl" violates check constraint "sequence_con"
DETAIL:  Failing row contains (6, check failed, 11).
INSERT INTO CHECK2_TBL VALUES (7, 'check ok', 7);
SELECT * from CHECK2_TBL;
 x |    y     | z  
---+----------+----
 4 | check ok | -2
 7 | check ok |  7
(2 rows)

--
-- Check constraints on INSERT
--
CREATE SEQUENCE INSERT_SEQ;
CREATE TABLE INSERT_TBL (x INT DEFAULT nextval('insert_seq'),
	y TEXT DEFAULT '-NULL-',
	z INT DEFAULT -1 * currval('insert_seq'),
	CONSTRAINT INSERT_TBL_CON CHECK (x >= 3 AND y <> 'check failed' AND x < 8),
	CHECK (x + z = 0) ENFORCED, /* no change it is a default */
	CONSTRAINT NE_INSERT_TBL_CON CHECK (x + z = 1) NOT ENFORCED);
INSERT INTO INSERT_TBL(x,z) VALUES (2, -2);
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (2, -NULL-, -2).
SELECT * FROM INSERT_TBL;
 x | y | z 
---+---+---
(0 rows)

SELECT 'one' AS one, nextval('insert_seq');
 one | nextval 
-----+---------
 one |       1
(1 row)

INSERT INTO INSERT_TBL(y) VALUES ('Y');
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (2, Y, -2).
INSERT INTO INSERT_TBL(y) VALUES ('Y');
INSERT INTO INSERT_TBL(x,z) VALUES (1, -2);
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_check"
DETAIL:  Failing row contains (1, -NULL-, -2).
INSERT INTO INSERT_TBL(z,x) VALUES (-7,  7);
INSERT INTO INSERT_TBL VALUES (5, 'check failed', -5);
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (5, check failed, -5).
INSERT INTO INSERT_TBL VALUES (7, '!check failed', -7);
INSERT INTO INSERT_TBL(y) VALUES ('-!NULL-');
SELECT * FROM INSERT_TBL;
 x |       y       | z  
---+---------------+----
 3 | Y             | -3
 7 | -NULL-        | -7
 7 | !check failed | -7
 4 | -!NULL-       | -4
(4 rows)

INSERT INTO INSERT_TBL(y,z) VALUES ('check failed', 4);
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_check"
DETAIL:  Failing row contains (5, check failed, 4).
INSERT INTO INSERT_TBL(x,y) VALUES (5, 'check failed');
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (5, check failed, -5).
INSERT INTO INSERT_TBL(x,y) VALUES (5, '!check failed');
INSERT INTO INSERT_TBL(y) VALUES ('-!NULL-');
SELECT * FROM INSERT_TBL;
 x |       y       | z  
---+---------------+----
 3 | Y             | -3
 7 | -NULL-        | -7
 7 | !check failed | -7
 4 | -!NULL-       | -4
 5 | !check failed | -5
 6 | -!NULL-       | -6
(6 rows)

SELECT 'seven' AS one, nextval('insert_seq');
  one  | nextval 
-------+---------
 seven |       7
(1 row)

INSERT INTO INSERT_TBL(y) VALUES ('Y');
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (8, Y, -8).
SELECT 'eight' AS one, currval('insert_seq');
  one  | currval 
-------+---------
 eight |       8
(1 row)

-- According to SQL, it is OK to insert a record that gives rise to NULL
-- constraint-condition results.  Postgres used to reject this, but it
-- was wrong:
INSERT INTO INSERT_TBL VALUES (null, null, null);
SELECT * FROM INSERT_TBL;
 x |       y       | z  
---+---------------+----
 3 | Y             | -3
 7 | -NULL-        | -7
 7 | !check failed | -7
 4 | -!NULL-       | -4
 5 | !check failed | -5
 6 | -!NULL-       | -6
   |               |   
(7 rows)

--
-- Check constraints on system columns
--
CREATE TABLE SYS_COL_CHECK_TBL (city text, state text, is_capital bool,
                  altitude int,
                  CHECK (NOT (is_capital AND tableoid::regclass::text = 'sys_col_check_tbl')));
INSERT INTO SYS_COL_CHECK_TBL VALUES ('Seattle', 'Washington', false, 100);
INSERT INTO SYS_COL_CHECK_TBL VALUES ('Olympia', 'Washington', true, 100);
ERROR:  new row for relation "sys_col_check_tbl" violates check constraint "sys_col_check_tbl_check"
DETAIL:  Failing row contains (Olympia, Washington, t, 100).
SELECT *, tableoid::regclass::text FROM SYS_COL_CHECK_TBL;
  city   |   state    | is_capital | altitude |     tableoid      
---------+------------+------------+----------+-------------------
 Seattle | Washington | f          |      100 | sys_col_check_tbl
(1 row)

DROP TABLE SYS_COL_CHECK_TBL;
--
-- Check constraints on system columns other then TableOid should return error
--
CREATE TABLE SYS_COL_CHECK_TBL (city text, state text, is_capital bool,
                  altitude int,
				  CHECK (NOT (is_capital AND ctid::text = 'sys_col_check_tbl')));
ERROR:  system column "ctid" reference in check constraint is invalid
LINE 3:       CHECK (NOT (is_capital AND ctid::text = 'sys_col_check...
                                         ^
--
-- Check inheritance of defaults and constraints
--
CREATE TABLE INSERT_CHILD (cx INT default 42,
	cy INT CHECK (cy > x))
	INHERITS (INSERT_TBL);
INSERT INTO INSERT_CHILD(x,z,cy) VALUES (7,-7,11);
INSERT INTO INSERT_CHILD(x,z,cy) VALUES (7,-7,6);
ERROR:  new row for relation "insert_child" violates check constraint "insert_child_check"
DETAIL:  Failing row contains (7, -NULL-, -7, 42, 6).
INSERT INTO INSERT_CHILD(x,z,cy) VALUES (6,-7,7);
ERROR:  new row for relation "insert_child" violates check constraint "insert_tbl_check"
DETAIL:  Failing row contains (6, -NULL-, -7, 42, 7).
INSERT INTO INSERT_CHILD(x,y,z,cy) VALUES (6,'check failed',-6,7);
ERROR:  new row for relation "insert_child" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (6, check failed, -6, 42, 7).
SELECT * FROM INSERT_CHILD;
 x |   y    | z  | cx | cy 
---+--------+----+----+----
 7 | -NULL- | -7 | 42 | 11
(1 row)

DROP TABLE INSERT_CHILD;
--
-- Check NO INHERIT type of constraints and inheritance
--
CREATE TABLE ATACC1 (TEST INT
	CHECK (TEST > 0) NO INHERIT);
CREATE TABLE ATACC2 (TEST2 INT) INHERITS (ATACC1);
-- check constraint is not there on child
INSERT INTO ATACC2 (TEST) VALUES (-3);
-- check constraint is there on parent
INSERT INTO ATACC1 (TEST) VALUES (-3);
ERROR:  new row for relation "atacc1" violates check constraint "atacc1_test_check"
DETAIL:  Failing row contains (-3).
DROP TABLE ATACC1 CASCADE;
NOTICE:  drop cascades to table atacc2
CREATE TABLE ATACC1 (TEST INT, TEST2 INT
	CHECK (TEST > 0), CHECK (TEST2 > 10) NO INHERIT);
CREATE TABLE ATACC2 () INHERITS (ATACC1);
-- check constraint is there on child
INSERT INTO ATACC2 (TEST) VALUES (-3);
ERROR:  new row for relation "atacc2" violates check constraint "atacc1_test_check"
DETAIL:  Failing row contains (-3, null).
-- check constraint is there on parent
INSERT INTO ATACC1 (TEST) VALUES (-3);
ERROR:  new row for relation "atacc1" violates check constraint "atacc1_test_check"
DETAIL:  Failing row contains (-3, null).
-- check constraint is not there on child
INSERT INTO ATACC2 (TEST2) VALUES (3);
-- check constraint is there on parent
INSERT INTO ATACC1 (TEST2) VALUES (3);
ERROR:  new row for relation "atacc1" violates check constraint "atacc1_test2_check"
DETAIL:  Failing row contains (null, 3).
DROP TABLE ATACC1 CASCADE;
NOTICE:  drop cascades to table atacc2
--
-- Check constraints on INSERT INTO
--
DELETE FROM INSERT_TBL;
ALTER SEQUENCE INSERT_SEQ RESTART WITH 4;
CREATE TEMP TABLE tmp (xd INT, yd TEXT, zd INT);
INSERT INTO tmp VALUES (null, 'Y', null);
INSERT INTO tmp VALUES (5, '!check failed', null);
INSERT INTO tmp VALUES (null, 'try again', null);
INSERT INTO INSERT_TBL(y) select yd from tmp;
SELECT * FROM INSERT_TBL;
 x |       y       | z  
---+---------------+----
 4 | Y             | -4
 5 | !check failed | -5
 6 | try again     | -6
(3 rows)

INSERT INTO INSERT_TBL SELECT * FROM tmp WHERE yd = 'try again';
INSERT INTO INSERT_TBL(y,z) SELECT yd, -7 FROM tmp WHERE yd = 'try again';
INSERT INTO INSERT_TBL(y,z) SELECT yd, -8 FROM tmp WHERE yd = 'try again';
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (8, try again, -8).
SELECT * FROM INSERT_TBL;
 x |       y       | z  
---+---------------+----
 4 | Y             | -4
 5 | !check failed | -5
 6 | try again     | -6
   | try again     |   
 7 | try again     | -7
(5 rows)

DROP TABLE tmp;
--
-- Check constraints on UPDATE
--
UPDATE INSERT_TBL SET x = NULL WHERE x = 5;
UPDATE INSERT_TBL SET x = 6 WHERE x = 6;
UPDATE INSERT_TBL SET x = -z, z = -x;
UPDATE INSERT_TBL SET x = z, z = x;
ERROR:  new row for relation "insert_tbl" violates check constraint "insert_tbl_con"
DETAIL:  Failing row contains (-4, Y, 4).
SELECT * FROM INSERT_TBL;
 x |       y       | z  
---+---------------+----
 4 | Y             | -4
   | try again     |   
 7 | try again     | -7
 5 | !check failed |   
 6 | try again     | -6
(5 rows)

-- DROP TABLE INSERT_TBL;
--
-- Check constraints on COPY FROM
--
CREATE TABLE COPY_TBL (x INT, y TEXT, z INT,
	CONSTRAINT COPY_CON
	CHECK (x > 3 AND y <> 'check failed' AND x < 7 ));
\set filename :abs_srcdir '/data/constro.data'
COPY COPY_TBL FROM :'filename';
SELECT * FROM COPY_TBL;
 x |       y       | z 
---+---------------+---
 4 | !check failed | 5
 6 | OK            | 4
(2 rows)

\set filename :abs_srcdir '/data/constrf.data'
COPY COPY_TBL FROM :'filename';
ERROR:  new row for relation "copy_tbl" violates check constraint "copy_con"
DETAIL:  Failing row contains (7, check failed, 6).
CONTEXT:  COPY copy_tbl, line 2: "7	check failed	6"
SELECT * FROM COPY_TBL;
 x |       y       | z 
---+---------------+---
 4 | !check failed | 5
 6 | OK            | 4
(2 rows)

--
-- Primary keys
--
CREATE TABLE PRIMARY_TBL (i int PRIMARY KEY, t text);
INSERT INTO PRIMARY_TBL VALUES (1, 'one');
INSERT INTO PRIMARY_TBL VALUES (2, 'two');
INSERT INTO PRIMARY_TBL VALUES (1, 'three');
ERROR:  duplicate key value violates unique constraint "primary_tbl_pkey"
DETAIL:  Key (i)=(1) already exists.
INSERT INTO PRIMARY_TBL VALUES (4, 'three');
INSERT INTO PRIMARY_TBL VALUES (5, 'one');
INSERT INTO PRIMARY_TBL (t) VALUES ('six');
ERROR:  null value in column "i" of relation "primary_tbl" violates not-null constraint
DETAIL:  Failing row contains (null, six).
SELECT * FROM PRIMARY_TBL;
 i |   t   
---+-------
 1 | one
 2 | two
 4 | three
 5 | one
(4 rows)

DROP TABLE PRIMARY_TBL;
CREATE TABLE PRIMARY_TBL (i int, t text,
	PRIMARY KEY(i,t));
INSERT INTO PRIMARY_TBL VALUES (1, 'one');
INSERT INTO PRIMARY_TBL VALUES (2, 'two');
INSERT INTO PRIMARY_TBL VALUES (1, 'three');
INSERT INTO PRIMARY_TBL VALUES (4, 'three');
INSERT INTO PRIMARY_TBL VALUES (5, 'one');
INSERT INTO PRIMARY_TBL (t) VALUES ('six');
ERROR:  null value in column "i" of relation "primary_tbl" violates not-null constraint
DETAIL:  Failing row contains (null, six).
SELECT * FROM PRIMARY_TBL;
 i |   t   
---+-------
 1 | one
 2 | two
 1 | three
 4 | three
 5 | one
(5 rows)

DROP TABLE PRIMARY_TBL;
--
-- Unique keys
--
CREATE TABLE UNIQUE_TBL (i int UNIQUE, t text);
INSERT INTO UNIQUE_TBL VALUES (1, 'one');
INSERT INTO UNIQUE_TBL VALUES (2, 'two');
INSERT INTO UNIQUE_TBL VALUES (1, 'three');
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(1) already exists.
INSERT INTO UNIQUE_TBL VALUES (4, 'four');
INSERT INTO UNIQUE_TBL VALUES (5, 'one');
INSERT INTO UNIQUE_TBL (t) VALUES ('six');
INSERT INTO UNIQUE_TBL (t) VALUES ('seven');
INSERT INTO UNIQUE_TBL VALUES (5, 'five-upsert-insert') ON CONFLICT (i) DO UPDATE SET t = 'five-upsert-update';
INSERT INTO UNIQUE_TBL VALUES (6, 'six-upsert-insert') ON CONFLICT (i) DO UPDATE SET t = 'six-upsert-update';
-- should fail
INSERT INTO UNIQUE_TBL VALUES (1, 'a'), (2, 'b'), (2, 'b') ON CONFLICT (i) DO UPDATE SET t = 'fails';
ERROR:  ON CONFLICT DO UPDATE command cannot affect row a second time
HINT:  Ensure that no rows proposed for insertion within the same command have duplicate constrained values.
SELECT * FROM UNIQUE_TBL;
 i |         t          
---+--------------------
 1 | one
 2 | two
 4 | four
   | six
   | seven
 5 | five-upsert-update
 6 | six-upsert-insert
(7 rows)

DROP TABLE UNIQUE_TBL;
CREATE TABLE UNIQUE_TBL (i int UNIQUE NULLS NOT DISTINCT, t text);
INSERT INTO UNIQUE_TBL VALUES (1, 'one');
INSERT INTO UNIQUE_TBL VALUES (2, 'two');
INSERT INTO UNIQUE_TBL VALUES (1, 'three');  -- fail
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(1) already exists.
INSERT INTO UNIQUE_TBL VALUES (4, 'four');
INSERT INTO UNIQUE_TBL VALUES (5, 'one');
INSERT INTO UNIQUE_TBL (t) VALUES ('six');
INSERT INTO UNIQUE_TBL (t) VALUES ('seven');  -- fail
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(null) already exists.
INSERT INTO UNIQUE_TBL (t) VALUES ('eight') ON CONFLICT DO NOTHING;  -- no-op
SELECT * FROM UNIQUE_TBL;
 i |  t   
---+------
 1 | one
 2 | two
 4 | four
 5 | one
   | six
(5 rows)

DROP TABLE UNIQUE_TBL;
CREATE TABLE UNIQUE_TBL (i int, t text,
	UNIQUE(i,t));
INSERT INTO UNIQUE_TBL VALUES (1, 'one');
INSERT INTO UNIQUE_TBL VALUES (2, 'two');
INSERT INTO UNIQUE_TBL VALUES (1, 'three');
INSERT INTO UNIQUE_TBL VALUES (1, 'one');
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_t_key"
DETAIL:  Key (i, t)=(1, one) already exists.
INSERT INTO UNIQUE_TBL VALUES (5, 'one');
INSERT INTO UNIQUE_TBL (t) VALUES ('six');
SELECT * FROM UNIQUE_TBL;
 i |   t   
---+-------
 1 | one
 2 | two
 1 | three
 5 | one
   | six
(5 rows)

DROP TABLE UNIQUE_TBL;
--
-- Deferrable unique constraints
--
CREATE TABLE unique_tbl (i int UNIQUE DEFERRABLE, t text);
INSERT INTO unique_tbl VALUES (0, 'one');
INSERT INTO unique_tbl VALUES (1, 'two');
INSERT INTO unique_tbl VALUES (2, 'tree');
INSERT INTO unique_tbl VALUES (3, 'four');
INSERT INTO unique_tbl VALUES (4, 'five');
BEGIN;
-- default is immediate so this should fail right away
UPDATE unique_tbl SET i = 1 WHERE i = 0;
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(1) already exists.
ROLLBACK;
-- check is done at end of statement, so this should succeed
UPDATE unique_tbl SET i = i+1;
SELECT * FROM unique_tbl;
 i |  t   
---+------
 1 | one
 2 | two
 3 | tree
 4 | four
 5 | five
(5 rows)

-- explicitly defer the constraint
BEGIN;
SET CONSTRAINTS unique_tbl_i_key DEFERRED;
INSERT INTO unique_tbl VALUES (3, 'three');
DELETE FROM unique_tbl WHERE t = 'tree'; -- makes constraint valid again
COMMIT; -- should succeed
SELECT * FROM unique_tbl;
 i |   t   
---+-------
 1 | one
 2 | two
 4 | four
 5 | five
 3 | three
(5 rows)

-- try adding an initially deferred constraint
ALTER TABLE unique_tbl DROP CONSTRAINT unique_tbl_i_key;
ALTER TABLE unique_tbl ADD CONSTRAINT unique_tbl_i_key
	UNIQUE (i) DEFERRABLE INITIALLY DEFERRED;
BEGIN;
INSERT INTO unique_tbl VALUES (1, 'five');
INSERT INTO unique_tbl VALUES (5, 'one');
UPDATE unique_tbl SET i = 4 WHERE i = 2;
UPDATE unique_tbl SET i = 2 WHERE i = 4 AND t = 'four';
DELETE FROM unique_tbl WHERE i = 1 AND t = 'one';
DELETE FROM unique_tbl WHERE i = 5 AND t = 'five';
COMMIT;
SELECT * FROM unique_tbl;
 i |   t   
---+-------
 3 | three
 1 | five
 5 | one
 4 | two
 2 | four
(5 rows)

-- should fail at commit-time
BEGIN;
INSERT INTO unique_tbl VALUES (3, 'Three'); -- should succeed for now
COMMIT; -- should fail
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(3) already exists.
-- make constraint check immediate
BEGIN;
SET CONSTRAINTS ALL IMMEDIATE;
INSERT INTO unique_tbl VALUES (3, 'Three'); -- should fail
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(3) already exists.
COMMIT;
-- forced check when SET CONSTRAINTS is called
BEGIN;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO unique_tbl VALUES (3, 'Three'); -- should succeed for now
SET CONSTRAINTS ALL IMMEDIATE; -- should fail
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(3) already exists.
COMMIT;
-- test deferrable UNIQUE with a partitioned table
CREATE TABLE parted_uniq_tbl (i int UNIQUE DEFERRABLE) partition by range (i);
CREATE TABLE parted_uniq_tbl_1 PARTITION OF parted_uniq_tbl FOR VALUES FROM (0) TO (10);
CREATE TABLE parted_uniq_tbl_2 PARTITION OF parted_uniq_tbl FOR VALUES FROM (20) TO (30);
SELECT conname, conrelid::regclass FROM pg_constraint
  WHERE conname LIKE 'parted_uniq%' ORDER BY conname;
         conname         |     conrelid      
-------------------------+-------------------
 parted_uniq_tbl_1_i_key | parted_uniq_tbl_1
 parted_uniq_tbl_2_i_key | parted_uniq_tbl_2
 parted_uniq_tbl_i_key   | parted_uniq_tbl
(3 rows)

BEGIN;
INSERT INTO parted_uniq_tbl VALUES (1);
SAVEPOINT f;
INSERT INTO parted_uniq_tbl VALUES (1);	-- unique violation
ERROR:  duplicate key value violates unique constraint "parted_uniq_tbl_1_i_key"
DETAIL:  Key (i)=(1) already exists.
ROLLBACK TO f;
SET CONSTRAINTS parted_uniq_tbl_i_key DEFERRED;
INSERT INTO parted_uniq_tbl VALUES (1);	-- OK now, fail at commit
COMMIT;
ERROR:  duplicate key value violates unique constraint "parted_uniq_tbl_1_i_key"
DETAIL:  Key (i)=(1) already exists.
DROP TABLE parted_uniq_tbl;
-- test naming a constraint in a partition when a conflict exists
CREATE TABLE parted_fk_naming (
    id bigint NOT NULL default 1,
    id_abc bigint,
    CONSTRAINT dummy_constr FOREIGN KEY (id_abc)
        REFERENCES parted_fk_naming (id),
    PRIMARY KEY (id)
)
PARTITION BY LIST (id);
CREATE TABLE parted_fk_naming_1 (
    id bigint NOT NULL default 1,
    id_abc bigint,
    PRIMARY KEY (id),
    CONSTRAINT dummy_constr CHECK (true)
);
ALTER TABLE parted_fk_naming ATTACH PARTITION parted_fk_naming_1 FOR VALUES IN ('1');
SELECT conname FROM pg_constraint WHERE conrelid = 'parted_fk_naming_1'::regclass AND contype = 'f';
    conname     
----------------
 dummy_constr_1
(1 row)

DROP TABLE parted_fk_naming;
--
-- Test various ways to create primary keys on partitions, linked to unique
-- indexes (without constraints) on the partitioned table.  Ideally these should
-- fail, but we don't dare change released behavior, so instead cope with it at
-- DETACH time.
CREATE TEMP TABLE t (a integer, b integer) PARTITION BY HASH (a, b);
CREATE TEMP TABLE tp (a integer, b integer, PRIMARY KEY (a, b), UNIQUE (b, a));
ALTER TABLE t ATTACH PARTITION tp FOR VALUES WITH (MODULUS 1, REMAINDER 0);
CREATE UNIQUE INDEX t_a_idx ON t (a, b);
CREATE UNIQUE INDEX t_b_idx ON t (b, a);
ALTER INDEX t_a_idx ATTACH PARTITION tp_pkey;
ALTER INDEX t_b_idx ATTACH PARTITION tp_b_a_key;
SELECT conname, conparentid, conislocal, coninhcount
  FROM pg_constraint WHERE conname IN ('tp_pkey', 'tp_b_a_key')
  ORDER BY conname DESC;
  conname   | conparentid | conislocal | coninhcount 
------------+-------------+------------+-------------
 tp_pkey    |           0 | t          |           0
 tp_b_a_key |           0 | t          |           0
(2 rows)

ALTER TABLE t DETACH PARTITION tp;
DROP TABLE t, tp;
CREATE TEMP TABLE t (a integer) PARTITION BY LIST (a);
CREATE TEMP TABLE tp (a integer PRIMARY KEY);
CREATE UNIQUE INDEX t_a_idx ON t (a);
ALTER TABLE t ATTACH PARTITION tp FOR VALUES IN (1);
ALTER TABLE t DETACH PARTITION tp;
DROP TABLE t, tp;
CREATE TEMP TABLE t (a integer) PARTITION BY LIST (a);
CREATE TEMP TABLE tp (a integer PRIMARY KEY);
CREATE UNIQUE INDEX t_a_idx ON ONLY t (a);
ALTER TABLE t ATTACH PARTITION tp FOR VALUES IN (1);
ALTER TABLE t DETACH PARTITION tp;
DROP TABLE t, tp;
CREATE TABLE regress_constr_partitioned (a integer) PARTITION BY LIST (a);
CREATE TABLE regress_constr_partition1 PARTITION OF regress_constr_partitioned FOR VALUES IN (1);
ALTER TABLE regress_constr_partition1 ADD PRIMARY KEY (a);
CREATE UNIQUE INDEX ON regress_constr_partitioned (a);
BEGIN;
ALTER TABLE regress_constr_partitioned DETACH PARTITION regress_constr_partition1;
ROLLBACK;
--  Leave this one in funny state for pg_upgrade testing
-- test a HOT update that invalidates the conflicting tuple.
-- the trigger should still fire and catch the violation
BEGIN;
INSERT INTO unique_tbl VALUES (3, 'Three'); -- should succeed for now
UPDATE unique_tbl SET t = 'THREE' WHERE i = 3 AND t = 'Three';
COMMIT; -- should fail
ERROR:  duplicate key value violates unique constraint "unique_tbl_i_key"
DETAIL:  Key (i)=(3) already exists.
SELECT * FROM unique_tbl;
 i |   t   
---+-------
 3 | three
 1 | five
 5 | one
 4 | two
 2 | four
(5 rows)

-- test a HOT update that modifies the newly inserted tuple,
-- but should succeed because we then remove the other conflicting tuple.
BEGIN;
INSERT INTO unique_tbl VALUES(3, 'tree'); -- should succeed for now
UPDATE unique_tbl SET t = 'threex' WHERE t = 'tree';
DELETE FROM unique_tbl WHERE t = 'three';
SELECT * FROM unique_tbl;
 i |   t    
---+--------
 1 | five
 5 | one
 4 | two
 2 | four
 3 | threex
(5 rows)

COMMIT;
SELECT * FROM unique_tbl;
 i |   t    
---+--------
 1 | five
 5 | one
 4 | two
 2 | four
 3 | threex
(5 rows)

-- enforceability cannot be specified or set for unique constraint
CREATE TABLE UNIQUE_EN_TBL(i int UNIQUE ENFORCED);
ERROR:  misplaced ENFORCED clause
LINE 1: CREATE TABLE UNIQUE_EN_TBL(i int UNIQUE ENFORCED);
                                                ^
CREATE TABLE UNIQUE_NOTEN_TBL(i int UNIQUE NOT ENFORCED);
ERROR:  misplaced NOT ENFORCED clause
LINE 1: CREATE TABLE UNIQUE_NOTEN_TBL(i int UNIQUE NOT ENFORCED);
                                                   ^
ALTER TABLE unique_tbl ALTER CONSTRAINT unique_tbl_i_key ENFORCED;
ERROR:  cannot alter enforceability of constraint "unique_tbl_i_key" of relation "unique_tbl"
ALTER TABLE unique_tbl ALTER CONSTRAINT unique_tbl_i_key NOT ENFORCED;
ERROR:  cannot alter enforceability of constraint "unique_tbl_i_key" of relation "unique_tbl"
DROP TABLE unique_tbl;
--
-- EXCLUDE constraints
--
CREATE TABLE circles (
  c1 CIRCLE,
  c2 TEXT,
  EXCLUDE USING gist
    (c1 WITH &&, (c2::circle) WITH &&)
    WHERE (circle_center(c1) <> '(0,0)')
);
-- these should succeed because they don't match the index predicate
INSERT INTO circles VALUES('<(0,0), 5>', '<(0,0), 5>');
INSERT INTO circles VALUES('<(0,0), 5>', '<(0,0), 4>');
-- succeed
INSERT INTO circles VALUES('<(10,10), 10>', '<(0,0), 5>');
-- fail, overlaps
INSERT INTO circles VALUES('<(20,20), 10>', '<(0,0), 4>');
ERROR:  conflicting key value violates exclusion constraint "circles_c1_c2_excl"
DETAIL:  Key (c1, (c2::circle))=(<(20,20),10>, <(0,0),4>) conflicts with existing key (c1, (c2::circle))=(<(10,10),10>, <(0,0),5>).
-- succeed, because violation is ignored
INSERT INTO circles VALUES('<(20,20), 10>', '<(0,0), 4>')
  ON CONFLICT ON CONSTRAINT circles_c1_c2_excl DO NOTHING;
-- fail, because DO UPDATE variant requires unique index
INSERT INTO circles VALUES('<(20,20), 10>', '<(0,0), 4>')
  ON CONFLICT ON CONSTRAINT circles_c1_c2_excl DO UPDATE SET c2 = EXCLUDED.c2;
ERROR:  ON CONFLICT DO UPDATE not supported with exclusion constraints
-- succeed because c1 doesn't overlap
INSERT INTO circles VALUES('<(20,20), 1>', '<(0,0), 5>');
-- succeed because c2 doesn't overlap
INSERT INTO circles VALUES('<(20,20), 10>', '<(10,10), 5>');
-- should fail on existing data without the WHERE clause
ALTER TABLE circles ADD EXCLUDE USING gist
  (c1 WITH &&, (c2::circle) WITH &&);
ERROR:  could not create exclusion constraint "circles_c1_c2_excl1"
DETAIL:  Key (c1, (c2::circle))=(<(0,0),5>, <(0,0),5>) conflicts with key (c1, (c2::circle))=(<(0,0),5>, <(0,0),4>).
-- try reindexing an existing constraint
REINDEX INDEX circles_c1_c2_excl;
DROP TABLE circles;
-- Check deferred exclusion constraint
CREATE TABLE deferred_excl (
  f1 int,
  f2 int,
  CONSTRAINT deferred_excl_con EXCLUDE (f1 WITH =) INITIALLY DEFERRED
);
INSERT INTO deferred_excl VALUES(1);
INSERT INTO deferred_excl VALUES(2);
INSERT INTO deferred_excl VALUES(1); -- fail
ERROR:  conflicting key value violates exclusion constraint "deferred_excl_con"
DETAIL:  Key (f1)=(1) conflicts with existing key (f1)=(1).
INSERT INTO deferred_excl VALUES(1) ON CONFLICT ON CONSTRAINT deferred_excl_con DO NOTHING; -- fail
ERROR:  ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters
BEGIN;
INSERT INTO deferred_excl VALUES(2); -- no fail here
COMMIT; -- should fail here
ERROR:  conflicting key value violates exclusion constraint "deferred_excl_con"
DETAIL:  Key (f1)=(2) conflicts with existing key (f1)=(2).
BEGIN;
INSERT INTO deferred_excl VALUES(3);
INSERT INTO deferred_excl VALUES(3); -- no fail here
COMMIT; -- should fail here
ERROR:  conflicting key value violates exclusion constraint "deferred_excl_con"
DETAIL:  Key (f1)=(3) conflicts with existing key (f1)=(3).
-- bug #13148: deferred constraint versus HOT update
BEGIN;
INSERT INTO deferred_excl VALUES(2, 1); -- no fail here
DELETE FROM deferred_excl WHERE f1 = 2 AND f2 IS NULL; -- remove old row
UPDATE deferred_excl SET f2 = 2 WHERE f1 = 2;
COMMIT; -- should not fail
SELECT * FROM deferred_excl;
 f1 | f2 
----+----
  1 |   
  2 |  2
(2 rows)

ALTER TABLE deferred_excl DROP CONSTRAINT deferred_excl_con;
-- This should fail, but worth testing because of HOT updates
UPDATE deferred_excl SET f1 = 3;
ALTER TABLE deferred_excl ADD EXCLUDE (f1 WITH =);
ERROR:  could not create exclusion constraint "deferred_excl_f1_excl"
DETAIL:  Key (f1)=(3) conflicts with key (f1)=(3).
DROP TABLE deferred_excl;
-- verify constraints created for NOT NULL clauses
CREATE TABLE notnull_tbl1 (a INTEGER NOT NULL NOT NULL);
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "notnull_tbl1_a_not_null" NOT NULL "a"

-- no-op
ALTER TABLE notnull_tbl1 ADD CONSTRAINT nn NOT NULL a;
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "notnull_tbl1_a_not_null" NOT NULL "a"

-- duplicate name
ALTER TABLE notnull_tbl1 ADD COLUMN b INT CONSTRAINT notnull_tbl1_a_not_null NOT NULL;
ERROR:  constraint "notnull_tbl1_a_not_null" for relation "notnull_tbl1" already exists
-- DROP NOT NULL gets rid of both the attnotnull flag and the constraint itself
ALTER TABLE notnull_tbl1 ALTER a DROP NOT NULL;
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 

-- SET NOT NULL puts both back
ALTER TABLE notnull_tbl1 ALTER a SET NOT NULL;
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "notnull_tbl1_a_not_null" NOT NULL "a"

-- Doing it twice doesn't create a redundant constraint
ALTER TABLE notnull_tbl1 ALTER a SET NOT NULL;
select conname, contype, conkey from pg_constraint where conrelid = 'notnull_tbl1'::regclass;
         conname         | contype | conkey 
-------------------------+---------+--------
 notnull_tbl1_a_not_null | n       | {1}
(1 row)

-- Using the "table constraint" syntax also works
ALTER TABLE notnull_tbl1 ALTER a DROP NOT NULL;
ALTER TABLE notnull_tbl1 ADD CONSTRAINT foobar NOT NULL a;
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "foobar" NOT NULL "a"

DROP TABLE notnull_tbl1;
-- Verify that constraint names and NO INHERIT are properly considered when
-- multiple constraint are specified, either explicitly or via SERIAL/PK/etc,
-- and that conflicting cases are rejected.  Mind that table constraints
-- handle this separately from column constraints.
create table notnull_tbl1 (a int primary key constraint foo not null);
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Indexes:
    "notnull_tbl1_pkey" PRIMARY KEY, btree (a)
Not-null constraints:
    "foo" NOT NULL "a"

create table notnull_tbl2 (a serial, constraint foo not null a);
\d+ notnull_tbl2
                                               Table "public.notnull_tbl2"
 Column |  Type   | Collation | Nullable |                 Default                 | Storage | Stats target | Description 
--------+---------+-----------+----------+-----------------------------------------+---------+--------------+-------------
 a      | integer |           | not null | nextval('notnull_tbl2_a_seq'::regclass) | plain   |              | 
Not-null constraints:
    "foo" NOT NULL "a"

create table notnull_tbl3 (constraint foo not null a, a int generated by default as identity);
\d+ notnull_tbl3
                                            Table "public.notnull_tbl3"
 Column |  Type   | Collation | Nullable |             Default              | Storage | Stats target | Description 
--------+---------+-----------+----------+----------------------------------+---------+--------------+-------------
 a      | integer |           | not null | generated by default as identity | plain   |              | 
Not-null constraints:
    "foo" NOT NULL "a"

create table notnull_tbl4 (a int not null constraint foo not null);
\d+ notnull_tbl4
                               Table "public.notnull_tbl4"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "foo" NOT NULL "a"

create table notnull_tbl5 (a int constraint foo not null constraint foo not null);
\d+ notnull_tbl5
                               Table "public.notnull_tbl5"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "foo" NOT NULL "a"

create table notnull_tbl6 (like notnull_tbl1, constraint foo not null a);
\d+ notnull_tbl6
                               Table "public.notnull_tbl6"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "foo" NOT NULL "a"

drop table notnull_tbl2, notnull_tbl3, notnull_tbl4, notnull_tbl5, notnull_tbl6;
-- error cases:
create table notnull_tbl_fail (a serial constraint foo not null constraint bar not null);
ERROR:  conflicting not-null constraint names "foo" and "bar"
create table notnull_tbl_fail (a serial constraint foo not null no inherit constraint foo not null);
ERROR:  conflicting NO INHERIT declarations for not-null constraints on column "a"
create table notnull_tbl_fail (a int constraint foo not null, constraint foo not null a no inherit);
ERROR:  conflicting NO INHERIT declaration for not-null constraint on column "a"
create table notnull_tbl_fail (a serial constraint foo not null, constraint bar not null a);
ERROR:  conflicting not-null constraint names "foo" and "bar"
create table notnull_tbl_fail (a serial, constraint foo not null a, constraint bar not null a);
ERROR:  conflicting not-null constraint names "foo" and "bar"
create table notnull_tbl_fail (a serial, constraint foo not null a no inherit);
ERROR:  conflicting NO INHERIT declaration for not-null constraint on column "a"
create table notnull_tbl_fail (a serial not null no inherit);
ERROR:  conflicting NO INHERIT declarations for not-null constraints on column "a"
create table notnull_tbl_fail (like notnull_tbl1, constraint foo2 not null a);
ERROR:  conflicting not-null constraint names "foo" and "foo2"
create table notnull_tbl_fail (a int primary key constraint foo not null no inherit);
ERROR:  conflicting NO INHERIT declarations for not-null constraints on column "a"
create table notnull_tbl_fail (a int not null no inherit primary key);
ERROR:  conflicting NO INHERIT declarations for not-null constraints on column "a"
create table notnull_tbl_fail (a int primary key, not null a no inherit);
ERROR:  conflicting NO INHERIT declaration for not-null constraint on column "a"
create table notnull_tbl_fail (a int, primary key(a), not null a no inherit);
ERROR:  conflicting NO INHERIT declaration for not-null constraint on column "a"
create table notnull_tbl_fail (a int generated by default as identity, constraint foo not null a no inherit);
ERROR:  conflicting NO INHERIT declaration for not-null constraint on column "a"
create table notnull_tbl_fail (a int generated by default as identity not null no inherit);
ERROR:  conflicting NO INHERIT declarations for not-null constraints on column "a"
drop table notnull_tbl1;
-- NOT NULL NO INHERIT
CREATE TABLE ATACC1 (a int, NOT NULL a NO INHERIT);
CREATE TABLE ATACC2 () INHERITS (ATACC1);
\d+ ATACC2
                                  Table "public.atacc2"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
Inherits: atacc1

DROP TABLE ATACC1, ATACC2;
CREATE TABLE ATACC1 (a int);
ALTER TABLE ATACC1 ADD NOT NULL a NO INHERIT;
CREATE TABLE ATACC2 () INHERITS (ATACC1);
\d+ ATACC2
                                  Table "public.atacc2"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
Inherits: atacc1

DROP TABLE ATACC1, ATACC2;
CREATE TABLE ATACC1 (a int);
CREATE TABLE ATACC2 () INHERITS (ATACC1);
ALTER TABLE ATACC1 ADD NOT NULL a NO INHERIT;
\d+ ATACC2
                                  Table "public.atacc2"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
Inherits: atacc1

CREATE TABLE ATACC3 (PRIMARY KEY (a)) INHERITS (ATACC1);
\d+ ATACC3
                                  Table "public.atacc3"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Indexes:
    "atacc3_pkey" PRIMARY KEY, btree (a)
Not-null constraints:
    "atacc3_a_not_null" NOT NULL "a"
Inherits: atacc1

DROP TABLE ATACC1, ATACC2, ATACC3;
-- NOT NULL NO INHERIT is not possible on partitioned tables
CREATE TABLE ATACC1 (a int NOT NULL NO INHERIT) PARTITION BY LIST (a);
ERROR:  not-null constraints on partitioned tables cannot be NO INHERIT
CREATE TABLE ATACC1 (a int, NOT NULL a NO INHERIT) PARTITION BY LIST (a);
ERROR:  not-null constraints on partitioned tables cannot be NO INHERIT
-- it's not possible to override a no-inherit constraint with an inheritable one
CREATE TABLE ATACC2 (a int, CONSTRAINT a_is_not_null NOT NULL a NO INHERIT);
CREATE TABLE ATACC1 (a int);
CREATE TABLE ATACC3 (a int) INHERITS (ATACC2);
NOTICE:  merging column "a" with inherited definition
ALTER TABLE ATACC2 INHERIT ATACC1;
-- can't override
ALTER TABLE ATACC1 ADD CONSTRAINT ditto NOT NULL a;
ERROR:  cannot change NO INHERIT status of NOT NULL constraint "a_is_not_null" on relation "atacc2"
HINT:  You might need to make the existing constraint inheritable using ALTER TABLE ... ALTER CONSTRAINT ... INHERIT.
-- dropping the NO INHERIT constraint allows this to work
ALTER TABLE ATACC2 DROP CONSTRAINT a_is_not_null;
ALTER TABLE ATACC1 ADD CONSTRAINT ditto NOT NULL a;
\d+ ATACC3
                                  Table "public.atacc3"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "ditto" NOT NULL "a" (inherited)
Inherits: atacc2

DROP TABLE ATACC1, ATACC2, ATACC3;
-- Can't have two constraints with the same name
CREATE TABLE notnull_tbl2 (a INTEGER CONSTRAINT blah NOT NULL, b INTEGER CONSTRAINT blah NOT NULL);
ERROR:  constraint "blah" for relation "notnull_tbl2" already exists
-- can't drop not-null in primary key
CREATE TABLE notnull_tbl2 (a INTEGER PRIMARY KEY);
ALTER TABLE notnull_tbl2 ALTER a DROP NOT NULL;
ERROR:  column "a" is in a primary key
DROP TABLE notnull_tbl2;
CREATE TABLE notnull_tbl3 (a INTEGER NOT NULL, CHECK (a IS NOT NULL));
ALTER TABLE notnull_tbl3 ALTER A DROP NOT NULL;
ALTER TABLE notnull_tbl3 ADD b int, ADD CONSTRAINT pk PRIMARY KEY (a, b);
\d notnull_tbl3
            Table "public.notnull_tbl3"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 a      | integer |           | not null | 
 b      | integer |           | not null | 
Indexes:
    "pk" PRIMARY KEY, btree (a, b)
Check constraints:
    "notnull_tbl3_a_check" CHECK (a IS NOT NULL)

ALTER TABLE notnull_tbl3 DROP CONSTRAINT pk;
\d notnull_tbl3
            Table "public.notnull_tbl3"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 a      | integer |           | not null | 
 b      | integer |           | not null | 
Check constraints:
    "notnull_tbl3_a_check" CHECK (a IS NOT NULL)

-- Primary keys cause not-null constraints to be created.
CREATE TABLE cnn_pk (a int, b int);
CREATE TABLE cnn_pk_child () INHERITS (cnn_pk);
ALTER TABLE cnn_pk ADD CONSTRAINT cnn_primarykey PRIMARY KEY (b);
\d+ cnn_pk*
                                  Table "public.cnn_pk"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Indexes:
    "cnn_primarykey" PRIMARY KEY, btree (b)
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b"
Child tables: cnn_pk_child

                               Table "public.cnn_pk_child"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b" (inherited)
Inherits: cnn_pk

ALTER TABLE cnn_pk DROP CONSTRAINT cnn_primarykey;
\d+ cnn_pk*
                                  Table "public.cnn_pk"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b"
Child tables: cnn_pk_child

                               Table "public.cnn_pk_child"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b" (inherited)
Inherits: cnn_pk

DROP TABLE cnn_pk, cnn_pk_child;
-- As above, but create the primary key ahead of time
CREATE TABLE cnn_pk (a int, b int, CONSTRAINT cnn_primarykey PRIMARY KEY (b));
CREATE TABLE cnn_pk_child () INHERITS (cnn_pk);
\d+ cnn_pk*
                                  Table "public.cnn_pk"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Indexes:
    "cnn_primarykey" PRIMARY KEY, btree (b)
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b"
Child tables: cnn_pk_child

                               Table "public.cnn_pk_child"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b" (inherited)
Inherits: cnn_pk

ALTER TABLE cnn_pk DROP CONSTRAINT cnn_primarykey;
\d+ cnn_pk*
                                  Table "public.cnn_pk"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b"
Child tables: cnn_pk_child

                               Table "public.cnn_pk_child"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b" (inherited)
Inherits: cnn_pk

DROP TABLE cnn_pk, cnn_pk_child;
-- As above, but create the primary key using a UNIQUE index
CREATE TABLE cnn_pk (a int, b int);
CREATE UNIQUE INDEX cnn_uq ON cnn_pk (b);
CREATE TABLE cnn_pk_child () INHERITS (cnn_pk);
ALTER TABLE cnn_pk ADD CONSTRAINT cnn_primarykey PRIMARY KEY USING INDEX cnn_uq;
NOTICE:  ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index "cnn_uq" to "cnn_primarykey"
\d+ cnn_pk*
                                  Table "public.cnn_pk"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Indexes:
    "cnn_primarykey" PRIMARY KEY, btree (b)
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b"
Child tables: cnn_pk_child

                               Table "public.cnn_pk_child"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "cnn_pk_b_not_null" NOT NULL "b" (inherited)
Inherits: cnn_pk

DROP TABLE cnn_pk, cnn_pk_child;
-- Unique constraints don't give raise to not-null constraints, however.
create table cnn_uq (a int);
alter table cnn_uq add unique (a);
\d+ cnn_uq
                                  Table "public.cnn_uq"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
Indexes:
    "cnn_uq_a_key" UNIQUE CONSTRAINT, btree (a)

drop table cnn_uq;
create table cnn_uq (a int);
create unique index cnn_uq_idx on cnn_uq (a);
alter table cnn_uq add unique using index cnn_uq_idx;
\d+ cnn_uq
                                  Table "public.cnn_uq"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           |          |         | plain   |              | 
Indexes:
    "cnn_uq_idx" UNIQUE CONSTRAINT, btree (a)

-- can't create a primary key on a noinherit not-null
create table cnn_pk (a int not null no inherit);
alter table cnn_pk add primary key (a);
ERROR:  cannot create primary key on column "a"
DETAIL:  The constraint "cnn_pk_a_not_null" on column "a" of table "cnn_pk", marked NO INHERIT, is incompatible with a primary key.
HINT:  You might need to make the existing constraint inheritable using ALTER TABLE ... ALTER CONSTRAINT ... INHERIT.
drop table cnn_pk;
-- Ensure partitions are scanned for null values when adding a PK
create table cnn2_parted(a int) partition by list (a);
create table cnn_part1 partition of cnn2_parted for values in (1, null);
insert into cnn_part1 values (null);
alter table cnn2_parted add primary key (a);
ERROR:  column "a" of relation "cnn_part1" contains null values
drop table cnn2_parted;
-- columns in regular and LIKE inheritance should be marked not-nullable
-- for primary keys, even if those are deferred
CREATE TABLE notnull_tbl4 (a INTEGER PRIMARY KEY INITIALLY DEFERRED);
CREATE TABLE notnull_tbl4_lk (LIKE notnull_tbl4);
CREATE TABLE notnull_tbl4_lk2 (LIKE notnull_tbl4 INCLUDING INDEXES);
CREATE TABLE notnull_tbl4_lk3 (LIKE notnull_tbl4 INCLUDING INDEXES, NOT NULL a);
ALTER TABLE notnull_tbl4_lk3 RENAME CONSTRAINT notnull_tbl4_a_not_null TO a_nn;
CREATE TABLE notnull_tbl4_cld () INHERITS (notnull_tbl4);
CREATE TABLE notnull_tbl4_cld2 (PRIMARY KEY (a) DEFERRABLE) INHERITS (notnull_tbl4);
CREATE TABLE notnull_tbl4_cld3 (PRIMARY KEY (a) DEFERRABLE, CONSTRAINT a_nn NOT NULL a) INHERITS (notnull_tbl4);
\d+ notnull_tbl4
                               Table "public.notnull_tbl4"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Indexes:
    "notnull_tbl4_pkey" PRIMARY KEY, btree (a) DEFERRABLE INITIALLY DEFERRED
Not-null constraints:
    "notnull_tbl4_a_not_null" NOT NULL "a"
Child tables: notnull_tbl4_cld,
              notnull_tbl4_cld2,
              notnull_tbl4_cld3

\d+ notnull_tbl4_lk
                              Table "public.notnull_tbl4_lk"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "notnull_tbl4_a_not_null" NOT NULL "a"

\d+ notnull_tbl4_lk2
                             Table "public.notnull_tbl4_lk2"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Indexes:
    "notnull_tbl4_lk2_pkey" PRIMARY KEY, btree (a) DEFERRABLE INITIALLY DEFERRED
Not-null constraints:
    "notnull_tbl4_a_not_null" NOT NULL "a"

\d+ notnull_tbl4_lk3
                             Table "public.notnull_tbl4_lk3"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Indexes:
    "notnull_tbl4_lk3_pkey" PRIMARY KEY, btree (a) DEFERRABLE INITIALLY DEFERRED
Not-null constraints:
    "a_nn" NOT NULL "a"

\d+ notnull_tbl4_cld
                             Table "public.notnull_tbl4_cld"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "notnull_tbl4_a_not_null" NOT NULL "a" (inherited)
Inherits: notnull_tbl4

\d+ notnull_tbl4_cld2
                             Table "public.notnull_tbl4_cld2"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Indexes:
    "notnull_tbl4_cld2_pkey" PRIMARY KEY, btree (a) DEFERRABLE
Not-null constraints:
    "notnull_tbl4_cld2_a_not_null" NOT NULL "a" (local, inherited)
Inherits: notnull_tbl4

\d+ notnull_tbl4_cld3
                             Table "public.notnull_tbl4_cld3"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
Indexes:
    "notnull_tbl4_cld3_pkey" PRIMARY KEY, btree (a) DEFERRABLE
Not-null constraints:
    "a_nn" NOT NULL "a" (local, inherited)
Inherits: notnull_tbl4

-- leave these tables around for pg_upgrade testing
-- It's possible to remove a constraint from parents without affecting children
CREATE TABLE notnull_tbl5 (a int CONSTRAINT ann NOT NULL,
	b int CONSTRAINT bnn NOT NULL);
CREATE TABLE notnull_tbl5_child () INHERITS (notnull_tbl5);
ALTER TABLE ONLY notnull_tbl5 DROP CONSTRAINT ann;
ALTER TABLE ONLY notnull_tbl5 ALTER b DROP NOT NULL;
\d+ notnull_tbl5_child
                            Table "public.notnull_tbl5_child"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Not-null constraints:
    "ann" NOT NULL "a"
    "bnn" NOT NULL "b"
Inherits: notnull_tbl5

CREATE TABLE notnull_tbl6 (a int CONSTRAINT ann NOT NULL,
	b int CONSTRAINT bnn NOT NULL, check (a > 0)) PARTITION BY LIST (a);
CREATE TABLE notnull_tbl6_1 PARTITION OF notnull_tbl6 FOR VALUES IN (1);
ALTER TABLE ONLY notnull_tbl6 DROP CONSTRAINT ann;
ALTER TABLE ONLY notnull_tbl6 ALTER b DROP NOT NULL;
\d+ notnull_tbl6_1
                              Table "public.notnull_tbl6_1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
 b      | integer |           | not null |         | plain   |              | 
Partition of: notnull_tbl6 FOR VALUES IN (1)
Partition constraint: ((a IS NOT NULL) AND (a = 1))
Check constraints:
    "notnull_tbl6_a_check" CHECK (a > 0)
Not-null constraints:
    "ann" NOT NULL "a"
    "bnn" NOT NULL "b"

-- NOT NULL NOT VALID
PREPARE get_nnconstraint_info(regclass[]) AS
SELECT conrelid::regclass as tabname, conname, convalidated, conislocal, coninhcount
FROM  pg_constraint
WHERE conrelid = ANY($1)
ORDER BY conrelid::regclass::text COLLATE "C", conname;
CREATE TABLE notnull_tbl1 (a int, b int);
INSERT INTO notnull_tbl1 VALUES (NULL, 1), (300, 3);
ALTER TABLE notnull_tbl1 ADD CONSTRAINT nn NOT NULL a; -- error
ERROR:  column "a" of relation "notnull_tbl1" contains null values
ALTER TABLE notnull_tbl1 ADD CONSTRAINT nn NOT NULL a NOT VALID; -- ok
-- even an invalid not-null forbids new nulls
INSERT INTO notnull_tbl1 VALUES (NULL, 4);
ERROR:  null value in column "a" of relation "notnull_tbl1" violates not-null constraint
DETAIL:  Failing row contains (null, 4).
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
 b      | integer |           |          |         | plain   |              | 
Not-null constraints:
    "nn" NOT NULL "a" NOT VALID

-- If we have an invalid constraint, we can't have another
ALTER TABLE notnull_tbl1 ADD CONSTRAINT nn1 NOT NULL a NOT VALID NO INHERIT;
ERROR:  cannot change NO INHERIT status of NOT NULL constraint "nn" on relation "notnull_tbl1"
HINT:  You might need to make the existing constraint inheritable using ALTER TABLE ... ALTER CONSTRAINT ... INHERIT.
ALTER TABLE notnull_tbl1 ADD CONSTRAINT nn NOT NULL a;
ERROR:  incompatible NOT VALID constraint "nn" on relation "notnull_tbl1"
HINT:  You might need to validate it using ALTER TABLE ... VALIDATE CONSTRAINT.
-- cannot add primary key on a column with an invalid not-null
ALTER TABLE notnull_tbl1 ADD PRIMARY KEY (a);
ERROR:  cannot create primary key on column "a"
DETAIL:  The constraint "nn" on column "a" of table "notnull_tbl1", marked NOT VALID, is incompatible with a primary key.
HINT:  You might need to validate it using ALTER TABLE ... VALIDATE CONSTRAINT.
-- ALTER column SET NOT NULL validates an invalid constraint (but this fails
-- because of rows with null values)
ALTER TABLE notnull_tbl1 ALTER a SET NOT NULL;
ERROR:  column "a" of relation "notnull_tbl1" contains null values
\d+ notnull_tbl1
                               Table "public.notnull_tbl1"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 a      | integer |           | not null |         | plain   |              | 
 b      | integer |           |          |         | plain   |              | 
Not-null constraints:
    "nn" NOT NULL "a" NOT VALID

-- Creating a derived table using LIKE gets the constraint, but it's valid
CREATE TABLE notnull_tbl1_copy (LIKE notnull_tbl1);
EXECUTE get_nnconstraint_info('{notnull_tbl1_copy}');
      tabname      | conname | convalidated | conislocal | coninhcount 
-------------------+---------+--------------+------------+-------------
 notnull_tbl1_copy | nn      | t            | t          |           0
(1 row)

-- An inheritance child table gets the constraint, but it's valid
CREATE TABLE notnull_tbl1_child (a int, b int) INHERITS (notnull_tbl1);
NOTICE:  merging column "a" with inherited definition
NOTICE:  merging column "b" with inherited definition
EXECUTE get_nnconstraint_info('{notnull_tbl1_child, notnull_tbl1}');
      tabname       | conname | convalidated | conislocal | coninhcount 
--------------------+---------+--------------+------------+-------------
 notnull_tbl1       | nn      | f            | t          |           0
 notnull_tbl1_child | nn      | t            | f          |           1
(2 rows)

-- Also try inheritance added after table creation
CREATE TABLE notnull_tbl1_child2 (c int, b int, a int);
ALTER TABLE notnull_tbl1_child2 INHERIT notnull_tbl1;	-- nope
ERROR:  column "a" in child table "notnull_tbl1_child2" must be marked NOT NULL
ALTER TABLE notnull_tbl1_child2 ADD NOT NULL a NOT VALID;
ALTER TABLE notnull_tbl1_child2 INHERIT notnull_tbl1;
EXECUTE get_nnconstraint_info('{notnull_tbl1_child2}');
       tabname       |            conname             | convalidated | conislocal | coninhcount 
---------------------+--------------------------------+--------------+------------+-------------
 notnull_tbl1_child2 | notnull_tbl1_child2_a_not_null | f            | t          |           1
(1 row)

--table rewrite won't validate invalid constraint
ALTER TABLE notnull_tbl1 ADD column d float8 default random();
-- VALIDATE CONSTRAINT scans the table
ALTER TABLE notnull_tbl1 VALIDATE CONSTRAINT nn; -- error, nulls exist
ERROR:  column "a" of relation "notnull_tbl1" contains null values
UPDATE notnull_tbl1 SET a = 100 WHERE b = 1;
ALTER TABLE notnull_tbl1 VALIDATE CONSTRAINT nn; -- now ok
EXECUTE get_nnconstraint_info('{notnull_tbl1}');
   tabname    | conname | convalidated | conislocal | coninhcount 
--------------+---------+--------------+------------+-------------
 notnull_tbl1 | nn      | t            | t          |           0
(1 row)

--- now we can add primary key
ALTER TABLE notnull_tbl1 ADD PRIMARY KEY (a);
DROP TABLE notnull_tbl1, notnull_tbl1_child, notnull_tbl1_child2;
-- dropping an invalid constraint is possible
CREATE TABLE notnull_tbl1 (a int, b int);
ALTER TABLE notnull_tbl1 ADD NOT NULL a NOT VALID,
	ADD NOT NULL b NOT VALID;
ALTER TABLE notnull_tbl1 ALTER a DROP NOT NULL;
ALTER TABLE notnull_tbl1 DROP CONSTRAINT notnull_tbl1_b_not_null;
DROP TABLE notnull_tbl1;
-- ALTER .. NO INHERIT works for invalid constraints
CREATE TABLE notnull_tbl1 (a int);
CREATE TABLE notnull_tbl1_chld () INHERITS (notnull_tbl1);
ALTER TABLE notnull_tbl1 ADD CONSTRAINT nntbl1_a NOT NULL a NOT VALID;
ALTER TABLE notnull_tbl1 ALTER CONSTRAINT nntbl1_a NO INHERIT;
-- DROP CONSTRAINT recurses correctly on invalid constraints
ALTER TABLE notnull_tbl1 ALTER CONSTRAINT nntbl1_a INHERIT;
ALTER TABLE notnull_tbl1 DROP CONSTRAINT nntbl1_a;
DROP TABLE notnull_tbl1, notnull_tbl1_chld;
-- if a parent has a valid not null constraint then a child table cannot
-- have an invalid one
CREATE TABLE notnull_tbl1 (a int);
ALTER TABLE notnull_tbl1 ADD CONSTRAINT nn_parent NOT NULL a not valid;
CREATE TABLE notnull_chld0 (a int, CONSTRAINT nn_chld0 NOT NULL a);
ALTER TABLE notnull_tbl1 INHERIT notnull_chld0; --error
ERROR:  constraint "nn_parent" conflicts with NOT VALID constraint on child table "notnull_tbl1"
ALTER TABLE notnull_chld0 DROP CONSTRAINT nn_chld0;
ALTER TABLE notnull_chld0 ADD CONSTRAINT nn_chld0 NOT NULL a not valid;
ALTER TABLE notnull_tbl1 INHERIT notnull_chld0; --now ok
-- parents and child not-null will all be validated.
ALTER TABLE notnull_tbl1 VALIDATE CONSTRAINT nn_parent;
EXECUTE get_nnconstraint_info('{notnull_tbl1, notnull_chld0}');
    tabname    |  conname  | convalidated | conislocal | coninhcount 
---------------+-----------+--------------+------------+-------------
 notnull_chld0 | nn_chld0  | f            | t          |           0
 notnull_tbl1  | nn_parent | t            | t          |           1
(2 rows)

DROP TABLE notnull_tbl1, notnull_chld0;
-- Test invalid not null on inheritance table.
CREATE TABLE notnull_inhparent (i int);
CREATE TABLE notnull_inhchild (i int) INHERITS (notnull_inhparent);
NOTICE:  merging column "i" with inherited definition
CREATE TABLE notnull_inhgrand () INHERITS (notnull_inhparent, notnull_inhchild);
NOTICE:  merging multiple inherited definitions of column "i"
ALTER TABLE notnull_inhparent ADD CONSTRAINT nn NOT NULL i NOT VALID;
ALTER TABLE notnull_inhchild ADD CONSTRAINT nn1 NOT NULL i; -- error
ERROR:  incompatible NOT VALID constraint "nn" on relation "notnull_inhchild"
HINT:  You might need to validate it using ALTER TABLE ... VALIDATE CONSTRAINT.
EXECUTE get_nnconstraint_info('{notnull_inhparent, notnull_inhchild, notnull_inhgrand}');
      tabname      | conname | convalidated | conislocal | coninhcount 
-------------------+---------+--------------+------------+-------------
 notnull_inhchild  | nn      | f            | f          |           1
 notnull_inhgrand  | nn      | f            | f          |           2
 notnull_inhparent | nn      | f            | t          |           0
(3 rows)

ALTER TABLE notnull_inhparent ALTER i SET NOT NULL; -- ok
EXECUTE get_nnconstraint_info('{notnull_inhparent, notnull_inhchild, notnull_inhgrand}');
      tabname      | conname | convalidated | conislocal | coninhcount 
-------------------+---------+--------------+------------+-------------
 notnull_inhchild  | nn      | t            | f          |           1
 notnull_inhgrand  | nn      | t            | f          |           2
 notnull_inhparent | nn      | t            | t          |           0
(3 rows)

DROP TABLE notnull_inhparent, notnull_inhchild, notnull_inhgrand;
-- Verify NOT NULL VALID/NOT VALID with partition table.
DROP TABLE notnull_tbl1;
ERROR:  table "notnull_tbl1" does not exist
CREATE TABLE notnull_tbl1 (a int, b int) PARTITION BY LIST (a);
ALTER TABLE notnull_tbl1 ADD CONSTRAINT notnull_con NOT NULL a NOT VALID; --ok
CREATE TABLE notnull_tbl1_1 PARTITION OF notnull_tbl1 FOR VALUES IN (1,2);
CREATE TABLE notnull_tbl1_2(a int, CONSTRAINT nn2 NOT NULL a, b int);
ALTER TABLE notnull_tbl1 ATTACH PARTITION notnull_tbl1_2 FOR VALUES IN (3,4);
CREATE TABLE notnull_tbl1_3(a int, b int);
INSERT INTO notnull_tbl1_3 values(NULL,1);
ALTER TABLE notnull_tbl1_3 add CONSTRAINT nn3 NOT NULL a NOT VALID;
ALTER TABLE notnull_tbl1 ATTACH PARTITION notnull_tbl1_3 FOR VALUES IN (NULL,5);
EXECUTE get_nnconstraint_info('{notnull_tbl1, notnull_tbl1_1, notnull_tbl1_2, notnull_tbl1_3}');
    tabname     |   conname   | convalidated | conislocal | coninhcount 
----------------+-------------+--------------+------------+-------------
 notnull_tbl1   | notnull_con | f            | t          |           0
 notnull_tbl1_1 | notnull_con | t            | f          |           1
 notnull_tbl1_2 | nn2         | t            | f          |           1
 notnull_tbl1_3 | nn3         | f            | f          |           1
(4 rows)

ALTER TABLE notnull_tbl1 ALTER COLUMN a SET NOT NULL; --error, notnull_tbl1_3 have null values
ERROR:  column "a" of relation "notnull_tbl1_3" contains null values
ALTER TABLE notnull_tbl1_3 VALIDATE CONSTRAINT nn3; --error
ERROR:  column "a" of relation "notnull_tbl1_3" contains null values
TRUNCATE notnull_tbl1;
ALTER TABLE notnull_tbl1 ALTER COLUMN a SET NOT NULL; --OK
EXECUTE get_nnconstraint_info('{notnull_tbl1, notnull_tbl1_1, notnull_tbl1_2, notnull_tbl1_3}');
    tabname     |   conname   | convalidated | conislocal | coninhcount 
----------------+-------------+--------------+------------+-------------
 notnull_tbl1   | notnull_con | t            | t          |           0
 notnull_tbl1_1 | notnull_con | t            | f          |           1
 notnull_tbl1_2 | nn2         | t            | f          |           1
 notnull_tbl1_3 | nn3         | t            | f          |           1
(4 rows)

DROP TABLE notnull_tbl1;
-- partitioned table have not-null, then the partitions can not be NOT NULL NOT VALID.
CREATE TABLE pp_nn (a int, b int, NOT NULL a) PARTITION BY LIST (a);
CREATE TABLE pp_nn_1(a int, b int);
ALTER TABLE pp_nn_1 ADD CONSTRAINT nn1 NOT NULL a NOT VALID;
ALTER TABLE pp_nn ATTACH PARTITION pp_nn_1 FOR VALUES IN (NULL,5); --error
ERROR:  constraint "nn1" conflicts with NOT VALID constraint on child table "pp_nn_1"
ALTER TABLE pp_nn_1 VALIDATE CONSTRAINT nn1;
ALTER TABLE pp_nn ATTACH PARTITION pp_nn_1 FOR VALUES IN (NULL,5); --ok
DROP TABLE pp_nn;
-- Try a partition with an invalid constraint and create a PK on the parent.
CREATE TABLE pp_nn (a int) PARTITION BY HASH (a);
CREATE TABLE pp_nn_1 PARTITION OF pp_nn FOR VALUES WITH (MODULUS 2, REMAINDER 0);
ALTER TABLE pp_nn_1 ADD CONSTRAINT nn NOT NULL a NOT VALID;
ALTER TABLE ONLY pp_nn ADD PRIMARY KEY (a);
ERROR:  cannot create primary key on column "a"
DETAIL:  The constraint "nn" on column "a" of table "pp_nn_1", marked NOT VALID, is incompatible with a primary key.
HINT:  You might need to validate it using ALTER TABLE ... VALIDATE CONSTRAINT.
DROP TABLE pp_nn;
-- same as above, but the constraint is NO INHERIT
CREATE TABLE pp_nn (a int) PARTITION BY HASH (a);
CREATE TABLE pp_nn_1 PARTITION OF pp_nn FOR VALUES WITH (MODULUS 2, REMAINDER 0);
ALTER TABLE pp_nn_1 ADD CONSTRAINT nn NOT NULL a NO INHERIT;
ALTER TABLE ONLY pp_nn ADD PRIMARY KEY (a);
ERROR:  cannot create primary key on column "a"
DETAIL:  The constraint "nn" on column "a" of table "pp_nn_1", marked NO INHERIT, is incompatible with a primary key.
HINT:  You might need to make the existing constraint inheritable using ALTER TABLE ... ALTER CONSTRAINT ... INHERIT.
DROP TABLE pp_nn;
-- Create table with NOT NULL INVALID constraint, for pg_upgrade.
CREATE TABLE notnull_tbl1_upg (a int, b int);
INSERT INTO notnull_tbl1_upg VALUES (NULL, 1), (NULL, 2), (300, 3);
ALTER TABLE notnull_tbl1_upg ADD CONSTRAINT nn NOT NULL a NOT VALID;
-- Inherit test for pg_upgrade
CREATE TABLE notnull_parent_upg (a int);
CREATE TABLE notnull_child_upg () INHERITS (notnull_parent_upg);
ALTER TABLE notnull_child_upg ADD CONSTRAINT nn NOT NULL a;
ALTER TABLE notnull_parent_upg ADD CONSTRAINT nn NOT NULL a NOT VALID;
SELECT conrelid::regclass, contype, convalidated, conislocal
FROM pg_catalog.pg_constraint
WHERE conrelid in ('notnull_parent_upg'::regclass, 'notnull_child_upg'::regclass)
ORDER BY 1;
      conrelid      | contype | convalidated | conislocal 
--------------------+---------+--------------+------------
 notnull_parent_upg | n       | f            | t
 notnull_child_upg  | n       | t            | t
(2 rows)

-- Partition table test, for pg_upgrade
CREATE TABLE notnull_part1_upg (a int, b int) PARTITION BY LIST (a);
ALTER TABLE notnull_part1_upg ADD CONSTRAINT notnull_con NOT NULL a NOT VALID; --ok
CREATE TABLE notnull_part1_1_upg PARTITION OF notnull_part1_upg FOR VALUES IN (1,2);
CREATE TABLE notnull_part1_2_upg (a int, CONSTRAINT nn2 NOT NULL a, b int);
ALTER TABLE notnull_part1_upg ATTACH PARTITION notnull_part1_2_upg FOR VALUES IN (3,4);
CREATE TABLE notnull_part1_3_upg (a int, b int);
INSERT INTO notnull_part1_3_upg values(NULL,1);
ALTER TABLE notnull_part1_3_upg add CONSTRAINT nn3 NOT NULL a NOT VALID;
ALTER TABLE notnull_part1_upg ATTACH PARTITION notnull_part1_3_upg FOR VALUES IN (NULL,5);
EXECUTE get_nnconstraint_info('{notnull_part1_upg, notnull_part1_1_upg, notnull_part1_2_upg, notnull_part1_3_upg}');
       tabname       |   conname   | convalidated | conislocal | coninhcount 
---------------------+-------------+--------------+------------+-------------
 notnull_part1_1_upg | notnull_con | t            | f          |           1
 notnull_part1_2_upg | nn2         | t            | f          |           1
 notnull_part1_3_upg | nn3         | f            | f          |           1
 notnull_part1_upg   | notnull_con | f            | t          |           0
(4 rows)

-- Inheritance test tables for pg_upgrade
create table constr_parent (a int);
create table constr_child (a int) inherits (constr_parent);
NOTICE:  merging column "a" with inherited definition
alter table constr_parent add not null a not valid;
alter table constr_child validate constraint constr_parent_a_not_null;
EXECUTE get_nnconstraint_info('{constr_parent, constr_child}');
    tabname    |         conname          | convalidated | conislocal | coninhcount 
---------------+--------------------------+--------------+------------+-------------
 constr_child  | constr_parent_a_not_null | t            | f          |           1
 constr_parent | constr_parent_a_not_null | f            | t          |           0
(2 rows)

create table constr_parent2 (a int);
create table constr_child2 () inherits (constr_parent2);
alter table constr_parent2 add not null a not valid;
alter table constr_child2 validate constraint constr_parent2_a_not_null;
EXECUTE get_nnconstraint_info('{constr_parent2, constr_child2}');
    tabname     |          conname          | convalidated | conislocal | coninhcount 
----------------+---------------------------+--------------+------------+-------------
 constr_child2  | constr_parent2_a_not_null | t            | f          |           1
 constr_parent2 | constr_parent2_a_not_null | f            | t          |           0
(2 rows)

create table constr_parent3 (a int not null);
create table constr_child3 () inherits (constr_parent2, constr_parent3);
NOTICE:  merging multiple inherited definitions of column "a"
EXECUTE get_nnconstraint_info('{constr_parent3, constr_child3}');
    tabname     |          conname          | convalidated | conislocal | coninhcount 
----------------+---------------------------+--------------+------------+-------------
 constr_child3  | constr_parent2_a_not_null | t            | f          |           2
 constr_parent3 | constr_parent3_a_not_null | t            | t          |           0
(2 rows)

DEALLOCATE get_nnconstraint_info;
-- end NOT NULL NOT VALID
-- Comments
-- Setup a low-level role to enforce non-superuser checks.
CREATE ROLE regress_constraint_comments;
SET SESSION AUTHORIZATION regress_constraint_comments;
CREATE TABLE constraint_comments_tbl (a int CONSTRAINT the_constraint CHECK (a > 0));
CREATE DOMAIN constraint_comments_dom AS int CONSTRAINT the_constraint CHECK (value > 0);
COMMENT ON CONSTRAINT the_constraint ON constraint_comments_tbl IS 'yes, the comment';
COMMENT ON CONSTRAINT the_constraint ON DOMAIN constraint_comments_dom IS 'yes, another comment';
-- no such constraint
COMMENT ON CONSTRAINT no_constraint ON constraint_comments_tbl IS 'yes, the comment';
ERROR:  constraint "no_constraint" for table "constraint_comments_tbl" does not exist
COMMENT ON CONSTRAINT no_constraint ON DOMAIN constraint_comments_dom IS 'yes, another comment';
ERROR:  constraint "no_constraint" for domain constraint_comments_dom does not exist
-- no such table/domain
COMMENT ON CONSTRAINT the_constraint ON no_comments_tbl IS 'bad comment';
ERROR:  relation "no_comments_tbl" does not exist
COMMENT ON CONSTRAINT the_constraint ON DOMAIN no_comments_dom IS 'another bad comment';
ERROR:  type "no_comments_dom" does not exist
COMMENT ON CONSTRAINT the_constraint ON constraint_comments_tbl IS NULL;
COMMENT ON CONSTRAINT the_constraint ON DOMAIN constraint_comments_dom IS NULL;
-- unauthorized user
RESET SESSION AUTHORIZATION;
CREATE ROLE regress_constraint_comments_noaccess;
SET SESSION AUTHORIZATION regress_constraint_comments_noaccess;
COMMENT ON CONSTRAINT the_constraint ON constraint_comments_tbl IS 'no, the comment';
ERROR:  must be owner of relation constraint_comments_tbl
COMMENT ON CONSTRAINT the_constraint ON DOMAIN constraint_comments_dom IS 'no, another comment';
ERROR:  must be owner of type constraint_comments_dom
RESET SESSION AUTHORIZATION;
DROP TABLE constraint_comments_tbl;
DROP DOMAIN constraint_comments_dom;
DROP ROLE regress_constraint_comments;
DROP ROLE regress_constraint_comments_noaccess;