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/acl.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
Include dependency graph for dependency.c:

Go to the source code of this file.

Data Structures

struct  ObjectAddressExtra
 
struct  ObjectAddresses
 
struct  ObjectAddressStack
 
struct  ObjectAddressAndFlags
 
struct  find_expr_references_context
 

Macros

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

Typedefs

typedef struct ObjectAddressStack ObjectAddressStack
 

Functions

static void findDependentObjects (const ObjectAddress *object, int objflags, int flags, ObjectAddressStack *stack, ObjectAddresses *targetObjects, const ObjectAddresses *pendingObjects, Relation *depRel)
 
static void reportDependentObjects (const ObjectAddresses *targetObjects, DropBehavior behavior, int flags, const ObjectAddress *origObject)
 
static void deleteOneObject (const ObjectAddress *object, Relation *depRel, int32 flags)
 
static void doDeletion (const ObjectAddress *object, int flags)
 
static bool find_expr_references_walker (Node *node, find_expr_references_context *context)
 
static void 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 AcquireDeletionLock (const ObjectAddress *object, int flags)
 
void ReleaseDeletionLock (const ObjectAddress *object)
 
void recordDependencyOnExpr (const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
 
void recordDependencyOnSingleRelExpr (const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self)
 
ObjectAddressesnew_object_addresses (void)
 
void add_exact_object_address (const ObjectAddress *object, ObjectAddresses *addrs)
 
bool object_address_present (const ObjectAddress *object, const ObjectAddresses *addrs)
 
void record_object_address_dependencies (const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
 
void sort_object_addresses (ObjectAddresses *addrs)
 
void free_object_addresses (ObjectAddresses *addrs)
 
ObjectClass getObjectClass (const ObjectAddress *object)
 

Variables

static const Oid object_classes []
 

Macro Definition Documentation

◆ DEPFLAG_AUTO

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

Definition at line 101 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_EXTENSION

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

Definition at line 104 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_INTERNAL

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

Definition at line 102 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_IS_PART

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

Definition at line 106 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_NORMAL

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

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

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_REVERSE

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

Definition at line 105 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()

void AcquireDeletionLock ( const ObjectAddress object,
int  flags 
)

Definition at line 1536 of file dependency.c.

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

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

1537 {
1538  if (object->classId == RelationRelationId)
1539  {
1540  /*
1541  * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1542  * the index for the moment. index_drop() will promote the lock once
1543  * it's safe to do so. In all other cases we need full exclusive
1544  * lock.
1545  */
1546  if (flags & PERFORM_DELETION_CONCURRENTLY)
1548  else
1550  }
1551  else
1552  {
1553  /* assume we should lock the whole object not a sub-object */
1554  LockDatabaseObject(object->classId, object->objectId, 0,
1556  }
1557 }
#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 2473 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(), DropClonedTriggersFromPartition(), makeConfigurationDependencies(), PreCommit_on_commit_actions(), recordDependencyOnSingleRelExpr(), ReindexRelationConcurrently(), RemoveObjects(), RemoveRelations(), and shdepDropOwned().

2475 {
2476  ObjectAddress *item;
2477 
2478  /* enlarge array if needed */
2479  if (addrs->numrefs >= addrs->maxrefs)
2480  {
2481  addrs->maxrefs *= 2;
2482  addrs->refs = (ObjectAddress *)
2483  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2484  Assert(!addrs->extras);
2485  }
2486  /* record this item */
2487  item = addrs->refs + addrs->numrefs;
2488  *item = *object;
2489  addrs->numrefs++;
2490 }
ObjectAddress * refs
Definition: dependency.c:113
#define Assert(condition)
Definition: c.h:738
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
ObjectAddressExtra * extras
Definition: dependency.c:114

◆ add_exact_object_address_extra()

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

Definition at line 2498 of file dependency.c.

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

Referenced by findDependentObjects().

2501 {
2502  ObjectAddress *item;
2503  ObjectAddressExtra *itemextra;
2504 
2505  /* allocate extra space if first time */
2506  if (!addrs->extras)
2507  addrs->extras = (ObjectAddressExtra *)
2508  palloc(addrs->maxrefs * sizeof(ObjectAddressExtra));
2509 
2510  /* enlarge array if needed */
2511  if (addrs->numrefs >= addrs->maxrefs)
2512  {
2513  addrs->maxrefs *= 2;
2514  addrs->refs = (ObjectAddress *)
2515  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2516  addrs->extras = (ObjectAddressExtra *)
2517  repalloc(addrs->extras, addrs->maxrefs * sizeof(ObjectAddressExtra));
2518  }
2519  /* record this item */
2520  item = addrs->refs + addrs->numrefs;
2521  *item = *object;
2522  itemextra = addrs->extras + addrs->numrefs;
2523  *itemextra = *extra;
2524  addrs->numrefs++;
2525 }
ObjectAddress * refs
Definition: dependency.c:113
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
ObjectAddressExtra * extras
Definition: dependency.c:114
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 2440 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().

2442 {
2443  ObjectAddress *item;
2444 
2445  /*
2446  * Make sure object_classes is kept up to date with the ObjectClass enum.
2447  */
2449  "object_classes[] must cover all ObjectClasses");
2450 
2451  /* enlarge array if needed */
2452  if (addrs->numrefs >= addrs->maxrefs)
2453  {
2454  addrs->maxrefs *= 2;
2455  addrs->refs = (ObjectAddress *)
2456  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2457  Assert(!addrs->extras);
2458  }
2459  /* record this item */
2460  item = addrs->refs + addrs->numrefs;
2461  item->classId = object_classes[oclass];
2462  item->objectId = objectId;
2463  item->objectSubId = subId;
2464  addrs->numrefs++;
2465 }
#define LAST_OCLASS
Definition: dependency.h:131
#define lengthof(array)
Definition: c.h:668
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:852
static const Oid object_classes[]
Definition: dependency.c:147
ObjectAddress * refs
Definition: dependency.c:113
#define Assert(condition)
Definition: c.h:738
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
ObjectAddressExtra * extras
Definition: dependency.c:114

◆ DeleteInitPrivs()

static void DeleteInitPrivs ( const ObjectAddress object)
static

Definition at line 2863 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().

2864 {
2865  Relation relation;
2866  ScanKeyData key[3];
2867  SysScanDesc scan;
2868  HeapTuple oldtuple;
2869 
2870  relation = table_open(InitPrivsRelationId, RowExclusiveLock);
2871 
2872  ScanKeyInit(&key[0],
2873  Anum_pg_init_privs_objoid,
2874  BTEqualStrategyNumber, F_OIDEQ,
2875  ObjectIdGetDatum(object->objectId));
2876  ScanKeyInit(&key[1],
2877  Anum_pg_init_privs_classoid,
2878  BTEqualStrategyNumber, F_OIDEQ,
2879  ObjectIdGetDatum(object->classId));
2880  ScanKeyInit(&key[2],
2881  Anum_pg_init_privs_objsubid,
2882  BTEqualStrategyNumber, F_INT4EQ,
2883  Int32GetDatum(object->objectSubId));
2884 
2885  scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
2886  NULL, 3, key);
2887 
2888  while (HeapTupleIsValid(oldtuple = systable_getnext(scan)))
2889  CatalogTupleDelete(relation, &oldtuple->t_self);
2890 
2891  systable_endscan(scan);
2892 
2893  table_close(relation, RowExclusiveLock);
2894 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:529
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:356
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:448
#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 226 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().

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

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

◆ doDeletion()

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

Definition at line 1336 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().

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

◆ eliminate_duplicate_dependencies()

static void eliminate_duplicate_dependencies ( ObjectAddresses addrs)
static

Definition at line 2314 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().

2315 {
2316  ObjectAddress *priorobj;
2317  int oldref,
2318  newrefs;
2319 
2320  /*
2321  * We can't sort if the array has "extra" data, because there's no way to
2322  * keep it in sync. Fortunately that combination of features is not
2323  * needed.
2324  */
2325  Assert(!addrs->extras);
2326 
2327  if (addrs->numrefs <= 1)
2328  return; /* nothing to do */
2329 
2330  /* Sort the refs so that duplicates are adjacent */
2331  qsort((void *) addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
2333 
2334  /* Remove dups */
2335  priorobj = addrs->refs;
2336  newrefs = 1;
2337  for (oldref = 1; oldref < addrs->numrefs; oldref++)
2338  {
2339  ObjectAddress *thisobj = addrs->refs + oldref;
2340 
2341  if (priorobj->classId == thisobj->classId &&
2342  priorobj->objectId == thisobj->objectId)
2343  {
2344  if (priorobj->objectSubId == thisobj->objectSubId)
2345  continue; /* identical, so drop thisobj */
2346 
2347  /*
2348  * If we have a whole-object reference and a reference to a part
2349  * of the same object, we don't need the whole-object reference
2350  * (for example, we don't need to reference both table foo and
2351  * column foo.bar). The whole-object reference will always appear
2352  * first in the sorted list.
2353  */
2354  if (priorobj->objectSubId == 0)
2355  {
2356  /* replace whole ref with partial */
2357  priorobj->objectSubId = thisobj->objectSubId;
2358  continue;
2359  }
2360  }
2361  /* Not identical, so add thisobj to output set */
2362  priorobj++;
2363  *priorobj = *thisobj;
2364  newrefs++;
2365  }
2366 
2367  addrs->numrefs = newrefs;
2368 }
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2374
ObjectAddress * refs
Definition: dependency.c:113
#define Assert(condition)
Definition: c.h:738
ObjectAddressExtra * extras
Definition: dependency.c:114
#define qsort(a, b, c, d)
Definition: port.h:479

◆ find_expr_references_walker()

static bool find_expr_references_walker ( Node node,
find_expr_references_context context 
)
static

Definition at line 1736 of file dependency.c.

References add_object_address(), find_expr_references_context::addrs, Aggref::aggfnoid, FieldSelect::arg, CMD_INSERT, CMD_UPDATE, TableFunc::colcollations, CollateExpr::collOid, TableFunc::coltypes, 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, i, WindowClause::inRangeColl, InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, RangeTblEntry::joinmergedcols, lcons(), lfirst, lfirst_int, lfirst_oid, list_delete_first(), list_length(), list_nth(), NAMESPACEOID, ObjectIdGetDatum, OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_PROC, OCLASS_SCHEMA, OCLASS_TSCONFIG, OCLASS_TSDICT, OCLASS_TYPE, OidIsValid, OPEROID, RowCompareExpr::opfamilies, OpExpr::opno, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, Param::paramcollid, Param::paramtype, 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().

1738 {
1739  if (node == NULL)
1740  return false;
1741  if (IsA(node, Var))
1742  {
1743  Var *var = (Var *) node;
1744  List *rtable;
1745  RangeTblEntry *rte;
1746 
1747  /* Find matching rtable entry, or complain if not found */
1748  if (var->varlevelsup >= list_length(context->rtables))
1749  elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
1750  rtable = (List *) list_nth(context->rtables, var->varlevelsup);
1751  if (var->varno <= 0 || var->varno > list_length(rtable))
1752  elog(ERROR, "invalid varno %d", var->varno);
1753  rte = rt_fetch(var->varno, rtable);
1754 
1755  /*
1756  * A whole-row Var references no specific columns, so adds no new
1757  * dependency. (We assume that there is a whole-table dependency
1758  * arising from each underlying rangetable entry. While we could
1759  * record such a dependency when finding a whole-row Var that
1760  * references a relation directly, it's quite unclear how to extend
1761  * that to whole-row Vars for JOINs, so it seems better to leave the
1762  * responsibility with the range table. Note that this poses some
1763  * risks for identifying dependencies of stand-alone expressions:
1764  * whole-table references may need to be created separately.)
1765  */
1766  if (var->varattno == InvalidAttrNumber)
1767  return false;
1768  if (rte->rtekind == RTE_RELATION)
1769  {
1770  /* If it's a plain relation, reference this column */
1772  context->addrs);
1773  }
1774 
1775  /*
1776  * Vars referencing other RTE types require no additional work. In
1777  * particular, a join alias Var can be ignored, because it must
1778  * reference a merged USING column. The relevant join input columns
1779  * will also be referenced in the join qual, and any type coercion
1780  * functions involved in the alias expression will be dealt with when
1781  * we scan the RTE itself.
1782  */
1783  return false;
1784  }
1785  else if (IsA(node, Const))
1786  {
1787  Const *con = (Const *) node;
1788  Oid objoid;
1789 
1790  /* A constant must depend on the constant's datatype */
1792  context->addrs);
1793 
1794  /*
1795  * We must also depend on the constant's collation: it could be
1796  * different from the datatype's, if a CollateExpr was const-folded to
1797  * a simple constant. However we can save work in the most common
1798  * case where the collation is "default", since we know that's pinned.
1799  */
1800  if (OidIsValid(con->constcollid) &&
1801  con->constcollid != DEFAULT_COLLATION_OID)
1803  context->addrs);
1804 
1805  /*
1806  * If it's a regclass or similar literal referring to an existing
1807  * object, add a reference to that object. (Currently, only the
1808  * regclass and regconfig cases have any likely use, but we may as
1809  * well handle all the OID-alias datatypes consistently.)
1810  */
1811  if (!con->constisnull)
1812  {
1813  switch (con->consttype)
1814  {
1815  case REGPROCOID:
1816  case REGPROCEDUREOID:
1817  objoid = DatumGetObjectId(con->constvalue);
1819  ObjectIdGetDatum(objoid)))
1820  add_object_address(OCLASS_PROC, objoid, 0,
1821  context->addrs);
1822  break;
1823  case REGOPEROID:
1824  case REGOPERATOROID:
1825  objoid = DatumGetObjectId(con->constvalue);
1827  ObjectIdGetDatum(objoid)))
1829  context->addrs);
1830  break;
1831  case REGCLASSOID:
1832  objoid = DatumGetObjectId(con->constvalue);
1834  ObjectIdGetDatum(objoid)))
1835  add_object_address(OCLASS_CLASS, objoid, 0,
1836  context->addrs);
1837  break;
1838  case REGTYPEOID:
1839  objoid = DatumGetObjectId(con->constvalue);
1841  ObjectIdGetDatum(objoid)))
1842  add_object_address(OCLASS_TYPE, objoid, 0,
1843  context->addrs);
1844  break;
1845  case REGCONFIGOID:
1846  objoid = DatumGetObjectId(con->constvalue);
1848  ObjectIdGetDatum(objoid)))
1850  context->addrs);
1851  break;
1852  case REGDICTIONARYOID:
1853  objoid = DatumGetObjectId(con->constvalue);
1855  ObjectIdGetDatum(objoid)))
1856  add_object_address(OCLASS_TSDICT, objoid, 0,
1857  context->addrs);
1858  break;
1859 
1860  case REGNAMESPACEOID:
1861  objoid = DatumGetObjectId(con->constvalue);
1863  ObjectIdGetDatum(objoid)))
1864  add_object_address(OCLASS_SCHEMA, objoid, 0,
1865  context->addrs);
1866  break;
1867 
1868  /*
1869  * Dependencies for regrole should be shared among all
1870  * databases, so explicitly inhibit to have dependencies.
1871  */
1872  case REGROLEOID:
1873  ereport(ERROR,
1874  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1875  errmsg("constant of the type %s cannot be used here",
1876  "regrole")));
1877  break;
1878  }
1879  }
1880  return false;
1881  }
1882  else if (IsA(node, Param))
1883  {
1884  Param *param = (Param *) node;
1885 
1886  /* A parameter must depend on the parameter's datatype */
1888  context->addrs);
1889  /* and its collation, just as for Consts */
1890  if (OidIsValid(param->paramcollid) &&
1891  param->paramcollid != DEFAULT_COLLATION_OID)
1893  context->addrs);
1894  }
1895  else if (IsA(node, FuncExpr))
1896  {
1897  FuncExpr *funcexpr = (FuncExpr *) node;
1898 
1899  add_object_address(OCLASS_PROC, funcexpr->funcid, 0,
1900  context->addrs);
1901  /* fall through to examine arguments */
1902  }
1903  else if (IsA(node, OpExpr))
1904  {
1905  OpExpr *opexpr = (OpExpr *) node;
1906 
1908  context->addrs);
1909  /* fall through to examine arguments */
1910  }
1911  else if (IsA(node, DistinctExpr))
1912  {
1913  DistinctExpr *distinctexpr = (DistinctExpr *) node;
1914 
1915  add_object_address(OCLASS_OPERATOR, distinctexpr->opno, 0,
1916  context->addrs);
1917  /* fall through to examine arguments */
1918  }
1919  else if (IsA(node, NullIfExpr))
1920  {
1921  NullIfExpr *nullifexpr = (NullIfExpr *) node;
1922 
1923  add_object_address(OCLASS_OPERATOR, nullifexpr->opno, 0,
1924  context->addrs);
1925  /* fall through to examine arguments */
1926  }
1927  else if (IsA(node, ScalarArrayOpExpr))
1928  {
1929  ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
1930 
1932  context->addrs);
1933  /* fall through to examine arguments */
1934  }
1935  else if (IsA(node, Aggref))
1936  {
1937  Aggref *aggref = (Aggref *) node;
1938 
1940  context->addrs);
1941  /* fall through to examine arguments */
1942  }
1943  else if (IsA(node, WindowFunc))
1944  {
1945  WindowFunc *wfunc = (WindowFunc *) node;
1946 
1948  context->addrs);
1949  /* fall through to examine arguments */
1950  }
1951  else if (IsA(node, SubPlan))
1952  {
1953  /* Extra work needed here if we ever need this case */
1954  elog(ERROR, "already-planned subqueries not supported");
1955  }
1956  else if (IsA(node, FieldSelect))
1957  {
1958  FieldSelect *fselect = (FieldSelect *) node;
1959  Oid argtype = getBaseType(exprType((Node *) fselect->arg));
1960  Oid reltype = get_typ_typrelid(argtype);
1961 
1962  /*
1963  * We need a dependency on the specific column named in FieldSelect,
1964  * assuming we can identify the pg_class OID for it. (Probably we
1965  * always can at the moment, but in future it might be possible for
1966  * argtype to be RECORDOID.) If we can make a column dependency then
1967  * we shouldn't need a dependency on the column's type; but if we
1968  * can't, make a dependency on the type, as it might not appear
1969  * anywhere else in the expression.
1970  */
1971  if (OidIsValid(reltype))
1972  add_object_address(OCLASS_CLASS, reltype, fselect->fieldnum,
1973  context->addrs);
1974  else
1976  context->addrs);
1977  /* the collation might not be referenced anywhere else, either */
1978  if (OidIsValid(fselect->resultcollid) &&
1979  fselect->resultcollid != DEFAULT_COLLATION_OID)
1981  context->addrs);
1982  }
1983  else if (IsA(node, FieldStore))
1984  {
1985  FieldStore *fstore = (FieldStore *) node;
1986  Oid reltype = get_typ_typrelid(fstore->resulttype);
1987 
1988  /* similar considerations to FieldSelect, but multiple column(s) */
1989  if (OidIsValid(reltype))
1990  {
1991  ListCell *l;
1992 
1993  foreach(l, fstore->fieldnums)
1995  context->addrs);
1996  }
1997  else
1999  context->addrs);
2000  }
2001  else if (IsA(node, RelabelType))
2002  {
2003  RelabelType *relab = (RelabelType *) node;
2004 
2005  /* since there is no function dependency, need to depend on type */
2007  context->addrs);
2008  /* the collation might not be referenced anywhere else, either */
2009  if (OidIsValid(relab->resultcollid) &&
2010  relab->resultcollid != DEFAULT_COLLATION_OID)
2012  context->addrs);
2013  }
2014  else if (IsA(node, CoerceViaIO))
2015  {
2016  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2017 
2018  /* since there is no exposed function, need to depend on type */
2020  context->addrs);
2021  /* the collation might not be referenced anywhere else, either */
2022  if (OidIsValid(iocoerce->resultcollid) &&
2023  iocoerce->resultcollid != DEFAULT_COLLATION_OID)
2025  context->addrs);
2026  }
2027  else if (IsA(node, ArrayCoerceExpr))
2028  {
2029  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2030 
2031  /* as above, depend on type */
2033  context->addrs);
2034  /* the collation might not be referenced anywhere else, either */
2035  if (OidIsValid(acoerce->resultcollid) &&
2036  acoerce->resultcollid != DEFAULT_COLLATION_OID)
2038  context->addrs);
2039  /* fall through to examine arguments */
2040  }
2041  else if (IsA(node, ConvertRowtypeExpr))
2042  {
2043  ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
2044 
2045  /* since there is no function dependency, need to depend on type */
2047  context->addrs);
2048  }
2049  else if (IsA(node, CollateExpr))
2050  {
2051  CollateExpr *coll = (CollateExpr *) node;
2052 
2054  context->addrs);
2055  }
2056  else if (IsA(node, RowExpr))
2057  {
2058  RowExpr *rowexpr = (RowExpr *) node;
2059 
2061  context->addrs);
2062  }
2063  else if (IsA(node, RowCompareExpr))
2064  {
2065  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2066  ListCell *l;
2067 
2068  foreach(l, rcexpr->opnos)
2069  {
2071  context->addrs);
2072  }
2073  foreach(l, rcexpr->opfamilies)
2074  {
2076  context->addrs);
2077  }
2078  /* fall through to examine arguments */
2079  }
2080  else if (IsA(node, CoerceToDomain))
2081  {
2082  CoerceToDomain *cd = (CoerceToDomain *) node;
2083 
2085  context->addrs);
2086  }
2087  else if (IsA(node, NextValueExpr))
2088  {
2089  NextValueExpr *nve = (NextValueExpr *) node;
2090 
2092  context->addrs);
2093  }
2094  else if (IsA(node, OnConflictExpr))
2095  {
2096  OnConflictExpr *onconflict = (OnConflictExpr *) node;
2097 
2098  if (OidIsValid(onconflict->constraint))
2100  context->addrs);
2101  /* fall through to examine arguments */
2102  }
2103  else if (IsA(node, SortGroupClause))
2104  {
2105  SortGroupClause *sgc = (SortGroupClause *) node;
2106 
2108  context->addrs);
2109  if (OidIsValid(sgc->sortop))
2111  context->addrs);
2112  return false;
2113  }
2114  else if (IsA(node, WindowClause))
2115  {
2116  WindowClause *wc = (WindowClause *) node;
2117 
2118  if (OidIsValid(wc->startInRangeFunc))
2120  context->addrs);
2121  if (OidIsValid(wc->endInRangeFunc))
2123  context->addrs);
2124  if (OidIsValid(wc->inRangeColl) &&
2125  wc->inRangeColl != DEFAULT_COLLATION_OID)
2127  context->addrs);
2128  /* fall through to examine substructure */
2129  }
2130  else if (IsA(node, Query))
2131  {
2132  /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2133  Query *query = (Query *) node;
2134  ListCell *lc;
2135  bool result;
2136 
2137  /*
2138  * Add whole-relation refs for each plain relation mentioned in the
2139  * subquery's rtable, and ensure we add refs for any type-coercion
2140  * functions used in join alias lists.
2141  *
2142  * Note: query_tree_walker takes care of recursing into RTE_FUNCTION
2143  * RTEs, subqueries, etc, so no need to do that here. But we must
2144  * tell it not to visit join alias lists, or we'll add refs for join
2145  * input columns whether or not they are actually used in our query.
2146  *
2147  * Note: we don't need to worry about collations mentioned in
2148  * RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
2149  * collations referenced in other parts of the Query. We do have to
2150  * worry about collations mentioned in RTE_FUNCTION, but we take care
2151  * of those when we recurse to the RangeTblFunction node(s).
2152  */
2153  foreach(lc, query->rtable)
2154  {
2155  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2156 
2157  switch (rte->rtekind)
2158  {
2159  case RTE_RELATION:
2161  context->addrs);
2162  break;
2163  case RTE_JOIN:
2164 
2165  /*
2166  * Examine joinaliasvars entries only for merged JOIN
2167  * USING columns. Only those entries could contain
2168  * type-coercion functions. Also, their join input
2169  * columns must be referenced in the join quals, so this
2170  * won't accidentally add refs to otherwise-unused join
2171  * input columns. (We want to ref the type coercion
2172  * functions even if the merged column isn't explicitly
2173  * used anywhere, to protect possible expansion of the
2174  * join RTE as a whole-row var, and because it seems like
2175  * a bad idea to allow dropping a function that's present
2176  * in our query tree, whether or not it could get called.)
2177  */
2178  context->rtables = lcons(query->rtable, context->rtables);
2179  for (int i = 0; i < rte->joinmergedcols; i++)
2180  {
2181  Node *aliasvar = list_nth(rte->joinaliasvars, i);
2182 
2183  if (!IsA(aliasvar, Var))
2184  find_expr_references_walker(aliasvar, context);
2185  }
2186  context->rtables = list_delete_first(context->rtables);
2187  break;
2188  default:
2189  break;
2190  }
2191  }
2192 
2193  /*
2194  * If the query is an INSERT or UPDATE, we should create a dependency
2195  * on each target column, to prevent the specific target column from
2196  * being dropped. Although we will visit the TargetEntry nodes again
2197  * during query_tree_walker, we won't have enough context to do this
2198  * conveniently, so do it here.
2199  */
2200  if (query->commandType == CMD_INSERT ||
2201  query->commandType == CMD_UPDATE)
2202  {
2203  RangeTblEntry *rte;
2204 
2205  if (query->resultRelation <= 0 ||
2206  query->resultRelation > list_length(query->rtable))
2207  elog(ERROR, "invalid resultRelation %d",
2208  query->resultRelation);
2209  rte = rt_fetch(query->resultRelation, query->rtable);
2210  if (rte->rtekind == RTE_RELATION)
2211  {
2212  foreach(lc, query->targetList)
2213  {
2214  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2215 
2216  if (tle->resjunk)
2217  continue; /* ignore junk tlist items */
2219  context->addrs);
2220  }
2221  }
2222  }
2223 
2224  /*
2225  * Add dependencies on constraints listed in query's constraintDeps
2226  */
2227  foreach(lc, query->constraintDeps)
2228  {
2230  context->addrs);
2231  }
2232 
2233  /* Examine substructure of query */
2234  context->rtables = lcons(query->rtable, context->rtables);
2235  result = query_tree_walker(query,
2237  (void *) context,
2240  context->rtables = list_delete_first(context->rtables);
2241  return result;
2242  }
2243  else if (IsA(node, SetOperationStmt))
2244  {
2245  SetOperationStmt *setop = (SetOperationStmt *) node;
2246 
2247  /* we need to look at the groupClauses for operator references */
2248  find_expr_references_walker((Node *) setop->groupClauses, context);
2249  /* fall through to examine child nodes */
2250  }
2251  else if (IsA(node, RangeTblFunction))
2252  {
2253  RangeTblFunction *rtfunc = (RangeTblFunction *) node;
2254  ListCell *ct;
2255 
2256  /*
2257  * Add refs for any datatypes and collations used in a column
2258  * definition list for a RECORD function. (For other cases, it should
2259  * be enough to depend on the function itself.)
2260  */
2261  foreach(ct, rtfunc->funccoltypes)
2262  {
2264  context->addrs);
2265  }
2266  foreach(ct, rtfunc->funccolcollations)
2267  {
2268  Oid collid = lfirst_oid(ct);
2269 
2270  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2272  context->addrs);
2273  }
2274  }
2275  else if (IsA(node, TableFunc))
2276  {
2277  TableFunc *tf = (TableFunc *) node;
2278  ListCell *ct;
2279 
2280  /*
2281  * Add refs for the datatypes and collations used in the TableFunc.
2282  */
2283  foreach(ct, tf->coltypes)
2284  {
2286  context->addrs);
2287  }
2288  foreach(ct, tf->colcollations)
2289  {
2290  Oid collid = lfirst_oid(ct);
2291 
2292  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
2294  context->addrs);
2295  }
2296  }
2297  else if (IsA(node, TableSampleClause))
2298  {
2299  TableSampleClause *tsc = (TableSampleClause *) node;
2300 
2302  context->addrs);
2303  /* fall through to examine arguments */
2304  }
2305 
2307  (void *) context);
2308 }
Datum constvalue
Definition: primnodes.h:214
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
List * joinaliasvars
Definition: parsenodes.h:1051
Index varlevelsup
Definition: primnodes.h:191
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1736
Oid resulttype
Definition: primnodes.h:764
ObjectAddresses * addrs
Definition: dependency.c:139
List * constraintDeps
Definition: parsenodes.h:169
#define DatumGetObjectId(X)
Definition: postgres.h:500
Oid resulttype
Definition: primnodes.h:835
#define QTW_EXAMINE_SORTGROUP
Definition: nodeFuncs.h:30
List * opfamilies
Definition: primnodes.h:1072
int resultRelation
Definition: parsenodes.h:122
Oid endInRangeFunc
Definition: parsenodes.h:1359
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
AttrNumber varattno
Definition: primnodes.h:186
Expr * arg
Definition: primnodes.h:762
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
#define OidIsValid(objectId)
Definition: c.h:644
List * colcollations
Definition: primnodes.h:92
List * targetList
Definition: parsenodes.h:140
Oid consttype
Definition: primnodes.h:210
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:183
Oid get_typ_typrelid(Oid typid)
Definition: lsyscache.c:2609
bool resjunk
Definition: primnodes.h:1414
List * rtable
Definition: parsenodes.h:137
Oid funcid
Definition: primnodes.h:469
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid paramcollid
Definition: primnodes.h:266
#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:212
Oid resultcollid
Definition: primnodes.h:767
AttrNumber resno
Definition: primnodes.h:1408
Oid resulttype
Definition: primnodes.h:794
Oid winfnoid
Definition: primnodes.h:373
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Index varno
Definition: primnodes.h:184
Oid resultcollid
Definition: primnodes.h:837
Oid resulttype
Definition: primnodes.h:815
List * coltypes
Definition: primnodes.h:90
Oid resultcollid
Definition: primnodes.h:817
Oid aggfnoid
Definition: primnodes.h:312
#define ereport(elevel,...)
Definition: elog.h:144
CmdType commandType
Definition: parsenodes.h:112
List * lcons(void *datum, List *list)
Definition: list.c:453
List * funccolcollations
Definition: parsenodes.h:1154
#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:1023
static int list_length(const List *l)
Definition: pg_list.h:169
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:976
int errmsg(const char *fmt,...)
Definition: elog.c:824
List * fieldnums
Definition: primnodes.h:793
#define elog(elevel,...)
Definition: elog.h:214
int i
Oid opno
Definition: primnodes.h:516
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2409
Definition: pg_list.h:50
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId, ObjectAddresses *addrs)
Definition: dependency.c:2440
Oid startInRangeFunc
Definition: parsenodes.h:1358
Oid paramtype
Definition: primnodes.h:264
bool constisnull
Definition: primnodes.h:215
#define lfirst_oid(lc)
Definition: pg_list.h:192
List * list_delete_first(List *list)
Definition: list.c:860
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:23
AttrNumber fieldnum
Definition: primnodes.h:763

◆ findDependentObjects()

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

Definition at line 473 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().

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

◆ free_object_addresses()

void free_object_addresses ( ObjectAddresses addrs)

◆ getObjectClass()

ObjectClass getObjectClass ( const ObjectAddress object)

Definition at line 2728 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().

2729 {
2730  /* only pg_class entries can have nonzero objectSubId */
2731  if (object->classId != RelationRelationId &&
2732  object->objectSubId != 0)
2733  elog(ERROR, "invalid non-zero objectSubId for object class %u",
2734  object->classId);
2735 
2736  switch (object->classId)
2737  {
2738  case RelationRelationId:
2739  /* caller must check objectSubId */
2740  return OCLASS_CLASS;
2741 
2742  case ProcedureRelationId:
2743  return OCLASS_PROC;
2744 
2745  case TypeRelationId:
2746  return OCLASS_TYPE;
2747 
2748  case CastRelationId:
2749  return OCLASS_CAST;
2750 
2751  case CollationRelationId:
2752  return OCLASS_COLLATION;
2753 
2754  case ConstraintRelationId:
2755  return OCLASS_CONSTRAINT;
2756 
2757  case ConversionRelationId:
2758  return OCLASS_CONVERSION;
2759 
2760  case AttrDefaultRelationId:
2761  return OCLASS_DEFAULT;
2762 
2763  case LanguageRelationId:
2764  return OCLASS_LANGUAGE;
2765 
2766  case LargeObjectRelationId:
2767  return OCLASS_LARGEOBJECT;
2768 
2769  case OperatorRelationId:
2770  return OCLASS_OPERATOR;
2771 
2772  case OperatorClassRelationId:
2773  return OCLASS_OPCLASS;
2774 
2775  case OperatorFamilyRelationId:
2776  return OCLASS_OPFAMILY;
2777 
2778  case AccessMethodRelationId:
2779  return OCLASS_AM;
2780 
2781  case AccessMethodOperatorRelationId:
2782  return OCLASS_AMOP;
2783 
2784  case AccessMethodProcedureRelationId:
2785  return OCLASS_AMPROC;
2786 
2787  case RewriteRelationId:
2788  return OCLASS_REWRITE;
2789 
2790  case TriggerRelationId:
2791  return OCLASS_TRIGGER;
2792 
2793  case NamespaceRelationId:
2794  return OCLASS_SCHEMA;
2795 
2796  case StatisticExtRelationId:
2797  return OCLASS_STATISTIC_EXT;
2798 
2799  case TSParserRelationId:
2800  return OCLASS_TSPARSER;
2801 
2802  case TSDictionaryRelationId:
2803  return OCLASS_TSDICT;
2804 
2805  case TSTemplateRelationId:
2806  return OCLASS_TSTEMPLATE;
2807 
2808  case TSConfigRelationId:
2809  return OCLASS_TSCONFIG;
2810 
2811  case AuthIdRelationId:
2812  return OCLASS_ROLE;
2813 
2814  case DatabaseRelationId:
2815  return OCLASS_DATABASE;
2816 
2817  case TableSpaceRelationId:
2818  return OCLASS_TBLSPACE;
2819 
2820  case ForeignDataWrapperRelationId:
2821  return OCLASS_FDW;
2822 
2823  case ForeignServerRelationId:
2824  return OCLASS_FOREIGN_SERVER;
2825 
2826  case UserMappingRelationId:
2827  return OCLASS_USER_MAPPING;
2828 
2829  case DefaultAclRelationId:
2830  return OCLASS_DEFACL;
2831 
2832  case ExtensionRelationId:
2833  return OCLASS_EXTENSION;
2834 
2835  case EventTriggerRelationId:
2836  return OCLASS_EVENT_TRIGGER;
2837 
2838  case PolicyRelationId:
2839  return OCLASS_POLICY;
2840 
2841  case PublicationRelationId:
2842  return OCLASS_PUBLICATION;
2843 
2844  case PublicationRelRelationId:
2845  return OCLASS_PUBLICATION_REL;
2846 
2847  case SubscriptionRelationId:
2848  return OCLASS_SUBSCRIPTION;
2849 
2850  case TransformRelationId:
2851  return OCLASS_TRANSFORM;
2852  }
2853 
2854  /* shouldn't get here */
2855  elog(ERROR, "unrecognized object class: %u", object->classId);
2856  return OCLASS_CLASS; /* keep compiler quiet */
2857 }
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:214

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

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

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

2375 {
2376  const ObjectAddress *obja = (const ObjectAddress *) a;
2377  const ObjectAddress *objb = (const ObjectAddress *) b;
2378 
2379  /*
2380  * Primary sort key is OID descending. Most of the time, this will result
2381  * in putting newer objects before older ones, which is likely to be the
2382  * right order to delete in.
2383  */
2384  if (obja->objectId > objb->objectId)
2385  return -1;
2386  if (obja->objectId < objb->objectId)
2387  return 1;
2388 
2389  /*
2390  * Next sort on catalog ID, in case identical OIDs appear in different
2391  * catalogs. Sort direction is pretty arbitrary here.
2392  */
2393  if (obja->classId < objb->classId)
2394  return -1;
2395  if (obja->classId > objb->classId)
2396  return 1;
2397 
2398  /*
2399  * Last, sort on object subId.
2400  *
2401  * We sort the subId as an unsigned int so that 0 (the whole object) will
2402  * come first. This is essential for eliminate_duplicate_dependencies,
2403  * and is also the best order for findDependentObjects.
2404  */
2405  if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
2406  return -1;
2407  if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
2408  return 1;
2409  return 0;
2410 }

◆ object_address_present()

bool object_address_present ( const ObjectAddress object,
const ObjectAddresses addrs 
)

Definition at line 2533 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().

2535 {
2536  int i;
2537 
2538  for (i = addrs->numrefs - 1; i >= 0; i--)
2539  {
2540  const ObjectAddress *thisobj = addrs->refs + i;
2541 
2542  if (object->classId == thisobj->classId &&
2543  object->objectId == thisobj->objectId)
2544  {
2545  if (object->objectSubId == thisobj->objectSubId ||
2546  thisobj->objectSubId == 0)
2547  return true;
2548  }
2549  }
2550 
2551  return false;
2552 }
ObjectAddress * refs
Definition: dependency.c:113
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 2559 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().

2562 {
2563  bool result = false;
2564  int i;
2565 
2566  for (i = addrs->numrefs - 1; i >= 0; i--)
2567  {
2568  ObjectAddress *thisobj = addrs->refs + i;
2569 
2570  if (object->classId == thisobj->classId &&
2571  object->objectId == thisobj->objectId)
2572  {
2573  if (object->objectSubId == thisobj->objectSubId)
2574  {
2575  ObjectAddressExtra *thisextra = addrs->extras + i;
2576 
2577  thisextra->flags |= flags;
2578  result = true;
2579  }
2580  else if (thisobj->objectSubId == 0)
2581  {
2582  /*
2583  * We get here if we find a need to delete a column after
2584  * having already decided to drop its whole table. Obviously
2585  * we no longer need to drop the subobject, so report that we
2586  * found the subobject in the array. But don't plaster its
2587  * flags on the whole object.
2588  */
2589  result = true;
2590  }
2591  else if (object->objectSubId == 0)
2592  {
2593  /*
2594  * We get here if we find a need to delete a whole table after
2595  * having already decided to drop one of its columns. We
2596  * can't report that the whole object is in the array, but we
2597  * should mark the subobject with the whole object's flags.
2598  *
2599  * It might seem attractive to physically delete the column's
2600  * array entry, or at least mark it as no longer needing
2601  * separate deletion. But that could lead to, e.g., dropping
2602  * the column's datatype before we drop the table, which does
2603  * not seem like a good idea. This is a very rare situation
2604  * in practice, so we just take the hit of doing a separate
2605  * DROP COLUMN action even though we know we're gonna delete
2606  * the table later.
2607  *
2608  * What we can do, though, is mark this as a subobject so that
2609  * we don't report it separately, which is confusing because
2610  * it's unpredictable whether it happens or not. But do so
2611  * only if flags != 0 (flags == 0 is a read-only probe).
2612  *
2613  * Because there could be other subobjects of this object in
2614  * the array, this case means we always have to loop through
2615  * the whole array; we cannot exit early on a match.
2616  */
2617  ObjectAddressExtra *thisextra = addrs->extras + i;
2618 
2619  if (flags)
2620  thisextra->flags |= (flags | DEPFLAG_SUBOBJECT);
2621  }
2622  }
2623  }
2624 
2625  return result;
2626 }
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:107
ObjectAddress * refs
Definition: dependency.c:113
ObjectAddressExtra * extras
Definition: dependency.c:114
int i

◆ performDeletion()

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

Definition at line 314 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().

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

◆ performMultipleDeletions()

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

Definition at line 373 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(), DropClonedTriggersFromPartition(), PreCommit_on_commit_actions(), ReindexRelationConcurrently(), RemoveObjects(), RemoveRelations(), and shdepDropOwned().

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

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

Referenced by makeConfigurationDependencies().

2685 {
2687  recordMultipleDependencies(depender,
2688  referenced->refs, referenced->numrefs,
2689  behavior);
2690 }
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2314
ObjectAddress * refs
Definition: dependency.c:113
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 1590 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().

1593 {
1595 
1596  context.addrs = new_object_addresses();
1597 
1598  /* Set up interpretation for Vars at varlevelsup = 0 */
1599  context.rtables = list_make1(rtable);
1600 
1601  /* Scan the expression tree for referenceable objects */
1602  find_expr_references_walker(expr, &context);
1603 
1604  /* Remove any duplicates */
1606 
1607  /* And record 'em */
1608  recordMultipleDependencies(depender,
1609  context.addrs->refs, context.addrs->numrefs,
1610  behavior);
1611 
1612  free_object_addresses(context.addrs);
1613 }
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1736
ObjectAddresses * addrs
Definition: dependency.c:139
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2418
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2713
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2314
#define list_make1(x1)
Definition: pg_list.h:227
ObjectAddress * refs
Definition: dependency.c:113
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 1633 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().

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

◆ ReleaseDeletionLock()

void ReleaseDeletionLock ( const ObjectAddress object)

Definition at line 1565 of file dependency.c.

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

Referenced by findDependentObjects(), and shdepDropOwned().

1566 {
1567  if (object->classId == RelationRelationId)
1569  else
1570  /* assume we should lock the whole object not a sub-object */
1571  UnlockDatabaseObject(object->classId, object->objectId, 0,
1573 }
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 1026 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().

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

◆ sort_object_addresses()

void sort_object_addresses ( ObjectAddresses addrs)

Definition at line 2701 of file dependency.c.

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

Referenced by shdepDropOwned().

2702 {
2703  if (addrs->numrefs > 1)
2704  qsort((void *) addrs->refs, addrs->numrefs,
2705  sizeof(ObjectAddress),
2707 }
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2374
ObjectAddress * refs
Definition: dependency.c:113
#define qsort(a, b, c, d)
Definition: port.h:479

◆ stack_address_present_add_flags()

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

Definition at line 2632 of file dependency.c.

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

Referenced by findDependentObjects().

2635 {
2636  bool result = false;
2637  ObjectAddressStack *stackptr;
2638 
2639  for (stackptr = stack; stackptr; stackptr = stackptr->next)
2640  {
2641  const ObjectAddress *thisobj = stackptr->object;
2642 
2643  if (object->classId == thisobj->classId &&
2644  object->objectId == thisobj->objectId)
2645  {
2646  if (object->objectSubId == thisobj->objectSubId)
2647  {
2648  stackptr->flags |= flags;
2649  result = true;
2650  }
2651  else if (thisobj->objectSubId == 0)
2652  {
2653  /*
2654  * We're visiting a column with whole table already on stack.
2655  * As in object_address_present_add_flags(), we can skip
2656  * further processing of the subobject, but we don't want to
2657  * propagate flags for the subobject to the whole object.
2658  */
2659  result = true;
2660  }
2661  else if (object->objectSubId == 0)
2662  {
2663  /*
2664  * We're visiting a table with column already on stack. As in
2665  * object_address_present_add_flags(), we should propagate
2666  * flags for the whole object to each of its subobjects.
2667  */
2668  if (flags)
2669  stackptr->flags |= (flags | DEPFLAG_SUBOBJECT);
2670  }
2671  }
2672  }
2673 
2674  return result;
2675 }
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:107
struct ObjectAddressStack * next
Definition: dependency.c:126
const ObjectAddress * object
Definition: dependency.c:124

Variable Documentation

◆ object_classes

const Oid object_classes[]
static

Definition at line 147 of file dependency.c.

Referenced by add_object_address().