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 "nodes/nodeFuncs.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteRemove.h"
#include "storage/lmgr.h"
#include "utils/acl.h"
#include "utils/fmgroids.h"
#include "utils/guc.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 (ObjectClass oclass, 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)
 
ObjectClass getObjectClass (const ObjectAddress *object)
 

Variables

static const Oid object_classes []
 

Macro Definition Documentation

◆ DEPFLAG_AUTO

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

Definition at line 104 of file dependency.c.

◆ DEPFLAG_EXTENSION

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

Definition at line 107 of file dependency.c.

◆ DEPFLAG_INTERNAL

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

Definition at line 105 of file dependency.c.

◆ DEPFLAG_IS_PART

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

Definition at line 109 of file dependency.c.

◆ DEPFLAG_NORMAL

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

Definition at line 103 of file dependency.c.

◆ DEPFLAG_ORIGINAL

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

Definition at line 102 of file dependency.c.

◆ DEPFLAG_PARTITION

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

Definition at line 106 of file dependency.c.

◆ DEPFLAG_REVERSE

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

Definition at line 108 of file dependency.c.

◆ DEPFLAG_SUBOBJECT

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

Definition at line 110 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 1539 of file dependency.c.

1540 {
1541  if (object->classId == RelationRelationId)
1542  {
1543  /*
1544  * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1545  * the index for the moment. index_drop() will promote the lock once
1546  * it's safe to do so. In all other cases we need full exclusive
1547  * lock.
1548  */
1549  if (flags & PERFORM_DELETION_CONCURRENTLY)
1551  else
1553  }
1554  else if (object->classId == AuthMemRelationId)
1555  LockSharedObject(object->classId, object->objectId, 0,
1557  else
1558  {
1559  /* assume we should lock the whole object not a sub-object */
1560  LockDatabaseObject(object->classId, object->objectId, 0,
1562  }
1563 }
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:137
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1005
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
#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 2581 of file dependency.c.

2583 {
2584  ObjectAddress *item;
2585 
2586  /* enlarge array if needed */
2587  if (addrs->numrefs >= addrs->maxrefs)
2588  {
2589  addrs->maxrefs *= 2;
2590  addrs->refs = (ObjectAddress *)
2591  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2592  Assert(!addrs->extras);
2593  }
2594  /* record this item */
2595  item = addrs->refs + addrs->numrefs;
2596  *item = *object;
2597  addrs->numrefs++;
2598 }
Assert(fmt[strlen(fmt) - 1] !='\n')
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1321
ObjectAddressExtra * extras
Definition: dependency.c:117
ObjectAddress * refs
Definition: dependency.c:116

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 2606 of file dependency.c.

2609 {
2610  ObjectAddress *item;
2611  ObjectAddressExtra *itemextra;
2612 
2613  /* allocate extra space if first time */
2614  if (!addrs->extras)
2615  addrs->extras = (ObjectAddressExtra *)
2616  palloc(addrs->maxrefs * sizeof(ObjectAddressExtra));
2617 
2618  /* enlarge array if needed */
2619  if (addrs->numrefs >= addrs->maxrefs)
2620  {
2621  addrs->maxrefs *= 2;
2622  addrs->refs = (ObjectAddress *)
2623  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2624  addrs->extras = (ObjectAddressExtra *)
2625  repalloc(addrs->extras, addrs->maxrefs * sizeof(ObjectAddressExtra));
2626  }
2627  /* record this item */
2628  item = addrs->refs + addrs->numrefs;
2629  *item = *object;
2630  itemextra = addrs->extras + addrs->numrefs;
2631  *itemextra = *extra;
2632  addrs->numrefs++;
2633 }
void * palloc(Size size)
Definition: mcxt.c:1199

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 ( ObjectClass  oclass,
Oid  objectId,
int32  subId,
ObjectAddresses addrs 
)
static

Definition at line 2548 of file dependency.c.

2550 {
2551  ObjectAddress *item;
2552 
2553  /*
2554  * Make sure object_classes is kept up to date with the ObjectClass enum.
2555  */
2557  "object_classes[] must cover all ObjectClasses");
2558 
2559  /* enlarge array if needed */
2560  if (addrs->numrefs >= addrs->maxrefs)
2561  {
2562  addrs->maxrefs *= 2;
2563  addrs->refs = (ObjectAddress *)
2564  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2565  Assert(!addrs->extras);
2566  }
2567  /* record this item */
2568  item = addrs->refs + addrs->numrefs;
2569  item->classId = object_classes[oclass];
2570  item->objectId = objectId;
2571  item->objectSubId = subId;
2572  addrs->numrefs++;
2573 }
#define lengthof(array)
Definition: c.h:724
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:869
static const Oid object_classes[]
Definition: dependency.c:150
#define LAST_OCLASS
Definition: dependency.h:133

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

Referenced by find_expr_references_walker(), and process_function_rte_ref().

◆ DeleteInitPrivs()

static void DeleteInitPrivs ( const ObjectAddress object)
static

Definition at line 2980 of file dependency.c.

2981 {
2982  Relation relation;
2983  ScanKeyData key[3];
2984  SysScanDesc scan;
2985  HeapTuple oldtuple;
2986 
2987  relation = table_open(InitPrivsRelationId, RowExclusiveLock);
2988 
2989  ScanKeyInit(&key[0],
2990  Anum_pg_init_privs_objoid,
2991  BTEqualStrategyNumber, F_OIDEQ,
2992  ObjectIdGetDatum(object->objectId));
2993  ScanKeyInit(&key[1],
2994  Anum_pg_init_privs_classoid,
2995  BTEqualStrategyNumber, F_OIDEQ,
2996  ObjectIdGetDatum(object->classId));
2997  ScanKeyInit(&key[2],
2998  Anum_pg_init_privs_objsubid,
2999  BTEqualStrategyNumber, F_INT4EQ,
3000  Int32GetDatum(object->objectSubId));
3001 
3002  scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
3003  NULL, 3, key);
3004 
3005  while (HeapTupleIsValid(oldtuple = systable_getnext(scan)))
3006  CatalogTupleDelete(relation, &oldtuple->t_self);
3007 
3008  systable_endscan(scan);
3009 
3010  table_close(relation, RowExclusiveLock);
3011 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
#define RowExclusiveLock
Definition: lockdefs.h:38
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560
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 234 of file dependency.c.

236 {
237  int i;
238 
239  /*
240  * Keep track of objects for event triggers, if necessary.
241  */
243  {
244  for (i = 0; i < targetObjects->numrefs; i++)
245  {
246  const ObjectAddress *thisobj = &targetObjects->refs[i];
247  const ObjectAddressExtra *extra = &targetObjects->extras[i];
248  bool original = false;
249  bool normal = false;
250 
251  if (extra->flags & DEPFLAG_ORIGINAL)
252  original = true;
253  if (extra->flags & DEPFLAG_NORMAL)
254  normal = true;
255  if (extra->flags & DEPFLAG_REVERSE)
256  normal = true;
257 
259  {
260  EventTriggerSQLDropAddObject(thisobj, original, normal);
261  }
262  }
263  }
264 
265  /*
266  * Delete all the objects in the proper order, except that if told to, we
267  * should skip the original object(s).
268  */
269  for (i = 0; i < targetObjects->numrefs; i++)
270  {
271  ObjectAddress *thisobj = targetObjects->refs + i;
272  ObjectAddressExtra *thisextra = targetObjects->extras + i;
273 
274  if ((flags & PERFORM_DELETION_SKIP_ORIGINAL) &&
275  (thisextra->flags & DEPFLAG_ORIGINAL))
276  continue;
277 
278  deleteOneObject(thisobj, depRel, flags);
279  }
280 }
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2836
static void deleteOneObject(const ObjectAddress *object, Relation *depRel, int32 flags)
#define DEPFLAG_ORIGINAL
Definition: dependency.c:102
#define DEPFLAG_REVERSE
Definition: dependency.c:108
#define DEPFLAG_NORMAL
Definition: dependency.c:103
#define PERFORM_DELETION_SKIP_ORIGINAL
Definition: dependency.h:139
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:136
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
bool trackDroppedObjectsNeeded(void)
bool EventTriggerSupportsObjectClass(ObjectClass objclass)
int i
Definition: isn.c:73

References deleteOneObject(), DEPFLAG_NORMAL, DEPFLAG_ORIGINAL, DEPFLAG_REVERSE, EventTriggerSQLDropAddObject(), EventTriggerSupportsObjectClass(), ObjectAddresses::extras, ObjectAddressExtra::flags, ObjectAddressStack::flags, getObjectClass(), 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 1289 of file dependency.c.

1290 {
1291  ScanKeyData key[3];
1292  int nkeys;
1293  SysScanDesc scan;
1294  HeapTuple tup;
1295 
1296  /* DROP hook of the objects being removed */
1297  InvokeObjectDropHookArg(object->classId, object->objectId,
1298  object->objectSubId, flags);
1299 
1300  /*
1301  * Close depRel if we are doing a drop concurrently. The object deletion
1302  * subroutine will commit the current transaction, so we can't keep the
1303  * relation open across doDeletion().
1304  */
1305  if (flags & PERFORM_DELETION_CONCURRENTLY)
1306  table_close(*depRel, RowExclusiveLock);
1307 
1308  /*
1309  * Delete the object itself, in an object-type-dependent way.
1310  *
1311  * We used to do this after removing the outgoing dependency links, but it
1312  * seems just as reasonable to do it beforehand. In the concurrent case
1313  * we *must* do it in this order, because we can't make any transactional
1314  * updates before calling doDeletion() --- they'd get committed right
1315  * away, which is not cool if the deletion then fails.
1316  */
1317  doDeletion(object, flags);
1318 
1319  /*
1320  * Reopen depRel if we closed it above
1321  */
1322  if (flags & PERFORM_DELETION_CONCURRENTLY)
1323  *depRel = table_open(DependRelationId, RowExclusiveLock);
1324 
1325  /*
1326  * Now remove any pg_depend records that link from this object to others.
1327  * (Any records linking to this object should be gone already.)
1328  *
1329  * When dropping a whole object (subId = 0), remove all pg_depend records
1330  * for its sub-objects too.
1331  */
1332  ScanKeyInit(&key[0],
1333  Anum_pg_depend_classid,
1334  BTEqualStrategyNumber, F_OIDEQ,
1335  ObjectIdGetDatum(object->classId));
1336  ScanKeyInit(&key[1],
1337  Anum_pg_depend_objid,
1338  BTEqualStrategyNumber, F_OIDEQ,
1339  ObjectIdGetDatum(object->objectId));
1340  if (object->objectSubId != 0)
1341  {
1342  ScanKeyInit(&key[2],
1343  Anum_pg_depend_objsubid,
1344  BTEqualStrategyNumber, F_INT4EQ,
1345  Int32GetDatum(object->objectSubId));
1346  nkeys = 3;
1347  }
1348  else
1349  nkeys = 2;
1350 
1351  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
1352  NULL, nkeys, key);
1353 
1354  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1355  {
1356  CatalogTupleDelete(*depRel, &tup->t_self);
1357  }
1358 
1359  systable_endscan(scan);
1360 
1361  /*
1362  * Delete shared dependency references related to this object. Again, if
1363  * subId = 0, remove records for sub-objects too.
1364  */
1366  object->objectSubId);
1367 
1368 
1369  /*
1370  * Delete any comments, security labels, or initial privileges associated
1371  * with this object. (This is a convenient place to do these things,
1372  * rather than having every object type know to do it.)
1373  */
1374  DeleteComments(object->objectId, object->classId, object->objectSubId);
1375  DeleteSecurityLabel(object);
1376  DeleteInitPrivs(object);
1377 
1378  /*
1379  * CommandCounterIncrement here to ensure that preceding changes are all
1380  * visible to the next deletion step.
1381  */
1383 
1384  /*
1385  * And we're done!
1386  */
1387 }
void DeleteComments(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:326
static void doDeletion(const ObjectAddress *object, int flags)
Definition: dependency.c:1393
static void DeleteInitPrivs(const ObjectAddress *object)
Definition: dependency.c:2980
#define InvokeObjectDropHookArg(classId, objectId, subId, dropflags)
Definition: objectaccess.h:184
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1002
void DeleteSecurityLabel(const ObjectAddress *object)
Definition: seclabel.c:523
void CommandCounterIncrement(void)
Definition: xact.c:1077

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 1393 of file dependency.c.

1394 {
1395  switch (getObjectClass(object))
1396  {
1397  case OCLASS_CLASS:
1398  {
1399  char relKind = get_rel_relkind(object->objectId);
1400 
1401  if (relKind == RELKIND_INDEX ||
1402  relKind == RELKIND_PARTITIONED_INDEX)
1403  {
1404  bool concurrent = ((flags & PERFORM_DELETION_CONCURRENTLY) != 0);
1405  bool concurrent_lock_mode = ((flags & PERFORM_DELETION_CONCURRENT_LOCK) != 0);
1406 
1407  Assert(object->objectSubId == 0);
1408  index_drop(object->objectId, concurrent, concurrent_lock_mode);
1409  }
1410  else
1411  {
1412  if (object->objectSubId != 0)
1413  RemoveAttributeById(object->objectId,
1414  object->objectSubId);
1415  else
1417  }
1418 
1419  /*
1420  * for a sequence, in addition to dropping the heap, also
1421  * delete pg_sequence tuple
1422  */
1423  if (relKind == RELKIND_SEQUENCE)
1424  DeleteSequenceTuple(object->objectId);
1425  break;
1426  }
1427 
1428  case OCLASS_PROC:
1429  RemoveFunctionById(object->objectId);
1430  break;
1431 
1432  case OCLASS_TYPE:
1433  RemoveTypeById(object->objectId);
1434  break;
1435 
1436  case OCLASS_CONSTRAINT:
1437  RemoveConstraintById(object->objectId);
1438  break;
1439 
1440  case OCLASS_DEFAULT:
1442  break;
1443 
1444  case OCLASS_LARGEOBJECT:
1445  LargeObjectDrop(object->objectId);
1446  break;
1447 
1448  case OCLASS_OPERATOR:
1449  RemoveOperatorById(object->objectId);
1450  break;
1451 
1452  case OCLASS_REWRITE:
1454  break;
1455 
1456  case OCLASS_TRIGGER:
1457  RemoveTriggerById(object->objectId);
1458  break;
1459 
1460  case OCLASS_STATISTIC_EXT:
1461  RemoveStatisticsById(object->objectId);
1462  break;
1463 
1464  case OCLASS_TSCONFIG:
1466  break;
1467 
1468  case OCLASS_EXTENSION:
1469  RemoveExtensionById(object->objectId);
1470  break;
1471 
1472  case OCLASS_POLICY:
1473  RemovePolicyById(object->objectId);
1474  break;
1475 
1478  break;
1479 
1482  break;
1483 
1484  case OCLASS_PUBLICATION:
1486  break;
1487 
1488  case OCLASS_CAST:
1489  case OCLASS_COLLATION:
1490  case OCLASS_CONVERSION:
1491  case OCLASS_LANGUAGE:
1492  case OCLASS_OPCLASS:
1493  case OCLASS_OPFAMILY:
1494  case OCLASS_AM:
1495  case OCLASS_AMOP:
1496  case OCLASS_AMPROC:
1497  case OCLASS_SCHEMA:
1498  case OCLASS_TSPARSER:
1499  case OCLASS_TSDICT:
1500  case OCLASS_TSTEMPLATE:
1501  case OCLASS_FDW:
1502  case OCLASS_FOREIGN_SERVER:
1503  case OCLASS_USER_MAPPING:
1504  case OCLASS_DEFACL:
1505  case OCLASS_EVENT_TRIGGER:
1506  case OCLASS_TRANSFORM:
1508  DropObjectById(object);
1509  break;
1510 
1511  /*
1512  * These global object types are not supported here.
1513  */
1514  case OCLASS_ROLE:
1515  case OCLASS_DATABASE:
1516  case OCLASS_TBLSPACE:
1517  case OCLASS_SUBSCRIPTION:
1518  case OCLASS_PARAMETER_ACL:
1519  elog(ERROR, "global objects cannot be deleted by doDeletion");
1520  break;
1521 
1522  /*
1523  * There's intentionally no default: case here; we want the
1524  * compiler to warn if a new OCLASS hasn't been handled above.
1525  */
1526  }
1527 }
static void DropObjectById(const ObjectAddress *object)
Definition: dependency.c:1232
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:141
@ OCLASS_OPERATOR
Definition: dependency.h:100
@ OCLASS_PARAMETER_ACL
Definition: dependency.h:124
@ OCLASS_LARGEOBJECT
Definition: dependency.h:99
@ OCLASS_FDW
Definition: dependency.h:118
@ OCLASS_OPFAMILY
Definition: dependency.h:102
@ OCLASS_DEFACL
Definition: dependency.h:121
@ OCLASS_TSPARSER
Definition: dependency.h:110
@ OCLASS_TRIGGER
Definition: dependency.h:107
@ OCLASS_DEFAULT
Definition: dependency.h:97
@ OCLASS_TSTEMPLATE
Definition: dependency.h:112
@ OCLASS_AMPROC
Definition: dependency.h:105
@ OCLASS_TBLSPACE
Definition: dependency.h:117
@ OCLASS_TSCONFIG
Definition: dependency.h:113
@ OCLASS_TYPE
Definition: dependency.h:92
@ OCLASS_LANGUAGE
Definition: dependency.h:98
@ OCLASS_CAST
Definition: dependency.h:93
@ OCLASS_SUBSCRIPTION
Definition: dependency.h:129
@ OCLASS_PUBLICATION_NAMESPACE
Definition: dependency.h:127
@ OCLASS_EXTENSION
Definition: dependency.h:122
@ OCLASS_COLLATION
Definition: dependency.h:94
@ OCLASS_FOREIGN_SERVER
Definition: dependency.h:119
@ OCLASS_REWRITE
Definition: dependency.h:106
@ OCLASS_STATISTIC_EXT
Definition: dependency.h:109
@ OCLASS_PROC
Definition: dependency.h:91
@ OCLASS_OPCLASS
Definition: dependency.h:101
@ OCLASS_CONVERSION
Definition: dependency.h:96
@ OCLASS_DATABASE
Definition: dependency.h:116
@ OCLASS_ROLE_MEMBERSHIP
Definition: dependency.h:115
@ OCLASS_SCHEMA
Definition: dependency.h:108
@ OCLASS_EVENT_TRIGGER
Definition: dependency.h:123
@ OCLASS_CLASS
Definition: dependency.h:90
@ OCLASS_TRANSFORM
Definition: dependency.h:130
@ OCLASS_ROLE
Definition: dependency.h:114
@ OCLASS_CONSTRAINT
Definition: dependency.h:95
@ OCLASS_POLICY
Definition: dependency.h:125
@ OCLASS_USER_MAPPING
Definition: dependency.h:120
@ OCLASS_PUBLICATION_REL
Definition: dependency.h:128
@ OCLASS_AM
Definition: dependency.h:103
@ OCLASS_TSDICT
Definition: dependency.h:111
@ OCLASS_PUBLICATION
Definition: dependency.h:126
@ OCLASS_AMOP
Definition: dependency.h:104
#define ERROR
Definition: elog.h:35
void RemoveExtensionById(Oid extId)
Definition: extension.c:1890
void RemoveFunctionById(Oid funcOid)
void RemoveAttributeById(Oid relid, AttrNumber attnum)
Definition: heap.c:1643
void heap_drop_with_catalog(Oid relid)
Definition: heap.c:1755
void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
Definition: index.c:2130
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
void RemoveOperatorById(Oid operOid)
Definition: operatorcmds.c:366
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:335
void RemovePublicationSchemaById(Oid psoid)
void RemovePublicationById(Oid pubid)
void RemovePublicationRelById(Oid proid)
void RemoveRewriteRuleById(Oid ruleOid)
Definition: rewriteRemove.c:39
void DeleteSequenceTuple(Oid relid)
Definition: sequence.c:576
void RemoveStatisticsById(Oid statsOid)
Definition: statscmds.c:734
void RemoveTriggerById(Oid trigOid)
Definition: trigger.c:1297
void RemoveTSConfigurationById(Oid cfgId)
Definition: tsearchcmds.c:1102
void RemoveTypeById(Oid typeOid)
Definition: typecmds.c:653

References Assert(), DeleteSequenceTuple(), DropObjectById(), elog(), ERROR, ObjectAddressStack::flags, get_rel_relkind(), getObjectClass(), heap_drop_with_catalog(), index_drop(), LargeObjectDrop(), ObjectAddressStack::object, ObjectAddress::objectId, ObjectAddress::objectSubId, OCLASS_AM, OCLASS_AMOP, OCLASS_AMPROC, OCLASS_CAST, OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_CONVERSION, OCLASS_DATABASE, OCLASS_DEFACL, OCLASS_DEFAULT, OCLASS_EVENT_TRIGGER, OCLASS_EXTENSION, OCLASS_FDW, OCLASS_FOREIGN_SERVER, OCLASS_LANGUAGE, OCLASS_LARGEOBJECT, OCLASS_OPCLASS, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_PARAMETER_ACL, OCLASS_POLICY, OCLASS_PROC, OCLASS_PUBLICATION, OCLASS_PUBLICATION_NAMESPACE, OCLASS_PUBLICATION_REL, OCLASS_REWRITE, OCLASS_ROLE, OCLASS_ROLE_MEMBERSHIP, OCLASS_SCHEMA, OCLASS_STATISTIC_EXT, OCLASS_SUBSCRIPTION, OCLASS_TBLSPACE, OCLASS_TRANSFORM, OCLASS_TRIGGER, OCLASS_TSCONFIG, OCLASS_TSDICT, OCLASS_TSPARSER, OCLASS_TSTEMPLATE, OCLASS_TYPE, OCLASS_USER_MAPPING, 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 1232 of file dependency.c.

1233 {
1234  int cacheId;
1235  Relation rel;
1236  HeapTuple tup;
1237 
1238  cacheId = get_object_catcache_oid(object->classId);
1239 
1240  rel = table_open(object->classId, RowExclusiveLock);
1241 
1242  /*
1243  * Use the system cache for the oid column, if one exists.
1244  */
1245  if (cacheId >= 0)
1246  {
1247  tup = SearchSysCache1(cacheId, ObjectIdGetDatum(object->objectId));
1248  if (!HeapTupleIsValid(tup))
1249  elog(ERROR, "cache lookup failed for %s %u",
1250  get_object_class_descr(object->classId), object->objectId);
1251 
1252  CatalogTupleDelete(rel, &tup->t_self);
1253 
1254  ReleaseSysCache(tup);
1255  }
1256  else
1257  {
1258  ScanKeyData skey[1];
1259  SysScanDesc scan;
1260 
1261  ScanKeyInit(&skey[0],
1262  get_object_attnum_oid(object->classId),
1263  BTEqualStrategyNumber, F_OIDEQ,
1264  ObjectIdGetDatum(object->objectId));
1265 
1266  scan = systable_beginscan(rel, get_object_oid_index(object->classId), true,
1267  NULL, 1, skey);
1268 
1269  /* we expect exactly one match */
1270  tup = systable_getnext(scan);
1271  if (!HeapTupleIsValid(tup))
1272  elog(ERROR, "could not find tuple for %s %u",
1273  get_object_class_descr(object->classId), object->objectId);
1274 
1275  CatalogTupleDelete(rel, &tup->t_self);
1276 
1277  systable_endscan(scan);
1278  }
1279 
1281 }
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:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173

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 2422 of file dependency.c.

2423 {
2424  ObjectAddress *priorobj;
2425  int oldref,
2426  newrefs;
2427 
2428  /*
2429  * We can't sort if the array has "extra" data, because there's no way to
2430  * keep it in sync. Fortunately that combination of features is not
2431  * needed.
2432  */
2433  Assert(!addrs->extras);
2434 
2435  if (addrs->numrefs <= 1)
2436  return; /* nothing to do */
2437 
2438  /* Sort the refs so that duplicates are adjacent */
2439  qsort((void *) addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
2441 
2442  /* Remove dups */
2443  priorobj = addrs->refs;
2444  newrefs = 1;
2445  for (oldref = 1; oldref < addrs->numrefs; oldref++)
2446  {
2447  ObjectAddress *thisobj = addrs->refs + oldref;
2448 
2449  if (priorobj->classId == thisobj->classId &&
2450  priorobj->objectId == thisobj->objectId)
2451  {
2452  if (priorobj->objectSubId == thisobj->objectSubId)
2453  continue; /* identical, so drop thisobj */
2454 
2455  /*
2456  * If we have a whole-object reference and a reference to a part
2457  * of the same object, we don't need the whole-object reference
2458  * (for example, we don't need to reference both table foo and
2459  * column foo.bar). The whole-object reference will always appear
2460  * first in the sorted list.
2461  */
2462  if (priorobj->objectSubId == 0)
2463  {
2464  /* replace whole ref with partial */
2465  priorobj->objectSubId = thisobj->objectSubId;
2466  continue;
2467  }
2468  }
2469  /* Not identical, so add thisobj to output set */
2470  priorobj++;
2471  *priorobj = *thisobj;
2472  newrefs++;
2473  }
2474 
2475  addrs->numrefs = newrefs;
2476 }
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2482
#define qsort(a, b, c, d)
Definition: port.h:445

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 1741 of file dependency.c.

1743 {
1744  if (node == NULL)
1745  return false;
1746  if (IsA(node, Var))
1747  {
1748  Var *var = (Var *) node;
1749  List *rtable;
1750  RangeTblEntry *rte;
1751 
1752  /* Find matching rtable entry, or complain if not found */
1753  if (var->varlevelsup >= list_length(context->rtables))
1754  elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
1755  rtable = (List *) list_nth(context->rtables, var->varlevelsup);
1756  if (var->varno <= 0 || var->varno > list_length(rtable))
1757  elog(ERROR, "invalid varno %d", var->varno);
1758  rte = rt_fetch(var->varno, rtable);
1759 
1760  /*
1761  * A whole-row Var references no specific columns, so adds no new
1762  * dependency. (We assume that there is a whole-table dependency
1763  * arising from each underlying rangetable entry. While we could
1764  * record such a dependency when finding a whole-row Var that
1765  * references a relation directly, it's quite unclear how to extend
1766  * that to whole-row Vars for JOINs, so it seems better to leave the
1767  * responsibility with the range table. Note that this poses some
1768  * risks for identifying dependencies of stand-alone expressions:
1769  * whole-table references may need to be created separately.)
1770  */
1771  if (var->varattno == InvalidAttrNumber)
1772  return false;
1773  if (rte->rtekind == RTE_RELATION)
1774  {
1775  /* If it's a plain relation, reference this column */
1777  context->addrs);
1778  }
1779  else if (rte->rtekind == RTE_FUNCTION)
1780  {
1781  /* Might need to add a dependency on a composite type's column */
1782  /* (done out of line, because it's a bit bulky) */
1783  process_function_rte_ref(rte, var->varattno, context);
1784  }
1785 
1786  /*
1787  * Vars referencing other RTE types require no additional work. In
1788  * particular, a join alias Var can be ignored, because it must
1789  * reference a merged USING column. The relevant join input columns
1790  * will also be referenced in the join qual, and any type coercion
1791  * functions involved in the alias expression will be dealt with when
1792  * we scan the RTE itself.
1793  */
1794  return false;
1795  }
1796  else if (IsA(node, Const))
1797  {
1798  Const *con = (Const *) node;
1799  Oid objoid;
1800 
1801  /* A constant must depend on the constant's datatype */
1803  context->addrs);
1804 
1805  /*
1806  * We must also depend on the constant's collation: it could be
1807  * different from the datatype's, if a CollateExpr was const-folded to
1808  * a simple constant. However we can save work in the most common
1809  * case where the collation is "default", since we know that's pinned.
1810  */
1811  if (OidIsValid(con->constcollid) &&
1812  con->constcollid != DEFAULT_COLLATION_OID)
1814  context->addrs);
1815 
1816  /*
1817  * If it's a regclass or similar literal referring to an existing
1818  * object, add a reference to that object. (Currently, only the
1819  * regclass and regconfig cases have any likely use, but we may as
1820  * well handle all the OID-alias datatypes consistently.)
1821  */
1822  if (!con->constisnull)
1823  {
1824  switch (con->consttype)
1825  {
1826  case REGPROCOID:
1827  case REGPROCEDUREOID:
1828  objoid = DatumGetObjectId(con->constvalue);
1830  ObjectIdGetDatum(objoid)))
1831  add_object_address(OCLASS_PROC, objoid, 0,
1832  context->addrs);
1833  break;
1834  case REGOPEROID:
1835  case REGOPERATOROID:
1836  objoid = DatumGetObjectId(con->constvalue);
1838  ObjectIdGetDatum(objoid)))
1840  context->addrs);
1841  break;
1842  case REGCLASSOID:
1843  objoid = DatumGetObjectId(con->constvalue);
1845  ObjectIdGetDatum(objoid)))
1846  add_object_address(OCLASS_CLASS, objoid, 0,
1847  context->addrs);
1848  break;
1849  case REGTYPEOID:
1850  objoid = DatumGetObjectId(con->constvalue);
1852  ObjectIdGetDatum(objoid)))
1853  add_object_address(OCLASS_TYPE, objoid, 0,
1854  context->addrs);
1855  break;
1856  case REGCOLLATIONOID:
1857  objoid = DatumGetObjectId(con->constvalue);
1859  ObjectIdGetDatum(objoid)))
1861  context->addrs);
1862  break;
1863  case REGCONFIGOID:
1864  objoid = DatumGetObjectId(con->constvalue);
1866  ObjectIdGetDatum(objoid)))
1868  context->addrs);
1869  break;
1870  case REGDICTIONARYOID:
1871  objoid = DatumGetObjectId(con->constvalue);
1873  ObjectIdGetDatum(objoid)))
1874  add_object_address(OCLASS_TSDICT, objoid, 0,
1875  context->addrs);
1876  break;
1877 
1878  case REGNAMESPACEOID:
1879  objoid = DatumGetObjectId(con->constvalue);
1881  ObjectIdGetDatum(objoid)))
1882  add_object_address(OCLASS_SCHEMA, objoid, 0,
1883  context->addrs);
1884  break;
1885 
1886  /*
1887  * Dependencies for regrole should be shared among all
1888  * databases, so explicitly inhibit to have dependencies.
1889  */
1890  case REGROLEOID:
1891  ereport(ERROR,
1892  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1893  errmsg("constant of the type %s cannot be used here",
1894  "regrole")));
1895  break;
1896  }
1897  }
1898  return false;
1899  }
1900  else if (IsA(node, Param))
1901  {
1902  Param *param = (Param *) node;
1903 
1904  /* A parameter must depend on the parameter's datatype */
1906  context->addrs);
1907  /* and its collation, just as for Consts */
1908  if (OidIsValid(param->paramcollid) &&
1909  param->paramcollid != DEFAULT_COLLATION_OID)
1911  context->addrs);
1912  }
1913  else if (IsA(node, FuncExpr))
1914  {
1915  FuncExpr *funcexpr = (FuncExpr *) node;
1916 
1917  add_object_address(OCLASS_PROC, funcexpr->funcid, 0,
1918  context->addrs);
1919  /* fall through to examine arguments */
1920  }
1921  else if (IsA(node, OpExpr))
1922  {
1923  OpExpr *opexpr = (OpExpr *) node;
1924 
1926  context->addrs);
1927  /* fall through to examine arguments */
1928  }
1929  else if (IsA(node, DistinctExpr))
1930  {
1931  DistinctExpr *distinctexpr = (DistinctExpr *) node;
1932 
1933  add_object_address(OCLASS_OPERATOR, distinctexpr->opno, 0,
1934  context->addrs);
1935  /* fall through to examine arguments */
1936  }
1937  else if (IsA(node, NullIfExpr))
1938  {
1939  NullIfExpr *nullifexpr = (NullIfExpr *) node;
1940 
1941  add_object_address(OCLASS_OPERATOR, nullifexpr->opno, 0,
1942  context->addrs);
1943  /* fall through to examine arguments */
1944  }
1945  else if (IsA(node, ScalarArrayOpExpr))
1946  {
1947  ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
1948 
1950  context->addrs);
1951  /* fall through to examine arguments */
1952  }
1953  else if (IsA(node, Aggref))
1954  {
1955  Aggref *aggref = (Aggref *) node;
1956 
1958  context->addrs);
1959  /* fall through to examine arguments */
1960  }
1961  else if (IsA(node, WindowFunc))
1962  {
1963  WindowFunc *wfunc = (WindowFunc *) node;
1964 
1966  context->addrs);
1967  /* fall through to examine arguments */
1968  }
1969  else if (IsA(node, SubscriptingRef))
1970  {
1971  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1972 
1973  /*
1974  * The refexpr should provide adequate dependency on refcontainertype,
1975  * and that type in turn depends on refelemtype. However, a custom
1976  * subscripting handler might set refrestype to something different
1977  * from either of those, in which case we'd better record it.
1978  */
1979  if (sbsref->refrestype != sbsref->refcontainertype &&
1980  sbsref->refrestype != sbsref->refelemtype)
1982  context->addrs);
1983  /* fall through to examine arguments */
1984  }
1985  else if (IsA(node, SubPlan))
1986  {
1987  /* Extra work needed here if we ever need this case */
1988  elog(ERROR, "already-planned subqueries not supported");
1989  }
1990  else if (IsA(node, FieldSelect))
1991  {
1992  FieldSelect *fselect = (FieldSelect *) node;
1993  Oid argtype = getBaseType(exprType((Node *) fselect->arg));
1994  Oid reltype = get_typ_typrelid(argtype);
1995 
1996  /*
1997  * We need a dependency on the specific column named in FieldSelect,
1998  * assuming we can identify the pg_class OID for it. (Probably we
1999  * always can at the moment, but in future it might be possible for
2000  * argtype to be RECORDOID.) If we can make a column dependency then
2001  * we shouldn't need a dependency on the column's type; but if we
2002  * can't, make a dependency on the type, as it might not appear
2003  * anywhere else in the expression.
2004  */
2005  if (OidIsValid(reltype))
2006  add_object_address(OCLASS_CLASS, reltype, fselect->fieldnum,
2007  context->addrs);
2008  else
2010  context->addrs);
2011  /* the collation might not be referenced anywhere else, either */
2012  if (OidIsValid(fselect->resultcollid) &&
2013  fselect->resultcollid != DEFAULT_COLLATION_OID)
2015  context->addrs);
2016  }
2017  else if (IsA(node, FieldStore))
2018  {
2019  FieldStore *fstore = (FieldStore *) node;
2020  Oid reltype = get_typ_typrelid(fstore->resulttype);
2021 
2022  /* similar considerations to FieldSelect, but multiple column(s) */
2023  if (OidIsValid(reltype))
2024  {
2025  ListCell *l;
2026 
2027  foreach(l, fstore->fieldnums)
2029  context->addrs);
2030  }
2031  else
2033  context->addrs);
2034  }
2035  else if (IsA(node, RelabelType))
2036  {
2037  RelabelType *relab = (RelabelType *) node;
2038 
2039  /* since there is no function dependency, need to depend on type */
2041  context->addrs);
2042  /* the collation might not be referenced anywhere else, either */
2043  if (OidIsValid(relab->resultcollid) &&
2044  relab->resultcollid != DEFAULT_COLLATION_OID)
2046  context->addrs);
2047  }
2048  else if (IsA(node, CoerceViaIO))
2049  {
2050  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2051 
2052  /* since there is no exposed function, need to depend on type */
2054  context->addrs);
2055  /* the collation might not be referenced anywhere else, either */
2056  if (OidIsValid(iocoerce->resultcollid) &&
2057  iocoerce->resultcollid != DEFAULT_COLLATION_OID)
2059  context->addrs);
2060  }
2061  else if (IsA(node, ArrayCoerceExpr))
2062  {
2063  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2064 
2065  /* as above, depend on type */
2067  context->addrs);
2068  /* the collation might not be referenced anywhere else, either */
2069  if (OidIsValid(acoerce->resultcollid) &&
2070  acoerce->resultcollid != DEFAULT_COLLATION_OID)
2072  context->addrs);
2073  /* fall through to examine arguments */
2074  }
2075  else if (IsA(node, ConvertRowtypeExpr))
2076  {
2077  ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
2078 
2079  /* since there is no function dependency, need to depend on type */
2081  context->addrs);
2082  }
2083  else if (IsA(node, CollateExpr))
2084  {
2085  CollateExpr *coll = (CollateExpr *) node;
2086 
2088  context->addrs);
2089  }
2090  else if (IsA(node, RowExpr))
2091  {
2092  RowExpr *rowexpr = (RowExpr *) node;
2093 
2095  context->addrs);
2096  }
2097  else if (IsA(node, RowCompareExpr))
2098  {
2099  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2100  ListCell *l;
2101 
2102  foreach(l, rcexpr->opnos)
2103  {
2105  context->addrs);
2106  }
2107  foreach(l, rcexpr->opfamilies)
2108  {
2110  context->addrs);
2111  }
2112  /* fall through to examine arguments */
2113  }
2114  else if (IsA(node, CoerceToDomain))
2115  {
2116  CoerceToDomain *cd = (CoerceToDomain *) node;
2117 
2119  context->addrs);
2120  }
2121  else if (IsA(node, NextValueExpr))
2122  {
2123  NextValueExpr *nve = (NextValueExpr *) node;
2124 
2126  context->addrs);
2127  }
2128  else if (IsA(node, OnConflictExpr))
2129  {
2130  OnConflictExpr *onconflict = (OnConflictExpr *) node;
2131 
2132  if (OidIsValid(onconflict->constraint))
2134  context->addrs);
2135  /* fall through to examine arguments */
2136  }
2137  else if (IsA(node, SortGroupClause))
2138  {
2139  SortGroupClause *sgc = (SortGroupClause *) node;
2140 
2142  context->addrs);
2143  if (OidIsValid(sgc->sortop))
2145  context->addrs);
2146  return false;
2147  }
2148  else if (IsA(node, WindowClause))
2149  {
2150  WindowClause *wc = (WindowClause *) node;
2151 
2152  if (OidIsValid(wc->startInRangeFunc))
2154  context->addrs);
2155  if (OidIsValid(wc->endInRangeFunc))
2157  context->addrs);
2158  if (OidIsValid(wc->inRangeColl) &&
2159  wc->inRangeColl != DEFAULT_COLLATION_OID)
2161  context->addrs);
2162  /* fall through to examine substructure */
2163  }
2164  else if (IsA(node, CTECycleClause))
2165  {
2166  CTECycleClause *cc = (CTECycleClause *) node;
2167 
2168  if (OidIsValid(cc->cycle_mark_type))
2170  context->addrs);
2173  context->addrs);
2174  if (OidIsValid(cc->cycle_mark_neop))
2176  context->addrs);
2177  /* fall through to examine substructure */
2178  }
2179  else if (IsA(node, Query))
2180  {
2181  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2182  Query *query = (Query *) node;
2183  ListCell *lc;
2184  bool result;
2185 
2186  /*
2187  * Add whole-relation refs for each plain relation mentioned in the
2188  * subquery's rtable, and ensure we add refs for any type-coercion
2189  * functions used in join alias lists.
2190  *
2191  * Note: query_tree_walker takes care of recursing into RTE_FUNCTION
2192  * RTEs, subqueries, etc, so no need to do that here. But we must
2193  * tell it not to visit join alias lists, or we'll add refs for join
2194  * input columns whether or not they are actually used in our query.
2195  *
2196  * Note: we don't need to worry about collations mentioned in
2197  * RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
2198  * collations referenced in other parts of the Query. We do have to
2199  * worry about collations mentioned in RTE_FUNCTION, but we take care
2200  * of those when we recurse to the RangeTblFunction node(s).
2201  */
2202  foreach(lc, query->rtable)
2203  {
2204  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2205 
2206  switch (rte->rtekind)
2207  {
2208  case RTE_RELATION:
2210  context->addrs);
2211  break;
2212  case RTE_JOIN:
2213 
2214  /*
2215  * Examine joinaliasvars entries only for merged JOIN
2216  * USING columns. Only those entries could contain
2217  * type-coercion functions. Also, their join input
2218  * columns must be referenced in the join quals, so this
2219  * won't accidentally add refs to otherwise-unused join
2220  * input columns. (We want to ref the type coercion
2221  * functions even if the merged column isn't explicitly
2222  * used anywhere, to protect possible expansion of the
2223  * join RTE as a whole-row var, and because it seems like
2224  * a bad idea to allow dropping a function that's present
2225  * in our query tree, whether or not it could get called.)
2226  */
2227  context->rtables = lcons(query->rtable, context->rtables);
2228  for (int i = 0; i < rte->joinmergedcols; i++)
2229  {
2230  Node *aliasvar = list_nth(rte->joinaliasvars, i);
2231 
2232  if (!IsA(aliasvar, Var))
2233  find_expr_references_walker(aliasvar, context);
2234  }
2235  context->rtables = list_delete_first(context->rtables);
2236  break;
2237  default:
2238  break;
2239  }
2240  }
2241 
2242  /*
2243  * If the query is an INSERT or UPDATE, we should create a dependency
2244  * on each target column, to prevent the specific target column from
2245  * being dropped. Although we will visit the TargetEntry nodes again
2246  * during query_tree_walker, we won't have enough context to do this
2247  * conveniently, so do it here.
2248  */
2249  if (query->commandType == CMD_INSERT ||
2250  query->commandType == CMD_UPDATE)
2251  {
2252  RangeTblEntry *rte;
2253 
2254  if (query->resultRelation <= 0 ||
2255  query->resultRelation > list_length(query->rtable))
2256  elog(ERROR, "invalid resultRelation %d",
2257  query->resultRelation);
2258  rte = rt_fetch(query->resultRelation, query->rtable);
2259  if (rte->rtekind == RTE_RELATION)
2260  {
2261  foreach(lc, query->targetList)
2262  {
2263  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2264 
2265  if (tle->resjunk)
2266  continue; /* ignore junk tlist items */
2268  context->addrs);
2269  }
2270  }
2271  }
2272 
2273  /*
2274  * Add dependencies on constraints listed in query's constraintDeps
2275  */
2276  foreach(lc, query->constraintDeps)
2277  {
2279  context->addrs);
2280  }
2281 
2282  /* Examine substructure of query */
2283  context->rtables = lcons(query->rtable, context->rtables);
2284  result = query_tree_walker(query,
2286  (void *) context,
2289  context->rtables = list_delete_first(context->rtables);
2290  return result;
2291  }
2292  else if (IsA(node, SetOperationStmt))
2293  {
2294  SetOperationStmt *setop = (SetOperationStmt *) node;
2295 
2296  /* we need to look at the groupClauses for operator references */
2297  find_expr_references_walker((Node *) setop->groupClauses, context);
2298  /* fall through to examine child nodes */
2299  }
2300  else if (IsA(node, RangeTblFunction))
2301  {
2302  RangeTblFunction *rtfunc = (RangeTblFunction *) node;
2303  ListCell *ct;
2304 
2305  /*
2306  * Add refs for any datatypes and collations used in a column
2307  * definition list for a RECORD function. (For other cases, it should
2308  * be enough to depend on the function itself.)
2309  */
2310  foreach(ct, rtfunc->funccoltypes)
2311  {
2313  context->addrs);
2314  }
2315  foreach(ct, rtfunc->funccolcollations)
2316  {
2317  Oid collid = lfirst_oid(ct);
2318 
2319  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2321  context->addrs);
2322  }
2323  }
2324  else if (IsA(node, TableFunc))
2325  {
2326  TableFunc *tf = (TableFunc *) node;
2327  ListCell *ct;
2328 
2329  /*
2330  * Add refs for the datatypes and collations used in the TableFunc.
2331  */
2332  foreach(ct, tf->coltypes)
2333  {
2335  context->addrs);
2336  }
2337  foreach(ct, tf->colcollations)
2338  {
2339  Oid collid = lfirst_oid(ct);
2340 
2341  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2343  context->addrs);
2344  }
2345  }
2346  else if (IsA(node, TableSampleClause))
2347  {
2348  TableSampleClause *tsc = (TableSampleClause *) node;
2349 
2351  context->addrs);
2352  /* fall through to examine arguments */
2353  }
2354 
2356  (void *) context);
2357 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define OidIsValid(objectId)
Definition: c.h:711
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1741
static void process_function_rte_ref(RangeTblEntry *rte, AttrNumber attnum, find_expr_references_context *context)
Definition: dependency.c:2364
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId, ObjectAddresses *addrs)
Definition: dependency.c:2548
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ereport(elevel,...)
Definition: elog.h:145
List * list_delete_first(List *list)
Definition: list.c:942
List * lcons(void *datum, List *list)
Definition: list.c:494
Oid get_typ_typrelid(Oid typid)
Definition: lsyscache.c:2689
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2479
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
#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:168
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_UPDATE
Definition: nodes.h:266
@ RTE_JOIN
Definition: parsenodes.h:1013
@ RTE_FUNCTION
Definition: parsenodes.h:1014
@ RTE_RELATION
Definition: parsenodes.h:1011
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
#define lfirst_int(lc)
Definition: pg_list.h:171
static void * list_nth(const List *list, int n)
Definition: pg_list.h:297
#define lfirst_oid(lc)
Definition: pg_list.h:172
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:590
unsigned int Oid
Definition: postgres_ext.h:31
Oid aggfnoid
Definition: primnodes.h:373
Oid cycle_mark_collation
Definition: parsenodes.h:1531
Oid resultcollid
Definition: primnodes.h:1024
Oid resulttype
Definition: primnodes.h:1022
Oid constcollid
Definition: primnodes.h:261
Oid consttype
Definition: primnodes.h:259
Datum constvalue
Definition: primnodes.h:263
bool constisnull
Definition: primnodes.h:264
AttrNumber fieldnum
Definition: primnodes.h:950
Oid resulttype
Definition: primnodes.h:951
Oid resultcollid
Definition: primnodes.h:954
Expr * arg
Definition: primnodes.h:949
Oid resulttype
Definition: primnodes.h:981
List * fieldnums
Definition: primnodes.h:980
Oid funcid
Definition: primnodes.h:598
Definition: pg_list.h:52
Definition: nodes.h:118
Oid opno
Definition: primnodes.h:648
Oid paramtype
Definition: primnodes.h:313
Oid paramcollid
Definition: primnodes.h:315
List * constraintDeps
Definition: parsenodes.h:192
List * rtable
Definition: parsenodes.h:155
int resultRelation
Definition: parsenodes.h:138
CmdType commandType
Definition: parsenodes.h:124
List * targetList
Definition: parsenodes.h:162
List * joinaliasvars
Definition: parsenodes.h:1105
RTEKind rtekind
Definition: parsenodes.h:1030
List * funccolcollations
Definition: parsenodes.h:1215
Oid resultcollid
Definition: primnodes.h:1004
Oid resulttype
Definition: primnodes.h:1002
List * opfamilies
Definition: primnodes.h:1257
Oid row_typeid
Definition: primnodes.h:1208
Oid refcontainertype
Definition: primnodes.h:542
List * coltypes
Definition: primnodes.h:106
List * colcollations
Definition: primnodes.h:108
AttrNumber resno
Definition: primnodes.h:1556
bool resjunk
Definition: primnodes.h:1562
Definition: primnodes.h:205
AttrNumber varattno
Definition: primnodes.h:217
int varno
Definition: primnodes.h:212
Index varlevelsup
Definition: primnodes.h:230
Oid endInRangeFunc
Definition: parsenodes.h:1423
Oid startInRangeFunc
Definition: parsenodes.h:1422
Oid winfnoid
Definition: primnodes.h:489
ObjectAddresses * addrs
Definition: dependency.c:142
@ TSDICTOID
Definition: syscache.h:108
@ TYPEOID
Definition: syscache.h:114
@ OPEROID
Definition: syscache.h:72
@ PROCOID
Definition: syscache.h:79
@ RELOID
Definition: syscache.h:89
@ COLLOID
Definition: syscache.h:50
@ TSCONFIGOID
Definition: syscache.h:106
@ NAMESPACEOID
Definition: syscache.h:70
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:188

References add_object_address(), find_expr_references_context::addrs, Aggref::aggfnoid, FieldSelect::arg, CMD_INSERT, CMD_UPDATE, TableFunc::colcollations, CollateExpr::collOid, COLLOID, TableFunc::coltypes, Query::commandType, Const::constcollid, Const::constisnull, OnConflictExpr::constraint, Query::constraintDeps, Const::consttype, Const::constvalue, CTECycleClause::cycle_mark_collation, CTECycleClause::cycle_mark_neop, CTECycleClause::cycle_mark_type, DatumGetObjectId(), elog(), WindowClause::endInRangeFunc, SortGroupClause::eqop, ereport, errcode(), errmsg(), ERROR, expression_tree_walker, exprType(), FieldSelect::fieldnum, FieldStore::fieldnums, RangeTblFunction::funccolcollations, RangeTblFunction::funccoltypes, FuncExpr::funcid, get_typ_typrelid(), getBaseType(), SetOperationStmt::groupClauses, i, WindowClause::inRangeColl, InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, RangeTblEntry::joinmergedcols, lcons(), lfirst, lfirst_int, lfirst_oid, list_delete_first(), list_length(), list_nth(), NAMESPACEOID, ObjectIdGetDatum(), OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_PROC, OCLASS_SCHEMA, OCLASS_TSCONFIG, OCLASS_TSDICT, OCLASS_TYPE, OidIsValid, OPEROID, RowCompareExpr::opfamilies, OpExpr::opno, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, Param::paramcollid, Param::paramtype, process_function_rte_ref(), PROCOID, QTW_EXAMINE_SORTGROUP, QTW_IGNORE_JOINALIASES, query_tree_walker, SubscriptingRef::refcontainertype, SubscriptingRef::refelemtype, SubscriptingRef::refrestype, RangeTblEntry::relid, RELOID, TargetEntry::resjunk, TargetEntry::resno, FieldSelect::resultcollid, RelabelType::resultcollid, CoerceViaIO::resultcollid, ArrayCoerceExpr::resultcollid, Query::resultRelation, FieldSelect::resulttype, FieldStore::resulttype, RelabelType::resulttype, CoerceViaIO::resulttype, ArrayCoerceExpr::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, RowExpr::row_typeid, rt_fetch, Query::rtable, find_expr_references_context::rtables, RTE_FUNCTION, RTE_JOIN, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCacheExists1, NextValueExpr::seqid, SortGroupClause::sortop, WindowClause::startInRangeFunc, Query::targetList, TSCONFIGOID, TSDICTOID, TableSampleClause::tsmhandler, TYPEOID, 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 481 of file dependency.c.

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

References AcquireDeletionLock(), add_exact_object_address_extra(), BTEqualStrategyNumber, 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()

◆ getObjectClass()

ObjectClass getObjectClass ( const ObjectAddress object)

Definition at line 2836 of file dependency.c.

2837 {
2838  /* only pg_class entries can have nonzero objectSubId */
2839  if (object->classId != RelationRelationId &&
2840  object->objectSubId != 0)
2841  elog(ERROR, "invalid non-zero objectSubId for object class %u",
2842  object->classId);
2843 
2844  switch (object->classId)
2845  {
2846  case RelationRelationId:
2847  /* caller must check objectSubId */
2848  return OCLASS_CLASS;
2849 
2850  case ProcedureRelationId:
2851  return OCLASS_PROC;
2852 
2853  case TypeRelationId:
2854  return OCLASS_TYPE;
2855 
2856  case CastRelationId:
2857  return OCLASS_CAST;
2858 
2859  case CollationRelationId:
2860  return OCLASS_COLLATION;
2861 
2862  case ConstraintRelationId:
2863  return OCLASS_CONSTRAINT;
2864 
2865  case ConversionRelationId:
2866  return OCLASS_CONVERSION;
2867 
2868  case AttrDefaultRelationId:
2869  return OCLASS_DEFAULT;
2870 
2871  case LanguageRelationId:
2872  return OCLASS_LANGUAGE;
2873 
2874  case LargeObjectRelationId:
2875  return OCLASS_LARGEOBJECT;
2876 
2877  case OperatorRelationId:
2878  return OCLASS_OPERATOR;
2879 
2880  case OperatorClassRelationId:
2881  return OCLASS_OPCLASS;
2882 
2883  case OperatorFamilyRelationId:
2884  return OCLASS_OPFAMILY;
2885 
2886  case AccessMethodRelationId:
2887  return OCLASS_AM;
2888 
2889  case AccessMethodOperatorRelationId:
2890  return OCLASS_AMOP;
2891 
2892  case AccessMethodProcedureRelationId:
2893  return OCLASS_AMPROC;
2894 
2895  case RewriteRelationId:
2896  return OCLASS_REWRITE;
2897 
2898  case TriggerRelationId:
2899  return OCLASS_TRIGGER;
2900 
2901  case NamespaceRelationId:
2902  return OCLASS_SCHEMA;
2903 
2904  case StatisticExtRelationId:
2905  return OCLASS_STATISTIC_EXT;
2906 
2907  case TSParserRelationId:
2908  return OCLASS_TSPARSER;
2909 
2910  case TSDictionaryRelationId:
2911  return OCLASS_TSDICT;
2912 
2913  case TSTemplateRelationId:
2914  return OCLASS_TSTEMPLATE;
2915 
2916  case TSConfigRelationId:
2917  return OCLASS_TSCONFIG;
2918 
2919  case AuthIdRelationId:
2920  return OCLASS_ROLE;
2921 
2922  case AuthMemRelationId:
2923  return OCLASS_ROLE_MEMBERSHIP;
2924 
2925  case DatabaseRelationId:
2926  return OCLASS_DATABASE;
2927 
2928  case TableSpaceRelationId:
2929  return OCLASS_TBLSPACE;
2930 
2931  case ForeignDataWrapperRelationId:
2932  return OCLASS_FDW;
2933 
2934  case ForeignServerRelationId:
2935  return OCLASS_FOREIGN_SERVER;
2936 
2937  case UserMappingRelationId:
2938  return OCLASS_USER_MAPPING;
2939 
2940  case DefaultAclRelationId:
2941  return OCLASS_DEFACL;
2942 
2943  case ExtensionRelationId:
2944  return OCLASS_EXTENSION;
2945 
2946  case EventTriggerRelationId:
2947  return OCLASS_EVENT_TRIGGER;
2948 
2949  case ParameterAclRelationId:
2950  return OCLASS_PARAMETER_ACL;
2951 
2952  case PolicyRelationId:
2953  return OCLASS_POLICY;
2954 
2955  case PublicationNamespaceRelationId:
2957 
2958  case PublicationRelationId:
2959  return OCLASS_PUBLICATION;
2960 
2961  case PublicationRelRelationId:
2962  return OCLASS_PUBLICATION_REL;
2963 
2964  case SubscriptionRelationId:
2965  return OCLASS_SUBSCRIPTION;
2966 
2967  case TransformRelationId:
2968  return OCLASS_TRANSFORM;
2969  }
2970 
2971  /* shouldn't get here */
2972  elog(ERROR, "unrecognized object class: %u", object->classId);
2973  return OCLASS_CLASS; /* keep compiler quiet */
2974 }

References ObjectAddress::classId, elog(), ERROR, ObjectAddressStack::object, ObjectAddress::objectSubId, OCLASS_AM, OCLASS_AMOP, OCLASS_AMPROC, OCLASS_CAST, OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_CONVERSION, OCLASS_DATABASE, OCLASS_DEFACL, OCLASS_DEFAULT, OCLASS_EVENT_TRIGGER, OCLASS_EXTENSION, OCLASS_FDW, OCLASS_FOREIGN_SERVER, OCLASS_LANGUAGE, OCLASS_LARGEOBJECT, OCLASS_OPCLASS, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_PARAMETER_ACL, OCLASS_POLICY, OCLASS_PROC, OCLASS_PUBLICATION, OCLASS_PUBLICATION_NAMESPACE, OCLASS_PUBLICATION_REL, OCLASS_REWRITE, OCLASS_ROLE, OCLASS_ROLE_MEMBERSHIP, OCLASS_SCHEMA, OCLASS_STATISTIC_EXT, OCLASS_SUBSCRIPTION, OCLASS_TBLSPACE, OCLASS_TRANSFORM, OCLASS_TRIGGER, OCLASS_TSCONFIG, OCLASS_TSDICT, OCLASS_TSPARSER, OCLASS_TSTEMPLATE, OCLASS_TYPE, and OCLASS_USER_MAPPING.

Referenced by AlterObjectNamespace_oid(), ATExecAlterColumnType(), deleteObjectsInList(), doDeletion(), EventTriggerSQLDropAddObject(), getObjectDescription(), getObjectIdentityParts(), and getObjectTypeDescription().

◆ new_object_addresses()

◆ object_address_comparator()

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

Definition at line 2482 of file dependency.c.

2483 {
2484  const ObjectAddress *obja = (const ObjectAddress *) a;
2485  const ObjectAddress *objb = (const ObjectAddress *) b;
2486 
2487  /*
2488  * Primary sort key is OID descending. Most of the time, this will result
2489  * in putting newer objects before older ones, which is likely to be the
2490  * right order to delete in.
2491  */
2492  if (obja->objectId > objb->objectId)
2493  return -1;
2494  if (obja->objectId < objb->objectId)
2495  return 1;
2496 
2497  /*
2498  * Next sort on catalog ID, in case identical OIDs appear in different
2499  * catalogs. Sort direction is pretty arbitrary here.
2500  */
2501  if (obja->classId < objb->classId)
2502  return -1;
2503  if (obja->classId > objb->classId)
2504  return 1;
2505 
2506  /*
2507  * Last, sort on object subId.
2508  *
2509  * We sort the subId as an unsigned int so that 0 (the whole object) will
2510  * come first. This is essential for eliminate_duplicate_dependencies,
2511  * and is also the best order for findDependentObjects.
2512  */
2513  if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
2514  return -1;
2515  if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
2516  return 1;
2517  return 0;
2518 }
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 2641 of file dependency.c.

2643 {
2644  int i;
2645 
2646  for (i = addrs->numrefs - 1; i >= 0; i--)
2647  {
2648  const ObjectAddress *thisobj = addrs->refs + i;
2649 
2650  if (object->classId == thisobj->classId &&
2651  object->objectId == thisobj->objectId)
2652  {
2653  if (object->objectSubId == thisobj->objectSubId ||
2654  thisobj->objectSubId == 0)
2655  return true;
2656  }
2657  }
2658 
2659  return false;
2660 }

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 2667 of file dependency.c.

2670 {
2671  bool result = false;
2672  int i;
2673 
2674  for (i = addrs->numrefs - 1; i >= 0; i--)
2675  {
2676  ObjectAddress *thisobj = addrs->refs + i;
2677 
2678  if (object->classId == thisobj->classId &&
2679  object->objectId == thisobj->objectId)
2680  {
2681  if (object->objectSubId == thisobj->objectSubId)
2682  {
2683  ObjectAddressExtra *thisextra = addrs->extras + i;
2684 
2685  thisextra->flags |= flags;
2686  result = true;
2687  }
2688  else if (thisobj->objectSubId == 0)
2689  {
2690  /*
2691  * We get here if we find a need to delete a column after
2692  * having already decided to drop its whole table. Obviously
2693  * we no longer need to drop the subobject, so report that we
2694  * found the subobject in the array. But don't plaster its
2695  * flags on the whole object.
2696  */
2697  result = true;
2698  }
2699  else if (object->objectSubId == 0)
2700  {
2701  /*
2702  * We get here if we find a need to delete a whole table after
2703  * having already decided to drop one of its columns. We
2704  * can't report that the whole object is in the array, but we
2705  * should mark the subobject with the whole object's flags.
2706  *
2707  * It might seem attractive to physically delete the column's
2708  * array entry, or at least mark it as no longer needing
2709  * separate deletion. But that could lead to, e.g., dropping
2710  * the column's datatype before we drop the table, which does
2711  * not seem like a good idea. This is a very rare situation
2712  * in practice, so we just take the hit of doing a separate
2713  * DROP COLUMN action even though we know we're gonna delete
2714  * the table later.
2715  *
2716  * What we can do, though, is mark this as a subobject so that
2717  * we don't report it separately, which is confusing because
2718  * it's unpredictable whether it happens or not. But do so
2719  * only if flags != 0 (flags == 0 is a read-only probe).
2720  *
2721  * Because there could be other subobjects of this object in
2722  * the array, this case means we always have to loop through
2723  * the whole array; we cannot exit early on a match.
2724  */
2725  ObjectAddressExtra *thisextra = addrs->extras + i;
2726 
2727  if (flags)
2728  thisextra->flags |= (flags | DEPFLAG_SUBOBJECT);
2729  }
2730  }
2731  }
2732 
2733  return result;
2734 }
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:110

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 322 of file dependency.c.

324 {
325  Relation depRel;
326  ObjectAddresses *targetObjects;
327 
328  /*
329  * We save some cycles by opening pg_depend just once and passing the
330  * Relation pointer down to all the recursive deletion steps.
331  */
332  depRel = table_open(DependRelationId, RowExclusiveLock);
333 
334  /*
335  * Acquire deletion lock on the target object. (Ideally the caller has
336  * done this already, but many places are sloppy about it.)
337  */
338  AcquireDeletionLock(object, 0);
339 
340  /*
341  * Construct a list of objects to delete (ie, the given object plus
342  * everything directly or indirectly dependent on it).
343  */
344  targetObjects = new_object_addresses();
345 
346  findDependentObjects(object,
348  flags,
349  NULL, /* empty stack */
350  targetObjects,
351  NULL, /* no pendingObjects */
352  &depRel);
353 
354  /*
355  * Check if deletion is allowed, and report about cascaded deletes.
356  */
357  reportDependentObjects(targetObjects,
358  behavior,
359  flags,
360  object);
361 
362  /* do the deed */
363  deleteObjectsInList(targetObjects, &depRel, flags);
364 
365  /* And clean up */
366  free_object_addresses(targetObjects);
367 
368  table_close(depRel, RowExclusiveLock);
369 }
static void reportDependentObjects(const ObjectAddresses *targetObjects, DropBehavior behavior, int flags, const ObjectAddress *origObject)
Definition: dependency.c:1023
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2526
static void deleteObjectsInList(ObjectAddresses *targetObjects, Relation *depRel, int flags)
Definition: dependency.c:234
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2821

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

Referenced by AlterDomainDropConstraint(), ATExecDropConstraint(), ATExecDropIdentity(), 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 381 of file dependency.c.

383 {
384  Relation depRel;
385  ObjectAddresses *targetObjects;
386  int i;
387 
388  /* No work if no objects... */
389  if (objects->numrefs <= 0)
390  return;
391 
392  /*
393  * We save some cycles by opening pg_depend just once and passing the
394  * Relation pointer down to all the recursive deletion steps.
395  */
396  depRel = table_open(DependRelationId, RowExclusiveLock);
397 
398  /*
399  * Construct a list of objects to delete (ie, the given objects plus
400  * everything directly or indirectly dependent on them). Note that
401  * because we pass the whole objects list as pendingObjects context, we
402  * won't get a failure from trying to delete an object that is internally
403  * dependent on another one in the list; we'll just skip that object and
404  * delete it when we reach its owner.
405  */
406  targetObjects = new_object_addresses();
407 
408  for (i = 0; i < objects->numrefs; i++)
409  {
410  const ObjectAddress *thisobj = objects->refs + i;
411 
412  /*
413  * Acquire deletion lock on each target object. (Ideally the caller
414  * has done this already, but many places are sloppy about it.)
415  */
416  AcquireDeletionLock(thisobj, flags);
417 
418  findDependentObjects(thisobj,
420  flags,
421  NULL, /* empty stack */
422  targetObjects,
423  objects,
424  &depRel);
425  }
426 
427  /*
428  * Check if deletion is allowed, and report about cascaded deletes.
429  *
430  * If there's exactly one object being deleted, report it the same way as
431  * in performDeletion(), else we have to be vaguer.
432  */
433  reportDependentObjects(targetObjects,
434  behavior,
435  flags,
436  (objects->numrefs == 1 ? objects->refs : NULL));
437 
438  /* do the deed */
439  deleteObjectsInList(targetObjects, &depRel, flags);
440 
441  /* And clean up */
442  free_object_addresses(targetObjects);
443 
444  table_close(depRel, RowExclusiveLock);
445 }

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 2364 of file dependency.c.

2366 {
2367  int atts_done = 0;
2368  ListCell *lc;
2369 
2370  /*
2371  * Identify which RangeTblFunction produces this attnum, and see if it
2372  * returns a composite type. If so, we'd better make a dependency on the
2373  * referenced column of the composite type (or actually, of its associated
2374  * relation).
2375  */
2376  foreach(lc, rte->functions)
2377  {
2378  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2379 
2380  if (attnum > atts_done &&
2381  attnum <= atts_done + rtfunc->funccolcount)
2382  {
2383  TupleDesc tupdesc;
2384 
2385  tupdesc = get_expr_result_tupdesc(rtfunc->funcexpr, true);
2386  if (tupdesc && tupdesc->tdtypeid != RECORDOID)
2387  {
2388  /*
2389  * Named composite type, so individual columns could get
2390  * dropped. Make a dependency on this specific column.
2391  */
2392  Oid reltype = get_typ_typrelid(tupdesc->tdtypeid);
2393 
2394  Assert(attnum - atts_done <= tupdesc->natts);
2395  if (OidIsValid(reltype)) /* can this fail? */
2397  attnum - atts_done,
2398  context->addrs);
2399  return;
2400  }
2401  /* Nothing to do; function's result type is handled elsewhere */
2402  return;
2403  }
2404  atts_done += rtfunc->funccolcount;
2405  }
2406 
2407  /* If we get here, must be looking for the ordinality column */
2408  if (rte->funcordinality && attnum == atts_done + 1)
2409  return;
2410 
2411  /* this probably can't happen ... */
2412  ereport(ERROR,
2413  (errcode(ERRCODE_UNDEFINED_COLUMN),
2414  errmsg("column %d of relation \"%s\" does not exist",
2415  attnum, rte->eref->aliasname)));
2416 }
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:543
int16 attnum
Definition: pg_attribute.h:83
char * aliasname
Definition: primnodes.h:42
bool funcordinality
Definition: parsenodes.h:1125
Alias * eref
Definition: parsenodes.h:1176
List * functions
Definition: parsenodes.h:1124
Oid tdtypeid
Definition: tupdesc.h:82

References add_object_address(), find_expr_references_context::addrs, Alias::aliasname, Assert(), attnum, RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, RangeTblFunction::funccolcount, RangeTblFunction::funcexpr, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_tupdesc(), get_typ_typrelid(), lfirst, OCLASS_CLASS, 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 2790 of file dependency.c.

2793 {
2795  recordMultipleDependencies(depender,
2796  referenced->refs, referenced->numrefs,
2797  behavior);
2798 }
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2422
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:56

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 1596 of file dependency.c.

1599 {
1601 
1602  context.addrs = new_object_addresses();
1603 
1604  /* Set up interpretation for Vars at varlevelsup = 0 */
1605  context.rtables = list_make1(rtable);
1606 
1607  /* Scan the expression tree for referenceable objects */
1608  find_expr_references_walker(expr, &context);
1609 
1610  /* Remove any duplicates */
1612 
1613  /* And record 'em */
1614  recordMultipleDependencies(depender,
1615  context.addrs->refs, context.addrs->numrefs,
1616  behavior);
1617 
1618  free_object_addresses(context.addrs);
1619 }
#define list_make1(x1)
Definition: pg_list.h:210

References find_expr_references_context::addrs, eliminate_duplicate_dependencies(), find_expr_references_walker(), free_object_addresses(), list_make1, new_object_addresses(), ObjectAddresses::numrefs, recordMultipleDependencies(), ObjectAddresses::refs, and find_expr_references_context::rtables.

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 1639 of file dependency.c.

1644 {
1646  RangeTblEntry rte = {0};
1647 
1648  context.addrs = new_object_addresses();
1649 
1650  /* We gin up a rather bogus rangetable list to handle Vars */
1651  rte.type = T_RangeTblEntry;
1652  rte.rtekind = RTE_RELATION;
1653  rte.relid = relId;
1654  rte.relkind = RELKIND_RELATION; /* no need for exactness here */
1656 
1657  context.rtables = list_make1(list_make1(&rte));
1658 
1659  /* Scan the expression tree for referenceable objects */
1660  find_expr_references_walker(expr, &context);
1661 
1662  /* Remove any duplicates */
1664 
1665  /* Separate self-dependencies if necessary */
1666  if ((behavior != self_behavior || reverse_self) &&
1667  context.addrs->numrefs > 0)
1668  {
1669  ObjectAddresses *self_addrs;
1670  ObjectAddress *outobj;
1671  int oldref,
1672  outrefs;
1673 
1674  self_addrs = new_object_addresses();
1675 
1676  outobj = context.addrs->refs;
1677  outrefs = 0;
1678  for (oldref = 0; oldref < context.addrs->numrefs; oldref++)
1679  {
1680  ObjectAddress *thisobj = context.addrs->refs + oldref;
1681 
1682  if (thisobj->classId == RelationRelationId &&
1683  thisobj->objectId == relId)
1684  {
1685  /* Move this ref into self_addrs */
1686  add_exact_object_address(thisobj, self_addrs);
1687  }
1688  else
1689  {
1690  /* Keep it in context.addrs */
1691  *outobj = *thisobj;
1692  outobj++;
1693  outrefs++;
1694  }
1695  }
1696  context.addrs->numrefs = outrefs;
1697 
1698  /* Record the self-dependencies with the appropriate direction */
1699  if (!reverse_self)
1700  recordMultipleDependencies(depender,
1701  self_addrs->refs, self_addrs->numrefs,
1702  self_behavior);
1703  else
1704  {
1705  /* Can't use recordMultipleDependencies, so do it the hard way */
1706  int selfref;
1707 
1708  for (selfref = 0; selfref < self_addrs->numrefs; selfref++)
1709  {
1710  ObjectAddress *thisobj = self_addrs->refs + selfref;
1711 
1712  recordDependencyOn(thisobj, depender, self_behavior);
1713  }
1714  }
1715 
1716  free_object_addresses(self_addrs);
1717  }
1718 
1719  /* Record the external dependencies */
1720  recordMultipleDependencies(depender,
1721  context.addrs->refs, context.addrs->numrefs,
1722  behavior);
1723 
1724  free_object_addresses(context.addrs);
1725 }
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2581
#define AccessShareLock
Definition: lockdefs.h:36
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44

References AccessShareLock, add_exact_object_address(), find_expr_references_context::addrs, ObjectAddress::classId, 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, RangeTblEntry::relkind, RangeTblEntry::rellockmode, find_expr_references_context::rtables, 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 1571 of file dependency.c.

1572 {
1573  if (object->classId == RelationRelationId)
1575  else
1576  /* assume we should lock the whole object not a sub-object */
1577  UnlockDatabaseObject(object->classId, object->objectId, 0,
1579 }
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:228
void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1026

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 1023 of file dependency.c.

1027 {
1028  int msglevel = (flags & PERFORM_DELETION_QUIETLY) ? DEBUG2 : NOTICE;
1029  bool ok = true;
1030  StringInfoData clientdetail;
1031  StringInfoData logdetail;
1032  int numReportedClient = 0;
1033  int numNotReportedClient = 0;
1034  int i;
1035 
1036  /*
1037  * If we need to delete any partition-dependent objects, make sure that
1038  * we're deleting at least one of their partition dependencies, too. That
1039  * can be detected by checking that we reached them by a PARTITION
1040  * dependency at some point.
1041  *
1042  * We just report the first such object, as in most cases the only way to
1043  * trigger this complaint is to explicitly try to delete one partition of
1044  * a partitioned object.
1045  */
1046  for (i = 0; i < targetObjects->numrefs; i++)
1047  {
1048  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1049 
1050  if ((extra->flags & DEPFLAG_IS_PART) &&
1051  !(extra->flags & DEPFLAG_PARTITION))
1052  {
1053  const ObjectAddress *object = &targetObjects->refs[i];
1054  char *otherObjDesc = getObjectDescription(&extra->dependee,
1055  false);
1056 
1057  ereport(ERROR,
1058  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1059  errmsg("cannot drop %s because %s requires it",
1060  getObjectDescription(object, false), otherObjDesc),
1061  errhint("You can drop %s instead.", otherObjDesc)));
1062  }
1063  }
1064 
1065  /*
1066  * If no error is to be thrown, and the msglevel is too low to be shown to
1067  * either client or server log, there's no need to do any of the rest of
1068  * the work.
1069  */
1070  if (behavior == DROP_CASCADE &&
1071  !message_level_is_interesting(msglevel))
1072  return;
1073 
1074  /*
1075  * We limit the number of dependencies reported to the client to
1076  * MAX_REPORTED_DEPS, since client software may not deal well with
1077  * enormous error strings. The server log always gets a full report.
1078  */
1079 #define MAX_REPORTED_DEPS 100
1080 
1081  initStringInfo(&clientdetail);
1082  initStringInfo(&logdetail);
1083 
1084  /*
1085  * We process the list back to front (ie, in dependency order not deletion
1086  * order), since this makes for a more understandable display.
1087  */
1088  for (i = targetObjects->numrefs - 1; i >= 0; i--)
1089  {
1090  const ObjectAddress *obj = &targetObjects->refs[i];
1091  const ObjectAddressExtra *extra = &targetObjects->extras[i];
1092  char *objDesc;
1093 
1094  /* Ignore the original deletion target(s) */
1095  if (extra->flags & DEPFLAG_ORIGINAL)
1096  continue;
1097 
1098  /* Also ignore sub-objects; we'll report the whole object elsewhere */
1099  if (extra->flags & DEPFLAG_SUBOBJECT)
1100  continue;
1101 
1102  objDesc = getObjectDescription(obj, false);
1103 
1104  /* An object being dropped concurrently doesn't need to be reported */
1105  if (objDesc == NULL)
1106  continue;
1107 
1108  /*
1109  * If, at any stage of the recursive search, we reached the object via
1110  * an AUTO, INTERNAL, PARTITION, or EXTENSION dependency, then it's
1111  * okay to delete it even in RESTRICT mode.
1112  */
1113  if (extra->flags & (DEPFLAG_AUTO |
1117  {
1118  /*
1119  * auto-cascades are reported at DEBUG2, not msglevel. We don't
1120  * try to combine them with the regular message because the
1121  * results are too confusing when client_min_messages and
1122  * log_min_messages are different.
1123  */
1124  ereport(DEBUG2,
1125  (errmsg_internal("drop auto-cascades to %s",
1126  objDesc)));
1127  }
1128  else if (behavior == DROP_RESTRICT)
1129  {
1130  char *otherDesc = getObjectDescription(&extra->dependee,
1131  false);
1132 
1133  if (otherDesc)
1134  {
1135  if (numReportedClient < MAX_REPORTED_DEPS)
1136  {
1137  /* separate entries with a newline */
1138  if (clientdetail.len != 0)
1139  appendStringInfoChar(&clientdetail, '\n');
1140  appendStringInfo(&clientdetail, _("%s depends on %s"),
1141  objDesc, otherDesc);
1142  numReportedClient++;
1143  }
1144  else
1145  numNotReportedClient++;
1146  /* separate entries with a newline */
1147  if (logdetail.len != 0)
1148  appendStringInfoChar(&logdetail, '\n');
1149  appendStringInfo(&logdetail, _("%s depends on %s"),
1150  objDesc, otherDesc);
1151  pfree(otherDesc);
1152  }
1153  else
1154  numNotReportedClient++;
1155  ok = false;
1156  }
1157  else
1158  {
1159  if (numReportedClient < MAX_REPORTED_DEPS)
1160  {
1161  /* separate entries with a newline */
1162  if (clientdetail.len != 0)
1163  appendStringInfoChar(&clientdetail, '\n');
1164  appendStringInfo(&clientdetail, _("drop cascades to %s"),
1165  objDesc);
1166  numReportedClient++;
1167  }
1168  else
1169  numNotReportedClient++;
1170  /* separate entries with a newline */
1171  if (logdetail.len != 0)
1172  appendStringInfoChar(&logdetail, '\n');
1173  appendStringInfo(&logdetail, _("drop cascades to %s"),
1174  objDesc);
1175  }
1176 
1177  pfree(objDesc);
1178  }
1179 
1180  if (numNotReportedClient > 0)
1181  appendStringInfo(&clientdetail, ngettext("\nand %d other object "
1182  "(see server log for list)",
1183  "\nand %d other objects "
1184  "(see server log for list)",
1185  numNotReportedClient),
1186  numNotReportedClient);
1187 
1188  if (!ok)
1189  {
1190  if (origObject)
1191  ereport(ERROR,
1192  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1193  errmsg("cannot drop %s because other objects depend on it",
1194  getObjectDescription(origObject, false)),
1195  errdetail_internal("%s", clientdetail.data),
1196  errdetail_log("%s", logdetail.data),
1197  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1198  else
1199  ereport(ERROR,
1200  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
1201  errmsg("cannot drop desired object(s) because other objects depend on them"),
1202  errdetail_internal("%s", clientdetail.data),
1203  errdetail_log("%s", logdetail.data),
1204  errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
1205  }
1206  else if (numReportedClient > 1)
1207  {
1208  ereport(msglevel,
1209  (errmsg_plural("drop cascades to %d other object",
1210  "drop cascades to %d other objects",
1211  numReportedClient + numNotReportedClient,
1212  numReportedClient + numNotReportedClient),
1213  errdetail_internal("%s", clientdetail.data),
1214  errdetail_log("%s", logdetail.data)));
1215  }
1216  else if (numReportedClient == 1)
1217  {
1218  /* we just use the single item as-is */
1219  ereport(msglevel,
1220  (errmsg_internal("%s", clientdetail.data)));
1221  }
1222 
1223  pfree(clientdetail.data);
1224  pfree(logdetail.data);
1225 }
#define ngettext(s, p, n)
Definition: c.h:1120
#define MAX_REPORTED_DEPS
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:138
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1016
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1066
bool message_level_is_interesting(int elevel)
Definition: elog.c:269
int errdetail_log(const char *fmt,...)
Definition: elog.c:1087
#define _(x)
Definition: elog.c:90
#define DEBUG2
Definition: elog.h:25
#define NOTICE
Definition: elog.h:31
@ DROP_CASCADE
Definition: parsenodes.h:1936
@ DROP_RESTRICT
Definition: parsenodes.h:1935
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
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 2809 of file dependency.c.

2810 {
2811  if (addrs->numrefs > 1)
2812  qsort((void *) addrs->refs, addrs->numrefs,
2813  sizeof(ObjectAddress),
2815 }

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 2740 of file dependency.c.

2743 {
2744  bool result = false;
2745  ObjectAddressStack *stackptr;
2746 
2747  for (stackptr = stack; stackptr; stackptr = stackptr->next)
2748  {
2749  const ObjectAddress *thisobj = stackptr->object;
2750 
2751  if (object->classId == thisobj->classId &&
2752  object->objectId == thisobj->objectId)
2753  {
2754  if (object->objectSubId == thisobj->objectSubId)
2755  {
2756  stackptr->flags |= flags;
2757  result = true;
2758  }
2759  else if (thisobj->objectSubId == 0)
2760  {
2761  /*
2762  * We're visiting a column with whole table already on stack.
2763  * As in object_address_present_add_flags(), we can skip
2764  * further processing of the subobject, but we don't want to
2765  * propagate flags for the subobject to the whole object.
2766  */
2767  result = true;
2768  }
2769  else if (object->objectSubId == 0)
2770  {
2771  /*
2772  * We're visiting a table with column already on stack. As in
2773  * object_address_present_add_flags(), we should propagate
2774  * flags for the whole object to each of its subobjects.
2775  */
2776  if (flags)
2777  stackptr->flags |= (flags | DEPFLAG_SUBOBJECT);
2778  }
2779  }
2780  }
2781 
2782  return result;
2783 }

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

Referenced by findDependentObjects().

Variable Documentation

◆ object_classes

const Oid object_classes[]
static

Definition at line 150 of file dependency.c.

Referenced by add_object_address().