PostgreSQL Source Code  git master
dependency.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_am.h"
#include "catalog/pg_amop.h"
#include "catalog/pg_amproc.h"
#include "catalog/pg_attrdef.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_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/publicationcmds.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 DropObjectById (const ObjectAddress *object)
 
static void deleteOneObject (const ObjectAddress *object, Relation *depRel, int flags)
 
void AcquireDeletionLock (const ObjectAddress *object, int flags)
 
void ReleaseDeletionLock (const ObjectAddress *object)
 
void recordDependencyOnExpr (const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
 
void recordDependencyOnSingleRelExpr (const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self)
 
ObjectAddressesnew_object_addresses (void)
 
void add_exact_object_address (const ObjectAddress *object, ObjectAddresses *addrs)
 
bool object_address_present (const ObjectAddress *object, const ObjectAddresses *addrs)
 
void record_object_address_dependencies (const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
 
void sort_object_addresses (ObjectAddresses *addrs)
 
void free_object_addresses (ObjectAddresses *addrs)
 
ObjectClass getObjectClass (const ObjectAddress *object)
 

Variables

static const Oid object_classes []
 

Macro Definition Documentation

◆ DEPFLAG_AUTO

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

Definition at line 100 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_EXTENSION

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

Definition at line 103 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_INTERNAL

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

Definition at line 101 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_IS_PART

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

Definition at line 105 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_NORMAL

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

Definition at line 99 of file dependency.c.

Referenced by deleteObjectsInList(), and findDependentObjects().

◆ DEPFLAG_ORIGINAL

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

◆ DEPFLAG_PARTITION

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

Definition at line 102 of file dependency.c.

Referenced by findDependentObjects(), and reportDependentObjects().

◆ DEPFLAG_REVERSE

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

Definition at line 104 of file dependency.c.

Referenced by deleteObjectsInList(), and findDependentObjects().

◆ DEPFLAG_SUBOBJECT

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

◆ MAX_REPORTED_DEPS

#define MAX_REPORTED_DEPS   100

Referenced by reportDependentObjects().

Typedef Documentation

◆ ObjectAddressStack

Function Documentation

◆ AcquireDeletionLock()

void AcquireDeletionLock ( const ObjectAddress object,
int  flags 
)

Definition at line 1517 of file dependency.c.

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

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

1518 {
1519  if (object->classId == RelationRelationId)
1520  {
1521  /*
1522  * In DROP INDEX CONCURRENTLY, take only ShareUpdateExclusiveLock on
1523  * the index for the moment. index_drop() will promote the lock once
1524  * it's safe to do so. In all other cases we need full exclusive
1525  * lock.
1526  */
1527  if (flags & PERFORM_DELETION_CONCURRENTLY)
1529  else
1531  }
1532  else
1533  {
1534  /* assume we should lock the whole object not a sub-object */
1535  LockDatabaseObject(object->classId, object->objectId, 0,
1537  }
1538 }
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:134
void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:976
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define AccessExclusiveLock
Definition: lockdefs.h:45
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109

◆ add_exact_object_address()

void add_exact_object_address ( const ObjectAddress object,
ObjectAddresses addrs 
)

Definition at line 2485 of file dependency.c.

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

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

2487 {
2488  ObjectAddress *item;
2489 
2490  /* enlarge array if needed */
2491  if (addrs->numrefs >= addrs->maxrefs)
2492  {
2493  addrs->maxrefs *= 2;
2494  addrs->refs = (ObjectAddress *)
2495  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2496  Assert(!addrs->extras);
2497  }
2498  /* record this item */
2499  item = addrs->refs + addrs->numrefs;
2500  *item = *object;
2501  addrs->numrefs++;
2502 }
ObjectAddress * refs
Definition: dependency.c:112
#define Assert(condition)
Definition: c.h:804
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
ObjectAddressExtra * extras
Definition: dependency.c:113

◆ add_exact_object_address_extra()

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

Definition at line 2510 of file dependency.c.

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

Referenced by findDependentObjects().

2513 {
2514  ObjectAddress *item;
2515  ObjectAddressExtra *itemextra;
2516 
2517  /* allocate extra space if first time */
2518  if (!addrs->extras)
2519  addrs->extras = (ObjectAddressExtra *)
2520  palloc(addrs->maxrefs * sizeof(ObjectAddressExtra));
2521 
2522  /* enlarge array if needed */
2523  if (addrs->numrefs >= addrs->maxrefs)
2524  {
2525  addrs->maxrefs *= 2;
2526  addrs->refs = (ObjectAddress *)
2527  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2528  addrs->extras = (ObjectAddressExtra *)
2529  repalloc(addrs->extras, addrs->maxrefs * sizeof(ObjectAddressExtra));
2530  }
2531  /* record this item */
2532  item = addrs->refs + addrs->numrefs;
2533  *item = *object;
2534  itemextra = addrs->extras + addrs->numrefs;
2535  *itemextra = *extra;
2536  addrs->numrefs++;
2537 }
ObjectAddress * refs
Definition: dependency.c:112
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
ObjectAddressExtra * extras
Definition: dependency.c:113
void * palloc(Size size)
Definition: mcxt.c:1062

◆ add_object_address()

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

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

2454 {
2455  ObjectAddress *item;
2456 
2457  /*
2458  * Make sure object_classes is kept up to date with the ObjectClass enum.
2459  */
2461  "object_classes[] must cover all ObjectClasses");
2462 
2463  /* enlarge array if needed */
2464  if (addrs->numrefs >= addrs->maxrefs)
2465  {
2466  addrs->maxrefs *= 2;
2467  addrs->refs = (ObjectAddress *)
2468  repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
2469  Assert(!addrs->extras);
2470  }
2471  /* record this item */
2472  item = addrs->refs + addrs->numrefs;
2473  item->classId = object_classes[oclass];
2474  item->objectId = objectId;
2475  item->objectSubId = subId;
2476  addrs->numrefs++;
2477 }
#define LAST_OCLASS
Definition: dependency.h:130
#define lengthof(array)
Definition: c.h:734
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
static const Oid object_classes[]
Definition: dependency.c:146
ObjectAddress * refs
Definition: dependency.c:112
#define Assert(condition)
Definition: c.h:804
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
ObjectAddressExtra * extras
Definition: dependency.c:113

◆ DeleteInitPrivs()

static void DeleteInitPrivs ( const ObjectAddress object)
static

Definition at line 2875 of file dependency.c.

References BTEqualStrategyNumber, CatalogTupleDelete(), ObjectAddress::classId, HeapTupleIsValid, 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().

2876 {
2877  Relation relation;
2878  ScanKeyData key[3];
2879  SysScanDesc scan;
2880  HeapTuple oldtuple;
2881 
2882  relation = table_open(InitPrivsRelationId, RowExclusiveLock);
2883 
2884  ScanKeyInit(&key[0],
2885  Anum_pg_init_privs_objoid,
2886  BTEqualStrategyNumber, F_OIDEQ,
2887  ObjectIdGetDatum(object->objectId));
2888  ScanKeyInit(&key[1],
2889  Anum_pg_init_privs_classoid,
2890  BTEqualStrategyNumber, F_OIDEQ,
2891  ObjectIdGetDatum(object->classId));
2892  ScanKeyInit(&key[2],
2893  Anum_pg_init_privs_objsubid,
2894  BTEqualStrategyNumber, F_INT4EQ,
2895  Int32GetDatum(object->objectSubId));
2896 
2897  scan = systable_beginscan(relation, InitPrivsObjIndexId, true,
2898  NULL, 3, key);
2899 
2900  while (HeapTupleIsValid(oldtuple = systable_getnext(scan)))
2901  CatalogTupleDelete(relation, &oldtuple->t_self);
2902 
2903  systable_endscan(scan);
2904 
2905  table_close(relation, RowExclusiveLock);
2906 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
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:523
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 225 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().

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

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

References BTEqualStrategyNumber, CatalogTupleDelete(), ObjectAddress::classId, CommandCounterIncrement(), DeleteComments(), DeleteInitPrivs(), DeleteSecurityLabel(), deleteSharedDependencyRecordsFor(), 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().

1273 {
1274  ScanKeyData key[3];
1275  int nkeys;
1276  SysScanDesc scan;
1277  HeapTuple tup;
1278 
1279  /* DROP hook of the objects being removed */
1280  InvokeObjectDropHookArg(object->classId, object->objectId,
1281  object->objectSubId, flags);
1282 
1283  /*
1284  * Close depRel if we are doing a drop concurrently. The object deletion
1285  * subroutine will commit the current transaction, so we can't keep the
1286  * relation open across doDeletion().
1287  */
1288  if (flags & PERFORM_DELETION_CONCURRENTLY)
1289  table_close(*depRel, RowExclusiveLock);
1290 
1291  /*
1292  * Delete the object itself, in an object-type-dependent way.
1293  *
1294  * We used to do this after removing the outgoing dependency links, but it
1295  * seems just as reasonable to do it beforehand. In the concurrent case
1296  * we *must* do it in this order, because we can't make any transactional
1297  * updates before calling doDeletion() --- they'd get committed right
1298  * away, which is not cool if the deletion then fails.
1299  */
1300  doDeletion(object, flags);
1301 
1302  /*
1303  * Reopen depRel if we closed it above
1304  */
1305  if (flags & PERFORM_DELETION_CONCURRENTLY)
1306  *depRel = table_open(DependRelationId, RowExclusiveLock);
1307 
1308  /*
1309  * Now remove any pg_depend records that link from this object to others.
1310  * (Any records linking to this object should be gone already.)
1311  *
1312  * When dropping a whole object (subId = 0), remove all pg_depend records
1313  * for its sub-objects too.
1314  */
1315  ScanKeyInit(&key[0],
1316  Anum_pg_depend_classid,
1317  BTEqualStrategyNumber, F_OIDEQ,
1318  ObjectIdGetDatum(object->classId));
1319  ScanKeyInit(&key[1],
1320  Anum_pg_depend_objid,
1321  BTEqualStrategyNumber, F_OIDEQ,
1322  ObjectIdGetDatum(object->objectId));
1323  if (object->objectSubId != 0)
1324  {
1325  ScanKeyInit(&key[2],
1326  Anum_pg_depend_objsubid,
1327  BTEqualStrategyNumber, F_INT4EQ,
1328  Int32GetDatum(object->objectSubId));
1329  nkeys = 3;
1330  }
1331  else
1332  nkeys = 2;
1333 
1334  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
1335  NULL, nkeys, key);
1336 
1337  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1338  {
1339  CatalogTupleDelete(*depRel, &tup->t_self);
1340  }
1341 
1342  systable_endscan(scan);
1343 
1344  /*
1345  * Delete shared dependency references related to this object. Again, if
1346  * subId = 0, remove records for sub-objects too.
1347  */
1349  object->objectSubId);
1350 
1351 
1352  /*
1353  * Delete any comments, security labels, or initial privileges associated
1354  * with this object. (This is a convenient place to do these things,
1355  * rather than having every object type know to do it.)
1356  */
1357  DeleteComments(object->objectId, object->classId, object->objectSubId);
1358  DeleteSecurityLabel(object);
1359  DeleteInitPrivs(object);
1360 
1361  /*
1362  * CommandCounterIncrement here to ensure that preceding changes are all
1363  * visible to the next deletion step.
1364  */
1366 
1367  /*
1368  * And we're done!
1369  */
1370 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
void DeleteSecurityLabel(const ObjectAddress *object)
Definition: seclabel.c:521
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:134
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
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:997
void CommandCounterIncrement(void)
Definition: xact.c:1022
void DeleteComments(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:326
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void doDeletion(const ObjectAddress *object, int flags)
Definition: dependency.c:1376
#define Int32GetDatum(X)
Definition: postgres.h:523
static void DeleteInitPrivs(const ObjectAddress *object)
Definition: dependency.c:2875
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 1376 of file dependency.c.

References Assert, DeleteSequenceTuple(), DropObjectById(), 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, RemoveAttrDefaultById(), RemoveAttributeById(), RemoveConstraintById(), RemoveExtensionById(), RemoveFunctionById(), RemoveOperatorById(), RemovePolicyById(), RemovePublicationById(), RemovePublicationRelById(), RemoveRewriteRuleById(), RemoveStatisticsById(), RemoveTriggerById(), RemoveTSConfigurationById(), and RemoveTypeById().

Referenced by deleteOneObject().

1377 {
1378  switch (getObjectClass(object))
1379  {
1380  case OCLASS_CLASS:
1381  {
1382  char relKind = get_rel_relkind(object->objectId);
1383 
1384  if (relKind == RELKIND_INDEX ||
1385  relKind == RELKIND_PARTITIONED_INDEX)
1386  {
1387  bool concurrent = ((flags & PERFORM_DELETION_CONCURRENTLY) != 0);
1388  bool concurrent_lock_mode = ((flags & PERFORM_DELETION_CONCURRENT_LOCK) != 0);
1389 
1390  Assert(object->objectSubId == 0);
1391  index_drop(object->objectId, concurrent, concurrent_lock_mode);
1392  }
1393  else
1394  {
1395  if (object->objectSubId != 0)
1396  RemoveAttributeById(object->objectId,
1397  object->objectSubId);
1398  else
1400  }
1401 
1402  /*
1403  * for a sequence, in addition to dropping the heap, also
1404  * delete pg_sequence tuple
1405  */
1406  if (relKind == RELKIND_SEQUENCE)
1407  DeleteSequenceTuple(object->objectId);
1408  break;
1409  }
1410 
1411  case OCLASS_PROC:
1412  RemoveFunctionById(object->objectId);
1413  break;
1414 
1415  case OCLASS_TYPE:
1416  RemoveTypeById(object->objectId);
1417  break;
1418 
1419  case OCLASS_CONSTRAINT:
1420  RemoveConstraintById(object->objectId);
1421  break;
1422 
1423  case OCLASS_DEFAULT:
1425  break;
1426 
1427  case OCLASS_LARGEOBJECT:
1428  LargeObjectDrop(object->objectId);
1429  break;
1430 
1431  case OCLASS_OPERATOR:
1432  RemoveOperatorById(object->objectId);
1433  break;
1434 
1435  case OCLASS_REWRITE:
1437  break;
1438 
1439  case OCLASS_TRIGGER:
1440  RemoveTriggerById(object->objectId);
1441  break;
1442 
1443  case OCLASS_STATISTIC_EXT:
1444  RemoveStatisticsById(object->objectId);
1445  break;
1446 
1447  case OCLASS_TSCONFIG:
1449  break;
1450 
1451  case OCLASS_EXTENSION:
1452  RemoveExtensionById(object->objectId);
1453  break;
1454 
1455  case OCLASS_POLICY:
1456  RemovePolicyById(object->objectId);
1457  break;
1458 
1461  break;
1462 
1463  case OCLASS_PUBLICATION:
1465  break;
1466 
1467  case OCLASS_CAST:
1468  case OCLASS_COLLATION:
1469  case OCLASS_CONVERSION:
1470  case OCLASS_LANGUAGE:
1471  case OCLASS_OPCLASS:
1472  case OCLASS_OPFAMILY:
1473  case OCLASS_AM:
1474  case OCLASS_AMOP:
1475  case OCLASS_AMPROC:
1476  case OCLASS_SCHEMA:
1477  case OCLASS_TSPARSER:
1478  case OCLASS_TSDICT:
1479  case OCLASS_TSTEMPLATE:
1480  case OCLASS_FDW:
1481  case OCLASS_FOREIGN_SERVER:
1482  case OCLASS_USER_MAPPING:
1483  case OCLASS_DEFACL:
1484  case OCLASS_EVENT_TRIGGER:
1485  case OCLASS_TRANSFORM:
1486  DropObjectById(object);
1487  break;
1488 
1489  /*
1490  * These global object types are not supported here.
1491  */
1492  case OCLASS_ROLE:
1493  case OCLASS_DATABASE:
1494  case OCLASS_TBLSPACE:
1495  case OCLASS_SUBSCRIPTION:
1496  elog(ERROR, "global objects cannot be deleted by doDeletion");
1497  break;
1498 
1499  /*
1500  * There's intentionally no default: case here; we want the
1501  * compiler to warn if a new OCLASS hasn't been handled above.
1502  */
1503  }
1504 }
void RemoveTriggerById(Oid trigOid)
Definition: trigger.c:1251
void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
Definition: index.c:2091
void RemoveStatisticsById(Oid statsOid)
Definition: statscmds.c:723
void RemoveExtensionById(Oid extId)
Definition: extension.c:1867
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
void RemovePublicationById(Oid pubid)
void RemovePublicationRelById(Oid proid)
void RemoveTypeById(Oid typeOid)
Definition: typecmds.c:653
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2740
void RemoveOperatorById(Oid operOid)
Definition: operatorcmds.c:364
#define PERFORM_DELETION_CONCURRENTLY
Definition: dependency.h:134
#define ERROR
Definition: elog.h:46
void RemoveTSConfigurationById(Oid cfgId)
Definition: tsearchcmds.c:1061
void RemovePolicyById(Oid policy_id)
Definition: policy.c:335
void RemoveAttributeById(Oid relid, AttrNumber attnum)
Definition: heap.c:1661
void DeleteSequenceTuple(Oid relid)
Definition: sequence.c:526
void RemoveAttrDefaultById(Oid attrdefId)
Definition: heap.c:1829
void LargeObjectDrop(Oid loid)
static void DropObjectById(const ObjectAddress *object)
Definition: dependency.c:1215
#define Assert(condition)
Definition: c.h:804
void RemoveFunctionById(Oid funcOid)
void RemoveRewriteRuleById(Oid ruleOid)
Definition: rewriteRemove.c:39
#define elog(elevel,...)
Definition: elog.h:232
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:138
void heap_drop_with_catalog(Oid relid)
Definition: heap.c:1902
void RemoveConstraintById(Oid conId)

◆ DropObjectById()

static void DropObjectById ( const ObjectAddress object)
static

Definition at line 1215 of file dependency.c.

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

Referenced by doDeletion().

1216 {
1217  int cacheId;
1218  Relation rel;
1219  HeapTuple tup;
1220 
1221  cacheId = get_object_catcache_oid(object->classId);
1222 
1223  rel = table_open(object->classId, RowExclusiveLock);
1224 
1225  /*
1226  * Use the system cache for the oid column, if one exists.
1227  */
1228  if (cacheId >= 0)
1229  {
1230  tup = SearchSysCache1(cacheId, ObjectIdGetDatum(object->objectId));
1231  if (!HeapTupleIsValid(tup))
1232  elog(ERROR, "cache lookup failed for %s %u",
1233  get_object_class_descr(object->classId), object->objectId);
1234 
1235  CatalogTupleDelete(rel, &tup->t_self);
1236 
1237  ReleaseSysCache(tup);
1238  }
1239  else
1240  {
1241  ScanKeyData skey[1];
1242  SysScanDesc scan;
1243 
1244  ScanKeyInit(&skey[0],
1245  get_object_attnum_oid(object->classId),
1246  BTEqualStrategyNumber, F_OIDEQ,
1247  ObjectIdGetDatum(object->objectId));
1248 
1249  scan = systable_beginscan(rel, get_object_oid_index(object->classId), true,
1250  NULL, 1, skey);
1251 
1252  /* we expect exactly one match */
1253  tup = systable_getnext(scan);
1254  if (!HeapTupleIsValid(tup))
1255  elog(ERROR, "could not find tuple for %s %u",
1256  get_object_class_descr(object->classId), object->objectId);
1257 
1258  CatalogTupleDelete(rel, &tup->t_self);
1259 
1260  systable_endscan(scan);
1261  }
1262 
1264 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
AttrNumber get_object_attnum_oid(Oid class_id)
Oid get_object_oid_index(Oid class_id)
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int get_object_catcache_oid(Oid class_id)
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
const char * get_object_class_descr(Oid class_id)
#define elog(elevel,...)
Definition: elog.h:232
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

◆ eliminate_duplicate_dependencies()

static void eliminate_duplicate_dependencies ( ObjectAddresses addrs)
static

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

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

◆ find_expr_references_walker()

static bool find_expr_references_walker ( Node node,
find_expr_references_context context 
)
static

Definition at line 1717 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, CTECycleClause::cycle_mark_collation, CTECycleClause::cycle_mark_neop, CTECycleClause::cycle_mark_type, DatumGetObjectId, elog, WindowClause::endInRangeFunc, SortGroupClause::eqop, ereport, errcode(), errmsg(), ERROR, expression_tree_walker(), exprType(), FieldSelect::fieldnum, FieldStore::fieldnums, RangeTblFunction::funccolcollations, RangeTblFunction::funccoltypes, FuncExpr::funcid, get_typ_typrelid(), getBaseType(), SetOperationStmt::groupClauses, i, WindowClause::inRangeColl, InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, RangeTblEntry::joinmergedcols, lcons(), lfirst, lfirst_int, lfirst_oid, list_delete_first(), list_length(), list_nth(), NAMESPACEOID, ObjectIdGetDatum, OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_PROC, OCLASS_SCHEMA, OCLASS_TSCONFIG, OCLASS_TSDICT, OCLASS_TYPE, OidIsValid, OPEROID, RowCompareExpr::opfamilies, OpExpr::opno, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, Param::paramcollid, Param::paramtype, PROCOID, QTW_EXAMINE_SORTGROUP, QTW_IGNORE_JOINALIASES, query_tree_walker(), SubscriptingRef::refcontainertype, SubscriptingRef::refelemtype, SubscriptingRef::refrestype, RangeTblEntry::relid, RELOID, TargetEntry::resjunk, TargetEntry::resno, FieldSelect::resultcollid, RelabelType::resultcollid, CoerceViaIO::resultcollid, ArrayCoerceExpr::resultcollid, Query::resultRelation, FieldSelect::resulttype, FieldStore::resulttype, RelabelType::resulttype, CoerceViaIO::resulttype, ArrayCoerceExpr::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, RowExpr::row_typeid, rt_fetch, Query::rtable, find_expr_references_context::rtables, RTE_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().

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

◆ findDependentObjects()

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

Definition at line 472 of file dependency.c.

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

Referenced by performDeletion(), and performMultipleDeletions().

479 {
480  ScanKeyData key[3];
481  int nkeys;
482  SysScanDesc scan;
483  HeapTuple tup;
484  ObjectAddress otherObject;
485  ObjectAddress owningObject;
486  ObjectAddress partitionObject;
487  ObjectAddressAndFlags *dependentObjects;
488  int numDependentObjects;
489  int maxDependentObjects;
490  ObjectAddressStack mystack;
491  ObjectAddressExtra extra;
492 
493  /*
494  * If the target object is already being visited in an outer recursion
495  * level, just report the current objflags back to that level and exit.
496  * This is needed to avoid infinite recursion in the face of circular
497  * dependencies.
498  *
499  * The stack check alone would result in dependency loops being broken at
500  * an arbitrary point, ie, the first member object of the loop to be
501  * visited is the last one to be deleted. This is obviously unworkable.
502  * However, the check for internal dependency below guarantees that we
503  * will not break a loop at an internal dependency: if we enter the loop
504  * at an "owned" object we will switch and start at the "owning" object
505  * instead. We could probably hack something up to avoid breaking at an
506  * auto dependency, too, if we had to. However there are no known cases
507  * where that would be necessary.
508  */
509  if (stack_address_present_add_flags(object, objflags, stack))
510  return;
511 
512  /*
513  * It's also possible that the target object has already been completely
514  * processed and put into targetObjects. If so, again we just add the
515  * specified objflags to its entry and return.
516  *
517  * (Note: in these early-exit cases we could release the caller-taken
518  * lock, since the object is presumably now locked multiple times; but it
519  * seems not worth the cycles.)
520  */
521  if (object_address_present_add_flags(object, objflags, targetObjects))
522  return;
523 
524  /*
525  * If the target object is pinned, we can just error out immediately; it
526  * won't have any objects recorded as depending on it.
527  */
528  if (IsPinnedObject(object->classId, object->objectId))
529  ereport(ERROR,
530  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
531  errmsg("cannot drop %s because it is required by the database system",
532  getObjectDescription(object, false))));
533 
534  /*
535  * The target object might be internally dependent on some other object
536  * (its "owner"), and/or be a member of an extension (also considered its
537  * owner). If so, and if we aren't recursing from the owning object, we
538  * have to transform this deletion request into a deletion request of the
539  * owning object. (We'll eventually recurse back to this object, but the
540  * owning object has to be visited first so it will be deleted after.) The
541  * way to find out about this is to scan the pg_depend entries that show
542  * what this object depends on.
543  */
544  ScanKeyInit(&key[0],
545  Anum_pg_depend_classid,
546  BTEqualStrategyNumber, F_OIDEQ,
547  ObjectIdGetDatum(object->classId));
548  ScanKeyInit(&key[1],
549  Anum_pg_depend_objid,
550  BTEqualStrategyNumber, F_OIDEQ,
551  ObjectIdGetDatum(object->objectId));
552  if (object->objectSubId != 0)
553  {
554  /* Consider only dependencies of this sub-object */
555  ScanKeyInit(&key[2],
556  Anum_pg_depend_objsubid,
557  BTEqualStrategyNumber, F_INT4EQ,
558  Int32GetDatum(object->objectSubId));
559  nkeys = 3;
560  }
561  else
562  {
563  /* Consider dependencies of this object and any sub-objects it has */
564  nkeys = 2;
565  }
566 
567  scan = systable_beginscan(*depRel, DependDependerIndexId, true,
568  NULL, nkeys, key);
569 
570  /* initialize variables that loop may fill */
571  memset(&owningObject, 0, sizeof(owningObject));
572  memset(&partitionObject, 0, sizeof(partitionObject));
573 
574  while (HeapTupleIsValid(tup = systable_getnext(scan)))
575  {
576  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
577 
578  otherObject.classId = foundDep->refclassid;
579  otherObject.objectId = foundDep->refobjid;
580  otherObject.objectSubId = foundDep->refobjsubid;
581 
582  /*
583  * When scanning dependencies of a whole object, we may find rows
584  * linking sub-objects of the object to the object itself. (Normally,
585  * such a dependency is implicit, but we must make explicit ones in
586  * some cases involving partitioning.) We must ignore such rows to
587  * avoid infinite recursion.
588  */
589  if (otherObject.classId == object->classId &&
590  otherObject.objectId == object->objectId &&
591  object->objectSubId == 0)
592  continue;
593 
594  switch (foundDep->deptype)
595  {
596  case DEPENDENCY_NORMAL:
597  case DEPENDENCY_AUTO:
599  /* no problem */
600  break;
601 
603 
604  /*
605  * If told to, ignore EXTENSION dependencies altogether. This
606  * flag is normally used to prevent dropping extensions during
607  * temporary-object cleanup, even if a temp object was created
608  * during an extension script.
609  */
611  break;
612 
613  /*
614  * If the other object is the extension currently being
615  * created/altered, ignore this dependency and continue with
616  * the deletion. This allows dropping of an extension's
617  * objects within the extension's scripts, as well as corner
618  * cases such as dropping a transient object created within
619  * such a script.
620  */
621  if (creating_extension &&
622  otherObject.classId == ExtensionRelationId &&
623  otherObject.objectId == CurrentExtensionObject)
624  break;
625 
626  /* Otherwise, treat this like an internal dependency */
627  /* FALL THRU */
628 
629  case DEPENDENCY_INTERNAL:
630 
631  /*
632  * This object is part of the internal implementation of
633  * another object, or is part of the extension that is the
634  * other object. We have three cases:
635  *
636  * 1. At the outermost recursion level, we must disallow the
637  * DROP. However, if the owning object is listed in
638  * pendingObjects, just release the caller's lock and return;
639  * we'll eventually complete the DROP when we reach that entry
640  * in the pending list.
641  *
642  * Note: the above statement is true only if this pg_depend
643  * entry still exists by then; in principle, therefore, we
644  * could miss deleting an item the user told us to delete.
645  * However, no inconsistency can result: since we're at outer
646  * level, there is no object depending on this one.
647  */
648  if (stack == NULL)
649  {
650  if (pendingObjects &&
651  object_address_present(&otherObject, pendingObjects))
652  {
653  systable_endscan(scan);
654  /* need to release caller's lock; see notes below */
655  ReleaseDeletionLock(object);
656  return;
657  }
658 
659  /*
660  * We postpone actually issuing the error message until
661  * after this loop, so that we can make the behavior
662  * independent of the ordering of pg_depend entries, at
663  * least if there's not more than one INTERNAL and one
664  * EXTENSION dependency. (If there's more, we'll complain
665  * about a random one of them.) Prefer to complain about
666  * EXTENSION, since that's generally a more important
667  * dependency.
668  */
669  if (!OidIsValid(owningObject.classId) ||
670  foundDep->deptype == DEPENDENCY_EXTENSION)
671  owningObject = otherObject;
672  break;
673  }
674 
675  /*
676  * 2. When recursing from the other end of this dependency,
677  * it's okay to continue with the deletion. This holds when
678  * recursing from a whole object that includes the nominal
679  * other end as a component, too. Since there can be more
680  * than one "owning" object, we have to allow matches that are
681  * more than one level down in the stack.
682  */
683  if (stack_address_present_add_flags(&otherObject, 0, stack))
684  break;
685 
686  /*
687  * 3. Not all the owning objects have been visited, so
688  * transform this deletion request into a delete of this
689  * owning object.
690  *
691  * First, release caller's lock on this object and get
692  * deletion lock on the owning object. (We must release
693  * caller's lock to avoid deadlock against a concurrent
694  * deletion of the owning object.)
695  */
696  ReleaseDeletionLock(object);
697  AcquireDeletionLock(&otherObject, 0);
698 
699  /*
700  * The owning object might have been deleted while we waited
701  * to lock it; if so, neither it nor the current object are
702  * interesting anymore. We test this by checking the
703  * pg_depend entry (see notes below).
704  */
705  if (!systable_recheck_tuple(scan, tup))
706  {
707  systable_endscan(scan);
708  ReleaseDeletionLock(&otherObject);
709  return;
710  }
711 
712  /*
713  * One way or the other, we're done with the scan; might as
714  * well close it down before recursing, to reduce peak
715  * resource consumption.
716  */
717  systable_endscan(scan);
718 
719  /*
720  * Okay, recurse to the owning object instead of proceeding.
721  *
722  * We do not need to stack the current object; we want the
723  * traversal order to be as if the original reference had
724  * linked to the owning object instead of this one.
725  *
726  * The dependency type is a "reverse" dependency: we need to
727  * delete the owning object if this one is to be deleted, but
728  * this linkage is never a reason for an automatic deletion.
729  */
730  findDependentObjects(&otherObject,
732  flags,
733  stack,
734  targetObjects,
735  pendingObjects,
736  depRel);
737 
738  /*
739  * The current target object should have been added to
740  * targetObjects while processing the owning object; but it
741  * probably got only the flag bits associated with the
742  * dependency we're looking at. We need to add the objflags
743  * that were passed to this recursion level, too, else we may
744  * get a bogus failure in reportDependentObjects (if, for
745  * example, we were called due to a partition dependency).
746  *
747  * If somehow the current object didn't get scheduled for
748  * deletion, bleat. (That would imply that somebody deleted
749  * this dependency record before the recursion got to it.)
750  * Another idea would be to reacquire lock on the current
751  * object and resume trying to delete it, but it seems not
752  * worth dealing with the race conditions inherent in that.
753  */
754  if (!object_address_present_add_flags(object, objflags,
755  targetObjects))
756  elog(ERROR, "deletion of owning object %s failed to delete %s",
757  getObjectDescription(&otherObject, false),
758  getObjectDescription(object, false));
759 
760  /* And we're done here. */
761  return;
762 
764 
765  /*
766  * Remember that this object has a partition-type dependency.
767  * After the dependency scan, we'll complain if we didn't find
768  * a reason to delete one of its partition dependencies.
769  */
770  objflags |= DEPFLAG_IS_PART;
771 
772  /*
773  * Also remember the primary partition owner, for error
774  * messages. If there are multiple primary owners (which
775  * there should not be), we'll report a random one of them.
776  */
777  partitionObject = otherObject;
778  break;
779 
781 
782  /*
783  * Only use secondary partition owners in error messages if we
784  * find no primary owner (which probably shouldn't happen).
785  */
786  if (!(objflags & DEPFLAG_IS_PART))
787  partitionObject = otherObject;
788 
789  /*
790  * Remember that this object has a partition-type dependency.
791  * After the dependency scan, we'll complain if we didn't find
792  * a reason to delete one of its partition dependencies.
793  */
794  objflags |= DEPFLAG_IS_PART;
795  break;
796 
797  default:
798  elog(ERROR, "unrecognized dependency type '%c' for %s",
799  foundDep->deptype, getObjectDescription(object, false));
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, false);
818  else
819  otherObjDesc = getObjectDescription(&owningObject, false);
820 
821  ereport(ERROR,
822  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
823  errmsg("cannot drop %s because %s requires it",
824  getObjectDescription(object, false), 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  default:
926  elog(ERROR, "unrecognized dependency type '%c' for %s",
927  foundDep->deptype, getObjectDescription(object, false));
928  subflags = 0; /* keep compiler quiet */
929  break;
930  }
931 
932  /* And add it to the pending-objects list */
933  if (numDependentObjects >= maxDependentObjects)
934  {
935  /* enlarge array if needed */
936  maxDependentObjects *= 2;
937  dependentObjects = (ObjectAddressAndFlags *)
938  repalloc(dependentObjects,
939  maxDependentObjects * sizeof(ObjectAddressAndFlags));
940  }
941 
942  dependentObjects[numDependentObjects].obj = otherObject;
943  dependentObjects[numDependentObjects].subflags = subflags;
944  numDependentObjects++;
945  }
946 
947  systable_endscan(scan);
948 
949  /*
950  * Now we can sort the dependent objects into a stable visitation order.
951  * It's safe to use object_address_comparator here since the obj field is
952  * first within ObjectAddressAndFlags.
953  */
954  if (numDependentObjects > 1)
955  qsort((void *) dependentObjects, numDependentObjects,
956  sizeof(ObjectAddressAndFlags),
958 
959  /*
960  * Now recurse to the dependent objects. We must visit them first since
961  * they have to be deleted before the current object.
962  */
963  mystack.object = object; /* set up a new stack level */
964  mystack.flags = objflags;
965  mystack.next = stack;
966 
967  for (int i = 0; i < numDependentObjects; i++)
968  {
969  ObjectAddressAndFlags *depObj = dependentObjects + i;
970 
971  findDependentObjects(&depObj->obj,
972  depObj->subflags,
973  flags,
974  &mystack,
975  targetObjects,
976  pendingObjects,
977  depRel);
978  }
979 
980  pfree(dependentObjects);
981 
982  /*
983  * Finally, we can add the target object to targetObjects. Be careful to
984  * include any flags that were passed back down to us from inner recursion
985  * levels. Record the "dependee" as being either the most important
986  * partition owner if there is one, else the object we recursed from, if
987  * any. (The logic in reportDependentObjects() is such that it can only
988  * need one of those objects.)
989  */
990  extra.flags = mystack.flags;
991  if (extra.flags & DEPFLAG_IS_PART)
992  extra.dependee = partitionObject;
993  else if (stack)
994  extra.dependee = *stack->object;
995  else
996  memset(&extra.dependee, 0, sizeof(extra.dependee));
997  add_exact_object_address_extra(object, &extra, targetObjects);
998 }
static void findDependentObjects(const ObjectAddress *object, int objflags, int flags, ObjectAddressStack *stack, ObjectAddresses *targetObjects, const ObjectAddresses *pendingObjects, Relation *depRel)
Definition: dependency.c:472
Oid CurrentExtensionObject
Definition: extension.c:72
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2386
#define DEPFLAG_PARTITION
Definition: dependency.c:102
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
int errhint(const char *fmt,...)
Definition: elog.c:1156
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
static void add_exact_object_address_extra(const ObjectAddress *object, const ObjectAddressExtra *extra, ObjectAddresses *addrs)
Definition: dependency.c:2510
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2545
void ReleaseDeletionLock(const ObjectAddress *object)
Definition: dependency.c:1546
int errcode(int sqlerrcode)
Definition: elog.c:698
#define DEPFLAG_REVERSE
Definition: dependency.c:104
#define OidIsValid(objectId)
Definition: c.h:710
struct ObjectAddressStack * next
Definition: dependency.c:125
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
bool systable_recheck_tuple(SysScanDesc sysscan, HeapTuple tup)
Definition: genam.c:561
ObjectAddress obj
Definition: dependency.c:131
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
void pfree(void *pointer)
Definition: mcxt.c:1169
bool IsPinnedObject(Oid classId, Oid objectId)
Definition: catalog.c:307
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define DEPFLAG_IS_PART
Definition: dependency.c:105
#define DEPFLAG_AUTO
Definition: dependency.c:100
const ObjectAddress * object
Definition: dependency.c:123
#define DEPFLAG_INTERNAL
Definition: dependency.c:101
static bool object_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddresses *addrs)
Definition: dependency.c:2571
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
void AcquireDeletionLock(const ObjectAddress *object, int flags)
Definition: dependency.c:1517
bool creating_extension
Definition: extension.c:71
#define ereport(elevel,...)
Definition: elog.h:157
#define DEPFLAG_EXTENSION
Definition: dependency.c:103
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
#define Int32GetDatum(X)
Definition: postgres.h:523
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define DEPFLAG_NORMAL
Definition: dependency.c:99
#define elog(elevel,...)
Definition: elog.h:232
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:505
static bool stack_address_present_add_flags(const ObjectAddress *object, int flags, ObjectAddressStack *stack)
Definition: dependency.c:2644
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:137
ObjectAddress dependee
Definition: dependency.c:94
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ free_object_addresses()

◆ getObjectClass()

ObjectClass getObjectClass ( const ObjectAddress object)

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

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

◆ new_object_addresses()

ObjectAddresses* new_object_addresses ( void  )

Definition at line 2430 of file dependency.c.

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

Referenced by AggregateCreate(), AlterExtensionNamespace(), AlterTableNamespace(), AlterTypeNamespace(), ATExecDropColumn(), ATPostAlterTypeCleanup(), CastCreate(), CreateConstraintEntry(), CreateProceduralLanguage(), CreateTransform(), DropClonedTriggersFromPartition(), GenerateTypeDependencies(), heap_create_with_catalog(), index_create(), InsertExtensionTuple(), makeConfigurationDependencies(), makeDictionaryDependencies(), makeOperatorDependencies(), makeParserDependencies(), makeTSTemplateDependencies(), performDeletion(), performMultipleDeletions(), PreCommit_on_commit_actions(), ProcedureCreate(), RangeCreate(), recordDependencyOnExpr(), recordDependencyOnSingleRelExpr(), ReindexRelationConcurrently(), RemoveObjects(), RemoveRelations(), shdepDropOwned(), and StorePartitionKey().

2431 {
2432  ObjectAddresses *addrs;
2433 
2434  addrs = palloc(sizeof(ObjectAddresses));
2435 
2436  addrs->numrefs = 0;
2437  addrs->maxrefs = 32;
2438  addrs->refs = (ObjectAddress *)
2439  palloc(addrs->maxrefs * sizeof(ObjectAddress));
2440  addrs->extras = NULL; /* until/unless needed */
2441 
2442  return addrs;
2443 }
ObjectAddress * refs
Definition: dependency.c:112
ObjectAddressExtra * extras
Definition: dependency.c:113
void * palloc(Size size)
Definition: mcxt.c:1062

◆ object_address_comparator()

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

Definition at line 2386 of file dependency.c.

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

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

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

◆ object_address_present()

bool object_address_present ( const ObjectAddress object,
const ObjectAddresses addrs 
)

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

2547 {
2548  int i;
2549 
2550  for (i = addrs->numrefs - 1; i >= 0; i--)
2551  {
2552  const ObjectAddress *thisobj = addrs->refs + i;
2553 
2554  if (object->classId == thisobj->classId &&
2555  object->objectId == thisobj->objectId)
2556  {
2557  if (object->objectSubId == thisobj->objectSubId ||
2558  thisobj->objectSubId == 0)
2559  return true;
2560  }
2561  }
2562 
2563  return false;
2564 }
ObjectAddress * refs
Definition: dependency.c:112
int i

◆ object_address_present_add_flags()

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

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

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

◆ performDeletion()

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

Definition at line 313 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(), ATExecDropConstraint(), ATExecDropIdentity(), DefineQueryRewrite(), DetachPartitionFinalize(), do_autovacuum(), dropOperators(), dropProcedures(), finish_heap_swap(), inv_drop(), PublicationDropTables(), RemoveAttrDefault(), RemoveTempRelations(), RemoveUserMapping(), SetDefaultACL(), and tryAttachPartitionForeignKey().

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

◆ performMultipleDeletions()

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

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

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

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

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

2697 {
2699  recordMultipleDependencies(depender,
2700  referenced->refs, referenced->numrefs,
2701  behavior);
2702 }
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2326
ObjectAddress * refs
Definition: dependency.c:112
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:56

◆ recordDependencyOnExpr()

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

Definition at line 1571 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(), CreateTriggerFiringOn(), GenerateTypeDependencies(), InsertRule(), and ProcedureCreate().

1574 {
1576 
1577  context.addrs = new_object_addresses();
1578 
1579  /* Set up interpretation for Vars at varlevelsup = 0 */
1580  context.rtables = list_make1(rtable);
1581 
1582  /* Scan the expression tree for referenceable objects */
1583  find_expr_references_walker(expr, &context);
1584 
1585  /* Remove any duplicates */
1587 
1588  /* And record 'em */
1589  recordMultipleDependencies(depender,
1590  context.addrs->refs, context.addrs->numrefs,
1591  behavior);
1592 
1593  free_object_addresses(context.addrs);
1594 }
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1717
ObjectAddresses * addrs
Definition: dependency.c:138
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2430
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2725
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2326
#define list_make1(x1)
Definition: pg_list.h:206
ObjectAddress * refs
Definition: dependency.c:112
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:56

◆ recordDependencyOnSingleRelExpr()

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

Definition at line 1614 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(), CreateStatistics(), index_create(), StoreAttrDefault(), and StorePartitionKey().

1619 {
1621  RangeTblEntry rte;
1622 
1623  context.addrs = new_object_addresses();
1624 
1625  /* We gin up a rather bogus rangetable list to handle Vars */
1626  MemSet(&rte, 0, sizeof(rte));
1627  rte.type = T_RangeTblEntry;
1628  rte.rtekind = RTE_RELATION;
1629  rte.relid = relId;
1630  rte.relkind = RELKIND_RELATION; /* no need for exactness here */
1632 
1633  context.rtables = list_make1(list_make1(&rte));
1634 
1635  /* Scan the expression tree for referenceable objects */
1636  find_expr_references_walker(expr, &context);
1637 
1638  /* Remove any duplicates */
1640 
1641  /* Separate self-dependencies if necessary */
1642  if ((behavior != self_behavior || reverse_self) &&
1643  context.addrs->numrefs > 0)
1644  {
1645  ObjectAddresses *self_addrs;
1646  ObjectAddress *outobj;
1647  int oldref,
1648  outrefs;
1649 
1650  self_addrs = new_object_addresses();
1651 
1652  outobj = context.addrs->refs;
1653  outrefs = 0;
1654  for (oldref = 0; oldref < context.addrs->numrefs; oldref++)
1655  {
1656  ObjectAddress *thisobj = context.addrs->refs + oldref;
1657 
1658  if (thisobj->classId == RelationRelationId &&
1659  thisobj->objectId == relId)
1660  {
1661  /* Move this ref into self_addrs */
1662  add_exact_object_address(thisobj, self_addrs);
1663  }
1664  else
1665  {
1666  /* Keep it in context.addrs */
1667  *outobj = *thisobj;
1668  outobj++;
1669  outrefs++;
1670  }
1671  }
1672  context.addrs->numrefs = outrefs;
1673 
1674  /* Record the self-dependencies with the appropriate direction */
1675  if (!reverse_self)
1676  recordMultipleDependencies(depender,
1677  self_addrs->refs, self_addrs->numrefs,
1678  self_behavior);
1679  else
1680  {
1681  /* Can't use recordMultipleDependencies, so do it the hard way */
1682  int selfref;
1683 
1684  for (selfref = 0; selfref < self_addrs->numrefs; selfref++)
1685  {
1686  ObjectAddress *thisobj = self_addrs->refs + selfref;
1687 
1688  recordDependencyOn(thisobj, depender, self_behavior);
1689  }
1690  }
1691 
1692  free_object_addresses(self_addrs);
1693  }
1694 
1695  /* Record the external dependencies */
1696  recordMultipleDependencies(depender,
1697  context.addrs->refs, context.addrs->numrefs,
1698  behavior);
1699 
1700  free_object_addresses(context.addrs);
1701 }
static bool find_expr_references_walker(Node *node, find_expr_references_context *context)
Definition: dependency.c:1717
ObjectAddresses * addrs
Definition: dependency.c:138
#define AccessShareLock
Definition: lockdefs.h:36
#define MemSet(start, val, len)
Definition: c.h:1008
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2485
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2430
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2725
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs)
Definition: dependency.c:2326
#define list_make1(x1)
Definition: pg_list.h:206
ObjectAddress * refs
Definition: dependency.c:112
void recordMultipleDependencies(const ObjectAddress *depender, const ObjectAddress *referenced, int nreferenced, DependencyType behavior)
Definition: pg_depend.c:56
RTEKind rtekind
Definition: parsenodes.h:1007
NodeTag type
Definition: parsenodes.h:1005

◆ ReleaseDeletionLock()

void ReleaseDeletionLock ( const ObjectAddress object)

Definition at line 1546 of file dependency.c.

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

Referenced by findDependentObjects(), and shdepDropOwned().

1547 {
1548  if (object->classId == RelationRelationId)
1550  else
1551  /* assume we should lock the whole object not a sub-object */
1552  UnlockDatabaseObject(object->classId, object->objectId, 0,
1554 }
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:200
void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:997
#define AccessExclusiveLock
Definition: lockdefs.h:45

◆ reportDependentObjects()

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

Definition at line 1014 of file dependency.c.

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

Referenced by performDeletion(), and performMultipleDeletions().

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

◆ sort_object_addresses()

void sort_object_addresses ( ObjectAddresses addrs)

Definition at line 2713 of file dependency.c.

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

Referenced by shdepDropOwned().

2714 {
2715  if (addrs->numrefs > 1)
2716  qsort((void *) addrs->refs, addrs->numrefs,
2717  sizeof(ObjectAddress),
2719 }
static int object_address_comparator(const void *a, const void *b)
Definition: dependency.c:2386
ObjectAddress * refs
Definition: dependency.c:112
#define qsort(a, b, c, d)
Definition: port.h:505

◆ stack_address_present_add_flags()

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

Definition at line 2644 of file dependency.c.

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

Referenced by findDependentObjects().

2647 {
2648  bool result = false;
2649  ObjectAddressStack *stackptr;
2650 
2651  for (stackptr = stack; stackptr; stackptr = stackptr->next)
2652  {
2653  const ObjectAddress *thisobj = stackptr->object;
2654 
2655  if (object->classId == thisobj->classId &&
2656  object->objectId == thisobj->objectId)
2657  {
2658  if (object->objectSubId == thisobj->objectSubId)
2659  {
2660  stackptr->flags |= flags;
2661  result = true;
2662  }
2663  else if (thisobj->objectSubId == 0)
2664  {
2665  /*
2666  * We're visiting a column with whole table already on stack.
2667  * As in object_address_present_add_flags(), we can skip
2668  * further processing of the subobject, but we don't want to
2669  * propagate flags for the subobject to the whole object.
2670  */
2671  result = true;
2672  }
2673  else if (object->objectSubId == 0)
2674  {
2675  /*
2676  * We're visiting a table with column already on stack. As in
2677  * object_address_present_add_flags(), we should propagate
2678  * flags for the whole object to each of its subobjects.
2679  */
2680  if (flags)
2681  stackptr->flags |= (flags | DEPFLAG_SUBOBJECT);
2682  }
2683  }
2684  }
2685 
2686  return result;
2687 }
#define DEPFLAG_SUBOBJECT
Definition: dependency.c:106
struct ObjectAddressStack * next
Definition: dependency.c:125
const ObjectAddress * object
Definition: dependency.c:123

Variable Documentation

◆ object_classes

const Oid object_classes[]
static

Definition at line 146 of file dependency.c.

Referenced by add_object_address().