PostgreSQL Source Code  git master
dependency.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_am.h"
#include "catalog/pg_amop.h"
#include "catalog/pg_amproc.h"
#include "catalog/pg_attrdef.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_auth_members.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_conversion.h"
#include "catalog/pg_database.h"
#include "catalog/pg_default_acl.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_event_trigger.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_init_privs.h"
#include "catalog/pg_language.h"
#include "catalog/pg_largeobject.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_parameter_acl.h"
#include "catalog/pg_policy.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_publication.h"
#include "catalog/pg_publication_namespace.h"
#include "catalog/pg_publication_rel.h"
#include "catalog/pg_rewrite.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_subscription.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_transform.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_ts_config.h"
#include "catalog/pg_ts_dict.h"
#include "catalog/pg_ts_parser.h"
#include "catalog/pg_ts_template.h"
#include "catalog/pg_type.h"
#include "catalog/pg_user_mapping.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/extension.h"
#include "commands/policy.h"
#include "commands/publicationcmds.h"
#include "commands/seclabel.h"
#include "commands/sequence.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteRemove.h"
#include "storage/lmgr.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
Include dependency graph for dependency.c:

Go to the source code of this file.

Data Structures

struct  ObjectAddressExtra
 
struct  ObjectAddresses
 
struct  ObjectAddressStack
 
struct  ObjectAddressAndFlags
 
struct  find_expr_references_context
 

Macros

#define DEPFLAG_ORIGINAL   0x0001 /* an original deletion target */
 
#define DEPFLAG_NORMAL   0x0002 /* reached via normal dependency */
 
#define DEPFLAG_AUTO   0x0004 /* reached via auto dependency */
 
#define DEPFLAG_INTERNAL   0x0008 /* reached via internal dependency */
 
#define DEPFLAG_PARTITION   0x0010 /* reached via partition dependency */
 
#define DEPFLAG_EXTENSION   0x0020 /* reached via extension dependency */
 
#define DEPFLAG_REVERSE   0x0040 /* reverse internal/extension link */
 
#define DEPFLAG_IS_PART   0x0080 /* has a partition dependency */
 
#define DEPFLAG_SUBOBJECT   0x0100 /* subobject of another deletable object */
 
#define MAX_REPORTED_DEPS   100
 

Typedefs

typedef struct ObjectAddressStack ObjectAddressStack
 

Functions

static void findDependentObjects (const ObjectAddress *object, int objflags, int flags, ObjectAddressStack *stack, ObjectAddresses *targetObjects, const ObjectAddresses *pendingObjects, Relation *depRel)
 
static void reportDependentObjects (const ObjectAddresses *targetObjects, DropBehavior behavior, int flags, const ObjectAddress *origObject)
 
static void deleteOneObject (const ObjectAddress *object, Relation *depRel, int32 flags)
 
static void doDeletion (const ObjectAddress *object, int flags)
 
static bool find_expr_references_walker (Node *node, find_expr_references_context *context)
 
static void process_function_rte_ref (RangeTblEntry *rte, AttrNumber attnum, 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 add_object_address (Oid classId, Oid objectId, int32 subId, ObjectAddresses *addrs)
 
static void add_exact_object_address_extra (const ObjectAddress *object, const ObjectAddressExtra *extra, ObjectAddresses *addrs)
 
static bool object_address_present_add_flags (const ObjectAddress *object, int flags, ObjectAddresses *addrs)
 
static bool stack_address_present_add_flags (const ObjectAddress *object, int flags, ObjectAddressStack *stack)
 
static void DeleteInitPrivs (const ObjectAddress *object)
 
static void deleteObjectsInList (ObjectAddresses *targetObjects, Relation *depRel, int flags)
 
void performDeletion (const ObjectAddress *object, DropBehavior behavior, int flags)
 
void performMultipleDeletions (const ObjectAddresses *objects, DropBehavior behavior, int flags)
 
static void DropObjectById (const ObjectAddress *object)
 
static void deleteOneObject (const ObjectAddress *object, Relation *depRel, int flags)
 
void AcquireDeletionLock (const ObjectAddress *object, int flags)
 
void ReleaseDeletionLock (const ObjectAddress *object)
 
void recordDependencyOnExpr (const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
 
void recordDependencyOnSingleRelExpr (const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self)
 
ObjectAddressesnew_object_addresses (void)
 
void add_exact_object_address (const ObjectAddress *object, ObjectAddresses *addrs)
 
bool object_address_present (const ObjectAddress *object, const ObjectAddresses *addrs)
 
void record_object_address_dependencies (const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
 
void sort_object_addresses (ObjectAddresses *addrs)
 
void free_object_addresses (ObjectAddresses *addrs)
 

Macro Definition Documentation

◆ DEPFLAG_AUTO

#define DEPFLAG_AUTO   0x0004 /* reached via auto dependency */

Definition at line 103 of file dependency.c.

◆ DEPFLAG_EXTENSION

#define DEPFLAG_EXTENSION   0x0020 /* reached via extension dependency */

Definition at line 106 of file dependency.c.

◆ DEPFLAG_INTERNAL

#define DEPFLAG_INTERNAL   0x0008 /* reached via internal dependency */

Definition at line 104 of file dependency.c.

◆ DEPFLAG_IS_PART

#define DEPFLAG_IS_PART   0x0080 /* has a partition dependency */

Definition at line 108 of file dependency.c.

◆ DEPFLAG_NORMAL

#define DEPFLAG_NORMAL   0x0002 /* reached via normal dependency */

Definition at line 102 of file dependency.c.

◆ DEPFLAG_ORIGINAL

#define DEPFLAG_ORIGINAL   0x0001 /* an original deletion target */

Definition at line 101 of file dependency.c.

◆ DEPFLAG_PARTITION

#define DEPFLAG_PARTITION   0x0010 /* reached via partition dependency */

Definition at line 105 of file dependency.c.

◆ DEPFLAG_REVERSE

#define DEPFLAG_REVERSE   0x0040 /* reverse internal/extension link */

Definition at line 107 of file dependency.c.

◆ DEPFLAG_SUBOBJECT

#define DEPFLAG_SUBOBJECT   0x0100 /* subobject of another deletable object */

Definition at line 109 of file dependency.c.

◆ MAX_REPORTED_DEPS

#define MAX_REPORTED_DEPS   100

Typedef Documentation

◆ ObjectAddressStack

Function Documentation

◆ AcquireDeletionLock()

void AcquireDeletionLock ( const ObjectAddress object,
int  flags 
)

Definition at line 1494 of file dependency.c.

1495 {
1496  if (object->classId == RelationRelationId)
1497  {
1498  /*
1499  * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1500  * the index for the moment. index_drop() will promote the lock once
1501  * it's safe to do so. In all other cases we need full exclusive
1502  * lock.
1503  */
1504  if (flags & PERFORM_DELETION_CONCURRENTLY)
1506  else
1508  }
1509  else if (object->classId == AuthMemRelationId)
1510  LockSharedObject(object->classId, object->objectId, 0,
1512  else
1513  {
1514  /* assume we should lock the whole object not a sub-object */
1515  LockDatabaseObject(object->classId, object->objectId, 0,
1517  }
1518 }
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:93
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1083
void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1004
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39

References AccessExclusiveLock, ObjectAddress::classId, ObjectAddressStack::flags, LockDatabaseObject(), LockRelationOid(), LockSharedObject(), ObjectAddressStack::object, ObjectAddress::objectId, PERFORM_DELETION_CONCURRENTLY, and ShareUpdateExclusiveLock.

Referenced by findDependentObjects(), performDeletion(), performMultipleDeletions(), and shdepDropOwned().

◆ add_exact_object_address()

void add_exact_object_address ( const ObjectAddress object,
ObjectAddresses addrs 
)

Definition at line 2531 of file dependency.c.

2533 {
2534  ObjectAddress *item;
2535 
2536  /* enlarge array if needed */
2537  if (addrs->numrefs >= addrs->maxrefs)
2538  {
2539  addrs->maxrefs *= 2;
2540  addrs->refs = (ObjectAddress *)
2541  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2542  Assert(!addrs->extras);
2543  }
2544  /* record this item */
2545  item = addrs->refs + addrs->numrefs;
2546  *item = *object;
2547  addrs->numrefs++;
2548 }
#define Assert(condition)
Definition: c.h:858
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1540
ObjectAddressExtra * extras
Definition: dependency.c:116
ObjectAddress * refs
Definition: dependency.c:115

References Assert, ObjectAddresses::extras, ObjectAddresses::maxrefs, ObjectAddresses::numrefs, ObjectAddressStack::object, ObjectAddresses::refs, and repalloc().

Referenced by AggregateCreate(), AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterTypeNamespaceInternal(), ATExecDropColumn(), ATPostAlterTypeCleanup(), CastCreate(), CreateConstraintEntry(), CreateProceduralLanguage(), CreateTransform(), DropClonedTriggersFromPartition(), GenerateTypeDependencies(), heap_create_with_catalog(), index_create(), InsertExtensionTuple(), makeConfigurationDependencies(), makeDictionaryDependencies(), makeOperatorDependencies(), makeParserDependencies(), makeTSTemplateDependencies(), PreCommit_on_commit_actions(), ProcedureCreate(), RangeCreate(), recordDependencyOnSingleRelExpr(), ReindexRelationConcurrently(), RemoveObjects(), RemoveRelations(), shdepDropOwned(), and StorePartitionKey().

◆ add_exact_object_address_extra()

static void add_exact_object_address_extra ( const ObjectAddress object,
const ObjectAddressExtra extra,
ObjectAddresses addrs 
)
static

Definition at line 2556 of file dependency.c.

2559 {
2560  ObjectAddress *item;
2561  ObjectAddressExtra *itemextra;
2562 
2563  /* allocate extra space if first time */
2564  if (!addrs->extras)
2565  addrs->extras = (ObjectAddressExtra *)
2566  palloc(addrs->maxrefs * sizeof(ObjectAddressExtra));
2567 
2568  /* enlarge array if needed */
2569  if (addrs->numrefs >= addrs->maxrefs)
2570  {
2571  addrs->maxrefs *= 2;
2572  addrs->refs = (ObjectAddress *)
2573  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2574  addrs->extras = (ObjectAddressExtra *)
2575  repalloc(addrs->extras, addrs->maxrefs * sizeof(ObjectAddressExtra));
2576  }
2577  /* record this item */
2578  item = addrs->refs + addrs->numrefs;
2579  *item = *object;
2580  itemextra = addrs->extras + addrs->numrefs;
2581  *itemextra = *extra;
2582  addrs->numrefs++;
2583 }
void * palloc(Size size)
Definition: mcxt.c:1316

References ObjectAddresses::extras, ObjectAddresses::maxrefs, ObjectAddresses::numrefs, ObjectAddressStack::object, palloc(), ObjectAddresses::refs, and repalloc().

Referenced by findDependentObjects().

◆ add_object_address()

static void add_object_address ( Oid  classId,
Oid  objectId,
int32  subId,
ObjectAddresses addrs 
)
static

Definition at line 2504 of file dependency.c.

2506 {
2507  ObjectAddress *item;
2508 
2509  /* enlarge array if needed */
2510  if (addrs->numrefs >= addrs->maxrefs)
2511  {
2512  addrs->maxrefs *= 2;
2513  addrs->refs = (ObjectAddress *)
2514  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2515  Assert(!addrs->extras);
2516  }
2517  /* record this item */
2518  item = addrs->refs + addrs->numrefs;
2519  item->classId = classId;
2520  item->objectId = objectId;
2521  item->objectSubId = subId;
2522  addrs->numrefs++;
2523 }

References Assert, ObjectAddress::classId, ObjectAddresses::extras, ObjectAddresses::maxrefs, ObjectAddresses::numrefs, ObjectAddress::objectId, ObjectAddress::objectSubId, ObjectAddresses::refs, and repalloc().

Referenced by find_expr_references_walker(), and process_function_rte_ref().

◆ DeleteInitPrivs()

static void DeleteInitPrivs ( const ObjectAddress object)
static

Definition at line 2783 of file dependency.c.

2784 {
2785  Relation relation;
2786  ScanKeyData key[3];
2787  SysScanDesc scan;
2788  HeapTuple oldtuple;
2789 
2790  relation = table_open(InitPrivsRelationId, RowExclusiveLock);
2791 
2792  ScanKeyInit(&key[0],
2793  Anum_pg_init_privs_objoid,
2794  BTEqualStrategyNumber, F_OIDEQ,
2795  ObjectIdGetDatum(object->objectId));
2796  ScanKeyInit(&key[1],
2797  Anum_pg_init_privs_classoid,
2798  BTEqualStrategyNumber, F_OIDEQ,
2799  ObjectIdGetDatum(object->classId));
2800  ScanKeyInit(&key[2],
2801  Anum_pg_init_privs_objsubid,
2802  BTEqualStrategyNumber, F_INT4EQ,
2803  Int32GetDatum(object->objectSubId));
2804 
2805  scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
2806  NULL, 3, key);
2807 
2808  while (HeapTupleIsValid(oldtuple = systable_getnext(scan)))
2809  CatalogTupleDelete(relation, &oldtuple->t_self);
2810 
2811  systable_endscan(scan);
2812 
2813  table_close(relation, RowExclusiveLock);
2814 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:596
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:503
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:384
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
#define RowExclusiveLock
Definition: lockdefs.h:38
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
ItemPointerData t_self
Definition: htup.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References BTEqualStrategyNumber, CatalogTupleDelete(), ObjectAddress::classId, HeapTupleIsValid, Int32GetDatum(), sort-test::key, ObjectAddressStack::object, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by deleteOneObject().

◆ deleteObjectsInList()

static void deleteObjectsInList ( ObjectAddresses targetObjects,
Relation depRel,
int  flags 
)
static

Definition at line 185 of file dependency.c.

187 {
188  int i;
189 
190  /*
191  * Keep track of objects for event triggers, if necessary.
192  */
194  {
195  for (i = 0; i < targetObjects->numrefs; i++)
196  {
197  const ObjectAddress *thisobj = &targetObjects->refs[i];
198  const ObjectAddressExtra *extra = &targetObjects->extras[i];
199  bool original = false;
200  bool normal = false;
201 
202  if (extra->flags & DEPFLAG_ORIGINAL)
203  original = true;
204  if (extra->flags & DEPFLAG_NORMAL)
205  normal = true;
206  if (extra->flags & DEPFLAG_REVERSE)
207  normal = true;
208 
209  if (EventTriggerSupportsObject(thisobj))
210  {
211  EventTriggerSQLDropAddObject(thisobj, original, normal);
212  }
213  }
214  }
215 
216  /*
217  * Delete all the objects in the proper order, except that if told to, we
218  * should skip the original object(s).
219  */
220  for (i = 0; i < targetObjects->numrefs; i++)
221  {
222  ObjectAddress *thisobj = targetObjects->refs + i;
223  ObjectAddressExtra *thisextra = targetObjects->extras + i;
224 
225  if ((flags & PERFORM_DELETION_SKIP_ORIGINAL) &&
226  (thisextra->flags & DEPFLAG_ORIGINAL))
227  continue;
228 
229  deleteOneObject(thisobj, depRel, flags);
230  }
231 }
static void deleteOneObject(const ObjectAddress *object, Relation *depRel, int32 flags)
#define DEPFLAG_ORIGINAL
Definition: dependency.c:101
#define DEPFLAG_REVERSE
Definition: dependency.c:107
#define DEPFLAG_NORMAL
Definition: dependency.c:102
#define PERFORM_DELETION_SKIP_ORIGINAL
Definition: dependency.h:95
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:92
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
bool trackDroppedObjectsNeeded(void)
bool EventTriggerSupportsObject(const ObjectAddress *object)
int i
Definition: isn.c:73

References deleteOneObject(), DEPFLAG_NORMAL, DEPFLAG_ORIGINAL, DEPFLAG_REVERSE, EventTriggerSQLDropAddObject(), EventTriggerSupportsObject(), ObjectAddresses::extras, ObjectAddressExtra::flags, ObjectAddressStack::flags, i, ObjectAddresses::numrefs, PERFORM_DELETION_INTERNAL, PERFORM_DELETION_SKIP_ORIGINAL, ObjectAddresses::refs, and trackDroppedObjectsNeeded().

Referenced by performDeletion(), and performMultipleDeletions().

◆ deleteOneObject() [1/2]

static void deleteOneObject ( const ObjectAddress object,
Relation depRel,
int  flags 
)
static

Definition at line 1246 of file dependency.c.

1247 {
1248  ScanKeyData key[3];
1249  int nkeys;
1250  SysScanDesc scan;
1251  HeapTuple tup;
1252 
1253  /* DROP hook of the objects being removed */
1254  InvokeObjectDropHookArg(object->classId, object->objectId,
1255  object->objectSubId, flags);
1256 
1257  /*
1258  * Close depRel if we are doing a drop concurrently. The object deletion
1259  * subroutine will commit the current transaction, so we can't keep the
1260  * relation open across doDeletion().
1261  */
1262  if (flags & PERFORM_DELETION_CONCURRENTLY)
1263  table_close(*depRel, RowExclusiveLock);
1264 
1265  /*
1266  * Delete the object itself, in an object-type-dependent way.
1267  *
1268  * We used to do this after removing the outgoing dependency links, but it
1269  * seems just as reasonable to do it beforehand. In the concurrent case
1270  * we *must* do it in this order, because we can't make any transactional
1271  * updates before calling doDeletion() --- they'd get committed right
1272  * away, which is not cool if the deletion then fails.
1273  */
1274  doDeletion(object, flags);
1275 
1276  /*
1277  * Reopen depRel if we closed it above
1278  */
1279  if (flags & PERFORM_DELETION_CONCURRENTLY)
1280  *depRel = table_open(DependRelationId, RowExclusiveLock);
1281 
1282  /*
1283  * Now remove any pg_depend records that link from this object to others.
1284  * (Any records linking to this object should be gone already.)
1285  *
1286  * When dropping a whole object (subId = 0), remove all pg_depend records
1287  * for its sub-objects too.
1288  */
1289  ScanKeyInit(&key[0],
1290  Anum_pg_depend_classid,
1291  BTEqualStrategyNumber, F_OIDEQ,
1292  ObjectIdGetDatum(object->classId));
1293  ScanKeyInit(&key[1],
1294  Anum_pg_depend_objid,
1295  BTEqualStrategyNumber, F_OIDEQ,
1296  ObjectIdGetDatum(object->objectId));
1297  if (object->objectSubId != 0)
1298  {
1299  ScanKeyInit(&key[2],
1300  Anum_pg_depend_objsubid,
1301  BTEqualStrategyNumber, F_INT4EQ,
1302  Int32GetDatum(object->objectSubId));
1303  nkeys = 3;
1304  }
1305  else
1306  nkeys = 2;
1307 
1308  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
1309  NULL, nkeys, key);
1310 
1311  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1312  {
1313  CatalogTupleDelete(*depRel, &tup->t_self);
1314  }
1315 
1316  systable_endscan(scan);
1317 
1318  /*
1319  * Delete shared dependency references related to this object. Again, if
1320  * subId = 0, remove records for sub-objects too.
1321  */
1323  object->objectSubId);
1324 
1325 
1326  /*
1327  * Delete any comments, security labels, or initial privileges associated
1328  * with this object. (This is a convenient place to do these things,
1329  * rather than having every object type know to do it.)
1330  */
1331  DeleteComments(object->objectId, object->classId, object->objectSubId);
1332  DeleteSecurityLabel(object);
1333  DeleteInitPrivs(object);
1334 
1335  /*
1336  * CommandCounterIncrement here to ensure that preceding changes are all
1337  * visible to the next deletion step.
1338  */
1340 
1341  /*
1342  * And we're done!
1343  */
1344 }
void DeleteComments(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:326
static void doDeletion(const ObjectAddress *object, int flags)
Definition: dependency.c:1350
static void DeleteInitPrivs(const ObjectAddress *object)
Definition: dependency.c:2783
#define InvokeObjectDropHookArg(classId, objectId, subId, dropflags)
Definition: objectaccess.h:184
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1039
void DeleteSecurityLabel(const ObjectAddress *object)
Definition: seclabel.c:523
void CommandCounterIncrement(void)
Definition: xact.c:1097

References BTEqualStrategyNumber, CatalogTupleDelete(), ObjectAddress::classId, CommandCounterIncrement(), DeleteComments(), DeleteInitPrivs(), DeleteSecurityLabel(), deleteSharedDependencyRecordsFor(), doDeletion(), ObjectAddressStack::flags, HeapTupleIsValid, Int32GetDatum(), InvokeObjectDropHookArg, sort-test::key, ObjectAddressStack::object, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, PERFORM_DELETION_CONCURRENTLY, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

◆ deleteOneObject() [2/2]

static void deleteOneObject ( const ObjectAddress object,
Relation depRel,
int32  flags 
)
static

Referenced by deleteObjectsInList().

◆ doDeletion()

static void doDeletion ( const ObjectAddress object,
int  flags 
)
static

Definition at line 1350 of file dependency.c.

1351 {
1352  switch (object->classId)
1353  {
1354  case RelationRelationId:
1355  {
1356  char relKind = get_rel_relkind(object->objectId);
1357 
1358  if (relKind == RELKIND_INDEX ||
1359  relKind == RELKIND_PARTITIONED_INDEX)
1360  {
1361  bool concurrent = ((flags & PERFORM_DELETION_CONCURRENTLY) != 0);
1362  bool concurrent_lock_mode = ((flags & PERFORM_DELETION_CONCURRENT_LOCK) != 0);
1363 
1364  Assert(object->objectSubId == 0);
1365  index_drop(object->objectId, concurrent, concurrent_lock_mode);
1366  }
1367  else
1368  {
1369  if (object->objectSubId != 0)
1370  RemoveAttributeById(object->objectId,
1371  object->objectSubId);
1372  else
1374  }
1375 
1376  /*
1377  * for a sequence, in addition to dropping the heap, also
1378  * delete pg_sequence tuple
1379  */
1380  if (relKind == RELKIND_SEQUENCE)
1381  DeleteSequenceTuple(object->objectId);
1382  break;
1383  }
1384 
1385  case ProcedureRelationId:
1386  RemoveFunctionById(object->objectId);
1387  break;
1388 
1389  case TypeRelationId:
1390  RemoveTypeById(object->objectId);
1391  break;
1392 
1393  case ConstraintRelationId:
1394  RemoveConstraintById(object->objectId);
1395  break;
1396 
1397  case AttrDefaultRelationId:
1399  break;
1400 
1401  case LargeObjectRelationId:
1402  LargeObjectDrop(object->objectId);
1403  break;
1404 
1405  case OperatorRelationId:
1406  RemoveOperatorById(object->objectId);
1407  break;
1408 
1409  case RewriteRelationId:
1411  break;
1412 
1413  case TriggerRelationId:
1414  RemoveTriggerById(object->objectId);
1415  break;
1416 
1417  case StatisticExtRelationId:
1418  RemoveStatisticsById(object->objectId);
1419  break;
1420 
1421  case TSConfigRelationId:
1423  break;
1424 
1425  case ExtensionRelationId:
1426  RemoveExtensionById(object->objectId);
1427  break;
1428 
1429  case PolicyRelationId:
1430  RemovePolicyById(object->objectId);
1431  break;
1432 
1433  case PublicationNamespaceRelationId:
1435  break;
1436 
1437  case PublicationRelRelationId:
1439  break;
1440 
1441  case PublicationRelationId:
1443  break;
1444 
1445  case CastRelationId:
1446  case CollationRelationId:
1447  case ConversionRelationId:
1448  case LanguageRelationId:
1449  case OperatorClassRelationId:
1450  case OperatorFamilyRelationId:
1451  case AccessMethodRelationId:
1452  case AccessMethodOperatorRelationId:
1453  case AccessMethodProcedureRelationId:
1454  case NamespaceRelationId:
1455  case TSParserRelationId:
1456  case TSDictionaryRelationId:
1457  case TSTemplateRelationId:
1458  case ForeignDataWrapperRelationId:
1459  case ForeignServerRelationId:
1460  case UserMappingRelationId:
1461  case DefaultAclRelationId:
1462  case EventTriggerRelationId:
1463  case TransformRelationId:
1464  case AuthMemRelationId:
1465  DropObjectById(object);
1466  break;
1467 
1468  /*
1469  * These global object types are not supported here.
1470  */
1471  case AuthIdRelationId:
1472  case DatabaseRelationId:
1473  case TableSpaceRelationId:
1474  case SubscriptionRelationId:
1475  case ParameterAclRelationId:
1476  elog(ERROR, "global objects cannot be deleted by doDeletion");
1477  break;
1478 
1479  default:
1480  elog(ERROR, "unsupported object class: %u", object->classId);
1481  }
1482 }
void DeleteSequenceTuple(Oid relid)
Definition: sequence.c:563
static void DropObjectById(const ObjectAddress *object)
Definition: dependency.c:1189
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:97
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
void RemoveExtensionById(Oid extId)
Definition: extension.c:1954
void RemoveFunctionById(Oid funcOid)
void RemoveAttributeById(Oid relid, AttrNumber attnum)
Definition: heap.c:1656
void heap_drop_with_catalog(Oid relid)
Definition: heap.c:1757
void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
Definition: index.c:2113
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2003
void RemoveOperatorById(Oid operOid)
Definition: operatorcmds.c:413
void RemoveAttrDefaultById(Oid attrdefId)
Definition: pg_attrdef.c:268
void RemoveConstraintById(Oid conId)
void LargeObjectDrop(Oid loid)
void RemovePolicyById(Oid policy_id)
Definition: policy.c:332
void RemovePublicationSchemaById(Oid psoid)
void RemovePublicationById(Oid pubid)
void RemovePublicationRelById(Oid proid)
void RemoveRewriteRuleById(Oid ruleOid)
Definition: rewriteRemove.c:33
void RemoveStatisticsById(Oid statsOid)
Definition: statscmds.c:747
void RemoveTriggerById(Oid trigOid)
Definition: trigger.c:1286
void RemoveTSConfigurationById(Oid cfgId)
Definition: tsearchcmds.c:1108
void RemoveTypeById(Oid typeOid)
Definition: typecmds.c:657

References Assert, ObjectAddress::classId, DeleteSequenceTuple(), DropObjectById(), elog, ERROR, ObjectAddressStack::flags, get_rel_relkind(), heap_drop_with_catalog(), index_drop(), LargeObjectDrop(), ObjectAddressStack::object, ObjectAddress::objectId, ObjectAddress::objectSubId, PERFORM_DELETION_CONCURRENT_LOCK, PERFORM_DELETION_CONCURRENTLY, RemoveAttrDefaultById(), RemoveAttributeById(), RemoveConstraintById(), RemoveExtensionById(), RemoveFunctionById(), RemoveOperatorById(), RemovePolicyById(), RemovePublicationById(), RemovePublicationRelById(), RemovePublicationSchemaById(), RemoveRewriteRuleById(), RemoveStatisticsById(), RemoveTriggerById(), RemoveTSConfigurationById(), and RemoveTypeById().

Referenced by deleteOneObject().

◆ DropObjectById()

static void DropObjectById ( const ObjectAddress object)
static

Definition at line 1189 of file dependency.c.

1190 {
1191  int cacheId;
1192  Relation rel;
1193  HeapTuple tup;
1194 
1195  cacheId = get_object_catcache_oid(object->classId);
1196 
1197  rel = table_open(object->classId, RowExclusiveLock);
1198 
1199  /*
1200  * Use the system cache for the oid column, if one exists.
1201  */
1202  if (cacheId >= 0)
1203  {
1204  tup = SearchSysCache1(cacheId, ObjectIdGetDatum(object->objectId));
1205  if (!HeapTupleIsValid(tup))
1206  elog(ERROR, "cache lookup failed for %s %u",
1207  get_object_class_descr(object->classId), object->objectId);
1208 
1209  CatalogTupleDelete(rel, &tup->t_self);
1210 
1211  ReleaseSysCache(tup);
1212  }
1213  else
1214  {
1215  ScanKeyData skey[1];
1216  SysScanDesc scan;
1217 
1218  ScanKeyInit(&skey[0],
1219  get_object_attnum_oid(object->classId),
1220  BTEqualStrategyNumber, F_OIDEQ,
1221  ObjectIdGetDatum(object->objectId));
1222 
1223  scan = systable_beginscan(rel, get_object_oid_index(object->classId), true,
1224  NULL, 1, skey);
1225 
1226  /* we expect exactly one match */
1227  tup = systable_getnext(scan);
1228  if (!HeapTupleIsValid(tup))
1229  elog(ERROR, "could not find tuple for %s %u",
1230  get_object_class_descr(object->classId), object->objectId);
1231 
1232  CatalogTupleDelete(rel, &tup->t_self);
1233 
1234  systable_endscan(scan);
1235  }
1236 
1238 }
AttrNumber get_object_attnum_oid(Oid class_id)
int get_object_catcache_oid(Oid class_id)
Oid get_object_oid_index(Oid class_id)
const char * get_object_class_descr(Oid class_id)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218

References BTEqualStrategyNumber, CatalogTupleDelete(), ObjectAddress::classId, elog, ERROR, get_object_attnum_oid(), get_object_catcache_oid(), get_object_class_descr(), get_object_oid_index(), HeapTupleIsValid, ObjectAddressStack::object, ObjectAddress::objectId, ObjectIdGetDatum(), ReleaseSysCache(), RowExclusiveLock, ScanKeyInit(), SearchSysCache1(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by doDeletion().

◆ eliminate_duplicate_dependencies()

static void eliminate_duplicate_dependencies ( ObjectAddresses addrs)
static

Definition at line 2381 of file dependency.c.

2382 {
2383  ObjectAddress *priorobj;
2384  int oldref,
2385  newrefs;
2386 
2387  /*
2388  * We can't sort if the array has "extra" data, because there's no way to
2389  * keep it in sync. Fortunately that combination of features is not
2390  * needed.
2391  */
2392  Assert(!addrs->extras);
2393 
2394  if (addrs->numrefs <= 1)
2395  return; /* nothing to do */
2396 
2397  /* Sort the refs so that duplicates are adjacent */
2398  qsort(addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
2400 
2401  /* Remove dups */
2402  priorobj = addrs->refs;
2403  newrefs = 1;
2404  for (oldref = 1; oldref < addrs->numrefs; oldref++)
2405  {
2406  ObjectAddress *thisobj = addrs->refs + oldref;
2407 
2408  if (priorobj->classId == thisobj->classId &&
2409  priorobj->objectId == thisobj->objectId)
2410  {
2411  if (priorobj->objectSubId == thisobj->objectSubId)
2412  continue; /* identical, so drop thisobj */
2413 
2414  /*
2415  * If we have a whole-object reference and a reference to a part
2416  * of the same object, we don't need the whole-object reference
2417  * (for example, we don't need to reference both table foo and
2418  * column foo.bar). The whole-object reference will always appear
2419  * first in the sorted list.
2420  */
2421  if (priorobj->objectSubId == 0)
2422  {
2423  /* replace whole ref with partial */
2424  priorobj->objectSubId = thisobj->objectSubId;
2425  continue;
2426  }
2427  }
2428  /* Not identical, so add thisobj to output set */
2429  priorobj++;
2430  *priorobj = *thisobj;
2431  newrefs++;
2432  }
2433 
2434  addrs->numrefs = newrefs;
2435 }
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2441
#define qsort(a, b, c, d)
Definition: port.h:449

References Assert, ObjectAddress::classId, ObjectAddresses::extras, ObjectAddresses::numrefs, object_address_comparator(), ObjectAddress::objectId, ObjectAddress::objectSubId, qsort, and ObjectAddresses::refs.

Referenced by record_object_address_dependencies(), recordDependencyOnExpr(), and recordDependencyOnSingleRelExpr().

◆ find_expr_references_walker()

static bool find_expr_references_walker ( Node node,
find_expr_references_context context 
)
static

Definition at line 1696 of file dependency.c.

1698 {
1699  if (node == NULL)
1700  return false;
1701  if (IsA(node, Var))
1702  {
1703  Var *var = (Var *) node;
1704  List *rtable;
1705  RangeTblEntry *rte;
1706 
1707  /* Find matching rtable entry, or complain if not found */
1708  if (var->varlevelsup >= list_length(context->rtables))
1709  elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
1710  rtable = (List *) list_nth(context->rtables, var->varlevelsup);
1711  if (var->varno <= 0 || var->varno > list_length(rtable))
1712  elog(ERROR, "invalid varno %d", var->varno);
1713  rte = rt_fetch(var->varno, rtable);
1714 
1715  /*
1716  * A whole-row Var references no specific columns, so adds no new
1717  * dependency. (We assume that there is a whole-table dependency
1718  * arising from each underlying rangetable entry. While we could
1719  * record such a dependency when finding a whole-row Var that
1720  * references a relation directly, it's quite unclear how to extend
1721  * that to whole-row Vars for JOINs, so it seems better to leave the
1722  * responsibility with the range table. Note that this poses some
1723  * risks for identifying dependencies of stand-alone expressions:
1724  * whole-table references may need to be created separately.)
1725  */
1726  if (var->varattno == InvalidAttrNumber)
1727  return false;
1728  if (rte->rtekind == RTE_RELATION)
1729  {
1730  /* If it's a plain relation, reference this column */
1731  add_object_address(RelationRelationId, rte->relid, var->varattno,
1732  context->addrs);
1733  }
1734  else if (rte->rtekind == RTE_FUNCTION)
1735  {
1736  /* Might need to add a dependency on a composite type's column */
1737  /* (done out of line, because it's a bit bulky) */
1739  }
1740 
1741  /*
1742  * Vars referencing other RTE types require no additional work. In
1743  * particular, a join alias Var can be ignored, because it must
1744  * reference a merged USING column. The relevant join input columns
1745  * will also be referenced in the join qual, and any type coercion
1746  * functions involved in the alias expression will be dealt with when
1747  * we scan the RTE itself.
1748  */
1749  return false;
1750  }
1751  else if (IsA(node, Const))
1752  {
1753  Const *con = (Const *) node;
1754  Oid objoid;
1755 
1756  /* A constant must depend on the constant's datatype */
1757  add_object_address(TypeRelationId, con->consttype, 0,
1758  context->addrs);
1759 
1760  /*
1761  * We must also depend on the constant's collation: it could be
1762  * different from the datatype's, if a CollateExpr was const-folded to
1763  * a simple constant. However we can save work in the most common
1764  * case where the collation is "default", since we know that's pinned.
1765  */
1766  if (OidIsValid(con->constcollid) &&
1767  con->constcollid != DEFAULT_COLLATION_OID)
1768  add_object_address(CollationRelationId, con->constcollid, 0,
1769  context->addrs);
1770 
1771  /*
1772  * If it's a regclass or similar literal referring to an existing
1773  * object, add a reference to that object. (Currently, only the
1774  * regclass and regconfig cases have any likely use, but we may as
1775  * well handle all the OID-alias datatypes consistently.)
1776  */
1777  if (!con->constisnull)
1778  {
1779  switch (con->consttype)
1780  {
1781  case REGPROCOID:
1782  case REGPROCEDUREOID:
1783  objoid = DatumGetObjectId(con->constvalue);
1784  if (SearchSysCacheExists1(PROCOID,
1785  ObjectIdGetDatum(objoid)))
1786  add_object_address(ProcedureRelationId, objoid, 0,
1787  context->addrs);
1788  break;
1789  case REGOPEROID:
1790  case REGOPERATOROID:
1791  objoid = DatumGetObjectId(con->constvalue);
1792  if (SearchSysCacheExists1(OPEROID,
1793  ObjectIdGetDatum(objoid)))
1794  add_object_address(OperatorRelationId, objoid, 0,
1795  context->addrs);
1796  break;
1797  case REGCLASSOID:
1798  objoid = DatumGetObjectId(con->constvalue);
1799  if (SearchSysCacheExists1(RELOID,
1800  ObjectIdGetDatum(objoid)))
1801  add_object_address(RelationRelationId, objoid, 0,
1802  context->addrs);
1803  break;
1804  case REGTYPEOID:
1805  objoid = DatumGetObjectId(con->constvalue);
1806  if (SearchSysCacheExists1(TYPEOID,
1807  ObjectIdGetDatum(objoid)))
1808  add_object_address(TypeRelationId, objoid, 0,
1809  context->addrs);
1810  break;
1811  case REGCOLLATIONOID:
1812  objoid = DatumGetObjectId(con->constvalue);
1813  if (SearchSysCacheExists1(COLLOID,
1814  ObjectIdGetDatum(objoid)))
1815  add_object_address(CollationRelationId, objoid, 0,
1816  context->addrs);
1817  break;
1818  case REGCONFIGOID:
1819  objoid = DatumGetObjectId(con->constvalue);
1820  if (SearchSysCacheExists1(TSCONFIGOID,
1821  ObjectIdGetDatum(objoid)))
1822  add_object_address(TSConfigRelationId, objoid, 0,
1823  context->addrs);
1824  break;
1825  case REGDICTIONARYOID:
1826  objoid = DatumGetObjectId(con->constvalue);
1827  if (SearchSysCacheExists1(TSDICTOID,
1828  ObjectIdGetDatum(objoid)))
1829  add_object_address(TSDictionaryRelationId, objoid, 0,
1830  context->addrs);
1831  break;
1832 
1833  case REGNAMESPACEOID:
1834  objoid = DatumGetObjectId(con->constvalue);
1835  if (SearchSysCacheExists1(NAMESPACEOID,
1836  ObjectIdGetDatum(objoid)))
1837  add_object_address(NamespaceRelationId, objoid, 0,
1838  context->addrs);
1839  break;
1840 
1841  /*
1842  * Dependencies for regrole should be shared among all
1843  * databases, so explicitly inhibit to have dependencies.
1844  */
1845  case REGROLEOID:
1846  ereport(ERROR,
1847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1848  errmsg("constant of the type %s cannot be used here",
1849  "regrole")));
1850  break;
1851  }
1852  }
1853  return false;
1854  }
1855  else if (IsA(node, Param))
1856  {
1857  Param *param = (Param *) node;
1858 
1859  /* A parameter must depend on the parameter's datatype */
1860  add_object_address(TypeRelationId, param->paramtype, 0,
1861  context->addrs);
1862  /* and its collation, just as for Consts */
1863  if (OidIsValid(param->paramcollid) &&
1864  param->paramcollid != DEFAULT_COLLATION_OID)
1865  add_object_address(CollationRelationId, param->paramcollid, 0,
1866  context->addrs);
1867  }
1868  else if (IsA(node, FuncExpr))
1869  {
1870  FuncExpr *funcexpr = (FuncExpr *) node;
1871 
1872  add_object_address(ProcedureRelationId, funcexpr->funcid, 0,
1873  context->addrs);
1874  /* fall through to examine arguments */
1875  }
1876  else if (IsA(node, OpExpr))
1877  {
1878  OpExpr *opexpr = (OpExpr *) node;
1879 
1880  add_object_address(OperatorRelationId, opexpr->opno, 0,
1881  context->addrs);
1882  /* fall through to examine arguments */
1883  }
1884  else if (IsA(node, DistinctExpr))
1885  {
1886  DistinctExpr *distinctexpr = (DistinctExpr *) node;
1887 
1888  add_object_address(OperatorRelationId, distinctexpr->opno, 0,
1889  context->addrs);
1890  /* fall through to examine arguments */
1891  }
1892  else if (IsA(node, NullIfExpr))
1893  {
1894  NullIfExpr *nullifexpr = (NullIfExpr *) node;
1895 
1896  add_object_address(OperatorRelationId, nullifexpr->opno, 0,
1897  context->addrs);
1898  /* fall through to examine arguments */
1899  }
1900  else if (IsA(node, ScalarArrayOpExpr))
1901  {
1902  ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
1903 
1904  add_object_address(OperatorRelationId, opexpr->opno, 0,
1905  context->addrs);
1906  /* fall through to examine arguments */
1907  }
1908  else if (IsA(node, Aggref))
1909  {
1910  Aggref *aggref = (Aggref *) node;
1911 
1912  add_object_address(ProcedureRelationId, aggref->aggfnoid, 0,
1913  context->addrs);
1914  /* fall through to examine arguments */
1915  }
1916  else if (IsA(node, WindowFunc))
1917  {
1918  WindowFunc *wfunc = (WindowFunc *) node;
1919 
1920  add_object_address(ProcedureRelationId, wfunc->winfnoid, 0,
1921  context->addrs);
1922  /* fall through to examine arguments */
1923  }
1924  else if (IsA(node, SubscriptingRef))
1925  {
1926  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1927 
1928  /*
1929  * The refexpr should provide adequate dependency on refcontainertype,
1930  * and that type in turn depends on refelemtype. However, a custom
1931  * subscripting handler might set refrestype to something different
1932  * from either of those, in which case we'd better record it.
1933  */
1934  if (sbsref->refrestype != sbsref->refcontainertype &&
1935  sbsref->refrestype != sbsref->refelemtype)
1936  add_object_address(TypeRelationId, sbsref->refrestype, 0,
1937  context->addrs);
1938  /* fall through to examine arguments */
1939  }
1940  else if (IsA(node, SubPlan))
1941  {
1942  /* Extra work needed here if we ever need this case */
1943  elog(ERROR, "already-planned subqueries not supported");
1944  }
1945  else if (IsA(node, FieldSelect))
1946  {
1947  FieldSelect *fselect = (FieldSelect *) node;
1948  Oid argtype = getBaseType(exprType((Node *) fselect->arg));
1949  Oid reltype = get_typ_typrelid(argtype);
1950 
1951  /*
1952  * We need a dependency on the specific column named in FieldSelect,
1953  * assuming we can identify the pg_class OID for it. (Probably we
1954  * always can at the moment, but in future it might be possible for
1955  * argtype to be RECORDOID.) If we can make a column dependency then
1956  * we shouldn't need a dependency on the column's type; but if we
1957  * can't, make a dependency on the type, as it might not appear
1958  * anywhere else in the expression.
1959  */
1960  if (OidIsValid(reltype))
1961  add_object_address(RelationRelationId, reltype, fselect->fieldnum,
1962  context->addrs);
1963  else
1964  add_object_address(TypeRelationId, fselect->resulttype, 0,
1965  context->addrs);
1966  /* the collation might not be referenced anywhere else, either */
1967  if (OidIsValid(fselect->resultcollid) &&
1968  fselect->resultcollid != DEFAULT_COLLATION_OID)
1969  add_object_address(CollationRelationId, fselect->resultcollid, 0,
1970  context->addrs);
1971  }
1972  else if (IsA(node, FieldStore))
1973  {
1974  FieldStore *fstore = (FieldStore *) node;
1975  Oid reltype = get_typ_typrelid(fstore->resulttype);
1976 
1977  /* similar considerations to FieldSelect, but multiple column(s) */
1978  if (OidIsValid(reltype))
1979  {
1980  ListCell *l;
1981 
1982  foreach(l, fstore->fieldnums)
1983  add_object_address(RelationRelationId, reltype, lfirst_int(l),
1984  context->addrs);
1985  }
1986  else
1987  add_object_address(TypeRelationId, fstore->resulttype, 0,
1988  context->addrs);
1989  }
1990  else if (IsA(node, RelabelType))
1991  {
1992  RelabelType *relab = (RelabelType *) node;
1993 
1994  /* since there is no function dependency, need to depend on type */
1995  add_object_address(TypeRelationId, relab->resulttype, 0,
1996  context->addrs);
1997  /* the collation might not be referenced anywhere else, either */
1998  if (OidIsValid(relab->resultcollid) &&
1999  relab->resultcollid != DEFAULT_COLLATION_OID)
2000  add_object_address(CollationRelationId, relab->resultcollid, 0,
2001  context->addrs);
2002  }
2003  else if (IsA(node, CoerceViaIO))
2004  {
2005  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2006 
2007  /* since there is no exposed function, need to depend on type */
2008  add_object_address(TypeRelationId, iocoerce->resulttype, 0,
2009  context->addrs);
2010  /* the collation might not be referenced anywhere else, either */
2011  if (OidIsValid(iocoerce->resultcollid) &&
2012  iocoerce->resultcollid != DEFAULT_COLLATION_OID)
2013  add_object_address(CollationRelationId, iocoerce->resultcollid, 0,
2014  context->addrs);
2015  }
2016  else if (IsA(node, ArrayCoerceExpr))
2017  {
2018  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2019 
2020  /* as above, depend on type */
2021  add_object_address(TypeRelationId, acoerce->resulttype, 0,
2022  context->addrs);
2023  /* the collation might not be referenced anywhere else, either */
2024  if (OidIsValid(acoerce->resultcollid) &&
2025  acoerce->resultcollid != DEFAULT_COLLATION_OID)
2026  add_object_address(CollationRelationId, acoerce->resultcollid, 0,
2027  context->addrs);
2028  /* fall through to examine arguments */
2029  }
2030  else if (IsA(node, ConvertRowtypeExpr))
2031  {
2032  ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
2033 
2034  /* since there is no function dependency, need to depend on type */
2035  add_object_address(TypeRelationId, cvt->resulttype, 0,
2036  context->addrs);
2037  }
2038  else if (IsA(node, CollateExpr))
2039  {
2040  CollateExpr *coll = (CollateExpr *) node;
2041 
2042  add_object_address(CollationRelationId, coll->collOid, 0,
2043  context->addrs);
2044  }
2045  else if (IsA(node, RowExpr))
2046  {
2047  RowExpr *rowexpr = (RowExpr *) node;
2048 
2049  add_object_address(TypeRelationId, rowexpr->row_typeid, 0,
2050  context->addrs);
2051  }
2052  else if (IsA(node, RowCompareExpr))
2053  {
2054  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2055  ListCell *l;
2056 
2057  foreach(l, rcexpr->opnos)
2058  {
2059  add_object_address(OperatorRelationId, lfirst_oid(l), 0,
2060  context->addrs);
2061  }
2062  foreach(l, rcexpr->opfamilies)
2063  {
2064  add_object_address(OperatorFamilyRelationId, lfirst_oid(l), 0,
2065  context->addrs);
2066  }
2067  /* fall through to examine arguments */
2068  }
2069  else if (IsA(node, CoerceToDomain))
2070  {
2071  CoerceToDomain *cd = (CoerceToDomain *) node;
2072 
2073  add_object_address(TypeRelationId, cd->resulttype, 0,
2074  context->addrs);
2075  }
2076  else if (IsA(node, NextValueExpr))
2077  {
2078  NextValueExpr *nve = (NextValueExpr *) node;
2079 
2080  add_object_address(RelationRelationId, nve->seqid, 0,
2081  context->addrs);
2082  }
2083  else if (IsA(node, OnConflictExpr))
2084  {
2085  OnConflictExpr *onconflict = (OnConflictExpr *) node;
2086 
2087  if (OidIsValid(onconflict->constraint))
2088  add_object_address(ConstraintRelationId, onconflict->constraint, 0,
2089  context->addrs);
2090  /* fall through to examine arguments */
2091  }
2092  else if (IsA(node, SortGroupClause))
2093  {
2094  SortGroupClause *sgc = (SortGroupClause *) node;
2095 
2096  add_object_address(OperatorRelationId, sgc->eqop, 0,
2097  context->addrs);
2098  if (OidIsValid(sgc->sortop))
2099  add_object_address(OperatorRelationId, sgc->sortop, 0,
2100  context->addrs);
2101  return false;
2102  }
2103  else if (IsA(node, WindowClause))
2104  {
2105  WindowClause *wc = (WindowClause *) node;
2106 
2107  if (OidIsValid(wc->startInRangeFunc))
2108  add_object_address(ProcedureRelationId, wc->startInRangeFunc, 0,
2109  context->addrs);
2110  if (OidIsValid(wc->endInRangeFunc))
2111  add_object_address(ProcedureRelationId, wc->endInRangeFunc, 0,
2112  context->addrs);
2113  if (OidIsValid(wc->inRangeColl) &&
2114  wc->inRangeColl != DEFAULT_COLLATION_OID)
2115  add_object_address(CollationRelationId, wc->inRangeColl, 0,
2116  context->addrs);
2117  /* fall through to examine substructure */
2118  }
2119  else if (IsA(node, CTECycleClause))
2120  {
2121  CTECycleClause *cc = (CTECycleClause *) node;
2122 
2123  if (OidIsValid(cc->cycle_mark_type))
2124  add_object_address(TypeRelationId, cc->cycle_mark_type, 0,
2125  context->addrs);
2127  add_object_address(CollationRelationId, cc->cycle_mark_collation, 0,
2128  context->addrs);
2129  if (OidIsValid(cc->cycle_mark_neop))
2130  add_object_address(OperatorRelationId, cc->cycle_mark_neop, 0,
2131  context->addrs);
2132  /* fall through to examine substructure */
2133  }
2134  else if (IsA(node, Query))
2135  {
2136  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2137  Query *query = (Query *) node;
2138  ListCell *lc;
2139  bool result;
2140 
2141  /*
2142  * Add whole-relation refs for each plain relation mentioned in the
2143  * subquery's rtable, and ensure we add refs for any type-coercion
2144  * functions used in join alias lists.
2145  *
2146  * Note: query_tree_walker takes care of recursing into RTE_FUNCTION
2147  * RTEs, subqueries, etc, so no need to do that here. But we must
2148  * tell it not to visit join alias lists, or we'll add refs for join
2149  * input columns whether or not they are actually used in our query.
2150  *
2151  * Note: we don't need to worry about collations mentioned in
2152  * RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
2153  * collations referenced in other parts of the Query. We do have to
2154  * worry about collations mentioned in RTE_FUNCTION, but we take care
2155  * of those when we recurse to the RangeTblFunction node(s).
2156  */
2157  foreach(lc, query->rtable)
2158  {
2159  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2160 
2161  switch (rte->rtekind)
2162  {
2163  case RTE_RELATION:
2164  add_object_address(RelationRelationId, rte->relid, 0,
2165  context->addrs);
2166  break;
2167  case RTE_JOIN:
2168 
2169  /*
2170  * Examine joinaliasvars entries only for merged JOIN
2171  * USING columns. Only those entries could contain
2172  * type-coercion functions. Also, their join input
2173  * columns must be referenced in the join quals, so this
2174  * won't accidentally add refs to otherwise-unused join
2175  * input columns. (We want to ref the type coercion
2176  * functions even if the merged column isn't explicitly
2177  * used anywhere, to protect possible expansion of the
2178  * join RTE as a whole-row var, and because it seems like
2179  * a bad idea to allow dropping a function that's present
2180  * in our query tree, whether or not it could get called.)
2181  */
2182  context->rtables = lcons(query->rtable, context->rtables);
2183  for (int i = 0; i < rte->joinmergedcols; i++)
2184  {
2185  Node *aliasvar = list_nth(rte->joinaliasvars, i);
2186 
2187  if (!IsA(aliasvar, Var))
2189  }
2190  context->rtables = list_delete_first(context->rtables);
2191  break;
2192  default:
2193  break;
2194  }
2195  }
2196 
2197  /*
2198  * If the query is an INSERT or UPDATE, we should create a dependency
2199  * on each target column, to prevent the specific target column from
2200  * being dropped. Although we will visit the TargetEntry nodes again
2201  * during query_tree_walker, we won't have enough context to do this
2202  * conveniently, so do it here.
2203  */
2204  if (query->commandType == CMD_INSERT ||
2205  query->commandType == CMD_UPDATE)
2206  {
2207  RangeTblEntry *rte;
2208 
2209  if (query->resultRelation <= 0 ||
2210  query->resultRelation > list_length(query->rtable))
2211  elog(ERROR, "invalid resultRelation %d",
2212  query->resultRelation);
2213  rte = rt_fetch(query->resultRelation, query->rtable);
2214  if (rte->rtekind == RTE_RELATION)
2215  {
2216  foreach(lc, query->targetList)
2217  {
2218  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2219 
2220  if (tle->resjunk)
2221  continue; /* ignore junk tlist items */
2222  add_object_address(RelationRelationId, rte->relid, tle->resno,
2223  context->addrs);
2224  }
2225  }
2226  }
2227 
2228  /*
2229  * Add dependencies on constraints listed in query's constraintDeps
2230  */
2231  foreach(lc, query->constraintDeps)
2232  {
2233  add_object_address(ConstraintRelationId, lfirst_oid(lc), 0,
2234  context->addrs);
2235  }
2236 
2237  /* Examine substructure of query */
2238  context->rtables = lcons(query->rtable, context->rtables);
2239  result = query_tree_walker(query,
2241  (void *) context,
2244  context->rtables = list_delete_first(context->rtables);
2245  return result;
2246  }
2247  else if (IsA(node, SetOperationStmt))
2248  {
2249  SetOperationStmt *setop = (SetOperationStmt *) node;
2250 
2251  /* we need to look at the groupClauses for operator references */
2252  find_expr_references_walker((Node *) setop->groupClauses, context);
2253  /* fall through to examine child nodes */
2254  }
2255  else if (IsA(node, RangeTblFunction))
2256  {
2257  RangeTblFunction *rtfunc = (RangeTblFunction *) node;
2258  ListCell *ct;
2259 
2260  /*
2261  * Add refs for any datatypes and collations used in a column
2262  * definition list for a RECORD function. (For other cases, it should
2263  * be enough to depend on the function itself.)
2264  */
2265  foreach(ct, rtfunc->funccoltypes)
2266  {
2267  add_object_address(TypeRelationId, lfirst_oid(ct), 0,
2268  context->addrs);
2269  }
2270  foreach(ct, rtfunc->funccolcollations)
2271  {
2272  Oid collid = lfirst_oid(ct);
2273 
2274  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2275  add_object_address(CollationRelationId, collid, 0,
2276  context->addrs);
2277  }
2278  }
2279  else if (IsA(node, TableFunc))
2280  {
2281  TableFunc *tf = (TableFunc *) node;
2282  ListCell *ct;
2283 
2284  /*
2285  * Add refs for the datatypes and collations used in the TableFunc.
2286  */
2287  foreach(ct, tf->coltypes)
2288  {
2289  add_object_address(TypeRelationId, lfirst_oid(ct), 0,
2290  context->addrs);
2291  }
2292  foreach(ct, tf->colcollations)
2293  {
2294  Oid collid = lfirst_oid(ct);
2295 
2296  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2297  add_object_address(CollationRelationId, collid, 0,
2298  context->addrs);
2299  }
2300  }
2301  else if (IsA(node, TableSampleClause))
2302  {
2303  TableSampleClause *tsc = (TableSampleClause *) node;
2304 
2305  add_object_address(ProcedureRelationId, tsc->tsmhandler, 0,
2306  context->addrs);
2307  /* fall through to examine arguments */
2308  }
2309 
2311  (void *) context);
2312 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define OidIsValid(objectId)
Definition: c.h:775
Oid collid
static void add_object_address(Oid classId, Oid objectId, int32 subId, ObjectAddresses *addrs)
Definition: dependency.c:2504
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1696
static void process_function_rte_ref(RangeTblEntry *rte, AttrNumber attnum, find_expr_references_context *context)
Definition: dependency.c:2319
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
List * list_delete_first(List *list)
Definition: list.c:943
List * lcons(void *datum, List *list)
Definition: list.c:495
Oid get_typ_typrelid(Oid typid)
Definition: lsyscache.c:2731
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2521
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
#define QTW_EXAMINE_SORTGROUP
Definition: nodeFuncs.h:30
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:25
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_UPDATE
Definition: nodes.h:266
@ RTE_JOIN
Definition: parsenodes.h:1030
@ RTE_FUNCTION
Definition: parsenodes.h:1031
@ RTE_RELATION
Definition: parsenodes.h:1028
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define lfirst_int(lc)
Definition: pg_list.h:173
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define lfirst_oid(lc)
Definition: pg_list.h:174
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
unsigned int Oid
Definition: postgres_ext.h:31
tree context
Definition: radixtree.h:1833
Oid aggfnoid
Definition: primnodes.h:444
Oid cycle_mark_collation
Definition: parsenodes.h:1667
Oid resulttype
Definition: primnodes.h:1208
Oid consttype
Definition: primnodes.h:312
AttrNumber fieldnum
Definition: primnodes.h:1129
Expr * arg
Definition: primnodes.h:1128
Oid funcid
Definition: primnodes.h:750
Definition: pg_list.h:54
Definition: nodes.h:129
Oid opno
Definition: primnodes.h:818
Oid paramtype
Definition: primnodes.h:378
List * rtable
Definition: parsenodes.h:168
CmdType commandType
Definition: parsenodes.h:121
List * targetList
Definition: parsenodes.h:191
RTEKind rtekind
Definition: parsenodes.h:1057
Oid resulttype
Definition: primnodes.h:1185
AttrNumber resno
Definition: primnodes.h:2194
Definition: primnodes.h:248
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255
Index varlevelsup
Definition: primnodes.h:280
Oid winfnoid
Definition: primnodes.h:567
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:95

References add_object_address(), Aggref::aggfnoid, FieldSelect::arg, CMD_INSERT, CMD_UPDATE, collid, CollateExpr::collOid, Query::commandType, OnConflictExpr::constraint, Const::consttype, context, CTECycleClause::cycle_mark_collation, CTECycleClause::cycle_mark_neop, CTECycleClause::cycle_mark_type, DatumGetObjectId(), elog, SortGroupClause::eqop, ereport, errcode(), errmsg(), ERROR, expression_tree_walker, exprType(), FieldSelect::fieldnum, FuncExpr::funcid, get_typ_typrelid(), getBaseType(), i, InvalidAttrNumber, IsA, lcons(), lfirst, lfirst_int, lfirst_oid, list_delete_first(), list_length(), list_nth(), ObjectIdGetDatum(), OidIsValid, OpExpr::opno, ScalarArrayOpExpr::opno, Param::paramtype, process_function_rte_ref(), QTW_EXAMINE_SORTGROUP, QTW_IGNORE_JOINALIASES, query_tree_walker, RangeTblEntry::relid, TargetEntry::resno, RelabelType::resulttype, CoerceViaIO::resulttype, ArrayCoerceExpr::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, rt_fetch, Query::rtable, RTE_FUNCTION, RTE_JOIN, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCacheExists1, NextValueExpr::seqid, SortGroupClause::sortop, Query::targetList, TableSampleClause::tsmhandler, Var::varattno, Var::varlevelsup, Var::varno, and WindowFunc::winfnoid.

Referenced by recordDependencyOnExpr(), and recordDependencyOnSingleRelExpr().

◆ findDependentObjects()

static void findDependentObjects ( const ObjectAddress object,
int  objflags,
int  flags,
ObjectAddressStack stack,
ObjectAddresses targetObjects,
const ObjectAddresses pendingObjects,
Relation depRel 
)
static

Definition at line 432 of file dependency.c.

439 {
440  ScanKeyData key[3];
441  int nkeys;
442  SysScanDesc scan;
443  HeapTuple tup;
444  ObjectAddress otherObject;
445  ObjectAddress owningObject;
446  ObjectAddress partitionObject;
447  ObjectAddressAndFlags *dependentObjects;
448  int numDependentObjects;
449  int maxDependentObjects;
450  ObjectAddressStack mystack;
451  ObjectAddressExtra extra;
452 
453  /*
454  * If the target object is already being visited in an outer recursion
455  * level, just report the current objflags back to that level and exit.
456  * This is needed to avoid infinite recursion in the face of circular
457  * dependencies.
458  *
459  * The stack check alone would result in dependency loops being broken at
460  * an arbitrary point, ie, the first member object of the loop to be
461  * visited is the last one to be deleted. This is obviously unworkable.
462  * However, the check for internal dependency below guarantees that we
463  * will not break a loop at an internal dependency: if we enter the loop
464  * at an "owned" object we will switch and start at the "owning" object
465  * instead. We could probably hack something up to avoid breaking at an
466  * auto dependency, too, if we had to. However there are no known cases
467  * where that would be necessary.
468  */
469  if (stack_address_present_add_flags(object, objflags, stack))
470  return;
471 
472  /*
473  * since this function recurses, it could be driven to stack overflow,
474  * because of the deep dependency tree, not only due to dependency loops.
475  */
477 
478  /*
479  * It's also possible that the target object has already been completely
480  * processed and put into targetObjects. If so, again we just add the
481  * specified objflags to its entry and return.
482  *
483  * (Note: in these early-exit cases we could release the caller-taken
484  * lock, since the object is presumably now locked multiple times; but it
485  * seems not worth the cycles.)
486  */
487  if (object_address_present_add_flags(object, objflags, targetObjects))
488  return;
489 
490  /*
491  * If the target object is pinned, we can just error out immediately; it
492  * won't have any objects recorded as depending on it.
493  */
494  if (IsPinnedObject(object->classId, object->objectId))
495  ereport(ERROR,
496  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
497  errmsg("cannot drop %s because it is required by the database system",
498  getObjectDescription(object, false))));
499 
500  /*
501  * The target object might be internally dependent on some other object
502  * (its "owner"), and/or be a member of an extension (also considered its
503  * owner). If so, and if we aren't recursing from the owning object, we
504  * have to transform this deletion request into a deletion request of the
505  * owning object. (We'll eventually recurse back to this object, but the
506  * owning object has to be visited first so it will be deleted after.) The
507  * way to find out about this is to scan the pg_depend entries that show
508  * what this object depends on.
509  */
510  ScanKeyInit(&key[0],
511  Anum_pg_depend_classid,
512  BTEqualStrategyNumber, F_OIDEQ,
513  ObjectIdGetDatum(object->classId));
514  ScanKeyInit(&key[1],
515  Anum_pg_depend_objid,
516  BTEqualStrategyNumber, F_OIDEQ,
517  ObjectIdGetDatum(object->objectId));
518  if (object->objectSubId != 0)
519  {
520  /* Consider only dependencies of this sub-object */
521  ScanKeyInit(&key[2],
522  Anum_pg_depend_objsubid,
523  BTEqualStrategyNumber, F_INT4EQ,
524  Int32GetDatum(object->objectSubId));
525  nkeys = 3;
526  }
527  else
528  {
529  /* Consider dependencies of this object and any sub-objects it has */
530  nkeys = 2;
531  }
532 
533  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
534  NULL, nkeys, key);
535 
536  /* initialize variables that loop may fill */
537  memset(&owningObject, 0, sizeof(owningObject));
538  memset(&partitionObject, 0, sizeof(partitionObject));
539 
540  while (HeapTupleIsValid(tup = systable_getnext(scan)))
541  {
542  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
543 
544  otherObject.classId = foundDep->refclassid;
545  otherObject.objectId = foundDep->refobjid;
546  otherObject.objectSubId = foundDep->refobjsubid;
547 
548  /*
549  * When scanning dependencies of a whole object, we may find rows
550  * linking sub-objects of the object to the object itself. (Normally,
551  * such a dependency is implicit, but we must make explicit ones in
552  * some cases involving partitioning.) We must ignore such rows to
553  * avoid infinite recursion.
554  */
555  if (otherObject.classId == object->classId &&
556  otherObject.objectId == object->objectId &&
557  object->objectSubId == 0)
558  continue;
559 
560  switch (foundDep->deptype)
561  {
562  case DEPENDENCY_NORMAL:
563  case DEPENDENCY_AUTO:
565  /* no problem */
566  break;
567 
569 
570  /*
571  * If told to, ignore EXTENSION dependencies altogether. This
572  * flag is normally used to prevent dropping extensions during
573  * temporary-object cleanup, even if a temp object was created
574  * during an extension script.
575  */
577  break;
578 
579  /*
580  * If the other object is the extension currently being
581  * created/altered, ignore this dependency and continue with
582  * the deletion. This allows dropping of an extension's
583  * objects within the extension's scripts, as well as corner
584  * cases such as dropping a transient object created within
585  * such a script.
586  */
587  if (creating_extension &&
588  otherObject.classId == ExtensionRelationId &&
589  otherObject.objectId == CurrentExtensionObject)
590  break;
591 
592  /* Otherwise, treat this like an internal dependency */
593  /* FALL THRU */
594 
595  case DEPENDENCY_INTERNAL:
596 
597  /*
598  * This object is part of the internal implementation of
599  * another object, or is part of the extension that is the
600  * other object. We have three cases:
601  *
602  * 1. At the outermost recursion level, we must disallow the
603  * DROP. However, if the owning object is listed in
604  * pendingObjects, just release the caller's lock and return;
605  * we'll eventually complete the DROP when we reach that entry
606  * in the pending list.
607  *
608  * Note: the above statement is true only if this pg_depend
609  * entry still exists by then; in principle, therefore, we
610  * could miss deleting an item the user told us to delete.
611  * However, no inconsistency can result: since we're at outer
612  * level, there is no object depending on this one.
613  */
614  if (stack == NULL)
615  {
616  if (pendingObjects &&
617  object_address_present(&otherObject, pendingObjects))
618  {
619  systable_endscan(scan);
620  /* need to release caller's lock; see notes below */
621  ReleaseDeletionLock(object);
622  return;
623  }
624 
625  /*
626  * We postpone actually issuing the error message until
627  * after this loop, so that we can make the behavior
628  * independent of the ordering of pg_depend entries, at
629  * least if there's not more than one INTERNAL and one
630  * EXTENSION dependency. (If there's more, we'll complain
631  * about a random one of them.) Prefer to complain about
632  * EXTENSION, since that's generally a more important
633  * dependency.
634  */
635  if (!OidIsValid(owningObject.classId) ||
636  foundDep->deptype == DEPENDENCY_EXTENSION)
637  owningObject = otherObject;
638  break;
639  }
640 
641  /*
642  * 2. When recursing from the other end of this dependency,
643  * it's okay to continue with the deletion. This holds when
644  * recursing from a whole object that includes the nominal
645  * other end as a component, too. Since there can be more
646  * than one "owning" object, we have to allow matches that are
647  * more than one level down in the stack.
648  */
649  if (stack_address_present_add_flags(&otherObject, 0, stack))
650  break;
651 
652  /*
653  * 3. Not all the owning objects have been visited, so
654  * transform this deletion request into a delete of this
655  * owning object.
656  *
657  * First, release caller's lock on this object and get
658  * deletion lock on the owning object. (We must release
659  * caller's lock to avoid deadlock against a concurrent
660  * deletion of the owning object.)
661  */
662  ReleaseDeletionLock(object);
663  AcquireDeletionLock(&otherObject, 0);
664 
665  /*
666  * The owning object might have been deleted while we waited
667  * to lock it; if so, neither it nor the current object are
668  * interesting anymore. We test this by checking the
669  * pg_depend entry (see notes below).
670  */
671  if (!systable_recheck_tuple(scan, tup))
672  {
673  systable_endscan(scan);
674  ReleaseDeletionLock(&otherObject);
675  return;
676  }
677 
678  /*
679  * One way or the other, we're done with the scan; might as
680  * well close it down before recursing, to reduce peak
681  * resource consumption.
682  */
683  systable_endscan(scan);
684 
685  /*
686  * Okay, recurse to the owning object instead of proceeding.
687  *
688  * We do not need to stack the current object; we want the
689  * traversal order to be as if the original reference had
690  * linked to the owning object instead of this one.
691  *
692  * The dependency type is a "reverse" dependency: we need to
693  * delete the owning object if this one is to be deleted, but
694  * this linkage is never a reason for an automatic deletion.
695  */
696  findDependentObjects(&otherObject,
698  flags,
699  stack,
700  targetObjects,
701  pendingObjects,
702  depRel);
703 
704  /*
705  * The current target object should have been added to
706  * targetObjects while processing the owning object; but it
707  * probably got only the flag bits associated with the
708  * dependency we're looking at. We need to add the objflags
709  * that were passed to this recursion level, too, else we may
710  * get a bogus failure in reportDependentObjects (if, for
711  * example, we were called due to a partition dependency).
712  *
713  * If somehow the current object didn't get scheduled for
714  * deletion, bleat. (That would imply that somebody deleted
715  * this dependency record before the recursion got to it.)
716  * Another idea would be to reacquire lock on the current
717  * object and resume trying to delete it, but it seems not
718  * worth dealing with the race conditions inherent in that.
719  */
720  if (!object_address_present_add_flags(object, objflags,
721  targetObjects))
722  elog(ERROR, "deletion of owning object %s failed to delete %s",
723  getObjectDescription(&otherObject, false),
724  getObjectDescription(object, false));
725 
726  /* And we're done here. */
727  return;
728 
730 
731  /*
732  * Remember that this object has a partition-type dependency.
733  * After the dependency scan, we'll complain if we didn't find
734  * a reason to delete one of its partition dependencies.
735  */
736  objflags |= DEPFLAG_IS_PART;
737 
738  /*
739  * Also remember the primary partition owner, for error
740  * messages. If there are multiple primary owners (which
741  * there should not be), we'll report a random one of them.
742  */
743  partitionObject = otherObject;
744  break;
745 
747 
748  /*
749  * Only use secondary partition owners in error messages if we
750  * find no primary owner (which probably shouldn't happen).
751  */
752  if (!(objflags & DEPFLAG_IS_PART))
753  partitionObject = otherObject;
754 
755  /*
756  * Remember that this object has a partition-type dependency.
757  * After the dependency scan, we'll complain if we didn't find
758  * a reason to delete one of its partition dependencies.
759  */
760  objflags |= DEPFLAG_IS_PART;
761  break;
762 
763  default:
764  elog(ERROR, "unrecognized dependency type '%c' for %s",
765  foundDep->deptype, getObjectDescription(object, false));
766  break;
767  }
768  }
769 
770  systable_endscan(scan);
771 
772  /*
773  * If we found an INTERNAL or EXTENSION dependency when we're at outer
774  * level, complain about it now. If we also found a PARTITION dependency,
775  * we prefer to report the PARTITION dependency. This is arbitrary but
776  * seems to be more useful in practice.
777  */
778  if (OidIsValid(owningObject.classId))
779  {
780  char *otherObjDesc;
781 
782  if (OidIsValid(partitionObject.classId))
783  otherObjDesc = getObjectDescription(&partitionObject, false);
784  else
785  otherObjDesc = getObjectDescription(&owningObject, false);
786 
787  ereport(ERROR,
788  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
789  errmsg("cannot drop %s because %s requires it",
790  getObjectDescription(object, false), otherObjDesc),
791  errhint("You can drop %s instead.", otherObjDesc)));
792  }
793 
794  /*
795  * Next, identify all objects that directly depend on the current object.
796  * To ensure predictable deletion order, we collect them up in
797  * dependentObjects and sort the list before actually recursing. (The
798  * deletion order would be valid in any case, but doing this ensures
799  * consistent output from DROP CASCADE commands, which is helpful for
800  * regression testing.)
801  */
802  maxDependentObjects = 128; /* arbitrary initial allocation */
803  dependentObjects = (ObjectAddressAndFlags *)
804  palloc(maxDependentObjects * sizeof(ObjectAddressAndFlags));
805  numDependentObjects = 0;
806 
807  ScanKeyInit(&key[0],
808  Anum_pg_depend_refclassid,
809  BTEqualStrategyNumber, F_OIDEQ,
810  ObjectIdGetDatum(object->classId));
811  ScanKeyInit(&key[1],
812  Anum_pg_depend_refobjid,
813  BTEqualStrategyNumber, F_OIDEQ,
814  ObjectIdGetDatum(object->objectId));
815  if (object->objectSubId != 0)
816  {
817  ScanKeyInit(&key[2],
818  Anum_pg_depend_refobjsubid,
819  BTEqualStrategyNumber, F_INT4EQ,
820  Int32GetDatum(object->objectSubId));
821  nkeys = 3;
822  }
823  else
824  nkeys = 2;
825 
826  scan = systable_beginscan(*depRel, DependReferenceIndexId, true,
827  NULL, nkeys, key);
828 
829  while (HeapTupleIsValid(tup = systable_getnext(scan)))
830  {
831  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
832  int subflags;
833 
834  otherObject.classId = foundDep->classid;
835  otherObject.objectId = foundDep->objid;
836  otherObject.objectSubId = foundDep->objsubid;
837 
838  /*
839  * If what we found is a sub-object of the current object, just ignore
840  * it. (Normally, such a dependency is implicit, but we must make
841  * explicit ones in some cases involving partitioning.)
842  */
843  if (otherObject.classId == object->classId &&
844  otherObject.objectId == object->objectId &&
845  object->objectSubId == 0)
846  continue;
847 
848  /*
849  * Must lock the dependent object before recursing to it.
850  */
851  AcquireDeletionLock(&otherObject, 0);
852 
853  /*
854  * The dependent object might have been deleted while we waited to
855  * lock it; if so, we don't need to do anything more with it. We can
856  * test this cheaply and independently of the object's type by seeing
857  * if the pg_depend tuple we are looking at is still live. (If the
858  * object got deleted, the tuple would have been deleted too.)
859  */
860  if (!systable_recheck_tuple(scan, tup))
861  {
862  /* release the now-useless lock */
863  ReleaseDeletionLock(&otherObject);
864  /* and continue scanning for dependencies */
865  continue;
866  }
867 
868  /*
869  * We do need to delete it, so identify objflags to be passed down,
870  * which depend on the dependency type.
871  */
872  switch (foundDep->deptype)
873  {
874  case DEPENDENCY_NORMAL:
875  subflags = DEPFLAG_NORMAL;
876  break;
877  case DEPENDENCY_AUTO:
879  subflags = DEPFLAG_AUTO;
880  break;
881  case DEPENDENCY_INTERNAL:
882  subflags = DEPFLAG_INTERNAL;
883  break;
886  subflags = DEPFLAG_PARTITION;
887  break;
889  subflags = DEPFLAG_EXTENSION;
890  break;
891  default:
892  elog(ERROR, "unrecognized dependency type '%c' for %s",
893  foundDep->deptype, getObjectDescription(object, false));
894  subflags = 0; /* keep compiler quiet */
895  break;
896  }
897 
898  /* And add it to the pending-objects list */
899  if (numDependentObjects >= maxDependentObjects)
900  {
901  /* enlarge array if needed */
902  maxDependentObjects *= 2;
903  dependentObjects = (ObjectAddressAndFlags *)
904  repalloc(dependentObjects,
905  maxDependentObjects * sizeof(ObjectAddressAndFlags));
906  }
907 
908  dependentObjects[numDependentObjects].obj = otherObject;
909  dependentObjects[numDependentObjects].subflags = subflags;
910  numDependentObjects++;
911  }
912 
913  systable_endscan(scan);
914 
915  /*
916  * Now we can sort the dependent objects into a stable visitation order.
917  * It's safe to use object_address_comparator here since the obj field is
918  * first within ObjectAddressAndFlags.
919  */
920  if (numDependentObjects > 1)
921  qsort(dependentObjects, numDependentObjects,
922  sizeof(ObjectAddressAndFlags),
924 
925  /*
926  * Now recurse to the dependent objects. We must visit them first since
927  * they have to be deleted before the current object.
928  */
929  mystack.object = object; /* set up a new stack level */
930  mystack.flags = objflags;
931  mystack.next = stack;
932 
933  for (int i = 0; i < numDependentObjects; i++)
934  {
935  ObjectAddressAndFlags *depObj = dependentObjects + i;
936 
937  findDependentObjects(&depObj->obj,
938  depObj->subflags,
939  flags,
940  &mystack,
941  targetObjects,
942  pendingObjects,
943  depRel);
944  }
945 
946  pfree(dependentObjects);
947 
948  /*
949  * Finally, we can add the target object to targetObjects. Be careful to
950  * include any flags that were passed back down to us from inner recursion
951  * levels. Record the "dependee" as being either the most important
952  * partition owner if there is one, else the object we recursed from, if
953  * any. (The logic in reportDependentObjects() is such that it can only
954  * need one of those objects.)
955  */
956  extra.flags = mystack.flags;
957  if (extra.flags & DEPFLAG_IS_PART)
958  extra.dependee = partitionObject;
959  else if (stack)
960  extra.dependee = *stack->object;
961  else
962  memset(&extra.dependee, 0, sizeof(extra.dependee));
963  add_exact_object_address_extra(object, &extra, targetObjects);
964 }
bool IsPinnedObject(Oid classId, Oid objectId)
Definition: catalog.c:313
static bool object_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddresses *addrs)
Definition: dependency.c:2617
#define DEPFLAG_PARTITION
Definition: dependency.c:105
static void add_exact_object_address_extra(const ObjectAddress *object, const ObjectAddressExtra *extra, ObjectAddresses *addrs)
Definition: dependency.c:2556
static bool stack_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddressStack *stack)
Definition: dependency.c:2690
#define DEPFLAG_IS_PART
Definition: dependency.c:108
void AcquireDeletionLock(const ObjectAddress *object, int flags)
Definition: dependency.c:1494
void ReleaseDeletionLock(const ObjectAddress *object)
Definition: dependency.c:1526
#define DEPFLAG_AUTO
Definition: dependency.c:103
static void findDependentObjects(const ObjectAddress *object, int objflags, int flags, ObjectAddressStack *stack, ObjectAddresses *targetObjects, const ObjectAddresses *pendingObjects, Relation *depRel)
Definition: dependency.c:432
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2591
#define DEPFLAG_EXTENSION
Definition: dependency.c:106
#define DEPFLAG_INTERNAL
Definition: dependency.c:104
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:96
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_AUTO_EXTENSION
Definition: dependency.h:39
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
@ DEPENDENCY_PARTITION_PRI
Definition: dependency.h:36
@ DEPENDENCY_PARTITION_SEC
Definition: dependency.h:37
@ DEPENDENCY_EXTENSION
Definition: dependency.h:38
@ DEPENDENCY_NORMAL
Definition: dependency.h:33
int errhint(const char *fmt,...)
Definition: elog.c:1317
bool creating_extension
Definition: extension.c:71
Oid CurrentExtensionObject
Definition: extension.c:72
bool systable_recheck_tuple(SysScanDesc sysscan, HeapTuple tup)
Definition: genam.c:562
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void pfree(void *pointer)
Definition: mcxt.c:1520
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
void check_stack_depth(void)
Definition: postgres.c:3531
ObjectAddress obj
Definition: dependency.c:134
ObjectAddress dependee
Definition: dependency.c:97
const ObjectAddress * object
Definition: dependency.c:126
struct ObjectAddressStack * next
Definition: dependency.c:128

References AcquireDeletionLock(), add_exact_object_address_extra(), BTEqualStrategyNumber, check_stack_depth(), ObjectAddress::classId, creating_extension, CurrentExtensionObject, ObjectAddressExtra::dependee, DEPENDENCY_AUTO, DEPENDENCY_AUTO_EXTENSION, DEPENDENCY_EXTENSION, DEPENDENCY_INTERNAL, DEPENDENCY_NORMAL, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, DEPFLAG_AUTO, DEPFLAG_EXTENSION, DEPFLAG_INTERNAL, DEPFLAG_IS_PART, DEPFLAG_NORMAL, DEPFLAG_PARTITION, DEPFLAG_REVERSE, elog, ereport, errcode(), errhint(), errmsg(), ERROR, ObjectAddressExtra::flags, ObjectAddressStack::flags, getObjectDescription(), GETSTRUCT, HeapTupleIsValid, i, Int32GetDatum(), IsPinnedObject(), sort-test::key, ObjectAddressStack::next, ObjectAddressAndFlags::obj, ObjectAddressStack::object, object_address_comparator(), object_address_present(), object_address_present_add_flags(), ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, OidIsValid, palloc(), PERFORM_DELETION_SKIP_EXTENSIONS, pfree(), qsort, ReleaseDeletionLock(), repalloc(), ScanKeyInit(), stack_address_present_add_flags(), ObjectAddressAndFlags::subflags, systable_beginscan(), systable_endscan(), systable_getnext(), and systable_recheck_tuple().

Referenced by performDeletion(), and performMultipleDeletions().

◆ free_object_addresses()

◆ new_object_addresses()

◆ object_address_comparator()

static int object_address_comparator ( const void *  a,
const void *  b 
)
static

Definition at line 2441 of file dependency.c.

2442 {
2443  const ObjectAddress *obja = (const ObjectAddress *) a;
2444  const ObjectAddress *objb = (const ObjectAddress *) b;
2445 
2446  /*
2447  * Primary sort key is OID descending. Most of the time, this will result
2448  * in putting newer objects before older ones, which is likely to be the
2449  * right order to delete in.
2450  */
2451  if (obja->objectId > objb->objectId)
2452  return -1;
2453  if (obja->objectId < objb->objectId)
2454  return 1;
2455 
2456  /*
2457  * Next sort on catalog ID, in case identical OIDs appear in different
2458  * catalogs. Sort direction is pretty arbitrary here.
2459  */
2460  if (obja->classId < objb->classId)
2461  return -1;
2462  if (obja->classId > objb->classId)
2463  return 1;
2464 
2465  /*
2466  * Last, sort on object subId.
2467  *
2468  * We sort the subId as an unsigned int so that 0 (the whole object) will
2469  * come first. This is essential for eliminate_duplicate_dependencies,
2470  * and is also the best order for findDependentObjects.
2471  */
2472  if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
2473  return -1;
2474  if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
2475  return 1;
2476  return 0;
2477 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69

References a, b, ObjectAddress::classId, ObjectAddress::objectId, and ObjectAddress::objectSubId.

Referenced by eliminate_duplicate_dependencies(), findDependentObjects(), and sort_object_addresses().

◆ object_address_present()

bool object_address_present ( const ObjectAddress object,
const ObjectAddresses addrs 
)

Definition at line 2591 of file dependency.c.

2593 {
2594  int i;
2595 
2596  for (i = addrs->numrefs - 1; i >= 0; i--)
2597  {
2598  const ObjectAddress *thisobj = addrs->refs + i;
2599 
2600  if (object->classId == thisobj->classId &&
2601  object->objectId == thisobj->objectId)
2602  {
2603  if (object->objectSubId == thisobj->objectSubId ||
2604  thisobj->objectSubId == 0)
2605  return true;
2606  }
2607  }
2608 
2609  return false;
2610 }

References ObjectAddress::classId, i, ObjectAddresses::numrefs, ObjectAddressStack::object, ObjectAddress::objectId, ObjectAddress::objectSubId, and ObjectAddresses::refs.

Referenced by AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterTypeNamespaceInternal(), findDependentObjects(), and PreCommit_on_commit_actions().

◆ object_address_present_add_flags()

static bool object_address_present_add_flags ( const ObjectAddress object,
int  flags,
ObjectAddresses addrs 
)
static

Definition at line 2617 of file dependency.c.

2620 {
2621  bool result = false;
2622  int i;
2623 
2624  for (i = addrs->numrefs - 1; i >= 0; i--)
2625  {
2626  ObjectAddress *thisobj = addrs->refs + i;
2627 
2628  if (object->classId == thisobj->classId &&
2629  object->objectId == thisobj->objectId)
2630  {
2631  if (object->objectSubId == thisobj->objectSubId)
2632  {
2633  ObjectAddressExtra *thisextra = addrs->extras + i;
2634 
2635  thisextra->flags |= flags;
2636  result = true;
2637  }
2638  else if (thisobj->objectSubId == 0)
2639  {
2640  /*
2641  * We get here if we find a need to delete a column after
2642  * having already decided to drop its whole table. Obviously
2643  * we no longer need to drop the subobject, so report that we
2644  * found the subobject in the array. But don't plaster its
2645  * flags on the whole object.
2646  */
2647  result = true;
2648  }
2649  else if (object->objectSubId == 0)
2650  {
2651  /*
2652  * We get here if we find a need to delete a whole table after
2653  * having already decided to drop one of its columns. We
2654  * can't report that the whole object is in the array, but we
2655  * should mark the subobject with the whole object's flags.
2656  *
2657  * It might seem attractive to physically delete the column's
2658  * array entry, or at least mark it as no longer needing
2659  * separate deletion. But that could lead to, e.g., dropping
2660  * the column's datatype before we drop the table, which does
2661  * not seem like a good idea. This is a very rare situation
2662  * in practice, so we just take the hit of doing a separate
2663  * DROP COLUMN action even though we know we're gonna delete
2664  * the table later.
2665  *
2666  * What we can do, though, is mark this as a subobject so that
2667  * we don't report it separately, which is confusing because
2668  * it's unpredictable whether it happens or not. But do so
2669  * only if flags != 0 (flags == 0 is a read-only probe).
2670  *
2671  * Because there could be other subobjects of this object in
2672  * the array, this case means we always have to loop through
2673  * the whole array; we cannot exit early on a match.
2674  */
2675  ObjectAddressExtra *thisextra = addrs->extras + i;
2676 
2677  if (flags)
2678  thisextra->flags |= (flags | DEPFLAG_SUBOBJECT);
2679  }
2680  }
2681  }
2682 
2683  return result;
2684 }
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:109

References ObjectAddress::classId, DEPFLAG_SUBOBJECT, ObjectAddresses::extras, ObjectAddressExtra::flags, ObjectAddressStack::flags, i, ObjectAddresses::numrefs, ObjectAddressStack::object, ObjectAddress::objectId, ObjectAddress::objectSubId, and ObjectAddresses::refs.

Referenced by findDependentObjects().

◆ performDeletion()

void performDeletion ( const ObjectAddress object,
DropBehavior  behavior,
int  flags 
)

Definition at line 273 of file dependency.c.

275 {
276  Relation depRel;
277  ObjectAddresses *targetObjects;
278 
279  /*
280  * We save some cycles by opening pg_depend just once and passing the
281  * Relation pointer down to all the recursive deletion steps.
282  */
283  depRel = table_open(DependRelationId, RowExclusiveLock);
284 
285  /*
286  * Acquire deletion lock on the target object. (Ideally the caller has
287  * done this already, but many places are sloppy about it.)
288  */
289  AcquireDeletionLock(object, 0);
290 
291  /*
292  * Construct a list of objects to delete (ie, the given object plus
293  * everything directly or indirectly dependent on it).
294  */
295  targetObjects = new_object_addresses();
296 
297  findDependentObjects(object,
299  flags,
300  NULL, /* empty stack */
301  targetObjects,
302  NULL, /* no pendingObjects */
303  &depRel);
304 
305  /*
306  * Check if deletion is allowed, and report about cascaded deletes.
307  */
308  reportDependentObjects(targetObjects,
309  behavior,
310  flags,
311  object);
312 
313  /* do the deed */
314  deleteObjectsInList(targetObjects, &depRel, flags);
315 
316  /* And clean up */
317  free_object_addresses(targetObjects);
318 
319  table_close(depRel, RowExclusiveLock);
320 }
static void reportDependentObjects(const ObjectAddresses *targetObjects, DropBehavior behavior, int flags, const ObjectAddress *origObject)
Definition: dependency.c:980
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2485
static void deleteObjectsInList(ObjectAddresses *targetObjects, Relation *depRel, int flags)
Definition: dependency.c:185
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2771

References AcquireDeletionLock(), deleteObjectsInList(), DEPFLAG_ORIGINAL, findDependentObjects(), ObjectAddressStack::flags, free_object_addresses(), new_object_addresses(), reportDependentObjects(), RowExclusiveLock, table_close(), and table_open().

Referenced by AlterDomainDropConstraint(), AlterDomainNotNull(), ATExecDropConstraint(), ATExecDropIdentity(), ATExecMergePartitions(), ATExecSplitPartition(), DetachPartitionFinalize(), do_autovacuum(), dropOperators(), dropProcedures(), finish_heap_swap(), inv_drop(), PublicationDropSchemas(), PublicationDropTables(), RemoveAttrDefault(), RemoveTempRelations(), RemoveUserMapping(), SetDefaultACL(), and tryAttachPartitionForeignKey().

◆ performMultipleDeletions()

void performMultipleDeletions ( const ObjectAddresses objects,
DropBehavior  behavior,
int  flags 
)

Definition at line 332 of file dependency.c.

334 {
335  Relation depRel;
336  ObjectAddresses *targetObjects;
337  int i;
338 
339  /* No work if no objects... */
340  if (objects->numrefs <= 0)
341  return;
342 
343  /*
344  * We save some cycles by opening pg_depend just once and passing the
345  * Relation pointer down to all the recursive deletion steps.
346  */
347  depRel = table_open(DependRelationId, RowExclusiveLock);
348 
349  /*
350  * Construct a list of objects to delete (ie, the given objects plus
351  * everything directly or indirectly dependent on them). Note that
352  * because we pass the whole objects list as pendingObjects context, we
353  * won't get a failure from trying to delete an object that is internally
354  * dependent on another one in the list; we'll just skip that object and
355  * delete it when we reach its owner.
356  */
357  targetObjects = new_object_addresses();
358 
359  for (i = 0; i < objects->numrefs; i++)
360  {
361  const ObjectAddress *thisobj = objects->refs + i;
362 
363  /*
364  * Acquire deletion lock on each target object. (Ideally the caller
365  * has done this already, but many places are sloppy about it.)
366  */
367  AcquireDeletionLock(thisobj, flags);
368 
369  findDependentObjects(thisobj,
371  flags,
372  NULL, /* empty stack */
373  targetObjects,
374  objects,
375  &depRel);
376  }
377 
378  /*
379  * Check if deletion is allowed, and report about cascaded deletes.
380  *
381  * If there's exactly one object being deleted, report it the same way as
382  * in performDeletion(), else we have to be vaguer.
383  */
384  reportDependentObjects(targetObjects,
385  behavior,
386  flags,
387  (objects->numrefs == 1 ? objects->refs : NULL));
388 
389  /* do the deed */
390  deleteObjectsInList(targetObjects, &depRel, flags);
391 
392  /* And clean up */
393  free_object_addresses(targetObjects);
394 
395  table_close(depRel, RowExclusiveLock);
396 }

References AcquireDeletionLock(), deleteObjectsInList(), DEPFLAG_ORIGINAL, findDependentObjects(), ObjectAddressStack::flags, free_object_addresses(), i, new_object_addresses(), ObjectAddresses::numrefs, ObjectAddresses::refs, reportDependentObjects(), RowExclusiveLock, table_close(), and table_open().

Referenced by ATExecDropColumn(), DropClonedTriggersFromPartition(), PreCommit_on_commit_actions(), ReindexRelationConcurrently(), RemoveObjects(), RemoveRelations(), and shdepDropOwned().

◆ process_function_rte_ref()

static void process_function_rte_ref ( RangeTblEntry rte,
AttrNumber  attnum,
find_expr_references_context context 
)
static

Definition at line 2319 of file dependency.c.

2321 {
2322  int atts_done = 0;
2323  ListCell *lc;
2324 
2325  /*
2326  * Identify which RangeTblFunction produces this attnum, and see if it
2327  * returns a composite type. If so, we'd better make a dependency on the
2328  * referenced column of the composite type (or actually, of its associated
2329  * relation).
2330  */
2331  foreach(lc, rte->functions)
2332  {
2333  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2334 
2335  if (attnum > atts_done &&
2336  attnum <= atts_done + rtfunc->funccolcount)
2337  {
2338  TupleDesc tupdesc;
2339 
2340  /* If it has a coldeflist, it certainly returns RECORD */
2341  if (rtfunc->funccolnames != NIL)
2342  tupdesc = NULL; /* no need to work hard */
2343  else
2344  tupdesc = get_expr_result_tupdesc(rtfunc->funcexpr, true);
2345  if (tupdesc && tupdesc->tdtypeid != RECORDOID)
2346  {
2347  /*
2348  * Named composite type, so individual columns could get
2349  * dropped. Make a dependency on this specific column.
2350  */
2351  Oid reltype = get_typ_typrelid(tupdesc->tdtypeid);
2352 
2353  Assert(attnum - atts_done <= tupdesc->natts);
2354  if (OidIsValid(reltype)) /* can this fail? */
2355  add_object_address(RelationRelationId, reltype,
2356  attnum - atts_done,
2357  context->addrs);
2358  return;
2359  }
2360  /* Nothing to do; function's result type is handled elsewhere */
2361  return;
2362  }
2363  atts_done += rtfunc->funccolcount;
2364  }
2365 
2366  /* If we get here, must be looking for the ordinality column */
2367  if (rte->funcordinality && attnum == atts_done + 1)
2368  return;
2369 
2370  /* this probably can't happen ... */
2371  ereport(ERROR,
2372  (errcode(ERRCODE_UNDEFINED_COLUMN),
2373  errmsg("column %d of relation \"%s\" does not exist",
2374  attnum, rte->eref->aliasname)));
2375 }
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:551
int16 attnum
Definition: pg_attribute.h:74
#define NIL
Definition: pg_list.h:68
bool funcordinality
Definition: parsenodes.h:1189
List * functions
Definition: parsenodes.h:1187
Oid tdtypeid
Definition: tupdesc.h:82

References add_object_address(), Assert, attnum, context, ereport, errcode(), errmsg(), ERROR, RangeTblFunction::funcexpr, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_tupdesc(), get_typ_typrelid(), lfirst, NIL, OidIsValid, and TupleDescData::tdtypeid.

Referenced by find_expr_references_walker().

◆ record_object_address_dependencies()

void record_object_address_dependencies ( const ObjectAddress depender,
ObjectAddresses referenced,
DependencyType  behavior 
)

Definition at line 2740 of file dependency.c.

2743 {
2745  recordMultipleDependencies(depender,
2746  referenced->refs, referenced->numrefs,
2747  behavior);
2748 }
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2381
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:58

References eliminate_duplicate_dependencies(), ObjectAddresses::numrefs, recordMultipleDependencies(), and ObjectAddresses::refs.

Referenced by AggregateCreate(), CastCreate(), CreateConstraintEntry(), CreateProceduralLanguage(), CreateTransform(), GenerateTypeDependencies(), heap_create_with_catalog(), index_create(), InsertExtensionTuple(), makeConfigurationDependencies(), makeDictionaryDependencies(), makeOperatorDependencies(), makeParserDependencies(), makeTSTemplateDependencies(), ProcedureCreate(), RangeCreate(), and StorePartitionKey().

◆ recordDependencyOnExpr()

void recordDependencyOnExpr ( const ObjectAddress depender,
Node expr,
List rtable,
DependencyType  behavior 
)

Definition at line 1551 of file dependency.c.

1554 {
1556 
1557  context.addrs = new_object_addresses();
1558 
1559  /* Set up interpretation for Vars at varlevelsup = 0 */
1560  context.rtables = list_make1(rtable);
1561 
1562  /* Scan the expression tree for referenceable objects */
1564 
1565  /* Remove any duplicates */
1567 
1568  /* And record 'em */
1569  recordMultipleDependencies(depender,
1570  context.addrs->refs, context.addrs->numrefs,
1571  behavior);
1572 
1574 }
#define list_make1(x1)
Definition: pg_list.h:212

References context, eliminate_duplicate_dependencies(), find_expr_references_walker(), free_object_addresses(), list_make1, new_object_addresses(), and recordMultipleDependencies().

Referenced by AlterPolicy(), CreatePolicy(), CreateTriggerFiringOn(), GenerateTypeDependencies(), InsertRule(), and ProcedureCreate().

◆ recordDependencyOnSingleRelExpr()

void recordDependencyOnSingleRelExpr ( const ObjectAddress depender,
Node expr,
Oid  relId,
DependencyType  behavior,
DependencyType  self_behavior,
bool  reverse_self 
)

Definition at line 1594 of file dependency.c.

1599 {
1601  RangeTblEntry rte = {0};
1602 
1603  context.addrs = new_object_addresses();
1604 
1605  /* We gin up a rather bogus rangetable list to handle Vars */
1606  rte.type = T_RangeTblEntry;
1607  rte.rtekind = RTE_RELATION;
1608  rte.relid = relId;
1609  rte.relkind = RELKIND_RELATION; /* no need for exactness here */
1610  rte.rellockmode = AccessShareLock;
1611 
1612  context.rtables = list_make1(list_make1(&rte));
1613 
1614  /* Scan the expression tree for referenceable objects */
1616 
1617  /* Remove any duplicates */
1619 
1620  /* Separate self-dependencies if necessary */
1621  if ((behavior != self_behavior || reverse_self) &&
1622  context.addrs->numrefs > 0)
1623  {
1624  ObjectAddresses *self_addrs;
1625  ObjectAddress *outobj;
1626  int oldref,
1627  outrefs;
1628 
1629  self_addrs = new_object_addresses();
1630 
1631  outobj = context.addrs->refs;
1632  outrefs = 0;
1633  for (oldref = 0; oldref < context.addrs->numrefs; oldref++)
1634  {
1635  ObjectAddress *thisobj = context.addrs->refs + oldref;
1636 
1637  if (thisobj->classId == RelationRelationId &&
1638  thisobj->objectId == relId)
1639  {
1640  /* Move this ref into self_addrs */
1641  add_exact_object_address(thisobj, self_addrs);
1642  }
1643  else
1644  {
1645  /* Keep it in context.addrs */
1646  *outobj = *thisobj;
1647  outobj++;
1648  outrefs++;
1649  }
1650  }
1651  context.addrs->numrefs = outrefs;
1652 
1653  /* Record the self-dependencies with the appropriate direction */
1654  if (!reverse_self)
1655  recordMultipleDependencies(depender,
1656  self_addrs->refs, self_addrs->numrefs,
1657  self_behavior);
1658  else
1659  {
1660  /* Can't use recordMultipleDependencies, so do it the hard way */
1661  int selfref;
1662 
1663  for (selfref = 0; selfref < self_addrs->numrefs; selfref++)
1664  {
1665  ObjectAddress *thisobj = self_addrs->refs + selfref;
1666 
1667  recordDependencyOn(thisobj, depender, self_behavior);
1668  }
1669  }
1670 
1671  free_object_addresses(self_addrs);
1672  }
1673 
1674  /* Record the external dependencies */
1675  recordMultipleDependencies(depender,
1676  context.addrs->refs, context.addrs->numrefs,
1677  behavior);
1678 
1680 }
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2531
#define AccessShareLock
Definition: lockdefs.h:36
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46

References AccessShareLock, add_exact_object_address(), ObjectAddress::classId, context, eliminate_duplicate_dependencies(), find_expr_references_walker(), free_object_addresses(), list_make1, new_object_addresses(), ObjectAddresses::numrefs, ObjectAddress::objectId, recordDependencyOn(), recordMultipleDependencies(), ObjectAddresses::refs, RangeTblEntry::relid, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by CreateConstraintEntry(), CreateStatistics(), index_create(), publication_add_relation(), StoreAttrDefault(), and StorePartitionKey().

◆ ReleaseDeletionLock()

void ReleaseDeletionLock ( const ObjectAddress object)

Definition at line 1526 of file dependency.c.

1527 {
1528  if (object->classId == RelationRelationId)
1530  else
1531  /* assume we should lock the whole object not a sub-object */
1532  UnlockDatabaseObject(object->classId, object->objectId, 0,
1534 }
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:227
void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1063

References AccessExclusiveLock, ObjectAddress::classId, ObjectAddressStack::object, ObjectAddress::objectId, UnlockDatabaseObject(), and UnlockRelationOid().

Referenced by findDependentObjects(), and shdepDropOwned().

◆ reportDependentObjects()

static void reportDependentObjects ( const ObjectAddresses targetObjects,
DropBehavior  behavior,
int  flags,
const ObjectAddress origObject 
)
static

Definition at line 980 of file dependency.c.

984 {
985  int msglevel = (flags & PERFORM_DELETION_QUIETLY) ? DEBUG2 : NOTICE;
986  bool ok = true;
987  StringInfoData clientdetail;
988  StringInfoData logdetail;
989  int numReportedClient = 0;
990  int numNotReportedClient = 0;
991  int i;
992 
993  /*
994  * If we need to delete any partition-dependent objects, make sure that
995  * we're deleting at least one of their partition dependencies, too. That
996  * can be detected by checking that we reached them by a PARTITION
997  * dependency at some point.
998  *
999  * We just report the first such object, as in most cases the only way to
1000  * trigger this complaint is to explicitly try to delete one partition of
1001  * a partitioned object.
1002  */
1003  for (i = 0; i < targetObjects->numrefs; i++)
1004  {
1005  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1006 
1007  if ((extra->flags & DEPFLAG_IS_PART) &&
1008  !(extra->flags & DEPFLAG_PARTITION))
1009  {
1010  const ObjectAddress *object = &targetObjects->refs[i];
1011  char *otherObjDesc = getObjectDescription(&extra->dependee,
1012  false);
1013 
1014  ereport(ERROR,
1015  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1016  errmsg("cannot drop %s because %s requires it",
1017  getObjectDescription(object, false), otherObjDesc),
1018  errhint("You can drop %s instead.", otherObjDesc)));
1019  }
1020  }
1021 
1022  /*
1023  * If no error is to be thrown, and the msglevel is too low to be shown to
1024  * either client or server log, there's no need to do any of the rest of
1025  * the work.
1026  */
1027  if (behavior == DROP_CASCADE &&
1028  !message_level_is_interesting(msglevel))
1029  return;
1030 
1031  /*
1032  * We limit the number of dependencies reported to the client to
1033  * MAX_REPORTED_DEPS, since client software may not deal well with
1034  * enormous error strings. The server log always gets a full report.
1035  */
1036 #define MAX_REPORTED_DEPS 100
1037 
1038  initStringInfo(&clientdetail);
1039  initStringInfo(&logdetail);
1040 
1041  /*
1042  * We process the list back to front (ie, in dependency order not deletion
1043  * order), since this makes for a more understandable display.
1044  */
1045  for (i = targetObjects->numrefs - 1; i >= 0; i--)
1046  {
1047  const ObjectAddress *obj = &targetObjects->refs[i];
1048  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1049  char *objDesc;
1050 
1051  /* Ignore the original deletion target(s) */
1052  if (extra->flags & DEPFLAG_ORIGINAL)
1053  continue;
1054 
1055  /* Also ignore sub-objects; we'll report the whole object elsewhere */
1056  if (extra->flags & DEPFLAG_SUBOBJECT)
1057  continue;
1058 
1059  objDesc = getObjectDescription(obj, false);
1060 
1061  /* An object being dropped concurrently doesn't need to be reported */
1062  if (objDesc == NULL)
1063  continue;
1064 
1065  /*
1066  * If, at any stage of the recursive search, we reached the object via
1067  * an AUTO, INTERNAL, PARTITION, or EXTENSION dependency, then it's
1068  * okay to delete it even in RESTRICT mode.
1069  */
1070  if (extra->flags & (DEPFLAG_AUTO |
1074  {
1075  /*
1076  * auto-cascades are reported at DEBUG2, not msglevel. We don't
1077  * try to combine them with the regular message because the
1078  * results are too confusing when client_min_messages and
1079  * log_min_messages are different.
1080  */
1081  ereport(DEBUG2,
1082  (errmsg_internal("drop auto-cascades to %s",
1083  objDesc)));
1084  }
1085  else if (behavior == DROP_RESTRICT)
1086  {
1087  char *otherDesc = getObjectDescription(&extra->dependee,
1088  false);
1089 
1090  if (otherDesc)
1091  {
1092  if (numReportedClient < MAX_REPORTED_DEPS)
1093  {
1094  /* separate entries with a newline */
1095  if (clientdetail.len != 0)
1096  appendStringInfoChar(&clientdetail, '\n');
1097  appendStringInfo(&clientdetail, _("%s depends on %s"),
1098  objDesc, otherDesc);
1099  numReportedClient++;
1100  }
1101  else
1102  numNotReportedClient++;
1103  /* separate entries with a newline */
1104  if (logdetail.len != 0)
1105  appendStringInfoChar(&logdetail, '\n');
1106  appendStringInfo(&logdetail, _("%s depends on %s"),
1107  objDesc, otherDesc);
1108  pfree(otherDesc);
1109  }
1110  else
1111  numNotReportedClient++;
1112  ok = false;
1113  }
1114  else
1115  {
1116  if (numReportedClient < MAX_REPORTED_DEPS)
1117  {
1118  /* separate entries with a newline */
1119  if (clientdetail.len != 0)
1120  appendStringInfoChar(&clientdetail, '\n');
1121  appendStringInfo(&clientdetail, _("drop cascades to %s"),
1122  objDesc);
1123  numReportedClient++;
1124  }
1125  else
1126  numNotReportedClient++;
1127  /* separate entries with a newline */
1128  if (logdetail.len != 0)
1129  appendStringInfoChar(&logdetail, '\n');
1130  appendStringInfo(&logdetail, _("drop cascades to %s"),
1131  objDesc);
1132  }
1133 
1134  pfree(objDesc);
1135  }
1136 
1137  if (numNotReportedClient > 0)
1138  appendStringInfo(&clientdetail, ngettext("\nand %d other object "
1139  "(see server log for list)",
1140  "\nand %d other objects "
1141  "(see server log for list)",
1142  numNotReportedClient),
1143  numNotReportedClient);
1144 
1145  if (!ok)
1146  {
1147  if (origObject)
1148  ereport(ERROR,
1149  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1150  errmsg("cannot drop %s because other objects depend on it",
1151  getObjectDescription(origObject, false)),
1152  errdetail_internal("%s", clientdetail.data),
1153  errdetail_log("%s", logdetail.data),
1154  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1155  else
1156  ereport(ERROR,
1157  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1158  errmsg("cannot drop desired object(s) because other objects depend on them"),
1159  errdetail_internal("%s", clientdetail.data),
1160  errdetail_log("%s", logdetail.data),
1161  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1162  }
1163  else if (numReportedClient > 1)
1164  {
1165  ereport(msglevel,
1166  (errmsg_plural("drop cascades to %d other object",
1167  "drop cascades to %d other objects",
1168  numReportedClient + numNotReportedClient,
1169  numReportedClient + numNotReportedClient),
1170  errdetail_internal("%s", clientdetail.data),
1171  errdetail_log("%s", logdetail.data)));
1172  }
1173  else if (numReportedClient == 1)
1174  {
1175  /* we just use the single item as-is */
1176  ereport(msglevel,
1177  (errmsg_internal("%s", clientdetail.data)));
1178  }
1179 
1180  pfree(clientdetail.data);
1181  pfree(logdetail.data);
1182 }
#define ngettext(s, p, n)
Definition: c.h:1181
#define MAX_REPORTED_DEPS
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:94
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1180
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
bool message_level_is_interesting(int elevel)
Definition: elog.c:276
int errdetail_log(const char *fmt,...)
Definition: elog.c:1251
#define _(x)
Definition: elog.c:90
#define DEBUG2
Definition: elog.h:29
#define NOTICE
Definition: elog.h:35
@ DROP_CASCADE
Definition: parsenodes.h:2335
@ DROP_RESTRICT
Definition: parsenodes.h:2334
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:194
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References _, appendStringInfo(), appendStringInfoChar(), StringInfoData::data, DEBUG2, ObjectAddressExtra::dependee, DEPFLAG_AUTO, DEPFLAG_EXTENSION, DEPFLAG_INTERNAL, DEPFLAG_IS_PART, DEPFLAG_ORIGINAL, DEPFLAG_PARTITION, DEPFLAG_SUBOBJECT, DROP_CASCADE, DROP_RESTRICT, ereport, errcode(), errdetail_internal(), errdetail_log(), errhint(), errmsg(), errmsg_internal(), errmsg_plural(), ERROR, ObjectAddresses::extras, ObjectAddressExtra::flags, ObjectAddressStack::flags, getObjectDescription(), i, initStringInfo(), StringInfoData::len, MAX_REPORTED_DEPS, message_level_is_interesting(), ngettext, NOTICE, ObjectAddresses::numrefs, PERFORM_DELETION_QUIETLY, pfree(), and ObjectAddresses::refs.

Referenced by performDeletion(), and performMultipleDeletions().

◆ sort_object_addresses()

void sort_object_addresses ( ObjectAddresses addrs)

Definition at line 2759 of file dependency.c.

2760 {
2761  if (addrs->numrefs > 1)
2762  qsort(addrs->refs, addrs->numrefs,
2763  sizeof(ObjectAddress),
2765 }

References ObjectAddresses::numrefs, object_address_comparator(), qsort, and ObjectAddresses::refs.

Referenced by shdepDropOwned().

◆ stack_address_present_add_flags()

static bool stack_address_present_add_flags ( const ObjectAddress object,
int  flags,
ObjectAddressStack stack 
)
static

Definition at line 2690 of file dependency.c.

2693 {
2694  bool result = false;
2695  ObjectAddressStack *stackptr;
2696 
2697  for (stackptr = stack; stackptr; stackptr = stackptr->next)
2698  {
2699  const ObjectAddress *thisobj = stackptr->object;
2700 
2701  if (object->classId == thisobj->classId &&
2702  object->objectId == thisobj->objectId)
2703  {
2704  if (object->objectSubId == thisobj->objectSubId)
2705  {
2706  stackptr->flags |= flags;
2707  result = true;
2708  }
2709  else if (thisobj->objectSubId == 0)
2710  {
2711  /*
2712  * We're visiting a column with whole table already on stack.
2713  * As in object_address_present_add_flags(), we can skip
2714  * further processing of the subobject, but we don't want to
2715  * propagate flags for the subobject to the whole object.
2716  */
2717  result = true;
2718  }
2719  else if (object->objectSubId == 0)
2720  {
2721  /*
2722  * We're visiting a table with column already on stack. As in
2723  * object_address_present_add_flags(), we should propagate
2724  * flags for the whole object to each of its subobjects.
2725  */
2726  if (flags)
2727  stackptr->flags |= (flags | DEPFLAG_SUBOBJECT);
2728  }
2729  }
2730  }
2731 
2732  return result;
2733 }

References ObjectAddress::classId, DEPFLAG_SUBOBJECT, ObjectAddressStack::flags, ObjectAddressStack::next, ObjectAddressStack::object, ObjectAddress::objectId, and ObjectAddress::objectSubId.

Referenced by findDependentObjects().