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/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_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_policy.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_publication.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/proclang.h"
#include "commands/publicationcmds.h"
#include "commands/schemacmds.h"
#include "commands/seclabel.h"
#include "commands/sequence.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "nodes/nodeFuncs.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteRemove.h"
#include "storage/lmgr.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 void AcquireDeletionLock (const ObjectAddress *object, int flags)
 
static void ReleaseDeletionLock (const ObjectAddress *object)
 
static bool find_expr_references_walker (Node *node, find_expr_references_context *context)
 
static void eliminate_duplicate_dependencies (ObjectAddresses *addrs)
 
static int object_address_comparator (const void *a, const void *b)
 
static void 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 deleteOneObject (const ObjectAddress *object, Relation *depRel, int flags)
 
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 100 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_EXTENSION

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

Definition at line 103 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_INTERNAL

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

Definition at line 101 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_IS_PART

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

Definition at line 105 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_NORMAL

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

Definition at line 99 of file dependency.c.

Referenced by deleteObjectsInList(), and findDependentObjects().

◆ DEPFLAG_ORIGINAL

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

◆ DEPFLAG_PARTITION

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

Definition at line 102 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_REVERSE

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

Definition at line 104 of file dependency.c.

Referenced by deleteObjectsInList(), and findDependentObjects().

◆ DEPFLAG_SUBOBJECT

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

◆ MAX_REPORTED_DEPS

#define MAX_REPORTED_DEPS   100

Referenced by reportDependentObjects().

Typedef Documentation

◆ ObjectAddressStack

Function Documentation

◆ AcquireDeletionLock()

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

Definition at line 1534 of file dependency.c.

References AccessExclusiveLock, ObjectAddress::classId, LockDatabaseObject(), LockRelationOid(), ObjectAddress::objectId, PERFORM_DELETION_CONCURRENTLY, and ShareUpdateExclusiveLock.

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

1535 {
1536  if (object->classId == RelationRelationId)
1537  {
1538  /*
1539  * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1540  * the index for the moment. index_drop() will promote the lock once
1541  * it's safe to do so. In all other cases we need full exclusive
1542  * lock.
1543  */
1544  if (flags & PERFORM_DELETION_CONCURRENTLY)
1546  else
1548  }
1549  else
1550  {
1551  /* assume we should lock the whole object not a sub-object */
1552  LockDatabaseObject(object->classId, object->objectId, 0,
1554  }
1555 }
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:961
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define AccessExclusiveLock
Definition: lockdefs.h:45
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108

◆ add_exact_object_address()

void add_exact_object_address ( const ObjectAddress object,
ObjectAddresses addrs 
)

Definition at line 2435 of file dependency.c.

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

Referenced by AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterTypeNamespaceInternal(), ATExecDropColumn(), ATPostAlterTypeCleanup(), makeConfigurationDependencies(), PreCommit_on_commit_actions(), recordDependencyOnSingleRelExpr(), ReindexRelationConcurrently(), RemoveObjects(), RemoveRelations(), and shdepDropOwned().

2437 {
2438  ObjectAddress *item;
2439 
2440  /* enlarge array if needed */
2441  if (addrs->numrefs >= addrs->maxrefs)
2442  {
2443  addrs->maxrefs *= 2;
2444  addrs->refs = (ObjectAddress *)
2445  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2446  Assert(!addrs->extras);
2447  }
2448  /* record this item */
2449  item = addrs->refs + addrs->numrefs;
2450  *item = *object;
2451  addrs->numrefs++;
2452 }
ObjectAddress * refs
Definition: dependency.c:112
#define Assert(condition)
Definition: c.h:733
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
ObjectAddressExtra * extras
Definition: dependency.c:113

◆ add_exact_object_address_extra()

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

Definition at line 2460 of file dependency.c.

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

Referenced by findDependentObjects().

2463 {
2464  ObjectAddress *item;
2465  ObjectAddressExtra *itemextra;
2466 
2467  /* allocate extra space if first time */
2468  if (!addrs->extras)
2469  addrs->extras = (ObjectAddressExtra *)
2470  palloc(addrs->maxrefs * sizeof(ObjectAddressExtra));
2471 
2472  /* enlarge array if needed */
2473  if (addrs->numrefs >= addrs->maxrefs)
2474  {
2475  addrs->maxrefs *= 2;
2476  addrs->refs = (ObjectAddress *)
2477  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2478  addrs->extras = (ObjectAddressExtra *)
2479  repalloc(addrs->extras, addrs->maxrefs * sizeof(ObjectAddressExtra));
2480  }
2481  /* record this item */
2482  item = addrs->refs + addrs->numrefs;
2483  *item = *object;
2484  itemextra = addrs->extras + addrs->numrefs;
2485  *itemextra = *extra;
2486  addrs->numrefs++;
2487 }
ObjectAddress * refs
Definition: dependency.c:112
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
ObjectAddressExtra * extras
Definition: dependency.c:113
void * palloc(Size size)
Definition: mcxt.c:949

◆ add_object_address()

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

Definition at line 2402 of file dependency.c.

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().

2404 {
2405  ObjectAddress *item;
2406 
2407  /*
2408  * Make sure object_classes is kept up to date with the ObjectClass enum.
2409  */
2411  "object_classes[] must cover all ObjectClasses");
2412 
2413  /* enlarge array if needed */
2414  if (addrs->numrefs >= addrs->maxrefs)
2415  {
2416  addrs->maxrefs *= 2;
2417  addrs->refs = (ObjectAddress *)
2418  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2419  Assert(!addrs->extras);
2420  }
2421  /* record this item */
2422  item = addrs->refs + addrs->numrefs;
2423  item->classId = object_classes[oclass];
2424  item->objectId = objectId;
2425  item->objectSubId = subId;
2426  addrs->numrefs++;
2427 }
#define LAST_OCLASS
Definition: dependency.h:131
#define lengthof(array)
Definition: c.h:663
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:843
static const Oid object_classes[]
Definition: dependency.c:146
ObjectAddress * refs
Definition: dependency.c:112
#define Assert(condition)
Definition: c.h:733
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
ObjectAddressExtra * extras
Definition: dependency.c:113

◆ DeleteInitPrivs()

static void DeleteInitPrivs ( const ObjectAddress object)
static

Definition at line 2825 of file dependency.c.

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

Referenced by deleteOneObject().

2826 {
2827  Relation relation;
2828  ScanKeyData key[3];
2829  SysScanDesc scan;
2830  HeapTuple oldtuple;
2831 
2832  relation = table_open(InitPrivsRelationId, RowExclusiveLock);
2833 
2834  ScanKeyInit(&key[0],
2835  Anum_pg_init_privs_objoid,
2836  BTEqualStrategyNumber, F_OIDEQ,
2837  ObjectIdGetDatum(object->objectId));
2838  ScanKeyInit(&key[1],
2839  Anum_pg_init_privs_classoid,
2840  BTEqualStrategyNumber, F_OIDEQ,
2841  ObjectIdGetDatum(object->classId));
2842  ScanKeyInit(&key[2],
2843  Anum_pg_init_privs_objsubid,
2844  BTEqualStrategyNumber, F_INT4EQ,
2845  Int32GetDatum(object->objectSubId));
2846 
2847  scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
2848  NULL, 3, key);
2849 
2850  while (HeapTupleIsValid(oldtuple = systable_getnext(scan)))
2851  CatalogTupleDelete(relation, &oldtuple->t_self);
2852 
2853  systable_endscan(scan);
2854 
2855  table_close(relation, RowExclusiveLock);
2856 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:269
#define InitPrivsObjIndexId
Definition: indexing.h:176
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Int32GetDatum(X)
Definition: postgres.h:479
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ deleteObjectsInList()

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

Definition at line 227 of file dependency.c.

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

Referenced by performDeletion(), and performMultipleDeletions().

229 {
230  int i;
231 
232  /*
233  * Keep track of objects for event triggers, if necessary.
234  */
236  {
237  for (i = 0; i < targetObjects->numrefs; i++)
238  {
239  const ObjectAddress *thisobj = &targetObjects->refs[i];
240  const ObjectAddressExtra *extra = &targetObjects->extras[i];
241  bool original = false;
242  bool normal = false;
243 
244  if (extra->flags & DEPFLAG_ORIGINAL)
245  original = true;
246  if (extra->flags & DEPFLAG_NORMAL)
247  normal = true;
248  if (extra->flags & DEPFLAG_REVERSE)
249  normal = true;
250 
252  {
253  EventTriggerSQLDropAddObject(thisobj, original, normal);
254  }
255  }
256  }
257 
258  /*
259  * Delete all the objects in the proper order, except that if told to, we
260  * should skip the original object(s).
261  */
262  for (i = 0; i < targetObjects->numrefs; i++)
263  {
264  ObjectAddress *thisobj = targetObjects->refs + i;
265  ObjectAddressExtra *thisextra = targetObjects->extras + i;
266 
267  if ((flags & PERFORM_DELETION_SKIP_ORIGINAL) &&
268  (thisextra->flags & DEPFLAG_ORIGINAL))
269  continue;
270 
271  deleteOneObject(thisobj, depRel, flags);
272  }
273 }
static void deleteOneObject(const ObjectAddress *object, Relation *depRel, int32 flags)
bool trackDroppedObjectsNeeded(void)
#define PERFORM_DELETION_SKIP_ORIGINAL
Definition: dependency.h:137
#define DEPFLAG_REVERSE
Definition: dependency.c:104
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2690
#define DEPFLAG_ORIGINAL
Definition: dependency.c:98
ObjectAddress * refs
Definition: dependency.c:112
bool EventTriggerSupportsObjectClass(ObjectClass objclass)
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
ObjectAddressExtra * extras
Definition: dependency.c:113
#define DEPFLAG_NORMAL
Definition: dependency.c:99
int i
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134

◆ deleteOneObject() [1/2]

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

Referenced by deleteObjectsInList().

◆ deleteOneObject() [2/2]

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

Definition at line 1233 of file dependency.c.

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

1234 {
1235  ScanKeyData key[3];
1236  int nkeys;
1237  SysScanDesc scan;
1238  HeapTuple tup;
1239 
1240  /* DROP hook of the objects being removed */
1241  InvokeObjectDropHookArg(object->classId, object->objectId,
1242  object->objectSubId, flags);
1243 
1244  /*
1245  * Close depRel if we are doing a drop concurrently. The object deletion
1246  * subroutine will commit the current transaction, so we can't keep the
1247  * relation open across doDeletion().
1248  */
1249  if (flags & PERFORM_DELETION_CONCURRENTLY)
1250  table_close(*depRel, RowExclusiveLock);
1251 
1252  /*
1253  * Delete the object itself, in an object-type-dependent way.
1254  *
1255  * We used to do this after removing the outgoing dependency links, but it
1256  * seems just as reasonable to do it beforehand. In the concurrent case
1257  * we *must* do it in this order, because we can't make any transactional
1258  * updates before calling doDeletion() --- they'd get committed right
1259  * away, which is not cool if the deletion then fails.
1260  */
1261  doDeletion(object, flags);
1262 
1263  /*
1264  * Reopen depRel if we closed it above
1265  */
1266  if (flags & PERFORM_DELETION_CONCURRENTLY)
1267  *depRel = table_open(DependRelationId, RowExclusiveLock);
1268 
1269  /*
1270  * Now remove any pg_depend records that link from this object to others.
1271  * (Any records linking to this object should be gone already.)
1272  *
1273  * When dropping a whole object (subId = 0), remove all pg_depend records
1274  * for its sub-objects too.
1275  */
1276  ScanKeyInit(&key[0],
1277  Anum_pg_depend_classid,
1278  BTEqualStrategyNumber, F_OIDEQ,
1279  ObjectIdGetDatum(object->classId));
1280  ScanKeyInit(&key[1],
1281  Anum_pg_depend_objid,
1282  BTEqualStrategyNumber, F_OIDEQ,
1283  ObjectIdGetDatum(object->objectId));
1284  if (object->objectSubId != 0)
1285  {
1286  ScanKeyInit(&key[2],
1287  Anum_pg_depend_objsubid,
1288  BTEqualStrategyNumber, F_INT4EQ,
1289  Int32GetDatum(object->objectSubId));
1290  nkeys = 3;
1291  }
1292  else
1293  nkeys = 2;
1294 
1295  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
1296  NULL, nkeys, key);
1297 
1298  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1299  {
1300  CatalogTupleDelete(*depRel, &tup->t_self);
1301  }
1302 
1303  systable_endscan(scan);
1304 
1305  /*
1306  * Delete shared dependency references related to this object. Again, if
1307  * subId = 0, remove records for sub-objects too.
1308  */
1310  object->objectSubId);
1311 
1312 
1313  /*
1314  * Delete any comments, security labels, or initial privileges associated
1315  * with this object. (This is a convenient place to do these things,
1316  * rather than having every object type know to do it.)
1317  */
1318  DeleteComments(object->objectId, object->classId, object->objectSubId);
1319  DeleteSecurityLabel(object);
1320  DeleteInitPrivs(object);
1321 
1322  /*
1323  * CommandCounterIncrement here to ensure that preceding changes are all
1324  * visible to the next deletion step.
1325  */
1327 
1328  /*
1329  * And we're done!
1330  */
1331 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define DependDependerIndexId
Definition: indexing.h:149
void DeleteSecurityLabel(const ObjectAddress *object)
Definition: seclabel.c:446
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:269
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:907
void CommandCounterIncrement(void)
Definition: xact.c:1005
void DeleteComments(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:325
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void doDeletion(const ObjectAddress *object, int flags)
Definition: dependency.c:1337
#define Int32GetDatum(X)
Definition: postgres.h:479
static void DeleteInitPrivs(const ObjectAddress *object)
Definition: dependency.c:2825
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define InvokeObjectDropHookArg(classId, objectId, subId, dropflags)
Definition: objectaccess.h:156
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ doDeletion()

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

Definition at line 1337 of file dependency.c.

References Assert, DeleteSequenceTuple(), DropCastById(), DropProceduralLanguageById(), DropTransformById(), elog, ERROR, get_rel_relkind(), getObjectClass(), heap_drop_with_catalog(), index_drop(), LargeObjectDrop(), 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_POLICY, OCLASS_PROC, OCLASS_PUBLICATION, OCLASS_PUBLICATION_REL, OCLASS_REWRITE, OCLASS_ROLE, 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, RemoveAccessMethodById(), RemoveAmOpEntryById(), RemoveAmProcEntryById(), RemoveAttrDefaultById(), RemoveAttributeById(), RemoveCollationById(), RemoveConstraintById(), RemoveConversionById(), RemoveDefaultACLById(), RemoveEventTriggerById(), RemoveExtensionById(), RemoveForeignDataWrapperById(), RemoveForeignServerById(), RemoveFunctionById(), RemoveOpClassById(), RemoveOperatorById(), RemoveOpFamilyById(), RemovePolicyById(), RemovePublicationById(), RemovePublicationRelById(), RemoveRewriteRuleById(), RemoveSchemaById(), RemoveStatisticsById(), RemoveTriggerById(), RemoveTSConfigurationById(), RemoveTSDictionaryById(), RemoveTSParserById(), RemoveTSTemplateById(), RemoveTypeById(), and RemoveUserMappingById().

Referenced by deleteOneObject().

1338 {
1339  switch (getObjectClass(object))
1340  {
1341  case OCLASS_CLASS:
1342  {
1343  char relKind = get_rel_relkind(object->objectId);
1344 
1345  if (relKind == RELKIND_INDEX ||
1346  relKind == RELKIND_PARTITIONED_INDEX)
1347  {
1348  bool concurrent = ((flags & PERFORM_DELETION_CONCURRENTLY) != 0);
1349  bool concurrent_lock_mode = ((flags & PERFORM_DELETION_CONCURRENT_LOCK) != 0);
1350 
1351  Assert(object->objectSubId == 0);
1352  index_drop(object->objectId, concurrent, concurrent_lock_mode);
1353  }
1354  else
1355  {
1356  if (object->objectSubId != 0)
1357  RemoveAttributeById(object->objectId,
1358  object->objectSubId);
1359  else
1361  }
1362 
1363  /*
1364  * for a sequence, in addition to dropping the heap, also
1365  * delete pg_sequence tuple
1366  */
1367  if (relKind == RELKIND_SEQUENCE)
1368  DeleteSequenceTuple(object->objectId);
1369  break;
1370  }
1371 
1372  case OCLASS_PROC:
1373  RemoveFunctionById(object->objectId);
1374  break;
1375 
1376  case OCLASS_TYPE:
1377  RemoveTypeById(object->objectId);
1378  break;
1379 
1380  case OCLASS_CAST:
1381  DropCastById(object->objectId);
1382  break;
1383 
1384  case OCLASS_COLLATION:
1385  RemoveCollationById(object->objectId);
1386  break;
1387 
1388  case OCLASS_CONSTRAINT:
1389  RemoveConstraintById(object->objectId);
1390  break;
1391 
1392  case OCLASS_CONVERSION:
1393  RemoveConversionById(object->objectId);
1394  break;
1395 
1396  case OCLASS_DEFAULT:
1398  break;
1399 
1400  case OCLASS_LANGUAGE:
1402  break;
1403 
1404  case OCLASS_LARGEOBJECT:
1405  LargeObjectDrop(object->objectId);
1406  break;
1407 
1408  case OCLASS_OPERATOR:
1409  RemoveOperatorById(object->objectId);
1410  break;
1411 
1412  case OCLASS_OPCLASS:
1413  RemoveOpClassById(object->objectId);
1414  break;
1415 
1416  case OCLASS_OPFAMILY:
1417  RemoveOpFamilyById(object->objectId);
1418  break;
1419 
1420  case OCLASS_AM:
1422  break;
1423 
1424  case OCLASS_AMOP:
1425  RemoveAmOpEntryById(object->objectId);
1426  break;
1427 
1428  case OCLASS_AMPROC:
1430  break;
1431 
1432  case OCLASS_REWRITE:
1434  break;
1435 
1436  case OCLASS_TRIGGER:
1437  RemoveTriggerById(object->objectId);
1438  break;
1439 
1440  case OCLASS_SCHEMA:
1441  RemoveSchemaById(object->objectId);
1442  break;
1443 
1444  case OCLASS_STATISTIC_EXT:
1445  RemoveStatisticsById(object->objectId);
1446  break;
1447 
1448  case OCLASS_TSPARSER:
1449  RemoveTSParserById(object->objectId);
1450  break;
1451 
1452  case OCLASS_TSDICT:
1454  break;
1455 
1456  case OCLASS_TSTEMPLATE:
1457  RemoveTSTemplateById(object->objectId);
1458  break;
1459 
1460  case OCLASS_TSCONFIG:
1462  break;
1463 
1464  /*
1465  * OCLASS_ROLE, OCLASS_DATABASE, OCLASS_TBLSPACE intentionally not
1466  * handled here
1467  */
1468 
1469  case OCLASS_FDW:
1471  break;
1472 
1473  case OCLASS_FOREIGN_SERVER:
1475  break;
1476 
1477  case OCLASS_USER_MAPPING:
1479  break;
1480 
1481  case OCLASS_DEFACL:
1482  RemoveDefaultACLById(object->objectId);
1483  break;
1484 
1485  case OCLASS_EXTENSION:
1486  RemoveExtensionById(object->objectId);
1487  break;
1488 
1489  case OCLASS_EVENT_TRIGGER:
1491  break;
1492 
1493  case OCLASS_POLICY:
1494  RemovePolicyById(object->objectId);
1495  break;
1496 
1497  case OCLASS_PUBLICATION:
1499  break;
1500 
1503  break;
1504 
1505  case OCLASS_TRANSFORM:
1506  DropTransformById(object->objectId);
1507  break;
1508 
1509  /*
1510  * These global object types are not supported here.
1511  */
1512  case OCLASS_ROLE:
1513  case OCLASS_DATABASE:
1514  case OCLASS_TBLSPACE:
1515  case OCLASS_SUBSCRIPTION:
1516  elog(ERROR, "global objects cannot be deleted by doDeletion");
1517  break;
1518 
1519  /*
1520  * There's intentionally no default: case here; we want the
1521  * compiler to warn if a new OCLASS hasn't been handled above.
1522  */
1523  }
1524 }
void RemoveTriggerById(Oid trigOid)
Definition: trigger.c:1498
void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
Definition: index.c:2007
void RemoveStatisticsById(Oid statsOid)
Definition: statscmds.c:529
void RemoveOpClassById(Oid opclassOid)
Definition: opclasscmds.c:1622
void DropTransformById(Oid transformOid)
void RemoveExtensionById(Oid extId)
Definition: extension.c:1851
void DropProceduralLanguageById(Oid langOid)
Definition: proclang.c:534
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
void RemoveForeignDataWrapperById(Oid fdwId)
Definition: foreigncmds.c:842
void RemoveSchemaById(Oid schemaOid)
Definition: schemacmds.c:217
void RemovePublicationById(Oid pubid)
void RemovePublicationRelById(Oid proid)
void RemoveAmProcEntryById(Oid entryOid)
Definition: opclasscmds.c:1670
void RemoveTypeById(Oid typeOid)
Definition: typecmds.c:690
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2690
void RemoveCollationById(Oid collationOid)
Definition: pg_collation.c:214
void RemoveUserMappingById(Oid umId)
Definition: foreigncmds.c:1439
void RemoveConversionById(Oid conversionOid)
void RemoveAccessMethodById(Oid amOid)
Definition: amcmds.c:119
void RemoveOperatorById(Oid operOid)
Definition: operatorcmds.c:339
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:135
void RemoveDefaultACLById(Oid defaclOid)
Definition: aclchk.c:1530
#define ERROR
Definition: elog.h:43
void RemoveTSConfigurationById(Oid cfgId)
Definition: tsearchcmds.c:1131
void RemoveOpFamilyById(Oid opfamilyOid)
Definition: opclasscmds.c:1603
void RemovePolicyById(Oid policy_id)
Definition: policy.c:354
void RemoveTSParserById(Oid prsId)
Definition: tsearchcmds.c:295
void RemoveAttributeById(Oid relid, AttrNumber attnum)
Definition: heap.c:1579
void RemoveTSTemplateById(Oid tmplId)
Definition: tsearchcmds.c:824
void DeleteSequenceTuple(Oid relid)
Definition: sequence.c:526
void RemoveEventTriggerById(Oid trigOid)
void RemoveAttrDefaultById(Oid attrdefId)
Definition: heap.c:1747
void LargeObjectDrop(Oid loid)
void RemoveAmOpEntryById(Oid entryOid)
Definition: opclasscmds.c:1641
void RemoveForeignServerById(Oid srvId)
Definition: foreigncmds.c:1092
#define Assert(condition)
Definition: c.h:733
void RemoveFunctionById(Oid funcOid)
void RemoveRewriteRuleById(Oid ruleOid)
Definition: rewriteRemove.c:37
#define elog(elevel,...)
Definition: elog.h:228
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:139
void DropCastById(Oid castOid)
void heap_drop_with_catalog(Oid relid)
Definition: heap.c:1820
void RemoveConstraintById(Oid conId)
void RemoveTSDictionaryById(Oid dictId)
Definition: tsearchcmds.c:508

◆ eliminate_duplicate_dependencies()

static void eliminate_duplicate_dependencies ( ObjectAddresses addrs)
static

Definition at line 2276 of file dependency.c.

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().

2277 {
2278  ObjectAddress *priorobj;
2279  int oldref,
2280  newrefs;
2281 
2282  /*
2283  * We can't sort if the array has "extra" data, because there's no way to
2284  * keep it in sync. Fortunately that combination of features is not
2285  * needed.
2286  */
2287  Assert(!addrs->extras);
2288 
2289  if (addrs->numrefs <= 1)
2290  return; /* nothing to do */
2291 
2292  /* Sort the refs so that duplicates are adjacent */
2293  qsort((void *) addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
2295 
2296  /* Remove dups */
2297  priorobj = addrs->refs;
2298  newrefs = 1;
2299  for (oldref = 1; oldref < addrs->numrefs; oldref++)
2300  {
2301  ObjectAddress *thisobj = addrs->refs + oldref;
2302 
2303  if (priorobj->classId == thisobj->classId &&
2304  priorobj->objectId == thisobj->objectId)
2305  {
2306  if (priorobj->objectSubId == thisobj->objectSubId)
2307  continue; /* identical, so drop thisobj */
2308 
2309  /*
2310  * If we have a whole-object reference and a reference to a part
2311  * of the same object, we don't need the whole-object reference
2312  * (for example, we don't need to reference both table foo and
2313  * column foo.bar). The whole-object reference will always appear
2314  * first in the sorted list.
2315  */
2316  if (priorobj->objectSubId == 0)
2317  {
2318  /* replace whole ref with partial */
2319  priorobj->objectSubId = thisobj->objectSubId;
2320  continue;
2321  }
2322  }
2323  /* Not identical, so add thisobj to output set */
2324  priorobj++;
2325  *priorobj = *thisobj;
2326  newrefs++;
2327  }
2328 
2329  addrs->numrefs = newrefs;
2330 }
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2336
ObjectAddress * refs
Definition: dependency.c:112
#define Assert(condition)
Definition: c.h:733
ObjectAddressExtra * extras
Definition: dependency.c:113
#define qsort(a, b, c, d)
Definition: port.h:492

◆ find_expr_references_walker()

static bool find_expr_references_walker ( Node node,
find_expr_references_context context 
)
static

Definition at line 1738 of file dependency.c.

References add_object_address(), find_expr_references_context::addrs, Aggref::aggfnoid, FieldSelect::arg, CMD_INSERT, CMD_UPDATE, CollateExpr::collOid, Query::commandType, Const::constcollid, Const::constisnull, OnConflictExpr::constraint, Query::constraintDeps, Const::consttype, Const::constvalue, 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, WindowClause::inRangeColl, InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, lcons(), lfirst, lfirst_int, lfirst_oid, list_copy_tail(), list_delete_first(), list_free(), 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, PROCOID, QTW_EXAMINE_SORTGROUP, QTW_IGNORE_JOINALIASES, query_tree_walker(), 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_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().

1740 {
1741  if (node == NULL)
1742  return false;
1743  if (IsA(node, Var))
1744  {
1745  Var *var = (Var *) node;
1746  List *rtable;
1747  RangeTblEntry *rte;
1748 
1749  /* Find matching rtable entry, or complain if not found */
1750  if (var->varlevelsup >= list_length(context->rtables))
1751  elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
1752  rtable = (List *) list_nth(context->rtables, var->varlevelsup);
1753  if (var->varno <= 0 || var->varno > list_length(rtable))
1754  elog(ERROR, "invalid varno %d", var->varno);
1755  rte = rt_fetch(var->varno, rtable);
1756 
1757  /*
1758  * A whole-row Var references no specific columns, so adds no new
1759  * dependency. (We assume that there is a whole-table dependency
1760  * arising from each underlying rangetable entry. While we could
1761  * record such a dependency when finding a whole-row Var that
1762  * references a relation directly, it's quite unclear how to extend
1763  * that to whole-row Vars for JOINs, so it seems better to leave the
1764  * responsibility with the range table. Note that this poses some
1765  * risks for identifying dependencies of stand-alone expressions:
1766  * whole-table references may need to be created separately.)
1767  */
1768  if (var->varattno == InvalidAttrNumber)
1769  return false;
1770  if (rte->rtekind == RTE_RELATION)
1771  {
1772  /* If it's a plain relation, reference this column */
1774  context->addrs);
1775  }
1776  else if (rte->rtekind == RTE_JOIN)
1777  {
1778  /* Scan join output column to add references to join inputs */
1779  List *save_rtables;
1780 
1781  /* We must make the context appropriate for join's level */
1782  save_rtables = context->rtables;
1783  context->rtables = list_copy_tail(context->rtables,
1784  var->varlevelsup);
1785  if (var->varattno <= 0 ||
1786  var->varattno > list_length(rte->joinaliasvars))
1787  elog(ERROR, "invalid varattno %d", var->varattno);
1789  var->varattno - 1),
1790  context);
1791  list_free(context->rtables);
1792  context->rtables = save_rtables;
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 REGCONFIGOID:
1857  objoid = DatumGetObjectId(con->constvalue);
1859  ObjectIdGetDatum(objoid)))
1861  context->addrs);
1862  break;
1863  case REGDICTIONARYOID:
1864  objoid = DatumGetObjectId(con->constvalue);
1866  ObjectIdGetDatum(objoid)))
1867  add_object_address(OCLASS_TSDICT, objoid, 0,
1868  context->addrs);
1869  break;
1870 
1871  case REGNAMESPACEOID:
1872  objoid = DatumGetObjectId(con->constvalue);
1874  ObjectIdGetDatum(objoid)))
1875  add_object_address(OCLASS_SCHEMA, objoid, 0,
1876  context->addrs);
1877  break;
1878 
1879  /*
1880  * Dependencies for regrole should be shared among all
1881  * databases, so explicitly inhibit to have dependencies.
1882  */
1883  case REGROLEOID:
1884  ereport(ERROR,
1885  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1886  errmsg("constant of the type %s cannot be used here",
1887  "regrole")));
1888  break;
1889  }
1890  }
1891  return false;
1892  }
1893  else if (IsA(node, Param))
1894  {
1895  Param *param = (Param *) node;
1896 
1897  /* A parameter must depend on the parameter's datatype */
1899  context->addrs);
1900  /* and its collation, just as for Consts */
1901  if (OidIsValid(param->paramcollid) &&
1902  param->paramcollid != DEFAULT_COLLATION_OID)
1904  context->addrs);
1905  }
1906  else if (IsA(node, FuncExpr))
1907  {
1908  FuncExpr *funcexpr = (FuncExpr *) node;
1909 
1910  add_object_address(OCLASS_PROC, funcexpr->funcid, 0,
1911  context->addrs);
1912  /* fall through to examine arguments */
1913  }
1914  else if (IsA(node, OpExpr))
1915  {
1916  OpExpr *opexpr = (OpExpr *) node;
1917 
1919  context->addrs);
1920  /* fall through to examine arguments */
1921  }
1922  else if (IsA(node, DistinctExpr))
1923  {
1924  DistinctExpr *distinctexpr = (DistinctExpr *) node;
1925 
1926  add_object_address(OCLASS_OPERATOR, distinctexpr->opno, 0,
1927  context->addrs);
1928  /* fall through to examine arguments */
1929  }
1930  else if (IsA(node, NullIfExpr))
1931  {
1932  NullIfExpr *nullifexpr = (NullIfExpr *) node;
1933 
1934  add_object_address(OCLASS_OPERATOR, nullifexpr->opno, 0,
1935  context->addrs);
1936  /* fall through to examine arguments */
1937  }
1938  else if (IsA(node, ScalarArrayOpExpr))
1939  {
1940  ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
1941 
1943  context->addrs);
1944  /* fall through to examine arguments */
1945  }
1946  else if (IsA(node, Aggref))
1947  {
1948  Aggref *aggref = (Aggref *) node;
1949 
1951  context->addrs);
1952  /* fall through to examine arguments */
1953  }
1954  else if (IsA(node, WindowFunc))
1955  {
1956  WindowFunc *wfunc = (WindowFunc *) node;
1957 
1959  context->addrs);
1960  /* fall through to examine arguments */
1961  }
1962  else if (IsA(node, SubPlan))
1963  {
1964  /* Extra work needed here if we ever need this case */
1965  elog(ERROR, "already-planned subqueries not supported");
1966  }
1967  else if (IsA(node, FieldSelect))
1968  {
1969  FieldSelect *fselect = (FieldSelect *) node;
1970  Oid argtype = getBaseType(exprType((Node *) fselect->arg));
1971  Oid reltype = get_typ_typrelid(argtype);
1972 
1973  /*
1974  * We need a dependency on the specific column named in FieldSelect,
1975  * assuming we can identify the pg_class OID for it. (Probably we
1976  * always can at the moment, but in future it might be possible for
1977  * argtype to be RECORDOID.) If we can make a column dependency then
1978  * we shouldn't need a dependency on the column's type; but if we
1979  * can't, make a dependency on the type, as it might not appear
1980  * anywhere else in the expression.
1981  */
1982  if (OidIsValid(reltype))
1983  add_object_address(OCLASS_CLASS, reltype, fselect->fieldnum,
1984  context->addrs);
1985  else
1987  context->addrs);
1988  /* the collation might not be referenced anywhere else, either */
1989  if (OidIsValid(fselect->resultcollid) &&
1990  fselect->resultcollid != DEFAULT_COLLATION_OID)
1992  context->addrs);
1993  }
1994  else if (IsA(node, FieldStore))
1995  {
1996  FieldStore *fstore = (FieldStore *) node;
1997  Oid reltype = get_typ_typrelid(fstore->resulttype);
1998 
1999  /* similar considerations to FieldSelect, but multiple column(s) */
2000  if (OidIsValid(reltype))
2001  {
2002  ListCell *l;
2003 
2004  foreach(l, fstore->fieldnums)
2006  context->addrs);
2007  }
2008  else
2010  context->addrs);
2011  }
2012  else if (IsA(node, RelabelType))
2013  {
2014  RelabelType *relab = (RelabelType *) node;
2015 
2016  /* since there is no function dependency, need to depend on type */
2018  context->addrs);
2019  /* the collation might not be referenced anywhere else, either */
2020  if (OidIsValid(relab->resultcollid) &&
2021  relab->resultcollid != DEFAULT_COLLATION_OID)
2023  context->addrs);
2024  }
2025  else if (IsA(node, CoerceViaIO))
2026  {
2027  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2028 
2029  /* since there is no exposed function, need to depend on type */
2031  context->addrs);
2032  /* the collation might not be referenced anywhere else, either */
2033  if (OidIsValid(iocoerce->resultcollid) &&
2034  iocoerce->resultcollid != DEFAULT_COLLATION_OID)
2036  context->addrs);
2037  }
2038  else if (IsA(node, ArrayCoerceExpr))
2039  {
2040  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2041 
2042  /* as above, depend on type */
2044  context->addrs);
2045  /* the collation might not be referenced anywhere else, either */
2046  if (OidIsValid(acoerce->resultcollid) &&
2047  acoerce->resultcollid != DEFAULT_COLLATION_OID)
2049  context->addrs);
2050  /* fall through to examine arguments */
2051  }
2052  else if (IsA(node, ConvertRowtypeExpr))
2053  {
2054  ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
2055 
2056  /* since there is no function dependency, need to depend on type */
2058  context->addrs);
2059  }
2060  else if (IsA(node, CollateExpr))
2061  {
2062  CollateExpr *coll = (CollateExpr *) node;
2063 
2065  context->addrs);
2066  }
2067  else if (IsA(node, RowExpr))
2068  {
2069  RowExpr *rowexpr = (RowExpr *) node;
2070 
2072  context->addrs);
2073  }
2074  else if (IsA(node, RowCompareExpr))
2075  {
2076  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2077  ListCell *l;
2078 
2079  foreach(l, rcexpr->opnos)
2080  {
2082  context->addrs);
2083  }
2084  foreach(l, rcexpr->opfamilies)
2085  {
2087  context->addrs);
2088  }
2089  /* fall through to examine arguments */
2090  }
2091  else if (IsA(node, CoerceToDomain))
2092  {
2093  CoerceToDomain *cd = (CoerceToDomain *) node;
2094 
2096  context->addrs);
2097  }
2098  else if (IsA(node, NextValueExpr))
2099  {
2100  NextValueExpr *nve = (NextValueExpr *) node;
2101 
2103  context->addrs);
2104  }
2105  else if (IsA(node, OnConflictExpr))
2106  {
2107  OnConflictExpr *onconflict = (OnConflictExpr *) node;
2108 
2109  if (OidIsValid(onconflict->constraint))
2111  context->addrs);
2112  /* fall through to examine arguments */
2113  }
2114  else if (IsA(node, SortGroupClause))
2115  {
2116  SortGroupClause *sgc = (SortGroupClause *) node;
2117 
2119  context->addrs);
2120  if (OidIsValid(sgc->sortop))
2122  context->addrs);
2123  return false;
2124  }
2125  else if (IsA(node, WindowClause))
2126  {
2127  WindowClause *wc = (WindowClause *) node;
2128 
2129  if (OidIsValid(wc->startInRangeFunc))
2131  context->addrs);
2132  if (OidIsValid(wc->endInRangeFunc))
2134  context->addrs);
2135  if (OidIsValid(wc->inRangeColl) &&
2136  wc->inRangeColl != DEFAULT_COLLATION_OID)
2138  context->addrs);
2139  /* fall through to examine substructure */
2140  }
2141  else if (IsA(node, Query))
2142  {
2143  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2144  Query *query = (Query *) node;
2145  ListCell *lc;
2146  bool result;
2147 
2148  /*
2149  * Add whole-relation refs for each plain relation mentioned in the
2150  * subquery's rtable.
2151  *
2152  * Note: query_tree_walker takes care of recursing into RTE_FUNCTION
2153  * RTEs, subqueries, etc, so no need to do that here. But keep it
2154  * from looking at join alias lists.
2155  *
2156  * Note: we don't need to worry about collations mentioned in
2157  * RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
2158  * collations referenced in other parts of the Query. We do have to
2159  * worry about collations mentioned in RTE_FUNCTION, but we take care
2160  * of those when we recurse to the RangeTblFunction node(s).
2161  */
2162  foreach(lc, query->rtable)
2163  {
2164  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2165 
2166  switch (rte->rtekind)
2167  {
2168  case RTE_RELATION:
2170  context->addrs);
2171  break;
2172  default:
2173  break;
2174  }
2175  }
2176 
2177  /*
2178  * If the query is an INSERT or UPDATE, we should create a dependency
2179  * on each target column, to prevent the specific target column from
2180  * being dropped. Although we will visit the TargetEntry nodes again
2181  * during query_tree_walker, we won't have enough context to do this
2182  * conveniently, so do it here.
2183  */
2184  if (query->commandType == CMD_INSERT ||
2185  query->commandType == CMD_UPDATE)
2186  {
2187  RangeTblEntry *rte;
2188 
2189  if (query->resultRelation <= 0 ||
2190  query->resultRelation > list_length(query->rtable))
2191  elog(ERROR, "invalid resultRelation %d",
2192  query->resultRelation);
2193  rte = rt_fetch(query->resultRelation, query->rtable);
2194  if (rte->rtekind == RTE_RELATION)
2195  {
2196  foreach(lc, query->targetList)
2197  {
2198  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2199 
2200  if (tle->resjunk)
2201  continue; /* ignore junk tlist items */
2203  context->addrs);
2204  }
2205  }
2206  }
2207 
2208  /*
2209  * Add dependencies on constraints listed in query's constraintDeps
2210  */
2211  foreach(lc, query->constraintDeps)
2212  {
2214  context->addrs);
2215  }
2216 
2217  /* Examine substructure of query */
2218  context->rtables = lcons(query->rtable, context->rtables);
2219  result = query_tree_walker(query,
2221  (void *) context,
2224  context->rtables = list_delete_first(context->rtables);
2225  return result;
2226  }
2227  else if (IsA(node, SetOperationStmt))
2228  {
2229  SetOperationStmt *setop = (SetOperationStmt *) node;
2230 
2231  /* we need to look at the groupClauses for operator references */
2232  find_expr_references_walker((Node *) setop->groupClauses, context);
2233  /* fall through to examine child nodes */
2234  }
2235  else if (IsA(node, RangeTblFunction))
2236  {
2237  RangeTblFunction *rtfunc = (RangeTblFunction *) node;
2238  ListCell *ct;
2239 
2240  /*
2241  * Add refs for any datatypes and collations used in a column
2242  * definition list for a RECORD function. (For other cases, it should
2243  * be enough to depend on the function itself.)
2244  */
2245  foreach(ct, rtfunc->funccoltypes)
2246  {
2248  context->addrs);
2249  }
2250  foreach(ct, rtfunc->funccolcollations)
2251  {
2252  Oid collid = lfirst_oid(ct);
2253 
2254  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2256  context->addrs);
2257  }
2258  }
2259  else if (IsA(node, TableSampleClause))
2260  {
2261  TableSampleClause *tsc = (TableSampleClause *) node;
2262 
2264  context->addrs);
2265  /* fall through to examine arguments */
2266  }
2267 
2269  (void *) context);
2270 }
Datum constvalue
Definition: primnodes.h:200
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * joinaliasvars
Definition: parsenodes.h:1030
Index varlevelsup
Definition: primnodes.h:177
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1738
Oid resulttype
Definition: primnodes.h:750
ObjectAddresses * addrs
Definition: dependency.c:138
List * constraintDeps
Definition: parsenodes.h:168
#define DatumGetObjectId(X)
Definition: postgres.h:500
Oid resulttype
Definition: primnodes.h:821
#define QTW_EXAMINE_SORTGROUP
Definition: nodeFuncs.h:30
List * opfamilies
Definition: primnodes.h:1058
int resultRelation
Definition: parsenodes.h:122
Oid endInRangeFunc
Definition: parsenodes.h:1336
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
AttrNumber varattno
Definition: primnodes.h:172
Expr * arg
Definition: primnodes.h:748
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1423
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:167
#define OidIsValid(objectId)
Definition: c.h:639
List * targetList
Definition: parsenodes.h:140
Oid consttype
Definition: primnodes.h:196
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:183
Oid get_typ_typrelid(Oid typid)
Definition: lsyscache.c:2499
bool resjunk
Definition: primnodes.h:1400
List * rtable
Definition: parsenodes.h:137
Oid funcid
Definition: primnodes.h:455
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid paramcollid
Definition: primnodes.h:252
#define lfirst_int(lc)
Definition: pg_list.h:191
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
Oid constcollid
Definition: primnodes.h:198
Oid resultcollid
Definition: primnodes.h:753
AttrNumber resno
Definition: primnodes.h:1394
Oid resulttype
Definition: primnodes.h:780
Oid winfnoid
Definition: primnodes.h:359
#define ereport(elevel, rest)
Definition: elog.h:141
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Index varno
Definition: primnodes.h:170
Oid resultcollid
Definition: primnodes.h:823
Oid resulttype
Definition: primnodes.h:801
Oid resultcollid
Definition: primnodes.h:803
Oid aggfnoid
Definition: primnodes.h:298
CmdType commandType
Definition: parsenodes.h:112
List * lcons(void *datum, List *list)
Definition: list.c:454
List * funccolcollations
Definition: parsenodes.h:1131
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
Oid row_typeid
Definition: primnodes.h:1009
static int list_length(const List *l)
Definition: pg_list.h:169
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:974
int errmsg(const char *fmt,...)
Definition: elog.c:822
List * fieldnums
Definition: primnodes.h:779
void list_free(List *list)
Definition: list.c:1377
#define elog(elevel,...)
Definition: elog.h:228
Oid opno
Definition: primnodes.h:502
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
Definition: pg_list.h:50
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId, ObjectAddresses *addrs)
Definition: dependency.c:2402
Oid startInRangeFunc
Definition: parsenodes.h:1335
Oid paramtype
Definition: primnodes.h:250
bool constisnull
Definition: primnodes.h:201
#define lfirst_oid(lc)
Definition: pg_list.h:192
List * list_delete_first(List *list)
Definition: list.c:861
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:23
AttrNumber fieldnum
Definition: primnodes.h:749

◆ findDependentObjects()

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

Definition at line 474 of file dependency.c.

References AcquireDeletionLock(), add_exact_object_address_extra(), BTEqualStrategyNumber, ObjectAddress::classId, creating_extension, CurrentExtensionObject, DependDependerIndexId, ObjectAddressExtra::dependee, DEPENDENCY_AUTO, DEPENDENCY_AUTO_EXTENSION, DEPENDENCY_EXTENSION, DEPENDENCY_INTERNAL, DEPENDENCY_NORMAL, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, DEPENDENCY_PIN, DependReferenceIndexId, 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, 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().

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

◆ free_object_addresses()

void free_object_addresses ( ObjectAddresses addrs)

◆ getObjectClass()

ObjectClass getObjectClass ( const ObjectAddress object)

Definition at line 2690 of file dependency.c.

References ObjectAddress::classId, elog, ERROR, 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_POLICY, OCLASS_PROC, OCLASS_PUBLICATION, OCLASS_PUBLICATION_REL, OCLASS_REWRITE, OCLASS_ROLE, 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().

2691 {
2692  /* only pg_class entries can have nonzero objectSubId */
2693  if (object->classId != RelationRelationId &&
2694  object->objectSubId != 0)
2695  elog(ERROR, "invalid non-zero objectSubId for object class %u",
2696  object->classId);
2697 
2698  switch (object->classId)
2699  {
2700  case RelationRelationId:
2701  /* caller must check objectSubId */
2702  return OCLASS_CLASS;
2703 
2704  case ProcedureRelationId:
2705  return OCLASS_PROC;
2706 
2707  case TypeRelationId:
2708  return OCLASS_TYPE;
2709 
2710  case CastRelationId:
2711  return OCLASS_CAST;
2712 
2713  case CollationRelationId:
2714  return OCLASS_COLLATION;
2715 
2716  case ConstraintRelationId:
2717  return OCLASS_CONSTRAINT;
2718 
2719  case ConversionRelationId:
2720  return OCLASS_CONVERSION;
2721 
2722  case AttrDefaultRelationId:
2723  return OCLASS_DEFAULT;
2724 
2725  case LanguageRelationId:
2726  return OCLASS_LANGUAGE;
2727 
2728  case LargeObjectRelationId:
2729  return OCLASS_LARGEOBJECT;
2730 
2731  case OperatorRelationId:
2732  return OCLASS_OPERATOR;
2733 
2734  case OperatorClassRelationId:
2735  return OCLASS_OPCLASS;
2736 
2737  case OperatorFamilyRelationId:
2738  return OCLASS_OPFAMILY;
2739 
2740  case AccessMethodRelationId:
2741  return OCLASS_AM;
2742 
2743  case AccessMethodOperatorRelationId:
2744  return OCLASS_AMOP;
2745 
2746  case AccessMethodProcedureRelationId:
2747  return OCLASS_AMPROC;
2748 
2749  case RewriteRelationId:
2750  return OCLASS_REWRITE;
2751 
2752  case TriggerRelationId:
2753  return OCLASS_TRIGGER;
2754 
2755  case NamespaceRelationId:
2756  return OCLASS_SCHEMA;
2757 
2758  case StatisticExtRelationId:
2759  return OCLASS_STATISTIC_EXT;
2760 
2761  case TSParserRelationId:
2762  return OCLASS_TSPARSER;
2763 
2764  case TSDictionaryRelationId:
2765  return OCLASS_TSDICT;
2766 
2767  case TSTemplateRelationId:
2768  return OCLASS_TSTEMPLATE;
2769 
2770  case TSConfigRelationId:
2771  return OCLASS_TSCONFIG;
2772 
2773  case AuthIdRelationId:
2774  return OCLASS_ROLE;
2775 
2776  case DatabaseRelationId:
2777  return OCLASS_DATABASE;
2778 
2779  case TableSpaceRelationId:
2780  return OCLASS_TBLSPACE;
2781 
2782  case ForeignDataWrapperRelationId:
2783  return OCLASS_FDW;
2784 
2785  case ForeignServerRelationId:
2786  return OCLASS_FOREIGN_SERVER;
2787 
2788  case UserMappingRelationId:
2789  return OCLASS_USER_MAPPING;
2790 
2791  case DefaultAclRelationId:
2792  return OCLASS_DEFACL;
2793 
2794  case ExtensionRelationId:
2795  return OCLASS_EXTENSION;
2796 
2797  case EventTriggerRelationId:
2798  return OCLASS_EVENT_TRIGGER;
2799 
2800  case PolicyRelationId:
2801  return OCLASS_POLICY;
2802 
2803  case PublicationRelationId:
2804  return OCLASS_PUBLICATION;
2805 
2806  case PublicationRelRelationId:
2807  return OCLASS_PUBLICATION_REL;
2808 
2809  case SubscriptionRelationId:
2810  return OCLASS_SUBSCRIPTION;
2811 
2812  case TransformRelationId:
2813  return OCLASS_TRANSFORM;
2814  }
2815 
2816  /* shouldn't get here */
2817  elog(ERROR, "unrecognized object class: %u", object->classId);
2818  return OCLASS_CLASS; /* keep compiler quiet */
2819 }
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:228

◆ new_object_addresses()

ObjectAddresses* new_object_addresses ( void  )

◆ object_address_comparator()

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

Definition at line 2336 of file dependency.c.

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

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

2337 {
2338  const ObjectAddress *obja = (const ObjectAddress *) a;
2339  const ObjectAddress *objb = (const ObjectAddress *) b;
2340 
2341  /*
2342  * Primary sort key is OID descending. Most of the time, this will result
2343  * in putting newer objects before older ones, which is likely to be the
2344  * right order to delete in.
2345  */
2346  if (obja->objectId > objb->objectId)
2347  return -1;
2348  if (obja->objectId < objb->objectId)
2349  return 1;
2350 
2351  /*
2352  * Next sort on catalog ID, in case identical OIDs appear in different
2353  * catalogs. Sort direction is pretty arbitrary here.
2354  */
2355  if (obja->classId < objb->classId)
2356  return -1;
2357  if (obja->classId > objb->classId)
2358  return 1;
2359 
2360  /*
2361  * Last, sort on object subId.
2362  *
2363  * We sort the subId as an unsigned int so that 0 (the whole object) will
2364  * come first. This is essential for eliminate_duplicate_dependencies,
2365  * and is also the best order for findDependentObjects.
2366  */
2367  if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
2368  return -1;
2369  if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
2370  return 1;
2371  return 0;
2372 }

◆ object_address_present()

bool object_address_present ( const ObjectAddress object,
const ObjectAddresses addrs 
)

Definition at line 2495 of file dependency.c.

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

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

2497 {
2498  int i;
2499 
2500  for (i = addrs->numrefs - 1; i >= 0; i--)
2501  {
2502  const ObjectAddress *thisobj = addrs->refs + i;
2503 
2504  if (object->classId == thisobj->classId &&
2505  object->objectId == thisobj->objectId)
2506  {
2507  if (object->objectSubId == thisobj->objectSubId ||
2508  thisobj->objectSubId == 0)
2509  return true;
2510  }
2511  }
2512 
2513  return false;
2514 }
ObjectAddress * refs
Definition: dependency.c:112
int i

◆ object_address_present_add_flags()

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

Definition at line 2521 of file dependency.c.

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

Referenced by findDependentObjects().

2524 {
2525  bool result = false;
2526  int i;
2527 
2528  for (i = addrs->numrefs - 1; i >= 0; i--)
2529  {
2530  ObjectAddress *thisobj = addrs->refs + i;
2531 
2532  if (object->classId == thisobj->classId &&
2533  object->objectId == thisobj->objectId)
2534  {
2535  if (object->objectSubId == thisobj->objectSubId)
2536  {
2537  ObjectAddressExtra *thisextra = addrs->extras + i;
2538 
2539  thisextra->flags |= flags;
2540  result = true;
2541  }
2542  else if (thisobj->objectSubId == 0)
2543  {
2544  /*
2545  * We get here if we find a need to delete a column after
2546  * having already decided to drop its whole table. Obviously
2547  * we no longer need to drop the subobject, so report that we
2548  * found the subobject in the array. But don't plaster its
2549  * flags on the whole object.
2550  */
2551  result = true;
2552  }
2553  else if (object->objectSubId == 0)
2554  {
2555  /*
2556  * We get here if we find a need to delete a whole table after
2557  * having already decided to drop one of its columns. We
2558  * can't report that the whole object is in the array, but we
2559  * should mark the subobject with the whole object's flags.
2560  *
2561  * It might seem attractive to physically delete the column's
2562  * array entry, or at least mark it as no longer needing
2563  * separate deletion. But that could lead to, e.g., dropping
2564  * the column's datatype before we drop the table, which does
2565  * not seem like a good idea. This is a very rare situation
2566  * in practice, so we just take the hit of doing a separate
2567  * DROP COLUMN action even though we know we're gonna delete
2568  * the table later.
2569  *
2570  * What we can do, though, is mark this as a subobject so that
2571  * we don't report it separately, which is confusing because
2572  * it's unpredictable whether it happens or not. But do so
2573  * only if flags != 0 (flags == 0 is a read-only probe).
2574  *
2575  * Because there could be other subobjects of this object in
2576  * the array, this case means we always have to loop through
2577  * the whole array; we cannot exit early on a match.
2578  */
2579  ObjectAddressExtra *thisextra = addrs->extras + i;
2580 
2581  if (flags)
2582  thisextra->flags |= (flags | DEPFLAG_SUBOBJECT);
2583  }
2584  }
2585  }
2586 
2587  return result;
2588 }
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:106
ObjectAddress * refs
Definition: dependency.c:112
ObjectAddressExtra * extras
Definition: dependency.c:113
int i

◆ performDeletion()

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

Definition at line 315 of file dependency.c.

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

Referenced by AlterDomainDropConstraint(), ATExecDetachPartition(), ATExecDropConstraint(), ATExecDropIdentity(), DefineQueryRewrite(), do_autovacuum(), dropOperators(), dropProcedures(), finish_heap_swap(), inv_drop(), PublicationDropTables(), RemoveAttrDefault(), RemoveTempRelations(), RemoveUserMapping(), SetDefaultACL(), and tryAttachPartitionForeignKey().

317 {
318  Relation depRel;
319  ObjectAddresses *targetObjects;
320 
321  /*
322  * We save some cycles by opening pg_depend just once and passing the
323  * Relation pointer down to all the recursive deletion steps.
324  */
325  depRel = table_open(DependRelationId, RowExclusiveLock);
326 
327  /*
328  * Acquire deletion lock on the target object. (Ideally the caller has
329  * done this already, but many places are sloppy about it.)
330  */
331  AcquireDeletionLock(object, 0);
332 
333  /*
334  * Construct a list of objects to delete (ie, the given object plus
335  * everything directly or indirectly dependent on it).
336  */
337  targetObjects = new_object_addresses();
338 
339  findDependentObjects(object,
341  flags,
342  NULL, /* empty stack */
343  targetObjects,
344  NULL, /* no pendingObjects */
345  &depRel);
346 
347  /*
348  * Check if deletion is allowed, and report about cascaded deletes.
349  */
350  reportDependentObjects(targetObjects,
351  behavior,
352  flags,
353  object);
354 
355  /* do the deed */
356  deleteObjectsInList(targetObjects, &depRel, flags);
357 
358  /* And clean up */
359  free_object_addresses(targetObjects);
360 
361  table_close(depRel, RowExclusiveLock);
362 }
static void findDependentObjects(const ObjectAddress *object, int objflags, int flags, ObjectAddressStack *stack, ObjectAddresses *targetObjects, const ObjectAddresses *pendingObjects, Relation *depRel)
Definition: dependency.c:474
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2380
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2675
#define DEPFLAG_ORIGINAL
Definition: dependency.c:98
#define RowExclusiveLock
Definition: lockdefs.h:38
static void reportDependentObjects(const ObjectAddresses *targetObjects, DropBehavior behavior, int flags, const ObjectAddress *origObject)
Definition: dependency.c:1027
static void AcquireDeletionLock(const ObjectAddress *object, int flags)
Definition: dependency.c:1534
static void deleteObjectsInList(ObjectAddresses *targetObjects, Relation *depRel, int flags)
Definition: dependency.c:227
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ performMultipleDeletions()

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

Definition at line 374 of file dependency.c.

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

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

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

◆ record_object_address_dependencies()

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

Definition at line 2644 of file dependency.c.

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

Referenced by makeConfigurationDependencies().

2647 {
2649  recordMultipleDependencies(depender,
2650  referenced->refs, referenced->numrefs,
2651  behavior);
2652 }
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2276
ObjectAddress * refs
Definition: dependency.c:112
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:55

◆ recordDependencyOnExpr()

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

Definition at line 1586 of file dependency.c.

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(), CreateTrigger(), GenerateTypeDependencies(), InsertRule(), ProcedureCreate(), and RemoveRoleFromObjectPolicy().

1589 {
1591 
1592  context.addrs = new_object_addresses();
1593 
1594  /* Set up interpretation for Vars at varlevelsup = 0 */
1595  context.rtables = list_make1(rtable);
1596 
1597  /* Scan the expression tree for referenceable objects */
1598  find_expr_references_walker(expr, &context);
1599 
1600  /* Remove any duplicates */
1602 
1603  /* And record 'em */
1604  recordMultipleDependencies(depender,
1605  context.addrs->refs, context.addrs->numrefs,
1606  behavior);
1607 
1608  free_object_addresses(context.addrs);
1609 }
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1738
ObjectAddresses * addrs
Definition: dependency.c:138
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2380
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2675
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2276
#define list_make1(x1)
Definition: pg_list.h:227
ObjectAddress * refs
Definition: dependency.c:112
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:55

◆ recordDependencyOnSingleRelExpr()

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

Definition at line 1629 of file dependency.c.

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, MemSet, new_object_addresses(), ObjectAddresses::numrefs, ObjectAddress::objectId, recordDependencyOn(), recordMultipleDependencies(), ObjectAddresses::refs, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::rellockmode, find_expr_references_context::rtables, RTE_RELATION, RangeTblEntry::rtekind, T_RangeTblEntry, and RangeTblEntry::type.

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

1634 {
1636  RangeTblEntry rte;
1637 
1638  context.addrs = new_object_addresses();
1639 
1640  /* We gin up a rather bogus rangetable list to handle Vars */
1641  MemSet(&rte, 0, sizeof(rte));
1642  rte.type = T_RangeTblEntry;
1643  rte.rtekind = RTE_RELATION;
1644  rte.relid = relId;
1645  rte.relkind = RELKIND_RELATION; /* no need for exactness here */
1647 
1648  context.rtables = list_make1(list_make1(&rte));
1649 
1650  /* Scan the expression tree for referenceable objects */
1651  find_expr_references_walker(expr, &context);
1652 
1653  /* Remove any duplicates */
1655 
1656  /* Separate self-dependencies if necessary */
1657  if ((behavior != self_behavior || reverse_self) &&
1658  context.addrs->numrefs > 0)
1659  {
1660  ObjectAddresses *self_addrs;
1661  ObjectAddress *outobj;
1662  int oldref,
1663  outrefs;
1664 
1665  self_addrs = new_object_addresses();
1666 
1667  outobj = context.addrs->refs;
1668  outrefs = 0;
1669  for (oldref = 0; oldref < context.addrs->numrefs; oldref++)
1670  {
1671  ObjectAddress *thisobj = context.addrs->refs + oldref;
1672 
1673  if (thisobj->classId == RelationRelationId &&
1674  thisobj->objectId == relId)
1675  {
1676  /* Move this ref into self_addrs */
1677  add_exact_object_address(thisobj, self_addrs);
1678  }
1679  else
1680  {
1681  /* Keep it in context.addrs */
1682  *outobj = *thisobj;
1683  outobj++;
1684  outrefs++;
1685  }
1686  }
1687  context.addrs->numrefs = outrefs;
1688 
1689  /* Record the self-dependencies with the appropriate direction */
1690  if (!reverse_self)
1691  recordMultipleDependencies(depender,
1692  self_addrs->refs, self_addrs->numrefs,
1693  self_behavior);
1694  else
1695  {
1696  /* Can't use recordMultipleDependencies, so do it the hard way */
1697  int selfref;
1698 
1699  for (selfref = 0; selfref < self_addrs->numrefs; selfref++)
1700  {
1701  ObjectAddress *thisobj = self_addrs->refs + selfref;
1702 
1703  recordDependencyOn(thisobj, depender, self_behavior);
1704  }
1705  }
1706 
1707  free_object_addresses(self_addrs);
1708  }
1709 
1710  /* Record the external dependencies */
1711  recordMultipleDependencies(depender,
1712  context.addrs->refs, context.addrs->numrefs,
1713  behavior);
1714 
1715  free_object_addresses(context.addrs);
1716 }
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1738
ObjectAddresses * addrs
Definition: dependency.c:138
#define AccessShareLock
Definition: lockdefs.h:36
#define MemSet(start, val, len)
Definition: c.h:956
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2435
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2380
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2675
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2276
#define list_make1(x1)
Definition: pg_list.h:227
ObjectAddress * refs
Definition: dependency.c:112
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:55
RTEKind rtekind
Definition: parsenodes.h:974
NodeTag type
Definition: parsenodes.h:972

◆ ReleaseDeletionLock()

static void ReleaseDeletionLock ( const ObjectAddress object)
static

Definition at line 1561 of file dependency.c.

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

Referenced by findDependentObjects().

1562 {
1563  if (object->classId == RelationRelationId)
1565  else
1566  /* assume we should lock the whole object not a sub-object */
1567  UnlockDatabaseObject(object->classId, object->objectId, 0,
1569 }
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:199
void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:982
#define AccessExclusiveLock
Definition: lockdefs.h:45

◆ reportDependentObjects()

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

Definition at line 1027 of file dependency.c.

References _, appendStringInfo(), appendStringInfoChar(), client_min_messages, 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(), errdetail_log(), errhint(), errmsg(), errmsg_internal(), errmsg_plural(), ERROR, ObjectAddresses::extras, ObjectAddressExtra::flags, getObjectDescription(), i, initStringInfo(), StringInfoData::len, LOG, log_min_messages, MAX_REPORTED_DEPS, ngettext, NOTICE, ObjectAddresses::numrefs, PERFORM_DELETION_QUIETLY, pfree(), and ObjectAddresses::refs.

Referenced by performDeletion(), and performMultipleDeletions().

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

◆ sort_object_addresses()

void sort_object_addresses ( ObjectAddresses addrs)

Definition at line 2663 of file dependency.c.

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

Referenced by shdepDropOwned().

2664 {
2665  if (addrs->numrefs > 1)
2666  qsort((void *) addrs->refs, addrs->numrefs,
2667  sizeof(ObjectAddress),
2669 }
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2336
ObjectAddress * refs
Definition: dependency.c:112
#define qsort(a, b, c, d)
Definition: port.h:492

◆ stack_address_present_add_flags()

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

Definition at line 2594 of file dependency.c.

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

Referenced by findDependentObjects().

2597 {
2598  bool result = false;
2599  ObjectAddressStack *stackptr;
2600 
2601  for (stackptr = stack; stackptr; stackptr = stackptr->next)
2602  {
2603  const ObjectAddress *thisobj = stackptr->object;
2604 
2605  if (object->classId == thisobj->classId &&
2606  object->objectId == thisobj->objectId)
2607  {
2608  if (object->objectSubId == thisobj->objectSubId)
2609  {
2610  stackptr->flags |= flags;
2611  result = true;
2612  }
2613  else if (thisobj->objectSubId == 0)
2614  {
2615  /*
2616  * We're visiting a column with whole table already on stack.
2617  * As in object_address_present_add_flags(), we can skip
2618  * further processing of the subobject, but we don't want to
2619  * propagate flags for the subobject to the whole object.
2620  */
2621  result = true;
2622  }
2623  else if (object->objectSubId == 0)
2624  {
2625  /*
2626  * We're visiting a table with column already on stack. As in
2627  * object_address_present_add_flags(), we should propagate
2628  * flags for the whole object to each of its subobjects.
2629  */
2630  if (flags)
2631  stackptr->flags |= (flags | DEPFLAG_SUBOBJECT);
2632  }
2633  }
2634  }
2635 
2636  return result;
2637 }
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:106
struct ObjectAddressStack * next
Definition: dependency.c:125
const ObjectAddress * object
Definition: dependency.c:123

Variable Documentation

◆ object_classes

const Oid object_classes[]
static

Definition at line 146 of file dependency.c.

Referenced by add_object_address().