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
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
|
/*-------------------------------------------------------------------------
*
* dependency.c
* Routines to support inter-object dependencies.
*
*
* Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/catalog/dependency.c,v 1.47.2.1 2005/11/22 18:23:06 momjian Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_attrdef.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_conversion.h"
#include "catalog/pg_database.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_language.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_rewrite.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/proclang.h"
#include "commands/schemacmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "lib/stringinfo.h"
#include "miscadmin.h"
#include "optimizer/clauses.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteRemove.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
/* expansible list of ObjectAddresses */
typedef struct
{
ObjectAddress *refs; /* => palloc'd array */
int numrefs; /* current number of references */
int maxrefs; /* current size of palloc'd array */
} ObjectAddresses;
/* for find_expr_references_walker */
typedef struct
{
ObjectAddresses addrs; /* addresses being accumulated */
List *rtables; /* list of rangetables to resolve Vars */
} find_expr_references_context;
/*
* This constant table maps ObjectClasses to the corresponding catalog OIDs.
* See also getObjectClass().
*/
static const Oid object_classes[MAX_OCLASS] = {
RelationRelationId, /* OCLASS_CLASS */
ProcedureRelationId, /* OCLASS_PROC */
TypeRelationId, /* OCLASS_TYPE */
CastRelationId, /* OCLASS_CAST */
ConstraintRelationId, /* OCLASS_CONSTRAINT */
ConversionRelationId, /* OCLASS_CONVERSION */
AttrDefaultRelationId, /* OCLASS_DEFAULT */
LanguageRelationId, /* OCLASS_LANGUAGE */
OperatorRelationId, /* OCLASS_OPERATOR */
OperatorClassRelationId, /* OCLASS_OPCLASS */
RewriteRelationId, /* OCLASS_REWRITE */
TriggerRelationId, /* OCLASS_TRIGGER */
NamespaceRelationId /* OCLASS_SCHEMA */
};
static void findAutoDeletableObjects(const ObjectAddress *object,
ObjectAddresses *oktodelete,
Relation depRel);
static bool recursiveDeletion(const ObjectAddress *object,
DropBehavior behavior,
int msglevel,
const ObjectAddress *callingObject,
ObjectAddresses *oktodelete,
Relation depRel);
static bool deleteDependentObjects(const ObjectAddress *object,
const char *objDescription,
DropBehavior behavior,
int msglevel,
ObjectAddresses *oktodelete,
Relation depRel);
static void doDeletion(const ObjectAddress *object);
static bool find_expr_references_walker(Node *node,
find_expr_references_context *context);
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs);
static int object_address_comparator(const void *a, const void *b);
static void init_object_addresses(ObjectAddresses *addrs);
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
ObjectAddresses *addrs);
static void add_exact_object_address(const ObjectAddress *object,
ObjectAddresses *addrs);
static bool object_address_present(const ObjectAddress *object,
ObjectAddresses *addrs);
static void term_object_addresses(ObjectAddresses *addrs);
static void getRelationDescription(StringInfo buffer, Oid relid);
/*
* performDeletion: attempt to drop the specified object. If CASCADE
* behavior is specified, also drop any dependent objects (recursively).
* If RESTRICT behavior is specified, error out if there are any dependent
* objects, except for those that should be implicitly dropped anyway
* according to the dependency type.
*
* This is the outer control routine for all forms of DROP that drop objects
* that can participate in dependencies.
*/
void
performDeletion(const ObjectAddress *object,
DropBehavior behavior)
{
char *objDescription;
Relation depRel;
ObjectAddresses oktodelete;
/*
* Get object description for possible use in failure message. Must do
* this before deleting it ...
*/
objDescription = getObjectDescription(object);
/*
* We save some cycles by opening pg_depend just once and passing the
* Relation pointer down to all the recursive deletion steps.
*/
depRel = heap_open(DependRelationId, RowExclusiveLock);
/*
* Construct a list of objects that are reachable by AUTO or INTERNAL
* dependencies from the target object. These should be deleted silently,
* even if the actual deletion pass first reaches one of them via a
* non-auto dependency.
*/
init_object_addresses(&oktodelete);
findAutoDeletableObjects(object, &oktodelete, depRel);
if (!recursiveDeletion(object, behavior, NOTICE,
NULL, &oktodelete, depRel))
ereport(ERROR,
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
errmsg("cannot drop %s because other objects depend on it",
objDescription),
errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
term_object_addresses(&oktodelete);
heap_close(depRel, RowExclusiveLock);
pfree(objDescription);
}
/*
* deleteWhatDependsOn: attempt to drop everything that depends on the
* specified object, though not the object itself. Behavior is always
* CASCADE.
*
* This is currently used only to clean out the contents of a schema
* (namespace): the passed object is a namespace. We normally want this
* to be done silently, so there's an option to suppress NOTICE messages.
*/
void
deleteWhatDependsOn(const ObjectAddress *object,
bool showNotices)
{
char *objDescription;
Relation depRel;
ObjectAddresses oktodelete;
/*
* Get object description for possible use in failure messages
*/
objDescription = getObjectDescription(object);
/*
* We save some cycles by opening pg_depend just once and passing the
* Relation pointer down to all the recursive deletion steps.
*/
depRel = heap_open(DependRelationId, RowExclusiveLock);
/*
* Construct a list of objects that are reachable by AUTO or INTERNAL
* dependencies from the target object. These should be deleted silently,
* even if the actual deletion pass first reaches one of them via a
* non-auto dependency.
*/
init_object_addresses(&oktodelete);
findAutoDeletableObjects(object, &oktodelete, depRel);
/*
* Now invoke only step 2 of recursiveDeletion: just recurse to the stuff
* dependent on the given object.
*/
if (!deleteDependentObjects(object, objDescription,
DROP_CASCADE,
showNotices ? NOTICE : DEBUG2,
&oktodelete, depRel))
ereport(ERROR,
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
errmsg("failed to drop all objects depending on %s",
objDescription)));
/*
* We do not need CommandCounterIncrement here, since if step 2 did
* anything then each recursive call will have ended with one.
*/
term_object_addresses(&oktodelete);
heap_close(depRel, RowExclusiveLock);
pfree(objDescription);
}
/*
* findAutoDeletableObjects: find all objects that are reachable by AUTO or
* INTERNAL dependency paths from the given object. Add them all to the
* oktodelete list. Note that the originally given object will also be
* added to the list.
*
* depRel is the already-open pg_depend relation.
*/
static void
findAutoDeletableObjects(const ObjectAddress *object,
ObjectAddresses *oktodelete,
Relation depRel)
{
ScanKeyData key[3];
int nkeys;
SysScanDesc scan;
HeapTuple tup;
ObjectAddress otherObject;
/*
* If this object is already in oktodelete, then we already visited it;
* don't do so again (this prevents infinite recursion if there's a loop
* in pg_depend). Otherwise, add it.
*/
if (object_address_present(object, oktodelete))
return;
add_exact_object_address(object, oktodelete);
/*
* Scan pg_depend records that link to this object, showing the things
* that depend on it. For each one that is AUTO or INTERNAL, visit the
* referencing object.
*
* When dropping a whole object (subId = 0), find pg_depend records for
* its sub-objects too.
*/
ScanKeyInit(&key[0],
Anum_pg_depend_refclassid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->classId));
ScanKeyInit(&key[1],
Anum_pg_depend_refobjid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
if (object->objectSubId != 0)
{
ScanKeyInit(&key[2],
Anum_pg_depend_refobjsubid,
BTEqualStrategyNumber, F_INT4EQ,
Int32GetDatum(object->objectSubId));
nkeys = 3;
}
else
nkeys = 2;
scan = systable_beginscan(depRel, DependReferenceIndexId, true,
SnapshotNow, nkeys, key);
while (HeapTupleIsValid(tup = systable_getnext(scan)))
{
Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
switch (foundDep->deptype)
{
case DEPENDENCY_NORMAL:
/* ignore */
break;
case DEPENDENCY_AUTO:
case DEPENDENCY_INTERNAL:
/* recurse */
otherObject.classId = foundDep->classid;
otherObject.objectId = foundDep->objid;
otherObject.objectSubId = foundDep->objsubid;
findAutoDeletableObjects(&otherObject, oktodelete, depRel);
break;
case DEPENDENCY_PIN:
/*
* For a PIN dependency we just ereport immediately; there
* won't be any others to examine, and we aren't ever going to
* let the user delete it.
*/
ereport(ERROR,
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
errmsg("cannot drop %s because it is required by the database system",
getObjectDescription(object))));
break;
default:
elog(ERROR, "unrecognized dependency type '%c' for %s",
foundDep->deptype, getObjectDescription(object));
break;
}
}
systable_endscan(scan);
}
/*
* recursiveDeletion: delete a single object for performDeletion, plus
* (recursively) anything that depends on it.
*
* Returns TRUE if successful, FALSE if not.
*
* callingObject is NULL at the outer level, else identifies the object that
* we recursed from (the reference object that someone else needs to delete).
*
* oktodelete is a list of objects verified deletable (ie, reachable by one
* or more AUTO or INTERNAL dependencies from the original target).
*
* depRel is the already-open pg_depend relation.
*
*
* In RESTRICT mode, we perform all the deletions anyway, but ereport a message
* and return FALSE if we find a restriction violation. performDeletion
* will then abort the transaction to nullify the deletions. We have to
* do it this way to (a) report all the direct and indirect dependencies
* while (b) not going into infinite recursion if there's a cycle.
*
* This is even more complex than one could wish, because it is possible for
* the same pair of objects to be related by both NORMAL and AUTO/INTERNAL
* dependencies. Also, we might have a situation where we've been asked to
* delete object A, and objects B and C both have AUTO dependencies on A,
* but B also has a NORMAL dependency on C. (Since any of these paths might
* be indirect, we can't prevent these scenarios, but must cope instead.)
* If we visit C before B then we would mistakenly decide that the B->C link
* should prevent the restricted drop from occurring. To handle this, we make
* a pre-scan to find all the objects that are auto-deletable from A. If we
* visit C first, but B is present in the oktodelete list, then we make no
* complaint but recurse to delete B anyway. (Note that in general we must
* delete B before deleting C; the drop routine for B may try to access C.)
*
* Note: in the case where the path to B is traversed first, we will not
* see the NORMAL dependency when we reach C, because of the pg_depend
* removals done in step 1. The oktodelete list is necessary just
* to make the behavior independent of the order in which pg_depend
* entries are visited.
*/
static bool
recursiveDeletion(const ObjectAddress *object,
DropBehavior behavior,
int msglevel,
const ObjectAddress *callingObject,
ObjectAddresses *oktodelete,
Relation depRel)
{
bool ok = true;
char *objDescription;
ScanKeyData key[3];
int nkeys;
SysScanDesc scan;
HeapTuple tup;
ObjectAddress otherObject;
ObjectAddress owningObject;
bool amOwned = false;
/*
* Get object description for possible use in messages. Must do this
* before deleting it ...
*/
objDescription = getObjectDescription(object);
/*
* Step 1: find and remove pg_depend records that link from this object to
* others. We have to do this anyway, and doing it first ensures that we
* avoid infinite recursion in the case of cycles. Also, some dependency
* types require extra processing here.
*
* When dropping a whole object (subId = 0), remove all pg_depend records
* for its sub-objects too.
*/
ScanKeyInit(&key[0],
Anum_pg_depend_classid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->classId));
ScanKeyInit(&key[1],
Anum_pg_depend_objid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
if (object->objectSubId != 0)
{
ScanKeyInit(&key[2],
Anum_pg_depend_objsubid,
BTEqualStrategyNumber, F_INT4EQ,
Int32GetDatum(object->objectSubId));
nkeys = 3;
}
else
nkeys = 2;
scan = systable_beginscan(depRel, DependDependerIndexId, true,
SnapshotNow, nkeys, key);
while (HeapTupleIsValid(tup = systable_getnext(scan)))
{
Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
otherObject.classId = foundDep->refclassid;
otherObject.objectId = foundDep->refobjid;
otherObject.objectSubId = foundDep->refobjsubid;
switch (foundDep->deptype)
{
case DEPENDENCY_NORMAL:
case DEPENDENCY_AUTO:
/* no problem */
break;
case DEPENDENCY_INTERNAL:
/*
* This object is part of the internal implementation of
* another object. We have three cases:
*
* 1. At the outermost recursion level, disallow the DROP. (We
* just ereport here, rather than proceeding, since no other
* dependencies are likely to be interesting.)
*/
if (callingObject == NULL)
{
char *otherObjDesc = getObjectDescription(&otherObject);
ereport(ERROR,
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
errmsg("cannot drop %s because %s requires it",
objDescription, otherObjDesc),
errhint("You may drop %s instead.",
otherObjDesc)));
}
/*
* 2. When recursing from the other end of this dependency,
* it's okay to continue with the deletion. This holds when
* recursing from a whole object that includes the nominal
* other end as a component, too.
*/
if (callingObject->classId == otherObject.classId &&
callingObject->objectId == otherObject.objectId &&
(callingObject->objectSubId == otherObject.objectSubId ||
callingObject->objectSubId == 0))
break;
/*
* 3. When recursing from anyplace else, transform this
* deletion request into a delete of the other object. (This
* will be an error condition iff RESTRICT mode.) In this case
* we finish deleting my dependencies except for the INTERNAL
* link, which will be needed to cause the owning object to
* recurse back to me.
*/
if (amOwned) /* shouldn't happen */
elog(ERROR, "multiple INTERNAL dependencies for %s",
objDescription);
owningObject = otherObject;
amOwned = true;
/* "continue" bypasses the simple_heap_delete call below */
continue;
case DEPENDENCY_PIN:
/*
* Should not happen; PIN dependencies should have zeroes in
* the depender fields...
*/
elog(ERROR, "incorrect use of PIN dependency with %s",
objDescription);
break;
default:
elog(ERROR, "unrecognized dependency type '%c' for %s",
foundDep->deptype, objDescription);
break;
}
/* delete the pg_depend tuple */
simple_heap_delete(depRel, &tup->t_self);
}
systable_endscan(scan);
/*
* CommandCounterIncrement here to ensure that preceding changes are all
* visible; in particular, that the above deletions of pg_depend entries
* are visible. That prevents infinite recursion in case of a dependency
* loop (which is perfectly legal).
*/
CommandCounterIncrement();
/*
* If we found we are owned by another object, ask it to delete itself
* instead of proceeding. Complain if RESTRICT mode, unless the other
* object is in oktodelete.
*/
if (amOwned)
{
if (object_address_present(&owningObject, oktodelete))
ereport(DEBUG2,
(errmsg("drop auto-cascades to %s",
getObjectDescription(&owningObject))));
else if (behavior == DROP_RESTRICT)
{
ereport(msglevel,
(errmsg("%s depends on %s",
getObjectDescription(&owningObject),
objDescription)));
ok = false;
}
else
ereport(msglevel,
(errmsg("drop cascades to %s",
getObjectDescription(&owningObject))));
if (!recursiveDeletion(&owningObject, behavior, msglevel,
object, oktodelete, depRel))
ok = false;
pfree(objDescription);
return ok;
}
/*
* Step 2: scan pg_depend records that link to this object, showing the
* things that depend on it. Recursively delete those things. Note it's
* important to delete the dependent objects before the referenced one,
* since the deletion routines might do things like try to update the
* pg_class record when deleting a check constraint.
*/
if (!deleteDependentObjects(object, objDescription,
behavior, msglevel,
oktodelete, depRel))
ok = false;
/*
* We do not need CommandCounterIncrement here, since if step 2 did
* anything then each recursive call will have ended with one.
*/
/*
* Step 3: delete the object itself.
*/
doDeletion(object);
/*
* Delete any comments associated with this object. (This is a convenient
* place to do it instead of having every object type know to do it.)
*/
DeleteComments(object->objectId, object->classId, object->objectSubId);
/*
* Delete shared dependency references related to this object. Sub-objects
* (columns) don't have dependencies on global objects, so skip them.
*/
if (object->objectSubId == 0)
deleteSharedDependencyRecordsFor(object->classId, object->objectId);
/*
* CommandCounterIncrement here to ensure that preceding changes are all
* visible.
*/
CommandCounterIncrement();
/*
* And we're done!
*/
pfree(objDescription);
return ok;
}
/*
* deleteDependentObjects - find and delete objects that depend on 'object'
*
* Scan pg_depend records that link to the given object, showing
* the things that depend on it. Recursively delete those things. (We
* don't delete the pg_depend records here, as the recursive call will
* do that.) Note it's important to delete the dependent objects
* before the referenced one, since the deletion routines might do
* things like try to update the pg_class record when deleting a check
* constraint.
*
* When dropping a whole object (subId = 0), find pg_depend records for
* its sub-objects too.
*
* object: the object to find dependencies on
* objDescription: description of object (only used for error messages)
* behavior: desired drop behavior
* oktodelete: stuff that's AUTO-deletable
* depRel: already opened pg_depend relation
*
* Returns TRUE if all is well, false if any problem found.
*
* NOTE: because we are using SnapshotNow, if a recursive call deletes
* any pg_depend tuples that our scan hasn't yet visited, we will not
* see them as good when we do visit them. This is essential for
* correct behavior if there are multiple dependency paths between two
* objects --- else we might try to delete an already-deleted object.
*/
static bool
deleteDependentObjects(const ObjectAddress *object,
const char *objDescription,
DropBehavior behavior,
int msglevel,
ObjectAddresses *oktodelete,
Relation depRel)
{
bool ok = true;
ScanKeyData key[3];
int nkeys;
SysScanDesc scan;
HeapTuple tup;
ObjectAddress otherObject;
ScanKeyInit(&key[0],
Anum_pg_depend_refclassid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->classId));
ScanKeyInit(&key[1],
Anum_pg_depend_refobjid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
if (object->objectSubId != 0)
{
ScanKeyInit(&key[2],
Anum_pg_depend_refobjsubid,
BTEqualStrategyNumber, F_INT4EQ,
Int32GetDatum(object->objectSubId));
nkeys = 3;
}
else
nkeys = 2;
scan = systable_beginscan(depRel, DependReferenceIndexId, true,
SnapshotNow, nkeys, key);
while (HeapTupleIsValid(tup = systable_getnext(scan)))
{
Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
otherObject.classId = foundDep->classid;
otherObject.objectId = foundDep->objid;
otherObject.objectSubId = foundDep->objsubid;
switch (foundDep->deptype)
{
case DEPENDENCY_NORMAL:
/*
* Perhaps there was another dependency path that would have
* allowed silent deletion of the otherObject, had we only
* taken that path first. In that case, act like this link is
* AUTO, too.
*/
if (object_address_present(&otherObject, oktodelete))
ereport(DEBUG2,
(errmsg("drop auto-cascades to %s",
getObjectDescription(&otherObject))));
else if (behavior == DROP_RESTRICT)
{
ereport(msglevel,
(errmsg("%s depends on %s",
getObjectDescription(&otherObject),
objDescription)));
ok = false;
}
else
ereport(msglevel,
(errmsg("drop cascades to %s",
getObjectDescription(&otherObject))));
if (!recursiveDeletion(&otherObject, behavior, msglevel,
object, oktodelete, depRel))
ok = false;
break;
case DEPENDENCY_AUTO:
case DEPENDENCY_INTERNAL:
/*
* We propagate the DROP without complaint even in the
* RESTRICT case. (However, normal dependencies on the
* component object could still cause failure.)
*/
ereport(DEBUG2,
(errmsg("drop auto-cascades to %s",
getObjectDescription(&otherObject))));
if (!recursiveDeletion(&otherObject, behavior, msglevel,
object, oktodelete, depRel))
ok = false;
break;
case DEPENDENCY_PIN:
/*
* For a PIN dependency we just ereport immediately; there
* won't be any others to report.
*/
ereport(ERROR,
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
errmsg("cannot drop %s because it is required by the database system",
objDescription)));
break;
default:
elog(ERROR, "unrecognized dependency type '%c' for %s",
foundDep->deptype, objDescription);
break;
}
}
systable_endscan(scan);
return ok;
}
/*
* doDeletion: actually delete a single object
*/
static void
doDeletion(const ObjectAddress *object)
{
switch (getObjectClass(object))
{
case OCLASS_CLASS:
{
char relKind = get_rel_relkind(object->objectId);
if (relKind == RELKIND_INDEX)
{
Assert(object->objectSubId == 0);
index_drop(object->objectId);
}
else
{
if (object->objectSubId != 0)
RemoveAttributeById(object->objectId,
object->objectSubId);
else
heap_drop_with_catalog(object->objectId);
}
break;
}
case OCLASS_PROC:
RemoveFunctionById(object->objectId);
break;
case OCLASS_TYPE:
RemoveTypeById(object->objectId);
break;
case OCLASS_CAST:
DropCastById(object->objectId);
break;
case OCLASS_CONSTRAINT:
RemoveConstraintById(object->objectId);
break;
case OCLASS_CONVERSION:
RemoveConversionById(object->objectId);
break;
case OCLASS_DEFAULT:
RemoveAttrDefaultById(object->objectId);
break;
case OCLASS_LANGUAGE:
DropProceduralLanguageById(object->objectId);
break;
case OCLASS_OPERATOR:
RemoveOperatorById(object->objectId);
break;
case OCLASS_OPCLASS:
RemoveOpClassById(object->objectId);
break;
case OCLASS_REWRITE:
RemoveRewriteRuleById(object->objectId);
break;
case OCLASS_TRIGGER:
RemoveTriggerById(object->objectId);
break;
case OCLASS_SCHEMA:
RemoveSchemaById(object->objectId);
break;
default:
elog(ERROR, "unrecognized object class: %u",
object->classId);
}
}
/*
* recordDependencyOnExpr - find expression dependencies
*
* This is used to find the dependencies of rules, constraint expressions,
* etc.
*
* Given an expression or query in node-tree form, find all the objects
* it refers to (tables, columns, operators, functions, etc). Record
* a dependency of the specified type from the given depender object
* to each object mentioned in the expression.
*
* rtable is the rangetable to be used to interpret Vars with varlevelsup=0.
* It can be NIL if no such variables are expected.
*
* XXX is it important to create dependencies on the datatypes mentioned in
* the expression? In most cases this would be redundant (eg, a ref to an
* operator indirectly references its input and output datatypes), but I'm
* not quite convinced there are no cases where we need it.
*/
void
recordDependencyOnExpr(const ObjectAddress *depender,
Node *expr, List *rtable,
DependencyType behavior)
{
find_expr_references_context context;
init_object_addresses(&context.addrs);
/* Set up interpretation for Vars at varlevelsup = 0 */
context.rtables = list_make1(rtable);
/* Scan the expression tree for referenceable objects */
find_expr_references_walker(expr, &context);
/* Remove any duplicates */
eliminate_duplicate_dependencies(&context.addrs);
/* And record 'em */
recordMultipleDependencies(depender,
context.addrs.refs, context.addrs.numrefs,
behavior);
term_object_addresses(&context.addrs);
}
/*
* recordDependencyOnSingleRelExpr - find expression dependencies
*
* As above, but only one relation is expected to be referenced (with
* varno = 1 and varlevelsup = 0). Pass the relation OID instead of a
* range table. An additional frammish is that dependencies on that
* relation (or its component columns) will be marked with 'self_behavior',
* whereas 'behavior' is used for everything else.
*/
void
recordDependencyOnSingleRelExpr(const ObjectAddress *depender,
Node *expr, Oid relId,
DependencyType behavior,
DependencyType self_behavior)
{
find_expr_references_context context;
RangeTblEntry rte;
init_object_addresses(&context.addrs);
/* We gin up a rather bogus rangetable list to handle Vars */
MemSet(&rte, 0, sizeof(rte));
rte.type = T_RangeTblEntry;
rte.rtekind = RTE_RELATION;
rte.relid = relId;
context.rtables = list_make1(list_make1(&rte));
/* Scan the expression tree for referenceable objects */
find_expr_references_walker(expr, &context);
/* Remove any duplicates */
eliminate_duplicate_dependencies(&context.addrs);
/* Separate self-dependencies if necessary */
if (behavior != self_behavior && context.addrs.numrefs > 0)
{
ObjectAddresses self_addrs;
ObjectAddress *outobj;
int oldref,
outrefs;
init_object_addresses(&self_addrs);
outobj = context.addrs.refs;
outrefs = 0;
for (oldref = 0; oldref < context.addrs.numrefs; oldref++)
{
ObjectAddress *thisobj = context.addrs.refs + oldref;
if (thisobj->classId == RelationRelationId &&
thisobj->objectId == relId)
{
/* Move this ref into self_addrs */
add_object_address(OCLASS_CLASS, relId, thisobj->objectSubId,
&self_addrs);
}
else
{
/* Keep it in context.addrs */
outobj->classId = thisobj->classId;
outobj->objectId = thisobj->objectId;
outobj->objectSubId = thisobj->objectSubId;
outobj++;
outrefs++;
}
}
context.addrs.numrefs = outrefs;
/* Record the self-dependencies */
recordMultipleDependencies(depender,
self_addrs.refs, self_addrs.numrefs,
self_behavior);
term_object_addresses(&self_addrs);
}
/* Record the external dependencies */
recordMultipleDependencies(depender,
context.addrs.refs, context.addrs.numrefs,
behavior);
term_object_addresses(&context.addrs);
}
/*
* Recursively search an expression tree for object references.
*
* Note: we avoid creating references to columns of tables that participate
* in an SQL JOIN construct, but are not actually used anywhere in the query.
* To do so, we do not scan the joinaliasvars list of a join RTE while
* scanning the query rangetable, but instead scan each individual entry
* of the alias list when we find a reference to it.
*/
static bool
find_expr_references_walker(Node *node,
find_expr_references_context *context)
{
if (node == NULL)
return false;
if (IsA(node, Var))
{
Var *var = (Var *) node;
List *rtable;
RangeTblEntry *rte;
/* Find matching rtable entry, or complain if not found */
if (var->varlevelsup >= list_length(context->rtables))
elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
rtable = (List *) list_nth(context->rtables, var->varlevelsup);
if (var->varno <= 0 || var->varno > list_length(rtable))
elog(ERROR, "invalid varno %d", var->varno);
rte = rt_fetch(var->varno, rtable);
/*
* A whole-row Var references no specific columns, so adds no new
* dependency.
*/
if (var->varattno == InvalidAttrNumber)
return false;
if (rte->rtekind == RTE_RELATION)
{
/* If it's a plain relation, reference this column */
add_object_address(OCLASS_CLASS, rte->relid, var->varattno,
&context->addrs);
}
else if (rte->rtekind == RTE_JOIN)
{
/* Scan join output column to add references to join inputs */
List *save_rtables;
/* We must make the context appropriate for join's level */
save_rtables = context->rtables;
context->rtables = list_copy_tail(context->rtables,
var->varlevelsup);
if (var->varattno <= 0 ||
var->varattno > list_length(rte->joinaliasvars))
elog(ERROR, "invalid varattno %d", var->varattno);
find_expr_references_walker((Node *) list_nth(rte->joinaliasvars,
var->varattno - 1),
context);
list_free(context->rtables);
context->rtables = save_rtables;
}
return false;
}
if (IsA(node, Const))
{
Const *con = (Const *) node;
Oid objoid;
/*
* If it's a regclass or similar literal referring to an existing
* object, add a reference to that object. (Currently, only the
* regclass case has any likely use, but we may as well handle all the
* OID-alias datatypes consistently.)
*/
if (!con->constisnull)
{
switch (con->consttype)
{
case REGPROCOID:
case REGPROCEDUREOID:
objoid = DatumGetObjectId(con->constvalue);
if (SearchSysCacheExists(PROCOID,
ObjectIdGetDatum(objoid),
0, 0, 0))
add_object_address(OCLASS_PROC, objoid, 0,
&context->addrs);
break;
case REGOPEROID:
case REGOPERATOROID:
objoid = DatumGetObjectId(con->constvalue);
if (SearchSysCacheExists(OPEROID,
ObjectIdGetDatum(objoid),
0, 0, 0))
add_object_address(OCLASS_OPERATOR, objoid, 0,
&context->addrs);
break;
case REGCLASSOID:
objoid = DatumGetObjectId(con->constvalue);
if (SearchSysCacheExists(RELOID,
ObjectIdGetDatum(objoid),
0, 0, 0))
add_object_address(OCLASS_CLASS, objoid, 0,
&context->addrs);
break;
case REGTYPEOID:
objoid = DatumGetObjectId(con->constvalue);
if (SearchSysCacheExists(TYPEOID,
ObjectIdGetDatum(objoid),
0, 0, 0))
add_object_address(OCLASS_TYPE, objoid, 0,
&context->addrs);
break;
}
}
return false;
}
if (IsA(node, FuncExpr))
{
FuncExpr *funcexpr = (FuncExpr *) node;
add_object_address(OCLASS_PROC, funcexpr->funcid, 0,
&context->addrs);
/* fall through to examine arguments */
}
if (IsA(node, OpExpr))
{
OpExpr *opexpr = (OpExpr *) node;
add_object_address(OCLASS_OPERATOR, opexpr->opno, 0,
&context->addrs);
/* fall through to examine arguments */
}
if (IsA(node, DistinctExpr))
{
DistinctExpr *distinctexpr = (DistinctExpr *) node;
add_object_address(OCLASS_OPERATOR, distinctexpr->opno, 0,
&context->addrs);
/* fall through to examine arguments */
}
if (IsA(node, ScalarArrayOpExpr))
{
ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
add_object_address(OCLASS_OPERATOR, opexpr->opno, 0,
&context->addrs);
/* fall through to examine arguments */
}
if (IsA(node, NullIfExpr))
{
NullIfExpr *nullifexpr = (NullIfExpr *) node;
add_object_address(OCLASS_OPERATOR, nullifexpr->opno, 0,
&context->addrs);
/* fall through to examine arguments */
}
if (IsA(node, Aggref))
{
Aggref *aggref = (Aggref *) node;
add_object_address(OCLASS_PROC, aggref->aggfnoid, 0,
&context->addrs);
/* fall through to examine arguments */
}
if (IsA(node, SubLink))
{
SubLink *sublink = (SubLink *) node;
ListCell *opid;
foreach(opid, sublink->operOids)
{
add_object_address(OCLASS_OPERATOR, lfirst_oid(opid), 0,
&context->addrs);
}
/* fall through to examine arguments */
}
if (is_subplan(node))
{
/* Extra work needed here if we ever need this case */
elog(ERROR, "already-planned subqueries not supported");
}
if (IsA(node, Query))
{
/* Recurse into RTE subquery or not-yet-planned sublink subquery */
Query *query = (Query *) node;
ListCell *rtable;
bool result;
/*
* Add whole-relation refs for each plain relation mentioned in the
* subquery's rtable. (Note: query_tree_walker takes care of
* recursing into RTE_FUNCTION and RTE_SUBQUERY RTEs, so no need to do
* that here. But keep it from looking at join alias lists.)
*/
foreach(rtable, query->rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(rtable);
if (rte->rtekind == RTE_RELATION)
add_object_address(OCLASS_CLASS, rte->relid, 0,
&context->addrs);
}
/* Examine substructure of query */
context->rtables = lcons(query->rtable, context->rtables);
result = query_tree_walker(query,
find_expr_references_walker,
(void *) context,
QTW_IGNORE_JOINALIASES);
context->rtables = list_delete_first(context->rtables);
return result;
}
return expression_tree_walker(node, find_expr_references_walker,
(void *) context);
}
/*
* Given an array of dependency references, eliminate any duplicates.
*/
static void
eliminate_duplicate_dependencies(ObjectAddresses *addrs)
{
ObjectAddress *priorobj;
int oldref,
newrefs;
if (addrs->numrefs <= 1)
return; /* nothing to do */
/* Sort the refs so that duplicates are adjacent */
qsort((void *) addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
object_address_comparator);
/* Remove dups */
priorobj = addrs->refs;
newrefs = 1;
for (oldref = 1; oldref < addrs->numrefs; oldref++)
{
ObjectAddress *thisobj = addrs->refs + oldref;
if (priorobj->classId == thisobj->classId &&
priorobj->objectId == thisobj->objectId)
{
if (priorobj->objectSubId == thisobj->objectSubId)
continue; /* identical, so drop thisobj */
/*
* If we have a whole-object reference and a reference to a part
* of the same object, we don't need the whole-object reference
* (for example, we don't need to reference both table foo and
* column foo.bar). The whole-object reference will always appear
* first in the sorted list.
*/
if (priorobj->objectSubId == 0)
{
/* replace whole ref with partial */
priorobj->objectSubId = thisobj->objectSubId;
continue;
}
}
/* Not identical, so add thisobj to output set */
priorobj++;
priorobj->classId = thisobj->classId;
priorobj->objectId = thisobj->objectId;
priorobj->objectSubId = thisobj->objectSubId;
newrefs++;
}
addrs->numrefs = newrefs;
}
/*
* qsort comparator for ObjectAddress items
*/
static int
object_address_comparator(const void *a, const void *b)
{
const ObjectAddress *obja = (const ObjectAddress *) a;
const ObjectAddress *objb = (const ObjectAddress *) b;
if (obja->classId < objb->classId)
return -1;
if (obja->classId > objb->classId)
return 1;
if (obja->objectId < objb->objectId)
return -1;
if (obja->objectId > objb->objectId)
return 1;
/*
* We sort the subId as an unsigned int so that 0 will come first. See
* logic in eliminate_duplicate_dependencies.
*/
if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
return -1;
if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
return 1;
return 0;
}
/*
* Routines for handling an expansible array of ObjectAddress items.
*
* init_object_addresses: initialize an ObjectAddresses array.
*/
static void
init_object_addresses(ObjectAddresses *addrs)
{
/* Initialize array to empty */
addrs->numrefs = 0;
addrs->maxrefs = 32; /* arbitrary initial array size */
addrs->refs = (ObjectAddress *)
palloc(addrs->maxrefs * sizeof(ObjectAddress));
}
/*
* Add an entry to an ObjectAddresses array.
*
* It is convenient to specify the class by ObjectClass rather than directly
* by catalog OID.
*/
static void
add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
ObjectAddresses *addrs)
{
ObjectAddress *item;
/* enlarge array if needed */
if (addrs->numrefs >= addrs->maxrefs)
{
addrs->maxrefs *= 2;
addrs->refs = (ObjectAddress *)
repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
}
/* record this item */
item = addrs->refs + addrs->numrefs;
item->classId = object_classes[oclass];
item->objectId = objectId;
item->objectSubId = subId;
addrs->numrefs++;
}
/*
* Add an entry to an ObjectAddresses array.
*
* As above, but specify entry exactly.
*/
static void
add_exact_object_address(const ObjectAddress *object,
ObjectAddresses *addrs)
{
ObjectAddress *item;
/* enlarge array if needed */
if (addrs->numrefs >= addrs->maxrefs)
{
addrs->maxrefs *= 2;
addrs->refs = (ObjectAddress *)
repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
}
/* record this item */
item = addrs->refs + addrs->numrefs;
*item = *object;
addrs->numrefs++;
}
/*
* Test whether an object is present in an ObjectAddresses array.
*
* We return "true" if object is a subobject of something in the array, too.
*/
static bool
object_address_present(const ObjectAddress *object,
ObjectAddresses *addrs)
{
int i;
for (i = addrs->numrefs - 1; i >= 0; i--)
{
ObjectAddress *thisobj = addrs->refs + i;
if (object->classId == thisobj->classId &&
object->objectId == thisobj->objectId)
{
if (object->objectSubId == thisobj->objectSubId ||
thisobj->objectSubId == 0)
return true;
}
}
return false;
}
/*
* Clean up when done with an ObjectAddresses array.
*/
static void
term_object_addresses(ObjectAddresses *addrs)
{
pfree(addrs->refs);
}
/*
* Determine the class of a given object identified by objectAddress.
*
* This function is essentially the reverse mapping for the object_classes[]
* table. We implement it as a function because the OIDs aren't consecutive.
*/
ObjectClass
getObjectClass(const ObjectAddress *object)
{
switch (object->classId)
{
case RelationRelationId:
/* caller must check objectSubId */
return OCLASS_CLASS;
case ProcedureRelationId:
Assert(object->objectSubId == 0);
return OCLASS_PROC;
case TypeRelationId:
Assert(object->objectSubId == 0);
return OCLASS_TYPE;
case CastRelationId:
Assert(object->objectSubId == 0);
return OCLASS_CAST;
case ConstraintRelationId:
Assert(object->objectSubId == 0);
return OCLASS_CONSTRAINT;
case ConversionRelationId:
Assert(object->objectSubId == 0);
return OCLASS_CONVERSION;
case AttrDefaultRelationId:
Assert(object->objectSubId == 0);
return OCLASS_DEFAULT;
case LanguageRelationId:
Assert(object->objectSubId == 0);
return OCLASS_LANGUAGE;
case OperatorRelationId:
Assert(object->objectSubId == 0);
return OCLASS_OPERATOR;
case OperatorClassRelationId:
Assert(object->objectSubId == 0);
return OCLASS_OPCLASS;
case RewriteRelationId:
Assert(object->objectSubId == 0);
return OCLASS_REWRITE;
case TriggerRelationId:
Assert(object->objectSubId == 0);
return OCLASS_TRIGGER;
case NamespaceRelationId:
Assert(object->objectSubId == 0);
return OCLASS_SCHEMA;
case AuthIdRelationId:
Assert(object->objectSubId == 0);
return OCLASS_ROLE;
case DatabaseRelationId:
Assert(object->objectSubId == 0);
return OCLASS_DATABASE;
case TableSpaceRelationId:
Assert(object->objectSubId == 0);
return OCLASS_TBLSPACE;
}
/* shouldn't get here */
elog(ERROR, "unrecognized object class: %u", object->classId);
return OCLASS_CLASS; /* keep compiler quiet */
}
/*
* getObjectDescription: build an object description for messages
*
* The result is a palloc'd string.
*/
char *
getObjectDescription(const ObjectAddress *object)
{
StringInfoData buffer;
initStringInfo(&buffer);
switch (getObjectClass(object))
{
case OCLASS_CLASS:
getRelationDescription(&buffer, object->objectId);
if (object->objectSubId != 0)
appendStringInfo(&buffer, _(" column %s"),
get_relid_attribute_name(object->objectId,
object->objectSubId));
break;
case OCLASS_PROC:
appendStringInfo(&buffer, _("function %s"),
format_procedure(object->objectId));
break;
case OCLASS_TYPE:
appendStringInfo(&buffer, _("type %s"),
format_type_be(object->objectId));
break;
case OCLASS_CAST:
{
Relation castDesc;
ScanKeyData skey[1];
SysScanDesc rcscan;
HeapTuple tup;
Form_pg_cast castForm;
castDesc = heap_open(CastRelationId, AccessShareLock);
ScanKeyInit(&skey[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
rcscan = systable_beginscan(castDesc, CastOidIndexId, true,
SnapshotNow, 1, skey);
tup = systable_getnext(rcscan);
if (!HeapTupleIsValid(tup))
elog(ERROR, "could not find tuple for cast %u",
object->objectId);
castForm = (Form_pg_cast) GETSTRUCT(tup);
appendStringInfo(&buffer, _("cast from %s to %s"),
format_type_be(castForm->castsource),
format_type_be(castForm->casttarget));
systable_endscan(rcscan);
heap_close(castDesc, AccessShareLock);
break;
}
case OCLASS_CONSTRAINT:
{
Relation conDesc;
ScanKeyData skey[1];
SysScanDesc rcscan;
HeapTuple tup;
Form_pg_constraint con;
conDesc = heap_open(ConstraintRelationId, AccessShareLock);
ScanKeyInit(&skey[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
rcscan = systable_beginscan(conDesc, ConstraintOidIndexId, true,
SnapshotNow, 1, skey);
tup = systable_getnext(rcscan);
if (!HeapTupleIsValid(tup))
elog(ERROR, "could not find tuple for constraint %u",
object->objectId);
con = (Form_pg_constraint) GETSTRUCT(tup);
if (OidIsValid(con->conrelid))
{
appendStringInfo(&buffer, _("constraint %s on "),
NameStr(con->conname));
getRelationDescription(&buffer, con->conrelid);
}
else
{
appendStringInfo(&buffer, _("constraint %s"),
NameStr(con->conname));
}
systable_endscan(rcscan);
heap_close(conDesc, AccessShareLock);
break;
}
case OCLASS_CONVERSION:
{
HeapTuple conTup;
conTup = SearchSysCache(CONOID,
ObjectIdGetDatum(object->objectId),
0, 0, 0);
if (!HeapTupleIsValid(conTup))
elog(ERROR, "cache lookup failed for conversion %u",
object->objectId);
appendStringInfo(&buffer, _("conversion %s"),
NameStr(((Form_pg_conversion) GETSTRUCT(conTup))->conname));
ReleaseSysCache(conTup);
break;
}
case OCLASS_DEFAULT:
{
Relation attrdefDesc;
ScanKeyData skey[1];
SysScanDesc adscan;
HeapTuple tup;
Form_pg_attrdef attrdef;
ObjectAddress colobject;
attrdefDesc = heap_open(AttrDefaultRelationId, AccessShareLock);
ScanKeyInit(&skey[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
adscan = systable_beginscan(attrdefDesc, AttrDefaultOidIndexId,
true, SnapshotNow, 1, skey);
tup = systable_getnext(adscan);
if (!HeapTupleIsValid(tup))
elog(ERROR, "could not find tuple for attrdef %u",
object->objectId);
attrdef = (Form_pg_attrdef) GETSTRUCT(tup);
colobject.classId = RelationRelationId;
colobject.objectId = attrdef->adrelid;
colobject.objectSubId = attrdef->adnum;
appendStringInfo(&buffer, _("default for %s"),
getObjectDescription(&colobject));
systable_endscan(adscan);
heap_close(attrdefDesc, AccessShareLock);
break;
}
case OCLASS_LANGUAGE:
{
HeapTuple langTup;
langTup = SearchSysCache(LANGOID,
ObjectIdGetDatum(object->objectId),
0, 0, 0);
if (!HeapTupleIsValid(langTup))
elog(ERROR, "cache lookup failed for language %u",
object->objectId);
appendStringInfo(&buffer, _("language %s"),
NameStr(((Form_pg_language) GETSTRUCT(langTup))->lanname));
ReleaseSysCache(langTup);
break;
}
case OCLASS_OPERATOR:
appendStringInfo(&buffer, _("operator %s"),
format_operator(object->objectId));
break;
case OCLASS_OPCLASS:
{
HeapTuple opcTup;
Form_pg_opclass opcForm;
HeapTuple amTup;
Form_pg_am amForm;
char *nspname;
opcTup = SearchSysCache(CLAOID,
ObjectIdGetDatum(object->objectId),
0, 0, 0);
if (!HeapTupleIsValid(opcTup))
elog(ERROR, "cache lookup failed for opclass %u",
object->objectId);
opcForm = (Form_pg_opclass) GETSTRUCT(opcTup);
amTup = SearchSysCache(AMOID,
ObjectIdGetDatum(opcForm->opcamid),
0, 0, 0);
if (!HeapTupleIsValid(amTup))
elog(ERROR, "cache lookup failed for access method %u",
opcForm->opcamid);
amForm = (Form_pg_am) GETSTRUCT(amTup);
/* Qualify the name if not visible in search path */
if (OpclassIsVisible(object->objectId))
nspname = NULL;
else
nspname = get_namespace_name(opcForm->opcnamespace);
appendStringInfo(&buffer, _("operator class %s for access method %s"),
quote_qualified_identifier(nspname,
NameStr(opcForm->opcname)),
NameStr(amForm->amname));
ReleaseSysCache(amTup);
ReleaseSysCache(opcTup);
break;
}
case OCLASS_REWRITE:
{
Relation ruleDesc;
ScanKeyData skey[1];
SysScanDesc rcscan;
HeapTuple tup;
Form_pg_rewrite rule;
ruleDesc = heap_open(RewriteRelationId, AccessShareLock);
ScanKeyInit(&skey[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
rcscan = systable_beginscan(ruleDesc, RewriteOidIndexId, true,
SnapshotNow, 1, skey);
tup = systable_getnext(rcscan);
if (!HeapTupleIsValid(tup))
elog(ERROR, "could not find tuple for rule %u",
object->objectId);
rule = (Form_pg_rewrite) GETSTRUCT(tup);
appendStringInfo(&buffer, _("rule %s on "),
NameStr(rule->rulename));
getRelationDescription(&buffer, rule->ev_class);
systable_endscan(rcscan);
heap_close(ruleDesc, AccessShareLock);
break;
}
case OCLASS_TRIGGER:
{
Relation trigDesc;
ScanKeyData skey[1];
SysScanDesc tgscan;
HeapTuple tup;
Form_pg_trigger trig;
trigDesc = heap_open(TriggerRelationId, AccessShareLock);
ScanKeyInit(&skey[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(object->objectId));
tgscan = systable_beginscan(trigDesc, TriggerOidIndexId, true,
SnapshotNow, 1, skey);
tup = systable_getnext(tgscan);
if (!HeapTupleIsValid(tup))
elog(ERROR, "could not find tuple for trigger %u",
object->objectId);
trig = (Form_pg_trigger) GETSTRUCT(tup);
appendStringInfo(&buffer, _("trigger %s on "),
NameStr(trig->tgname));
getRelationDescription(&buffer, trig->tgrelid);
systable_endscan(tgscan);
heap_close(trigDesc, AccessShareLock);
break;
}
case OCLASS_SCHEMA:
{
char *nspname;
nspname = get_namespace_name(object->objectId);
if (!nspname)
elog(ERROR, "cache lookup failed for namespace %u",
object->objectId);
appendStringInfo(&buffer, _("schema %s"), nspname);
break;
}
case OCLASS_ROLE:
{
appendStringInfo(&buffer, _("role %s"),
GetUserNameFromId(object->objectId));
break;
}
case OCLASS_DATABASE:
{
char *datname;
datname = get_database_name(object->objectId);
if (!datname)
elog(ERROR, "cache lookup failed for database %u",
object->objectId);
appendStringInfo(&buffer, _("database %s"), datname);
break;
}
case OCLASS_TBLSPACE:
{
char *tblspace;
tblspace = get_tablespace_name(object->objectId);
if (!tblspace)
elog(ERROR, "cache lookup failed for tablespace %u",
object->objectId);
appendStringInfo(&buffer, _("tablespace %s"), tblspace);
break;
}
default:
appendStringInfo(&buffer, "unrecognized object %u %u %d",
object->classId,
object->objectId,
object->objectSubId);
break;
}
return buffer.data;
}
/*
* subroutine for getObjectDescription: describe a relation
*/
static void
getRelationDescription(StringInfo buffer, Oid relid)
{
HeapTuple relTup;
Form_pg_class relForm;
char *nspname;
char *relname;
relTup = SearchSysCache(RELOID,
ObjectIdGetDatum(relid),
0, 0, 0);
if (!HeapTupleIsValid(relTup))
elog(ERROR, "cache lookup failed for relation %u", relid);
relForm = (Form_pg_class) GETSTRUCT(relTup);
/* Qualify the name if not visible in search path */
if (RelationIsVisible(relid))
nspname = NULL;
else
nspname = get_namespace_name(relForm->relnamespace);
relname = quote_qualified_identifier(nspname, NameStr(relForm->relname));
switch (relForm->relkind)
{
case RELKIND_RELATION:
appendStringInfo(buffer, _("table %s"),
relname);
break;
case RELKIND_INDEX:
appendStringInfo(buffer, _("index %s"),
relname);
break;
case RELKIND_SPECIAL:
appendStringInfo(buffer, _("special system relation %s"),
relname);
break;
case RELKIND_SEQUENCE:
appendStringInfo(buffer, _("sequence %s"),
relname);
break;
case RELKIND_UNCATALOGED:
appendStringInfo(buffer, _("uncataloged table %s"),
relname);
break;
case RELKIND_TOASTVALUE:
appendStringInfo(buffer, _("toast table %s"),
relname);
break;
case RELKIND_VIEW:
appendStringInfo(buffer, _("view %s"),
relname);
break;
case RELKIND_COMPOSITE_TYPE:
appendStringInfo(buffer, _("composite type %s"),
relname);
break;
default:
/* shouldn't get here */
appendStringInfo(buffer, _("relation %s"),
relname);
break;
}
ReleaseSysCache(relTup);
}
|