1
/*-------------------------------------------------------------------------
4
* Routines to support inter-object dependencies.
7
* Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
8
* Portions Copyright (c) 1994, Regents of the University of California
11
* src/backend/catalog/dependency.c
13
*-------------------------------------------------------------------------
17
#include "access/genam.h"
18
#include "access/heapam.h"
19
#include "access/sysattr.h"
20
#include "access/xact.h"
21
#include "catalog/dependency.h"
22
#include "catalog/heap.h"
23
#include "catalog/index.h"
24
#include "catalog/indexing.h"
25
#include "catalog/namespace.h"
26
#include "catalog/pg_amop.h"
27
#include "catalog/pg_amproc.h"
28
#include "catalog/pg_attrdef.h"
29
#include "catalog/pg_authid.h"
30
#include "catalog/pg_cast.h"
31
#include "catalog/pg_collation.h"
32
#include "catalog/pg_collation_fn.h"
33
#include "catalog/pg_constraint.h"
34
#include "catalog/pg_conversion.h"
35
#include "catalog/pg_conversion_fn.h"
36
#include "catalog/pg_database.h"
37
#include "catalog/pg_default_acl.h"
38
#include "catalog/pg_depend.h"
39
#include "catalog/pg_extension.h"
40
#include "catalog/pg_foreign_data_wrapper.h"
41
#include "catalog/pg_foreign_server.h"
42
#include "catalog/pg_foreign_table.h"
43
#include "catalog/pg_language.h"
44
#include "catalog/pg_largeobject.h"
45
#include "catalog/pg_namespace.h"
46
#include "catalog/pg_opclass.h"
47
#include "catalog/pg_operator.h"
48
#include "catalog/pg_opfamily.h"
49
#include "catalog/pg_proc.h"
50
#include "catalog/pg_rewrite.h"
51
#include "catalog/pg_tablespace.h"
52
#include "catalog/pg_trigger.h"
53
#include "catalog/pg_ts_config.h"
54
#include "catalog/pg_ts_dict.h"
55
#include "catalog/pg_ts_parser.h"
56
#include "catalog/pg_ts_template.h"
57
#include "catalog/pg_type.h"
58
#include "catalog/pg_user_mapping.h"
59
#include "commands/comment.h"
60
#include "commands/dbcommands.h"
61
#include "commands/defrem.h"
62
#include "commands/extension.h"
63
#include "commands/proclang.h"
64
#include "commands/schemacmds.h"
65
#include "commands/seclabel.h"
66
#include "commands/tablespace.h"
67
#include "commands/trigger.h"
68
#include "commands/typecmds.h"
69
#include "foreign/foreign.h"
70
#include "miscadmin.h"
71
#include "nodes/nodeFuncs.h"
72
#include "parser/parsetree.h"
73
#include "rewrite/rewriteRemove.h"
74
#include "storage/lmgr.h"
75
#include "utils/acl.h"
76
#include "utils/builtins.h"
77
#include "utils/fmgroids.h"
78
#include "utils/guc.h"
79
#include "utils/lsyscache.h"
80
#include "utils/syscache.h"
81
#include "utils/tqual.h"
85
* Deletion processing requires additional state for each ObjectAddress that
86
* it's planning to delete. For simplicity and code-sharing we make the
87
* ObjectAddresses code support arrays with or without this extra state.
91
int flags; /* bitmask, see bit definitions below */
92
ObjectAddress dependee; /* object whose deletion forced this one */
95
/* ObjectAddressExtra flag bits */
96
#define DEPFLAG_ORIGINAL 0x0001 /* an original deletion target */
97
#define DEPFLAG_NORMAL 0x0002 /* reached via normal dependency */
98
#define DEPFLAG_AUTO 0x0004 /* reached via auto dependency */
99
#define DEPFLAG_INTERNAL 0x0008 /* reached via internal dependency */
100
#define DEPFLAG_EXTENSION 0x0010 /* reached via extension dependency */
103
/* expansible list of ObjectAddresses */
104
struct ObjectAddresses
106
ObjectAddress *refs; /* => palloc'd array */
107
ObjectAddressExtra *extras; /* => palloc'd array, or NULL if not used */
108
int numrefs; /* current number of references */
109
int maxrefs; /* current size of palloc'd array(s) */
112
/* typedef ObjectAddresses appears in dependency.h */
114
/* threaded list of ObjectAddresses, for recursion detection */
115
typedef struct ObjectAddressStack
117
const ObjectAddress *object; /* object being visited */
118
int flags; /* its current flag bits */
119
struct ObjectAddressStack *next; /* next outer stack level */
120
} ObjectAddressStack;
122
/* for find_expr_references_walker */
125
ObjectAddresses *addrs; /* addresses being accumulated */
126
List *rtables; /* list of rangetables to resolve Vars */
127
} find_expr_references_context;
130
* This constant table maps ObjectClasses to the corresponding catalog OIDs.
131
* See also getObjectClass().
133
static const Oid object_classes[MAX_OCLASS] = {
134
RelationRelationId, /* OCLASS_CLASS */
135
ProcedureRelationId, /* OCLASS_PROC */
136
TypeRelationId, /* OCLASS_TYPE */
137
CastRelationId, /* OCLASS_CAST */
138
CollationRelationId, /* OCLASS_COLLATION */
139
ConstraintRelationId, /* OCLASS_CONSTRAINT */
140
ConversionRelationId, /* OCLASS_CONVERSION */
141
AttrDefaultRelationId, /* OCLASS_DEFAULT */
142
LanguageRelationId, /* OCLASS_LANGUAGE */
143
LargeObjectRelationId, /* OCLASS_LARGEOBJECT */
144
OperatorRelationId, /* OCLASS_OPERATOR */
145
OperatorClassRelationId, /* OCLASS_OPCLASS */
146
OperatorFamilyRelationId, /* OCLASS_OPFAMILY */
147
AccessMethodOperatorRelationId, /* OCLASS_AMOP */
148
AccessMethodProcedureRelationId, /* OCLASS_AMPROC */
149
RewriteRelationId, /* OCLASS_REWRITE */
150
TriggerRelationId, /* OCLASS_TRIGGER */
151
NamespaceRelationId, /* OCLASS_SCHEMA */
152
TSParserRelationId, /* OCLASS_TSPARSER */
153
TSDictionaryRelationId, /* OCLASS_TSDICT */
154
TSTemplateRelationId, /* OCLASS_TSTEMPLATE */
155
TSConfigRelationId, /* OCLASS_TSCONFIG */
156
AuthIdRelationId, /* OCLASS_ROLE */
157
DatabaseRelationId, /* OCLASS_DATABASE */
158
TableSpaceRelationId, /* OCLASS_TBLSPACE */
159
ForeignDataWrapperRelationId, /* OCLASS_FDW */
160
ForeignServerRelationId, /* OCLASS_FOREIGN_SERVER */
161
UserMappingRelationId, /* OCLASS_USER_MAPPING */
162
DefaultAclRelationId, /* OCLASS_DEFACL */
163
ExtensionRelationId /* OCLASS_EXTENSION */
167
static void findDependentObjects(const ObjectAddress *object,
169
ObjectAddressStack *stack,
170
ObjectAddresses *targetObjects,
171
const ObjectAddresses *pendingObjects,
173
static void reportDependentObjects(const ObjectAddresses *targetObjects,
174
DropBehavior behavior,
176
const ObjectAddress *origObject);
177
static void deleteOneObject(const ObjectAddress *object, Relation depRel);
178
static void doDeletion(const ObjectAddress *object);
179
static void AcquireDeletionLock(const ObjectAddress *object);
180
static void ReleaseDeletionLock(const ObjectAddress *object);
181
static bool find_expr_references_walker(Node *node,
182
find_expr_references_context *context);
183
static void eliminate_duplicate_dependencies(ObjectAddresses *addrs);
184
static int object_address_comparator(const void *a, const void *b);
185
static void add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
186
ObjectAddresses *addrs);
187
static void add_exact_object_address_extra(const ObjectAddress *object,
188
const ObjectAddressExtra *extra,
189
ObjectAddresses *addrs);
190
static bool object_address_present_add_flags(const ObjectAddress *object,
192
ObjectAddresses *addrs);
193
static void getRelationDescription(StringInfo buffer, Oid relid);
194
static void getOpFamilyDescription(StringInfo buffer, Oid opfid);
198
* performDeletion: attempt to drop the specified object. If CASCADE
199
* behavior is specified, also drop any dependent objects (recursively).
200
* If RESTRICT behavior is specified, error out if there are any dependent
201
* objects, except for those that should be implicitly dropped anyway
202
* according to the dependency type.
204
* This is the outer control routine for all forms of DROP that drop objects
205
* that can participate in dependencies. Note that the next two routines
206
* are variants on the same theme; if you change anything here you'll likely
207
* need to fix them too.
210
performDeletion(const ObjectAddress *object,
211
DropBehavior behavior)
214
ObjectAddresses *targetObjects;
218
* We save some cycles by opening pg_depend just once and passing the
219
* Relation pointer down to all the recursive deletion steps.
221
depRel = heap_open(DependRelationId, RowExclusiveLock);
224
* Acquire deletion lock on the target object. (Ideally the caller has
225
* done this already, but many places are sloppy about it.)
227
AcquireDeletionLock(object);
230
* Construct a list of objects to delete (ie, the given object plus
231
* everything directly or indirectly dependent on it).
233
targetObjects = new_object_addresses();
235
findDependentObjects(object,
237
NULL, /* empty stack */
239
NULL, /* no pendingObjects */
243
* Check if deletion is allowed, and report about cascaded deletes.
245
reportDependentObjects(targetObjects,
251
* Delete all the objects in the proper order.
253
for (i = 0; i < targetObjects->numrefs; i++)
255
ObjectAddress *thisobj = targetObjects->refs + i;
257
deleteOneObject(thisobj, depRel);
261
free_object_addresses(targetObjects);
263
heap_close(depRel, RowExclusiveLock);
267
* performMultipleDeletions: Similar to performDeletion, but act on multiple
270
* The main difference from issuing multiple performDeletion calls is that the
271
* list of objects that would be implicitly dropped, for each object to be
272
* dropped, is the union of the implicit-object list for all objects. This
273
* makes each check be more relaxed.
276
performMultipleDeletions(const ObjectAddresses *objects,
277
DropBehavior behavior)
280
ObjectAddresses *targetObjects;
283
/* No work if no objects... */
284
if (objects->numrefs <= 0)
288
* We save some cycles by opening pg_depend just once and passing the
289
* Relation pointer down to all the recursive deletion steps.
291
depRel = heap_open(DependRelationId, RowExclusiveLock);
294
* Construct a list of objects to delete (ie, the given objects plus
295
* everything directly or indirectly dependent on them). Note that
296
* because we pass the whole objects list as pendingObjects context, we
297
* won't get a failure from trying to delete an object that is internally
298
* dependent on another one in the list; we'll just skip that object and
299
* delete it when we reach its owner.
301
targetObjects = new_object_addresses();
303
for (i = 0; i < objects->numrefs; i++)
305
const ObjectAddress *thisobj = objects->refs + i;
308
* Acquire deletion lock on each target object. (Ideally the caller
309
* has done this already, but many places are sloppy about it.)
311
AcquireDeletionLock(thisobj);
313
findDependentObjects(thisobj,
315
NULL, /* empty stack */
322
* Check if deletion is allowed, and report about cascaded deletes.
324
* If there's exactly one object being deleted, report it the same way as
325
* in performDeletion(), else we have to be vaguer.
327
reportDependentObjects(targetObjects,
330
(objects->numrefs == 1 ? objects->refs : NULL));
333
* Delete all the objects in the proper order.
335
for (i = 0; i < targetObjects->numrefs; i++)
337
ObjectAddress *thisobj = targetObjects->refs + i;
339
deleteOneObject(thisobj, depRel);
343
free_object_addresses(targetObjects);
345
heap_close(depRel, RowExclusiveLock);
349
* deleteWhatDependsOn: attempt to drop everything that depends on the
350
* specified object, though not the object itself. Behavior is always
353
* This is currently used only to clean out the contents of a schema
354
* (namespace): the passed object is a namespace. We normally want this
355
* to be done silently, so there's an option to suppress NOTICE messages.
358
deleteWhatDependsOn(const ObjectAddress *object,
362
ObjectAddresses *targetObjects;
366
* We save some cycles by opening pg_depend just once and passing the
367
* Relation pointer down to all the recursive deletion steps.
369
depRel = heap_open(DependRelationId, RowExclusiveLock);
372
* Acquire deletion lock on the target object. (Ideally the caller has
373
* done this already, but many places are sloppy about it.)
375
AcquireDeletionLock(object);
378
* Construct a list of objects to delete (ie, the given object plus
379
* everything directly or indirectly dependent on it).
381
targetObjects = new_object_addresses();
383
findDependentObjects(object,
385
NULL, /* empty stack */
387
NULL, /* no pendingObjects */
391
* Check if deletion is allowed, and report about cascaded deletes.
393
reportDependentObjects(targetObjects,
395
showNotices ? NOTICE : DEBUG2,
399
* Delete all the objects in the proper order, except we skip the original
402
for (i = 0; i < targetObjects->numrefs; i++)
404
ObjectAddress *thisobj = targetObjects->refs + i;
405
ObjectAddressExtra *thisextra = targetObjects->extras + i;
407
if (thisextra->flags & DEPFLAG_ORIGINAL)
410
deleteOneObject(thisobj, depRel);
414
free_object_addresses(targetObjects);
416
heap_close(depRel, RowExclusiveLock);
420
* findDependentObjects - find all objects that depend on 'object'
422
* For every object that depends on the starting object, acquire a deletion
423
* lock on the object, add it to targetObjects (if not already there),
424
* and recursively find objects that depend on it. An object's dependencies
425
* will be placed into targetObjects before the object itself; this means
426
* that the finished list's order represents a safe deletion order.
428
* The caller must already have a deletion lock on 'object' itself,
429
* but must not have added it to targetObjects. (Note: there are corner
430
* cases where we won't add the object either, and will also release the
431
* caller-taken lock. This is a bit ugly, but the API is set up this way
432
* to allow easy rechecking of an object's liveness after we lock it. See
433
* notes within the function.)
435
* When dropping a whole object (subId = 0), we find dependencies for
436
* its sub-objects too.
438
* object: the object to add to targetObjects and find dependencies on
439
* flags: flags to be ORed into the object's targetObjects entry
440
* stack: list of objects being visited in current recursion; topmost item
441
* is the object that we recursed from (NULL for external callers)
442
* targetObjects: list of objects that are scheduled to be deleted
443
* pendingObjects: list of other objects slated for destruction, but
444
* not necessarily in targetObjects yet (can be NULL if none)
445
* depRel: already opened pg_depend relation
448
findDependentObjects(const ObjectAddress *object,
450
ObjectAddressStack *stack,
451
ObjectAddresses *targetObjects,
452
const ObjectAddresses *pendingObjects,
459
ObjectAddress otherObject;
460
ObjectAddressStack mystack;
461
ObjectAddressExtra extra;
462
ObjectAddressStack *stackptr;
465
* If the target object is already being visited in an outer recursion
466
* level, just report the current flags back to that level and exit. This
467
* is needed to avoid infinite recursion in the face of circular
470
* The stack check alone would result in dependency loops being broken at
471
* an arbitrary point, ie, the first member object of the loop to be
472
* visited is the last one to be deleted. This is obviously unworkable.
473
* However, the check for internal dependency below guarantees that we
474
* will not break a loop at an internal dependency: if we enter the loop
475
* at an "owned" object we will switch and start at the "owning" object
476
* instead. We could probably hack something up to avoid breaking at an
477
* auto dependency, too, if we had to. However there are no known cases
478
* where that would be necessary.
480
for (stackptr = stack; stackptr; stackptr = stackptr->next)
482
if (object->classId == stackptr->object->classId &&
483
object->objectId == stackptr->object->objectId)
485
if (object->objectSubId == stackptr->object->objectSubId)
487
stackptr->flags |= flags;
492
* Could visit column with whole table already on stack; this is
493
* the same case noted in object_address_present_add_flags().
494
* (It's not clear this can really happen, but we might as well
497
if (stackptr->object->objectSubId == 0)
503
* It's also possible that the target object has already been completely
504
* processed and put into targetObjects. If so, again we just add the
505
* specified flags to its entry and return.
507
* (Note: in these early-exit cases we could release the caller-taken
508
* lock, since the object is presumably now locked multiple times; but it
509
* seems not worth the cycles.)
511
if (object_address_present_add_flags(object, flags, targetObjects))
515
* The target object might be internally dependent on some other object
516
* (its "owner"). If so, and if we aren't recursing from the owning
517
* object, we have to transform this deletion request into a deletion
518
* request of the owning object. (We'll eventually recurse back to this
519
* object, but the owning object has to be visited first so it will be
520
* deleted after.) The way to find out about this is to scan the
521
* pg_depend entries that show what this object depends on.
524
Anum_pg_depend_classid,
525
BTEqualStrategyNumber, F_OIDEQ,
526
ObjectIdGetDatum(object->classId));
528
Anum_pg_depend_objid,
529
BTEqualStrategyNumber, F_OIDEQ,
530
ObjectIdGetDatum(object->objectId));
531
if (object->objectSubId != 0)
534
Anum_pg_depend_objsubid,
535
BTEqualStrategyNumber, F_INT4EQ,
536
Int32GetDatum(object->objectSubId));
542
scan = systable_beginscan(depRel, DependDependerIndexId, true,
543
SnapshotNow, nkeys, key);
545
while (HeapTupleIsValid(tup = systable_getnext(scan)))
547
Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
549
otherObject.classId = foundDep->refclassid;
550
otherObject.objectId = foundDep->refobjid;
551
otherObject.objectSubId = foundDep->refobjsubid;
553
switch (foundDep->deptype)
555
case DEPENDENCY_NORMAL:
556
case DEPENDENCY_AUTO:
559
case DEPENDENCY_INTERNAL:
560
case DEPENDENCY_EXTENSION:
563
* This object is part of the internal implementation of
564
* another object, or is part of the extension that is the
565
* other object. We have three cases:
567
* 1. At the outermost recursion level, disallow the DROP. (We
568
* just ereport here, rather than proceeding, since no other
569
* dependencies are likely to be interesting.) However, if
570
* the other object is listed in pendingObjects, just release
571
* the caller's lock and return; we'll eventually complete the
572
* DROP when we reach that entry in the pending list.
578
if (pendingObjects &&
579
object_address_present(&otherObject, pendingObjects))
581
systable_endscan(scan);
582
/* need to release caller's lock; see notes below */
583
ReleaseDeletionLock(object);
586
otherObjDesc = getObjectDescription(&otherObject);
588
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
589
errmsg("cannot drop %s because %s requires it",
590
getObjectDescription(object),
592
errhint("You can drop %s instead.",
597
* 2. When recursing from the other end of this dependency,
598
* it's okay to continue with the deletion. This holds when
599
* recursing from a whole object that includes the nominal
600
* other end as a component, too.
602
if (stack->object->classId == otherObject.classId &&
603
stack->object->objectId == otherObject.objectId &&
604
(stack->object->objectSubId == otherObject.objectSubId ||
605
stack->object->objectSubId == 0))
609
* 3. When recursing from anyplace else, transform this
610
* deletion request into a delete of the other object.
612
* First, release caller's lock on this object and get
613
* deletion lock on the other object. (We must release
614
* caller's lock to avoid deadlock against a concurrent
615
* deletion of the other object.)
617
ReleaseDeletionLock(object);
618
AcquireDeletionLock(&otherObject);
621
* The other object might have been deleted while we waited to
622
* lock it; if so, neither it nor the current object are
623
* interesting anymore. We test this by checking the
624
* pg_depend entry (see notes below).
626
if (!systable_recheck_tuple(scan, tup))
628
systable_endscan(scan);
629
ReleaseDeletionLock(&otherObject);
634
* Okay, recurse to the other object instead of proceeding. We
635
* treat this exactly as if the original reference had linked
636
* to that object instead of this one; hence, pass through the
637
* same flags and stack.
639
findDependentObjects(&otherObject,
645
/* And we're done here. */
646
systable_endscan(scan);
651
* Should not happen; PIN dependencies should have zeroes in
652
* the depender fields...
654
elog(ERROR, "incorrect use of PIN dependency with %s",
655
getObjectDescription(object));
658
elog(ERROR, "unrecognized dependency type '%c' for %s",
659
foundDep->deptype, getObjectDescription(object));
664
systable_endscan(scan);
667
* Now recurse to any dependent objects. We must visit them first since
668
* they have to be deleted before the current object.
670
mystack.object = object; /* set up a new stack level */
671
mystack.flags = flags;
672
mystack.next = stack;
675
Anum_pg_depend_refclassid,
676
BTEqualStrategyNumber, F_OIDEQ,
677
ObjectIdGetDatum(object->classId));
679
Anum_pg_depend_refobjid,
680
BTEqualStrategyNumber, F_OIDEQ,
681
ObjectIdGetDatum(object->objectId));
682
if (object->objectSubId != 0)
685
Anum_pg_depend_refobjsubid,
686
BTEqualStrategyNumber, F_INT4EQ,
687
Int32GetDatum(object->objectSubId));
693
scan = systable_beginscan(depRel, DependReferenceIndexId, true,
694
SnapshotNow, nkeys, key);
696
while (HeapTupleIsValid(tup = systable_getnext(scan)))
698
Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(tup);
701
otherObject.classId = foundDep->classid;
702
otherObject.objectId = foundDep->objid;
703
otherObject.objectSubId = foundDep->objsubid;
706
* Must lock the dependent object before recursing to it.
708
AcquireDeletionLock(&otherObject);
711
* The dependent object might have been deleted while we waited to
712
* lock it; if so, we don't need to do anything more with it. We can
713
* test this cheaply and independently of the object's type by seeing
714
* if the pg_depend tuple we are looking at is still live. (If the
715
* object got deleted, the tuple would have been deleted too.)
717
if (!systable_recheck_tuple(scan, tup))
719
/* release the now-useless lock */
720
ReleaseDeletionLock(&otherObject);
721
/* and continue scanning for dependencies */
725
/* Recurse, passing flags indicating the dependency type */
726
switch (foundDep->deptype)
728
case DEPENDENCY_NORMAL:
729
subflags = DEPFLAG_NORMAL;
731
case DEPENDENCY_AUTO:
732
subflags = DEPFLAG_AUTO;
734
case DEPENDENCY_INTERNAL:
735
subflags = DEPFLAG_INTERNAL;
737
case DEPENDENCY_EXTENSION:
738
subflags = DEPFLAG_EXTENSION;
743
* For a PIN dependency we just ereport immediately; there
744
* won't be any others to report.
747
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
748
errmsg("cannot drop %s because it is required by the database system",
749
getObjectDescription(object))));
750
subflags = 0; /* keep compiler quiet */
753
elog(ERROR, "unrecognized dependency type '%c' for %s",
754
foundDep->deptype, getObjectDescription(object));
755
subflags = 0; /* keep compiler quiet */
759
findDependentObjects(&otherObject,
767
systable_endscan(scan);
770
* Finally, we can add the target object to targetObjects. Be careful to
771
* include any flags that were passed back down to us from inner recursion
774
extra.flags = mystack.flags;
776
extra.dependee = *stack->object;
778
memset(&extra.dependee, 0, sizeof(extra.dependee));
779
add_exact_object_address_extra(object, &extra, targetObjects);
783
* reportDependentObjects - report about dependencies, and fail if RESTRICT
785
* Tell the user about dependent objects that we are going to delete
786
* (or would need to delete, but are prevented by RESTRICT mode);
787
* then error out if there are any and it's not CASCADE mode.
789
* targetObjects: list of objects that are scheduled to be deleted
790
* behavior: RESTRICT or CASCADE
791
* msglevel: elog level for non-error report messages
792
* origObject: base object of deletion, or NULL if not available
793
* (the latter case occurs in DROP OWNED)
796
reportDependentObjects(const ObjectAddresses *targetObjects,
797
DropBehavior behavior,
799
const ObjectAddress *origObject)
802
StringInfoData clientdetail;
803
StringInfoData logdetail;
804
int numReportedClient = 0;
805
int numNotReportedClient = 0;
809
* If no error is to be thrown, and the msglevel is too low to be shown to
810
* either client or server log, there's no need to do any of the work.
812
* Note: this code doesn't know all there is to be known about elog
813
* levels, but it works for NOTICE and DEBUG2, which are the only values
814
* msglevel can currently have. We also assume we are running in a normal
815
* operating environment.
817
if (behavior == DROP_CASCADE &&
818
msglevel < client_min_messages &&
819
(msglevel < log_min_messages || log_min_messages == LOG))
823
* We limit the number of dependencies reported to the client to
824
* MAX_REPORTED_DEPS, since client software may not deal well with
825
* enormous error strings. The server log always gets a full report.
827
#define MAX_REPORTED_DEPS 100
829
initStringInfo(&clientdetail);
830
initStringInfo(&logdetail);
833
* We process the list back to front (ie, in dependency order not deletion
834
* order), since this makes for a more understandable display.
836
for (i = targetObjects->numrefs - 1; i >= 0; i--)
838
const ObjectAddress *obj = &targetObjects->refs[i];
839
const ObjectAddressExtra *extra = &targetObjects->extras[i];
842
/* Ignore the original deletion target(s) */
843
if (extra->flags & DEPFLAG_ORIGINAL)
846
objDesc = getObjectDescription(obj);
849
* If, at any stage of the recursive search, we reached the object via
850
* an AUTO, INTERNAL, or EXTENSION dependency, then it's okay to
851
* delete it even in RESTRICT mode.
853
if (extra->flags & (DEPFLAG_AUTO |
858
* auto-cascades are reported at DEBUG2, not msglevel. We don't
859
* try to combine them with the regular message because the
860
* results are too confusing when client_min_messages and
861
* log_min_messages are different.
864
(errmsg("drop auto-cascades to %s",
867
else if (behavior == DROP_RESTRICT)
869
char *otherDesc = getObjectDescription(&extra->dependee);
871
if (numReportedClient < MAX_REPORTED_DEPS)
873
/* separate entries with a newline */
874
if (clientdetail.len != 0)
875
appendStringInfoChar(&clientdetail, '\n');
876
appendStringInfo(&clientdetail, _("%s depends on %s"),
881
numNotReportedClient++;
882
/* separate entries with a newline */
883
if (logdetail.len != 0)
884
appendStringInfoChar(&logdetail, '\n');
885
appendStringInfo(&logdetail, _("%s depends on %s"),
892
if (numReportedClient < MAX_REPORTED_DEPS)
894
/* separate entries with a newline */
895
if (clientdetail.len != 0)
896
appendStringInfoChar(&clientdetail, '\n');
897
appendStringInfo(&clientdetail, _("drop cascades to %s"),
902
numNotReportedClient++;
903
/* separate entries with a newline */
904
if (logdetail.len != 0)
905
appendStringInfoChar(&logdetail, '\n');
906
appendStringInfo(&logdetail, _("drop cascades to %s"),
913
if (numNotReportedClient > 0)
914
appendStringInfo(&clientdetail, ngettext("\nand %d other object "
915
"(see server log for list)",
916
"\nand %d other objects "
917
"(see server log for list)",
918
numNotReportedClient),
919
numNotReportedClient);
925
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
926
errmsg("cannot drop %s because other objects depend on it",
927
getObjectDescription(origObject)),
928
errdetail("%s", clientdetail.data),
929
errdetail_log("%s", logdetail.data),
930
errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
933
(errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
934
errmsg("cannot drop desired object(s) because other objects depend on them"),
935
errdetail("%s", clientdetail.data),
936
errdetail_log("%s", logdetail.data),
937
errhint("Use DROP ... CASCADE to drop the dependent objects too.")));
939
else if (numReportedClient > 1)
942
/* translator: %d always has a value larger than 1 */
943
(errmsg_plural("drop cascades to %d other object",
944
"drop cascades to %d other objects",
945
numReportedClient + numNotReportedClient,
946
numReportedClient + numNotReportedClient),
947
errdetail("%s", clientdetail.data),
948
errdetail_log("%s", logdetail.data)));
950
else if (numReportedClient == 1)
952
/* we just use the single item as-is */
954
(errmsg_internal("%s", clientdetail.data)));
957
pfree(clientdetail.data);
958
pfree(logdetail.data);
962
* deleteOneObject: delete a single object for performDeletion.
964
* depRel is the already-open pg_depend relation.
967
deleteOneObject(const ObjectAddress *object, Relation depRel)
975
* First remove any pg_depend records that link from this object to
976
* others. (Any records linking to this object should be gone already.)
978
* When dropping a whole object (subId = 0), remove all pg_depend records
979
* for its sub-objects too.
982
Anum_pg_depend_classid,
983
BTEqualStrategyNumber, F_OIDEQ,
984
ObjectIdGetDatum(object->classId));
986
Anum_pg_depend_objid,
987
BTEqualStrategyNumber, F_OIDEQ,
988
ObjectIdGetDatum(object->objectId));
989
if (object->objectSubId != 0)
992
Anum_pg_depend_objsubid,
993
BTEqualStrategyNumber, F_INT4EQ,
994
Int32GetDatum(object->objectSubId));
1000
scan = systable_beginscan(depRel, DependDependerIndexId, true,
1001
SnapshotNow, nkeys, key);
1003
while (HeapTupleIsValid(tup = systable_getnext(scan)))
1005
simple_heap_delete(depRel, &tup->t_self);
1008
systable_endscan(scan);
1011
* Delete shared dependency references related to this object. Again, if
1012
* subId = 0, remove records for sub-objects too.
1014
deleteSharedDependencyRecordsFor(object->classId, object->objectId,
1015
object->objectSubId);
1018
* Now delete the object itself, in an object-type-dependent way.
1023
* Delete any comments or security labels associated with this object.
1024
* (This is a convenient place to do these things, rather than having
1025
* every object type know to do it.)
1027
DeleteComments(object->objectId, object->classId, object->objectSubId);
1028
DeleteSecurityLabel(object);
1031
* CommandCounterIncrement here to ensure that preceding changes are all
1032
* visible to the next deletion step.
1034
CommandCounterIncrement();
1042
* doDeletion: actually delete a single object
1045
doDeletion(const ObjectAddress *object)
1047
switch (getObjectClass(object))
1051
char relKind = get_rel_relkind(object->objectId);
1053
if (relKind == RELKIND_INDEX)
1055
Assert(object->objectSubId == 0);
1056
index_drop(object->objectId);
1060
if (object->objectSubId != 0)
1061
RemoveAttributeById(object->objectId,
1062
object->objectSubId);
1064
heap_drop_with_catalog(object->objectId);
1070
RemoveFunctionById(object->objectId);
1074
RemoveTypeById(object->objectId);
1078
DropCastById(object->objectId);
1081
case OCLASS_COLLATION:
1082
RemoveCollationById(object->objectId);
1085
case OCLASS_CONSTRAINT:
1086
RemoveConstraintById(object->objectId);
1089
case OCLASS_CONVERSION:
1090
RemoveConversionById(object->objectId);
1093
case OCLASS_DEFAULT:
1094
RemoveAttrDefaultById(object->objectId);
1097
case OCLASS_LANGUAGE:
1098
DropProceduralLanguageById(object->objectId);
1101
case OCLASS_LARGEOBJECT:
1102
LargeObjectDrop(object->objectId);
1105
case OCLASS_OPERATOR:
1106
RemoveOperatorById(object->objectId);
1109
case OCLASS_OPCLASS:
1110
RemoveOpClassById(object->objectId);
1113
case OCLASS_OPFAMILY:
1114
RemoveOpFamilyById(object->objectId);
1118
RemoveAmOpEntryById(object->objectId);
1122
RemoveAmProcEntryById(object->objectId);
1125
case OCLASS_REWRITE:
1126
RemoveRewriteRuleById(object->objectId);
1129
case OCLASS_TRIGGER:
1130
RemoveTriggerById(object->objectId);
1134
RemoveSchemaById(object->objectId);
1137
case OCLASS_TSPARSER:
1138
RemoveTSParserById(object->objectId);
1142
RemoveTSDictionaryById(object->objectId);
1145
case OCLASS_TSTEMPLATE:
1146
RemoveTSTemplateById(object->objectId);
1149
case OCLASS_TSCONFIG:
1150
RemoveTSConfigurationById(object->objectId);
1154
* OCLASS_ROLE, OCLASS_DATABASE, OCLASS_TBLSPACE intentionally not
1159
RemoveForeignDataWrapperById(object->objectId);
1162
case OCLASS_FOREIGN_SERVER:
1163
RemoveForeignServerById(object->objectId);
1166
case OCLASS_USER_MAPPING:
1167
RemoveUserMappingById(object->objectId);
1171
RemoveDefaultACLById(object->objectId);
1174
case OCLASS_EXTENSION:
1175
RemoveExtensionById(object->objectId);
1179
elog(ERROR, "unrecognized object class: %u",
1185
* AcquireDeletionLock - acquire a suitable lock for deleting an object
1187
* We use LockRelation for relations, LockDatabaseObject for everything
1188
* else. Note that dependency.c is not concerned with deleting any kind of
1189
* shared-across-databases object, so we have no need for LockSharedObject.
1192
AcquireDeletionLock(const ObjectAddress *object)
1194
if (object->classId == RelationRelationId)
1195
LockRelationOid(object->objectId, AccessExclusiveLock);
1197
/* assume we should lock the whole object not a sub-object */
1198
LockDatabaseObject(object->classId, object->objectId, 0,
1199
AccessExclusiveLock);
1203
* ReleaseDeletionLock - release an object deletion lock
1206
ReleaseDeletionLock(const ObjectAddress *object)
1208
if (object->classId == RelationRelationId)
1209
UnlockRelationOid(object->objectId, AccessExclusiveLock);
1211
/* assume we should lock the whole object not a sub-object */
1212
UnlockDatabaseObject(object->classId, object->objectId, 0,
1213
AccessExclusiveLock);
1217
* recordDependencyOnExpr - find expression dependencies
1219
* This is used to find the dependencies of rules, constraint expressions,
1222
* Given an expression or query in node-tree form, find all the objects
1223
* it refers to (tables, columns, operators, functions, etc). Record
1224
* a dependency of the specified type from the given depender object
1225
* to each object mentioned in the expression.
1227
* rtable is the rangetable to be used to interpret Vars with varlevelsup=0.
1228
* It can be NIL if no such variables are expected.
1231
recordDependencyOnExpr(const ObjectAddress *depender,
1232
Node *expr, List *rtable,
1233
DependencyType behavior)
1235
find_expr_references_context context;
1237
context.addrs = new_object_addresses();
1239
/* Set up interpretation for Vars at varlevelsup = 0 */
1240
context.rtables = list_make1(rtable);
1242
/* Scan the expression tree for referenceable objects */
1243
find_expr_references_walker(expr, &context);
1245
/* Remove any duplicates */
1246
eliminate_duplicate_dependencies(context.addrs);
1248
/* And record 'em */
1249
recordMultipleDependencies(depender,
1250
context.addrs->refs, context.addrs->numrefs,
1253
free_object_addresses(context.addrs);
1257
* recordDependencyOnSingleRelExpr - find expression dependencies
1259
* As above, but only one relation is expected to be referenced (with
1260
* varno = 1 and varlevelsup = 0). Pass the relation OID instead of a
1261
* range table. An additional frammish is that dependencies on that
1262
* relation (or its component columns) will be marked with 'self_behavior',
1263
* whereas 'behavior' is used for everything else.
1265
* NOTE: the caller should ensure that a whole-table dependency on the
1266
* specified relation is created separately, if one is needed. In particular,
1267
* a whole-row Var "relation.*" will not cause this routine to emit any
1268
* dependency item. This is appropriate behavior for subexpressions of an
1269
* ordinary query, so other cases need to cope as necessary.
1272
recordDependencyOnSingleRelExpr(const ObjectAddress *depender,
1273
Node *expr, Oid relId,
1274
DependencyType behavior,
1275
DependencyType self_behavior)
1277
find_expr_references_context context;
1280
context.addrs = new_object_addresses();
1282
/* We gin up a rather bogus rangetable list to handle Vars */
1283
MemSet(&rte, 0, sizeof(rte));
1284
rte.type = T_RangeTblEntry;
1285
rte.rtekind = RTE_RELATION;
1287
rte.relkind = RELKIND_RELATION; /* no need for exactness here */
1289
context.rtables = list_make1(list_make1(&rte));
1291
/* Scan the expression tree for referenceable objects */
1292
find_expr_references_walker(expr, &context);
1294
/* Remove any duplicates */
1295
eliminate_duplicate_dependencies(context.addrs);
1297
/* Separate self-dependencies if necessary */
1298
if (behavior != self_behavior && context.addrs->numrefs > 0)
1300
ObjectAddresses *self_addrs;
1301
ObjectAddress *outobj;
1305
self_addrs = new_object_addresses();
1307
outobj = context.addrs->refs;
1309
for (oldref = 0; oldref < context.addrs->numrefs; oldref++)
1311
ObjectAddress *thisobj = context.addrs->refs + oldref;
1313
if (thisobj->classId == RelationRelationId &&
1314
thisobj->objectId == relId)
1316
/* Move this ref into self_addrs */
1317
add_exact_object_address(thisobj, self_addrs);
1321
/* Keep it in context.addrs */
1327
context.addrs->numrefs = outrefs;
1329
/* Record the self-dependencies */
1330
recordMultipleDependencies(depender,
1331
self_addrs->refs, self_addrs->numrefs,
1334
free_object_addresses(self_addrs);
1337
/* Record the external dependencies */
1338
recordMultipleDependencies(depender,
1339
context.addrs->refs, context.addrs->numrefs,
1342
free_object_addresses(context.addrs);
1346
* Recursively search an expression tree for object references.
1348
* Note: we avoid creating references to columns of tables that participate
1349
* in an SQL JOIN construct, but are not actually used anywhere in the query.
1350
* To do so, we do not scan the joinaliasvars list of a join RTE while
1351
* scanning the query rangetable, but instead scan each individual entry
1352
* of the alias list when we find a reference to it.
1354
* Note: in many cases we do not need to create dependencies on the datatypes
1355
* involved in an expression, because we'll have an indirect dependency via
1356
* some other object. For instance Var nodes depend on a column which depends
1357
* on the datatype, and OpExpr nodes depend on the operator which depends on
1358
* the datatype. However we do need a type dependency if there is no such
1359
* indirect dependency, as for example in Const and CoerceToDomain nodes.
1361
* Similarly, we don't need to create dependencies on collations except where
1362
* the collation is being freshly introduced to the expression.
1365
find_expr_references_walker(Node *node,
1366
find_expr_references_context *context)
1372
Var *var = (Var *) node;
1376
/* Find matching rtable entry, or complain if not found */
1377
if (var->varlevelsup >= list_length(context->rtables))
1378
elog(ERROR, "invalid varlevelsup %d", var->varlevelsup);
1379
rtable = (List *) list_nth(context->rtables, var->varlevelsup);
1380
if (var->varno <= 0 || var->varno > list_length(rtable))
1381
elog(ERROR, "invalid varno %d", var->varno);
1382
rte = rt_fetch(var->varno, rtable);
1385
* A whole-row Var references no specific columns, so adds no new
1386
* dependency. (We assume that there is a whole-table dependency
1387
* arising from each underlying rangetable entry. While we could
1388
* record such a dependency when finding a whole-row Var that
1389
* references a relation directly, it's quite unclear how to extend
1390
* that to whole-row Vars for JOINs, so it seems better to leave the
1391
* responsibility with the range table. Note that this poses some
1392
* risks for identifying dependencies of stand-alone expressions:
1393
* whole-table references may need to be created separately.)
1395
if (var->varattno == InvalidAttrNumber)
1397
if (rte->rtekind == RTE_RELATION)
1399
/* If it's a plain relation, reference this column */
1400
add_object_address(OCLASS_CLASS, rte->relid, var->varattno,
1403
else if (rte->rtekind == RTE_JOIN)
1405
/* Scan join output column to add references to join inputs */
1408
/* We must make the context appropriate for join's level */
1409
save_rtables = context->rtables;
1410
context->rtables = list_copy_tail(context->rtables,
1412
if (var->varattno <= 0 ||
1413
var->varattno > list_length(rte->joinaliasvars))
1414
elog(ERROR, "invalid varattno %d", var->varattno);
1415
find_expr_references_walker((Node *) list_nth(rte->joinaliasvars,
1418
list_free(context->rtables);
1419
context->rtables = save_rtables;
1423
else if (IsA(node, Const))
1425
Const *con = (Const *) node;
1428
/* A constant must depend on the constant's datatype */
1429
add_object_address(OCLASS_TYPE, con->consttype, 0,
1433
* We must also depend on the constant's collation: it could be
1434
* different from the datatype's, if a CollateExpr was const-folded to
1435
* a simple constant. However we can save work in the most common
1436
* case where the collation is "default", since we know that's pinned.
1438
if (OidIsValid(con->constcollid) &&
1439
con->constcollid != DEFAULT_COLLATION_OID)
1440
add_object_address(OCLASS_COLLATION, con->constcollid, 0,
1444
* If it's a regclass or similar literal referring to an existing
1445
* object, add a reference to that object. (Currently, only the
1446
* regclass and regconfig cases have any likely use, but we may as
1447
* well handle all the OID-alias datatypes consistently.)
1449
if (!con->constisnull)
1451
switch (con->consttype)
1454
case REGPROCEDUREOID:
1455
objoid = DatumGetObjectId(con->constvalue);
1456
if (SearchSysCacheExists1(PROCOID,
1457
ObjectIdGetDatum(objoid)))
1458
add_object_address(OCLASS_PROC, objoid, 0,
1462
case REGOPERATOROID:
1463
objoid = DatumGetObjectId(con->constvalue);
1464
if (SearchSysCacheExists1(OPEROID,
1465
ObjectIdGetDatum(objoid)))
1466
add_object_address(OCLASS_OPERATOR, objoid, 0,
1470
objoid = DatumGetObjectId(con->constvalue);
1471
if (SearchSysCacheExists1(RELOID,
1472
ObjectIdGetDatum(objoid)))
1473
add_object_address(OCLASS_CLASS, objoid, 0,
1477
objoid = DatumGetObjectId(con->constvalue);
1478
if (SearchSysCacheExists1(TYPEOID,
1479
ObjectIdGetDatum(objoid)))
1480
add_object_address(OCLASS_TYPE, objoid, 0,
1484
objoid = DatumGetObjectId(con->constvalue);
1485
if (SearchSysCacheExists1(TSCONFIGOID,
1486
ObjectIdGetDatum(objoid)))
1487
add_object_address(OCLASS_TSCONFIG, objoid, 0,
1490
case REGDICTIONARYOID:
1491
objoid = DatumGetObjectId(con->constvalue);
1492
if (SearchSysCacheExists1(TSDICTOID,
1493
ObjectIdGetDatum(objoid)))
1494
add_object_address(OCLASS_TSDICT, objoid, 0,
1501
else if (IsA(node, Param))
1503
Param *param = (Param *) node;
1505
/* A parameter must depend on the parameter's datatype */
1506
add_object_address(OCLASS_TYPE, param->paramtype, 0,
1508
/* and its collation, just as for Consts */
1509
if (OidIsValid(param->paramcollid) &&
1510
param->paramcollid != DEFAULT_COLLATION_OID)
1511
add_object_address(OCLASS_COLLATION, param->paramcollid, 0,
1514
else if (IsA(node, FuncExpr))
1516
FuncExpr *funcexpr = (FuncExpr *) node;
1518
add_object_address(OCLASS_PROC, funcexpr->funcid, 0,
1520
/* fall through to examine arguments */
1522
else if (IsA(node, OpExpr))
1524
OpExpr *opexpr = (OpExpr *) node;
1526
add_object_address(OCLASS_OPERATOR, opexpr->opno, 0,
1528
/* fall through to examine arguments */
1530
else if (IsA(node, DistinctExpr))
1532
DistinctExpr *distinctexpr = (DistinctExpr *) node;
1534
add_object_address(OCLASS_OPERATOR, distinctexpr->opno, 0,
1536
/* fall through to examine arguments */
1538
else if (IsA(node, NullIfExpr))
1540
NullIfExpr *nullifexpr = (NullIfExpr *) node;
1542
add_object_address(OCLASS_OPERATOR, nullifexpr->opno, 0,
1544
/* fall through to examine arguments */
1546
else if (IsA(node, ScalarArrayOpExpr))
1548
ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
1550
add_object_address(OCLASS_OPERATOR, opexpr->opno, 0,
1552
/* fall through to examine arguments */
1554
else if (IsA(node, Aggref))
1556
Aggref *aggref = (Aggref *) node;
1558
add_object_address(OCLASS_PROC, aggref->aggfnoid, 0,
1560
/* fall through to examine arguments */
1562
else if (IsA(node, WindowFunc))
1564
WindowFunc *wfunc = (WindowFunc *) node;
1566
add_object_address(OCLASS_PROC, wfunc->winfnoid, 0,
1568
/* fall through to examine arguments */
1570
else if (IsA(node, SubPlan))
1572
/* Extra work needed here if we ever need this case */
1573
elog(ERROR, "already-planned subqueries not supported");
1575
else if (IsA(node, RelabelType))
1577
RelabelType *relab = (RelabelType *) node;
1579
/* since there is no function dependency, need to depend on type */
1580
add_object_address(OCLASS_TYPE, relab->resulttype, 0,
1582
/* the collation might not be referenced anywhere else, either */
1583
if (OidIsValid(relab->resultcollid) &&
1584
relab->resultcollid != DEFAULT_COLLATION_OID)
1585
add_object_address(OCLASS_COLLATION, relab->resultcollid, 0,
1588
else if (IsA(node, CoerceViaIO))
1590
CoerceViaIO *iocoerce = (CoerceViaIO *) node;
1592
/* since there is no exposed function, need to depend on type */
1593
add_object_address(OCLASS_TYPE, iocoerce->resulttype, 0,
1596
else if (IsA(node, ArrayCoerceExpr))
1598
ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
1600
if (OidIsValid(acoerce->elemfuncid))
1601
add_object_address(OCLASS_PROC, acoerce->elemfuncid, 0,
1603
add_object_address(OCLASS_TYPE, acoerce->resulttype, 0,
1605
/* fall through to examine arguments */
1607
else if (IsA(node, ConvertRowtypeExpr))
1609
ConvertRowtypeExpr *cvt = (ConvertRowtypeExpr *) node;
1611
/* since there is no function dependency, need to depend on type */
1612
add_object_address(OCLASS_TYPE, cvt->resulttype, 0,
1615
else if (IsA(node, CollateExpr))
1617
CollateExpr *coll = (CollateExpr *) node;
1619
add_object_address(OCLASS_COLLATION, coll->collOid, 0,
1622
else if (IsA(node, RowExpr))
1624
RowExpr *rowexpr = (RowExpr *) node;
1626
add_object_address(OCLASS_TYPE, rowexpr->row_typeid, 0,
1629
else if (IsA(node, RowCompareExpr))
1631
RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1634
foreach(l, rcexpr->opnos)
1636
add_object_address(OCLASS_OPERATOR, lfirst_oid(l), 0,
1639
foreach(l, rcexpr->opfamilies)
1641
add_object_address(OCLASS_OPFAMILY, lfirst_oid(l), 0,
1644
/* fall through to examine arguments */
1646
else if (IsA(node, CoerceToDomain))
1648
CoerceToDomain *cd = (CoerceToDomain *) node;
1650
add_object_address(OCLASS_TYPE, cd->resulttype, 0,
1653
else if (IsA(node, SortGroupClause))
1655
SortGroupClause *sgc = (SortGroupClause *) node;
1657
add_object_address(OCLASS_OPERATOR, sgc->eqop, 0,
1659
if (OidIsValid(sgc->sortop))
1660
add_object_address(OCLASS_OPERATOR, sgc->sortop, 0,
1664
else if (IsA(node, Query))
1666
/* Recurse into RTE subquery or not-yet-planned sublink subquery */
1667
Query *query = (Query *) node;
1672
* Add whole-relation refs for each plain relation mentioned in the
1673
* subquery's rtable, as well as refs for any datatypes and collations
1674
* used in a RECORD function's output.
1676
* Note: query_tree_walker takes care of recursing into RTE_FUNCTION
1677
* RTEs, subqueries, etc, so no need to do that here. But keep it
1678
* from looking at join alias lists.
1680
* Note: we don't need to worry about collations mentioned in
1681
* RTE_VALUES or RTE_CTE RTEs, because those must just duplicate
1682
* collations referenced in other parts of the Query.
1684
foreach(lc, query->rtable)
1686
RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
1689
switch (rte->rtekind)
1692
add_object_address(OCLASS_CLASS, rte->relid, 0,
1696
foreach(ct, rte->funccoltypes)
1698
add_object_address(OCLASS_TYPE, lfirst_oid(ct), 0,
1701
foreach(ct, rte->funccolcollations)
1703
Oid collid = lfirst_oid(ct);
1705
if (OidIsValid(collid) &&
1706
collid != DEFAULT_COLLATION_OID)
1707
add_object_address(OCLASS_COLLATION, collid, 0,
1717
* Add dependencies on constraints listed in query's constraintDeps
1719
foreach(lc, query->constraintDeps)
1721
add_object_address(OCLASS_CONSTRAINT, lfirst_oid(lc), 0,
1725
/* query_tree_walker ignores ORDER BY etc, but we need those opers */
1726
find_expr_references_walker((Node *) query->sortClause, context);
1727
find_expr_references_walker((Node *) query->groupClause, context);
1728
find_expr_references_walker((Node *) query->windowClause, context);
1729
find_expr_references_walker((Node *) query->distinctClause, context);
1731
/* Examine substructure of query */
1732
context->rtables = lcons(query->rtable, context->rtables);
1733
result = query_tree_walker(query,
1734
find_expr_references_walker,
1736
QTW_IGNORE_JOINALIASES);
1737
context->rtables = list_delete_first(context->rtables);
1740
else if (IsA(node, SetOperationStmt))
1742
SetOperationStmt *setop = (SetOperationStmt *) node;
1744
/* we need to look at the groupClauses for operator references */
1745
find_expr_references_walker((Node *) setop->groupClauses, context);
1746
/* fall through to examine child nodes */
1749
return expression_tree_walker(node, find_expr_references_walker,
1754
* Given an array of dependency references, eliminate any duplicates.
1757
eliminate_duplicate_dependencies(ObjectAddresses *addrs)
1759
ObjectAddress *priorobj;
1764
* We can't sort if the array has "extra" data, because there's no way to
1765
* keep it in sync. Fortunately that combination of features is not
1768
Assert(!addrs->extras);
1770
if (addrs->numrefs <= 1)
1771
return; /* nothing to do */
1773
/* Sort the refs so that duplicates are adjacent */
1774
qsort((void *) addrs->refs, addrs->numrefs, sizeof(ObjectAddress),
1775
object_address_comparator);
1778
priorobj = addrs->refs;
1780
for (oldref = 1; oldref < addrs->numrefs; oldref++)
1782
ObjectAddress *thisobj = addrs->refs + oldref;
1784
if (priorobj->classId == thisobj->classId &&
1785
priorobj->objectId == thisobj->objectId)
1787
if (priorobj->objectSubId == thisobj->objectSubId)
1788
continue; /* identical, so drop thisobj */
1791
* If we have a whole-object reference and a reference to a part
1792
* of the same object, we don't need the whole-object reference
1793
* (for example, we don't need to reference both table foo and
1794
* column foo.bar). The whole-object reference will always appear
1795
* first in the sorted list.
1797
if (priorobj->objectSubId == 0)
1799
/* replace whole ref with partial */
1800
priorobj->objectSubId = thisobj->objectSubId;
1804
/* Not identical, so add thisobj to output set */
1806
*priorobj = *thisobj;
1810
addrs->numrefs = newrefs;
1814
* qsort comparator for ObjectAddress items
1817
object_address_comparator(const void *a, const void *b)
1819
const ObjectAddress *obja = (const ObjectAddress *) a;
1820
const ObjectAddress *objb = (const ObjectAddress *) b;
1822
if (obja->classId < objb->classId)
1824
if (obja->classId > objb->classId)
1826
if (obja->objectId < objb->objectId)
1828
if (obja->objectId > objb->objectId)
1832
* We sort the subId as an unsigned int so that 0 will come first. See
1833
* logic in eliminate_duplicate_dependencies.
1835
if ((unsigned int) obja->objectSubId < (unsigned int) objb->objectSubId)
1837
if ((unsigned int) obja->objectSubId > (unsigned int) objb->objectSubId)
1843
* Routines for handling an expansible array of ObjectAddress items.
1845
* new_object_addresses: create a new ObjectAddresses array.
1848
new_object_addresses(void)
1850
ObjectAddresses *addrs;
1852
addrs = palloc(sizeof(ObjectAddresses));
1855
addrs->maxrefs = 32;
1856
addrs->refs = (ObjectAddress *)
1857
palloc(addrs->maxrefs * sizeof(ObjectAddress));
1858
addrs->extras = NULL; /* until/unless needed */
1864
* Add an entry to an ObjectAddresses array.
1866
* It is convenient to specify the class by ObjectClass rather than directly
1870
add_object_address(ObjectClass oclass, Oid objectId, int32 subId,
1871
ObjectAddresses *addrs)
1873
ObjectAddress *item;
1875
/* enlarge array if needed */
1876
if (addrs->numrefs >= addrs->maxrefs)
1878
addrs->maxrefs *= 2;
1879
addrs->refs = (ObjectAddress *)
1880
repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
1881
Assert(!addrs->extras);
1883
/* record this item */
1884
item = addrs->refs + addrs->numrefs;
1885
item->classId = object_classes[oclass];
1886
item->objectId = objectId;
1887
item->objectSubId = subId;
1892
* Add an entry to an ObjectAddresses array.
1894
* As above, but specify entry exactly.
1897
add_exact_object_address(const ObjectAddress *object,
1898
ObjectAddresses *addrs)
1900
ObjectAddress *item;
1902
/* enlarge array if needed */
1903
if (addrs->numrefs >= addrs->maxrefs)
1905
addrs->maxrefs *= 2;
1906
addrs->refs = (ObjectAddress *)
1907
repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
1908
Assert(!addrs->extras);
1910
/* record this item */
1911
item = addrs->refs + addrs->numrefs;
1917
* Add an entry to an ObjectAddresses array.
1919
* As above, but specify entry exactly and provide some "extra" data too.
1922
add_exact_object_address_extra(const ObjectAddress *object,
1923
const ObjectAddressExtra *extra,
1924
ObjectAddresses *addrs)
1926
ObjectAddress *item;
1927
ObjectAddressExtra *itemextra;
1929
/* allocate extra space if first time */
1931
addrs->extras = (ObjectAddressExtra *)
1932
palloc(addrs->maxrefs * sizeof(ObjectAddressExtra));
1934
/* enlarge array if needed */
1935
if (addrs->numrefs >= addrs->maxrefs)
1937
addrs->maxrefs *= 2;
1938
addrs->refs = (ObjectAddress *)
1939
repalloc(addrs->refs, addrs->maxrefs * sizeof(ObjectAddress));
1940
addrs->extras = (ObjectAddressExtra *)
1941
repalloc(addrs->extras, addrs->maxrefs * sizeof(ObjectAddressExtra));
1943
/* record this item */
1944
item = addrs->refs + addrs->numrefs;
1946
itemextra = addrs->extras + addrs->numrefs;
1947
*itemextra = *extra;
1952
* Test whether an object is present in an ObjectAddresses array.
1954
* We return "true" if object is a subobject of something in the array, too.
1957
object_address_present(const ObjectAddress *object,
1958
const ObjectAddresses *addrs)
1962
for (i = addrs->numrefs - 1; i >= 0; i--)
1964
const ObjectAddress *thisobj = addrs->refs + i;
1966
if (object->classId == thisobj->classId &&
1967
object->objectId == thisobj->objectId)
1969
if (object->objectSubId == thisobj->objectSubId ||
1970
thisobj->objectSubId == 0)
1979
* As above, except that if the object is present then also OR the given
1980
* flags into its associated extra data (which must exist).
1983
object_address_present_add_flags(const ObjectAddress *object,
1985
ObjectAddresses *addrs)
1989
for (i = addrs->numrefs - 1; i >= 0; i--)
1991
ObjectAddress *thisobj = addrs->refs + i;
1993
if (object->classId == thisobj->classId &&
1994
object->objectId == thisobj->objectId)
1996
if (object->objectSubId == thisobj->objectSubId)
1998
ObjectAddressExtra *thisextra = addrs->extras + i;
2000
thisextra->flags |= flags;
2003
if (thisobj->objectSubId == 0)
2006
* We get here if we find a need to delete a column after
2007
* having already decided to drop its whole table. Obviously
2008
* we no longer need to drop the column. But don't plaster
2009
* its flags on the table.
2020
* Record multiple dependencies from an ObjectAddresses array, after first
2021
* removing any duplicates.
2024
record_object_address_dependencies(const ObjectAddress *depender,
2025
ObjectAddresses *referenced,
2026
DependencyType behavior)
2028
eliminate_duplicate_dependencies(referenced);
2029
recordMultipleDependencies(depender,
2030
referenced->refs, referenced->numrefs,
2035
* Clean up when done with an ObjectAddresses array.
2038
free_object_addresses(ObjectAddresses *addrs)
2042
pfree(addrs->extras);
2047
* Determine the class of a given object identified by objectAddress.
2049
* This function is essentially the reverse mapping for the object_classes[]
2050
* table. We implement it as a function because the OIDs aren't consecutive.
2053
getObjectClass(const ObjectAddress *object)
2055
/* only pg_class entries can have nonzero objectSubId */
2056
if (object->classId != RelationRelationId &&
2057
object->objectSubId != 0)
2058
elog(ERROR, "invalid objectSubId 0 for object class %u",
2061
switch (object->classId)
2063
case RelationRelationId:
2064
/* caller must check objectSubId */
2065
return OCLASS_CLASS;
2067
case ProcedureRelationId:
2070
case TypeRelationId:
2073
case CastRelationId:
2076
case CollationRelationId:
2077
return OCLASS_COLLATION;
2079
case ConstraintRelationId:
2080
return OCLASS_CONSTRAINT;
2082
case ConversionRelationId:
2083
return OCLASS_CONVERSION;
2085
case AttrDefaultRelationId:
2086
return OCLASS_DEFAULT;
2088
case LanguageRelationId:
2089
return OCLASS_LANGUAGE;
2091
case LargeObjectRelationId:
2092
return OCLASS_LARGEOBJECT;
2094
case OperatorRelationId:
2095
return OCLASS_OPERATOR;
2097
case OperatorClassRelationId:
2098
return OCLASS_OPCLASS;
2100
case OperatorFamilyRelationId:
2101
return OCLASS_OPFAMILY;
2103
case AccessMethodOperatorRelationId:
2106
case AccessMethodProcedureRelationId:
2107
return OCLASS_AMPROC;
2109
case RewriteRelationId:
2110
return OCLASS_REWRITE;
2112
case TriggerRelationId:
2113
return OCLASS_TRIGGER;
2115
case NamespaceRelationId:
2116
return OCLASS_SCHEMA;
2118
case TSParserRelationId:
2119
return OCLASS_TSPARSER;
2121
case TSDictionaryRelationId:
2122
return OCLASS_TSDICT;
2124
case TSTemplateRelationId:
2125
return OCLASS_TSTEMPLATE;
2127
case TSConfigRelationId:
2128
return OCLASS_TSCONFIG;
2130
case AuthIdRelationId:
2133
case DatabaseRelationId:
2134
return OCLASS_DATABASE;
2136
case TableSpaceRelationId:
2137
return OCLASS_TBLSPACE;
2139
case ForeignDataWrapperRelationId:
2142
case ForeignServerRelationId:
2143
return OCLASS_FOREIGN_SERVER;
2145
case UserMappingRelationId:
2146
return OCLASS_USER_MAPPING;
2148
case DefaultAclRelationId:
2149
return OCLASS_DEFACL;
2151
case ExtensionRelationId:
2152
return OCLASS_EXTENSION;
2155
/* shouldn't get here */
2156
elog(ERROR, "unrecognized object class: %u", object->classId);
2157
return OCLASS_CLASS; /* keep compiler quiet */
2161
* getObjectDescription: build an object description for messages
2163
* The result is a palloc'd string.
2166
getObjectDescription(const ObjectAddress *object)
2168
StringInfoData buffer;
2170
initStringInfo(&buffer);
2172
switch (getObjectClass(object))
2175
getRelationDescription(&buffer, object->objectId);
2176
if (object->objectSubId != 0)
2177
appendStringInfo(&buffer, _(" column %s"),
2178
get_relid_attribute_name(object->objectId,
2179
object->objectSubId));
2183
appendStringInfo(&buffer, _("function %s"),
2184
format_procedure(object->objectId));
2188
appendStringInfo(&buffer, _("type %s"),
2189
format_type_be(object->objectId));
2195
ScanKeyData skey[1];
2198
Form_pg_cast castForm;
2200
castDesc = heap_open(CastRelationId, AccessShareLock);
2202
ScanKeyInit(&skey[0],
2203
ObjectIdAttributeNumber,
2204
BTEqualStrategyNumber, F_OIDEQ,
2205
ObjectIdGetDatum(object->objectId));
2207
rcscan = systable_beginscan(castDesc, CastOidIndexId, true,
2208
SnapshotNow, 1, skey);
2210
tup = systable_getnext(rcscan);
2212
if (!HeapTupleIsValid(tup))
2213
elog(ERROR, "could not find tuple for cast %u",
2216
castForm = (Form_pg_cast) GETSTRUCT(tup);
2218
appendStringInfo(&buffer, _("cast from %s to %s"),
2219
format_type_be(castForm->castsource),
2220
format_type_be(castForm->casttarget));
2222
systable_endscan(rcscan);
2223
heap_close(castDesc, AccessShareLock);
2227
case OCLASS_COLLATION:
2230
Form_pg_collation coll;
2232
collTup = SearchSysCache1(COLLOID,
2233
ObjectIdGetDatum(object->objectId));
2234
if (!HeapTupleIsValid(collTup))
2235
elog(ERROR, "cache lookup failed for collation %u",
2237
coll = (Form_pg_collation) GETSTRUCT(collTup);
2238
appendStringInfo(&buffer, _("collation %s"),
2239
NameStr(coll->collname));
2240
ReleaseSysCache(collTup);
2244
case OCLASS_CONSTRAINT:
2247
Form_pg_constraint con;
2249
conTup = SearchSysCache1(CONSTROID,
2250
ObjectIdGetDatum(object->objectId));
2251
if (!HeapTupleIsValid(conTup))
2252
elog(ERROR, "cache lookup failed for constraint %u",
2254
con = (Form_pg_constraint) GETSTRUCT(conTup);
2256
if (OidIsValid(con->conrelid))
2260
initStringInfo(&rel);
2261
getRelationDescription(&rel, con->conrelid);
2262
appendStringInfo(&buffer, _("constraint %s on %s"),
2263
NameStr(con->conname), rel.data);
2268
appendStringInfo(&buffer, _("constraint %s"),
2269
NameStr(con->conname));
2272
ReleaseSysCache(conTup);
2276
case OCLASS_CONVERSION:
2280
conTup = SearchSysCache1(CONVOID,
2281
ObjectIdGetDatum(object->objectId));
2282
if (!HeapTupleIsValid(conTup))
2283
elog(ERROR, "cache lookup failed for conversion %u",
2285
appendStringInfo(&buffer, _("conversion %s"),
2286
NameStr(((Form_pg_conversion) GETSTRUCT(conTup))->conname));
2287
ReleaseSysCache(conTup);
2291
case OCLASS_DEFAULT:
2293
Relation attrdefDesc;
2294
ScanKeyData skey[1];
2297
Form_pg_attrdef attrdef;
2298
ObjectAddress colobject;
2300
attrdefDesc = heap_open(AttrDefaultRelationId, AccessShareLock);
2302
ScanKeyInit(&skey[0],
2303
ObjectIdAttributeNumber,
2304
BTEqualStrategyNumber, F_OIDEQ,
2305
ObjectIdGetDatum(object->objectId));
2307
adscan = systable_beginscan(attrdefDesc, AttrDefaultOidIndexId,
2308
true, SnapshotNow, 1, skey);
2310
tup = systable_getnext(adscan);
2312
if (!HeapTupleIsValid(tup))
2313
elog(ERROR, "could not find tuple for attrdef %u",
2316
attrdef = (Form_pg_attrdef) GETSTRUCT(tup);
2318
colobject.classId = RelationRelationId;
2319
colobject.objectId = attrdef->adrelid;
2320
colobject.objectSubId = attrdef->adnum;
2322
appendStringInfo(&buffer, _("default for %s"),
2323
getObjectDescription(&colobject));
2325
systable_endscan(adscan);
2326
heap_close(attrdefDesc, AccessShareLock);
2330
case OCLASS_LANGUAGE:
2334
langTup = SearchSysCache1(LANGOID,
2335
ObjectIdGetDatum(object->objectId));
2336
if (!HeapTupleIsValid(langTup))
2337
elog(ERROR, "cache lookup failed for language %u",
2339
appendStringInfo(&buffer, _("language %s"),
2340
NameStr(((Form_pg_language) GETSTRUCT(langTup))->lanname));
2341
ReleaseSysCache(langTup);
2344
case OCLASS_LARGEOBJECT:
2345
appendStringInfo(&buffer, _("large object %u"),
2349
case OCLASS_OPERATOR:
2350
appendStringInfo(&buffer, _("operator %s"),
2351
format_operator(object->objectId));
2354
case OCLASS_OPCLASS:
2357
Form_pg_opclass opcForm;
2362
opcTup = SearchSysCache1(CLAOID,
2363
ObjectIdGetDatum(object->objectId));
2364
if (!HeapTupleIsValid(opcTup))
2365
elog(ERROR, "cache lookup failed for opclass %u",
2367
opcForm = (Form_pg_opclass) GETSTRUCT(opcTup);
2369
amTup = SearchSysCache1(AMOID,
2370
ObjectIdGetDatum(opcForm->opcmethod));
2371
if (!HeapTupleIsValid(amTup))
2372
elog(ERROR, "cache lookup failed for access method %u",
2373
opcForm->opcmethod);
2374
amForm = (Form_pg_am) GETSTRUCT(amTup);
2376
/* Qualify the name if not visible in search path */
2377
if (OpclassIsVisible(object->objectId))
2380
nspname = get_namespace_name(opcForm->opcnamespace);
2382
appendStringInfo(&buffer, _("operator class %s for access method %s"),
2383
quote_qualified_identifier(nspname,
2384
NameStr(opcForm->opcname)),
2385
NameStr(amForm->amname));
2387
ReleaseSysCache(amTup);
2388
ReleaseSysCache(opcTup);
2392
case OCLASS_OPFAMILY:
2393
getOpFamilyDescription(&buffer, object->objectId);
2399
ScanKeyData skey[1];
2402
Form_pg_amop amopForm;
2403
StringInfoData opfam;
2405
amopDesc = heap_open(AccessMethodOperatorRelationId,
2408
ScanKeyInit(&skey[0],
2409
ObjectIdAttributeNumber,
2410
BTEqualStrategyNumber, F_OIDEQ,
2411
ObjectIdGetDatum(object->objectId));
2413
amscan = systable_beginscan(amopDesc, AccessMethodOperatorOidIndexId, true,
2414
SnapshotNow, 1, skey);
2416
tup = systable_getnext(amscan);
2418
if (!HeapTupleIsValid(tup))
2419
elog(ERROR, "could not find tuple for amop entry %u",
2422
amopForm = (Form_pg_amop) GETSTRUCT(tup);
2424
initStringInfo(&opfam);
2425
getOpFamilyDescription(&opfam, amopForm->amopfamily);
2428
* translator: %d is the operator strategy (a number), the
2429
* first two %s's are data type names, the third %s is the
2430
* description of the operator family, and the last %s is the
2431
* textual form of the operator with arguments.
2433
appendStringInfo(&buffer, _("operator %d (%s, %s) of %s: %s"),
2434
amopForm->amopstrategy,
2435
format_type_be(amopForm->amoplefttype),
2436
format_type_be(amopForm->amoprighttype),
2438
format_operator(amopForm->amopopr));
2442
systable_endscan(amscan);
2443
heap_close(amopDesc, AccessShareLock);
2449
Relation amprocDesc;
2450
ScanKeyData skey[1];
2453
Form_pg_amproc amprocForm;
2454
StringInfoData opfam;
2456
amprocDesc = heap_open(AccessMethodProcedureRelationId,
2459
ScanKeyInit(&skey[0],
2460
ObjectIdAttributeNumber,
2461
BTEqualStrategyNumber, F_OIDEQ,
2462
ObjectIdGetDatum(object->objectId));
2464
amscan = systable_beginscan(amprocDesc, AccessMethodProcedureOidIndexId, true,
2465
SnapshotNow, 1, skey);
2467
tup = systable_getnext(amscan);
2469
if (!HeapTupleIsValid(tup))
2470
elog(ERROR, "could not find tuple for amproc entry %u",
2473
amprocForm = (Form_pg_amproc) GETSTRUCT(tup);
2475
initStringInfo(&opfam);
2476
getOpFamilyDescription(&opfam, amprocForm->amprocfamily);
2479
* translator: %d is the function number, the first two %s's
2480
* are data type names, the third %s is the description of the
2481
* operator family, and the last %s is the textual form of the
2482
* function with arguments.
2484
appendStringInfo(&buffer, _("function %d (%s, %s) of %s: %s"),
2485
amprocForm->amprocnum,
2486
format_type_be(amprocForm->amproclefttype),
2487
format_type_be(amprocForm->amprocrighttype),
2489
format_procedure(amprocForm->amproc));
2493
systable_endscan(amscan);
2494
heap_close(amprocDesc, AccessShareLock);
2498
case OCLASS_REWRITE:
2501
ScanKeyData skey[1];
2504
Form_pg_rewrite rule;
2506
ruleDesc = heap_open(RewriteRelationId, AccessShareLock);
2508
ScanKeyInit(&skey[0],
2509
ObjectIdAttributeNumber,
2510
BTEqualStrategyNumber, F_OIDEQ,
2511
ObjectIdGetDatum(object->objectId));
2513
rcscan = systable_beginscan(ruleDesc, RewriteOidIndexId, true,
2514
SnapshotNow, 1, skey);
2516
tup = systable_getnext(rcscan);
2518
if (!HeapTupleIsValid(tup))
2519
elog(ERROR, "could not find tuple for rule %u",
2522
rule = (Form_pg_rewrite) GETSTRUCT(tup);
2524
appendStringInfo(&buffer, _("rule %s on "),
2525
NameStr(rule->rulename));
2526
getRelationDescription(&buffer, rule->ev_class);
2528
systable_endscan(rcscan);
2529
heap_close(ruleDesc, AccessShareLock);
2533
case OCLASS_TRIGGER:
2536
ScanKeyData skey[1];
2539
Form_pg_trigger trig;
2541
trigDesc = heap_open(TriggerRelationId, AccessShareLock);
2543
ScanKeyInit(&skey[0],
2544
ObjectIdAttributeNumber,
2545
BTEqualStrategyNumber, F_OIDEQ,
2546
ObjectIdGetDatum(object->objectId));
2548
tgscan = systable_beginscan(trigDesc, TriggerOidIndexId, true,
2549
SnapshotNow, 1, skey);
2551
tup = systable_getnext(tgscan);
2553
if (!HeapTupleIsValid(tup))
2554
elog(ERROR, "could not find tuple for trigger %u",
2557
trig = (Form_pg_trigger) GETSTRUCT(tup);
2559
appendStringInfo(&buffer, _("trigger %s on "),
2560
NameStr(trig->tgname));
2561
getRelationDescription(&buffer, trig->tgrelid);
2563
systable_endscan(tgscan);
2564
heap_close(trigDesc, AccessShareLock);
2572
nspname = get_namespace_name(object->objectId);
2574
elog(ERROR, "cache lookup failed for namespace %u",
2576
appendStringInfo(&buffer, _("schema %s"), nspname);
2580
case OCLASS_TSPARSER:
2584
tup = SearchSysCache1(TSPARSEROID,
2585
ObjectIdGetDatum(object->objectId));
2586
if (!HeapTupleIsValid(tup))
2587
elog(ERROR, "cache lookup failed for text search parser %u",
2589
appendStringInfo(&buffer, _("text search parser %s"),
2590
NameStr(((Form_pg_ts_parser) GETSTRUCT(tup))->prsname));
2591
ReleaseSysCache(tup);
2599
tup = SearchSysCache1(TSDICTOID,
2600
ObjectIdGetDatum(object->objectId));
2601
if (!HeapTupleIsValid(tup))
2602
elog(ERROR, "cache lookup failed for text search dictionary %u",
2604
appendStringInfo(&buffer, _("text search dictionary %s"),
2605
NameStr(((Form_pg_ts_dict) GETSTRUCT(tup))->dictname));
2606
ReleaseSysCache(tup);
2610
case OCLASS_TSTEMPLATE:
2614
tup = SearchSysCache1(TSTEMPLATEOID,
2615
ObjectIdGetDatum(object->objectId));
2616
if (!HeapTupleIsValid(tup))
2617
elog(ERROR, "cache lookup failed for text search template %u",
2619
appendStringInfo(&buffer, _("text search template %s"),
2620
NameStr(((Form_pg_ts_template) GETSTRUCT(tup))->tmplname));
2621
ReleaseSysCache(tup);
2625
case OCLASS_TSCONFIG:
2629
tup = SearchSysCache1(TSCONFIGOID,
2630
ObjectIdGetDatum(object->objectId));
2631
if (!HeapTupleIsValid(tup))
2632
elog(ERROR, "cache lookup failed for text search configuration %u",
2634
appendStringInfo(&buffer, _("text search configuration %s"),
2635
NameStr(((Form_pg_ts_config) GETSTRUCT(tup))->cfgname));
2636
ReleaseSysCache(tup);
2642
appendStringInfo(&buffer, _("role %s"),
2643
GetUserNameFromId(object->objectId));
2647
case OCLASS_DATABASE:
2651
datname = get_database_name(object->objectId);
2653
elog(ERROR, "cache lookup failed for database %u",
2655
appendStringInfo(&buffer, _("database %s"), datname);
2659
case OCLASS_TBLSPACE:
2663
tblspace = get_tablespace_name(object->objectId);
2665
elog(ERROR, "cache lookup failed for tablespace %u",
2667
appendStringInfo(&buffer, _("tablespace %s"), tblspace);
2673
ForeignDataWrapper *fdw;
2675
fdw = GetForeignDataWrapper(object->objectId);
2676
appendStringInfo(&buffer, _("foreign-data wrapper %s"), fdw->fdwname);
2680
case OCLASS_FOREIGN_SERVER:
2684
srv = GetForeignServer(object->objectId);
2685
appendStringInfo(&buffer, _("server %s"), srv->servername);
2689
case OCLASS_USER_MAPPING:
2695
tup = SearchSysCache1(USERMAPPINGOID,
2696
ObjectIdGetDatum(object->objectId));
2697
if (!HeapTupleIsValid(tup))
2698
elog(ERROR, "cache lookup failed for user mapping %u",
2701
useid = ((Form_pg_user_mapping) GETSTRUCT(tup))->umuser;
2703
ReleaseSysCache(tup);
2705
if (OidIsValid(useid))
2706
usename = GetUserNameFromId(useid);
2710
appendStringInfo(&buffer, _("user mapping for %s"), usename);
2717
ScanKeyData skey[1];
2720
Form_pg_default_acl defacl;
2722
defaclrel = heap_open(DefaultAclRelationId, AccessShareLock);
2724
ScanKeyInit(&skey[0],
2725
ObjectIdAttributeNumber,
2726
BTEqualStrategyNumber, F_OIDEQ,
2727
ObjectIdGetDatum(object->objectId));
2729
rcscan = systable_beginscan(defaclrel, DefaultAclOidIndexId,
2730
true, SnapshotNow, 1, skey);
2732
tup = systable_getnext(rcscan);
2734
if (!HeapTupleIsValid(tup))
2735
elog(ERROR, "could not find tuple for default ACL %u",
2738
defacl = (Form_pg_default_acl) GETSTRUCT(tup);
2740
switch (defacl->defaclobjtype)
2742
case DEFACLOBJ_RELATION:
2743
appendStringInfo(&buffer,
2744
_("default privileges on new relations belonging to role %s"),
2745
GetUserNameFromId(defacl->defaclrole));
2747
case DEFACLOBJ_SEQUENCE:
2748
appendStringInfo(&buffer,
2749
_("default privileges on new sequences belonging to role %s"),
2750
GetUserNameFromId(defacl->defaclrole));
2752
case DEFACLOBJ_FUNCTION:
2753
appendStringInfo(&buffer,
2754
_("default privileges on new functions belonging to role %s"),
2755
GetUserNameFromId(defacl->defaclrole));
2758
/* shouldn't get here */
2759
appendStringInfo(&buffer,
2760
_("default privileges belonging to role %s"),
2761
GetUserNameFromId(defacl->defaclrole));
2765
if (OidIsValid(defacl->defaclnamespace))
2767
appendStringInfo(&buffer,
2769
get_namespace_name(defacl->defaclnamespace));
2772
systable_endscan(rcscan);
2773
heap_close(defaclrel, AccessShareLock);
2777
case OCLASS_EXTENSION:
2781
extname = get_extension_name(object->objectId);
2783
elog(ERROR, "cache lookup failed for extension %u",
2785
appendStringInfo(&buffer, _("extension %s"), extname);
2790
appendStringInfo(&buffer, "unrecognized object %u %u %d",
2793
object->objectSubId);
2801
* getObjectDescriptionOids: as above, except the object is specified by Oids
2804
getObjectDescriptionOids(Oid classid, Oid objid)
2806
ObjectAddress address;
2808
address.classId = classid;
2809
address.objectId = objid;
2810
address.objectSubId = 0;
2812
return getObjectDescription(&address);
2816
* subroutine for getObjectDescription: describe a relation
2819
getRelationDescription(StringInfo buffer, Oid relid)
2822
Form_pg_class relForm;
2826
relTup = SearchSysCache1(RELOID,
2827
ObjectIdGetDatum(relid));
2828
if (!HeapTupleIsValid(relTup))
2829
elog(ERROR, "cache lookup failed for relation %u", relid);
2830
relForm = (Form_pg_class) GETSTRUCT(relTup);
2832
/* Qualify the name if not visible in search path */
2833
if (RelationIsVisible(relid))
2836
nspname = get_namespace_name(relForm->relnamespace);
2838
relname = quote_qualified_identifier(nspname, NameStr(relForm->relname));
2840
switch (relForm->relkind)
2842
case RELKIND_RELATION:
2843
appendStringInfo(buffer, _("table %s"),
2847
appendStringInfo(buffer, _("index %s"),
2850
case RELKIND_SEQUENCE:
2851
appendStringInfo(buffer, _("sequence %s"),
2854
case RELKIND_UNCATALOGED:
2855
appendStringInfo(buffer, _("uncataloged table %s"),
2858
case RELKIND_TOASTVALUE:
2859
appendStringInfo(buffer, _("toast table %s"),
2863
appendStringInfo(buffer, _("view %s"),
2866
case RELKIND_COMPOSITE_TYPE:
2867
appendStringInfo(buffer, _("composite type %s"),
2870
case RELKIND_FOREIGN_TABLE:
2871
appendStringInfo(buffer, _("foreign table %s"),
2875
/* shouldn't get here */
2876
appendStringInfo(buffer, _("relation %s"),
2881
ReleaseSysCache(relTup);
2885
* subroutine for getObjectDescription: describe an operator family
2888
getOpFamilyDescription(StringInfo buffer, Oid opfid)
2891
Form_pg_opfamily opfForm;
2896
opfTup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
2897
if (!HeapTupleIsValid(opfTup))
2898
elog(ERROR, "cache lookup failed for opfamily %u", opfid);
2899
opfForm = (Form_pg_opfamily) GETSTRUCT(opfTup);
2901
amTup = SearchSysCache1(AMOID, ObjectIdGetDatum(opfForm->opfmethod));
2902
if (!HeapTupleIsValid(amTup))
2903
elog(ERROR, "cache lookup failed for access method %u",
2904
opfForm->opfmethod);
2905
amForm = (Form_pg_am) GETSTRUCT(amTup);
2907
/* Qualify the name if not visible in search path */
2908
if (OpfamilyIsVisible(opfid))
2911
nspname = get_namespace_name(opfForm->opfnamespace);
2913
appendStringInfo(buffer, _("operator family %s for access method %s"),
2914
quote_qualified_identifier(nspname,
2915
NameStr(opfForm->opfname)),
2916
NameStr(amForm->amname));
2918
ReleaseSysCache(amTup);
2919
ReleaseSysCache(opfTup);
2923
* SQL-level callable version of getObjectDescription
2926
pg_describe_object(PG_FUNCTION_ARGS)
2928
Oid classid = PG_GETARG_OID(0);
2929
Oid objid = PG_GETARG_OID(1);
2930
int32 subobjid = PG_GETARG_INT32(2);
2931
char *description = NULL;
2932
ObjectAddress address;
2934
/* for "pinned" items in pg_depend, return null */
2935
if (!OidIsValid(classid) && !OidIsValid(objid))
2938
address.classId = classid;
2939
address.objectId = objid;
2940
address.objectSubId = subobjid;
2942
description = getObjectDescription(&address);
2943
PG_RETURN_TEXT_P(cstring_to_text(description));