1 /*-------------------------------------------------------------------------
2  *
3  * rewriteRemove.c
4  *	  routines for removing rewrite rules
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/rewrite/rewriteRemove.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "access/genam.h"
18 #include "access/heapam.h"
19 #include "access/htup_details.h"
20 #include "access/sysattr.h"
21 #include "catalog/dependency.h"
22 #include "catalog/indexing.h"
23 #include "catalog/namespace.h"
24 #include "catalog/pg_rewrite.h"
25 #include "miscadmin.h"
26 #include "rewrite/rewriteRemove.h"
27 #include "utils/acl.h"
28 #include "utils/fmgroids.h"
29 #include "utils/inval.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32 #include "utils/tqual.h"
33 
34 /*
35  * Guts of rule deletion.
36  */
37 void
RemoveRewriteRuleById(Oid ruleOid)38 RemoveRewriteRuleById(Oid ruleOid)
39 {
40 	Relation	RewriteRelation;
41 	ScanKeyData skey[1];
42 	SysScanDesc rcscan;
43 	Relation	event_relation;
44 	HeapTuple	tuple;
45 	Oid			eventRelationOid;
46 
47 	/*
48 	 * Open the pg_rewrite relation.
49 	 */
50 	RewriteRelation = heap_open(RewriteRelationId, RowExclusiveLock);
51 
52 	/*
53 	 * Find the tuple for the target rule.
54 	 */
55 	ScanKeyInit(&skey[0],
56 				ObjectIdAttributeNumber,
57 				BTEqualStrategyNumber, F_OIDEQ,
58 				ObjectIdGetDatum(ruleOid));
59 
60 	rcscan = systable_beginscan(RewriteRelation, RewriteOidIndexId, true,
61 								NULL, 1, skey);
62 
63 	tuple = systable_getnext(rcscan);
64 
65 	if (!HeapTupleIsValid(tuple))
66 		elog(ERROR, "could not find tuple for rule %u", ruleOid);
67 
68 	/*
69 	 * We had better grab AccessExclusiveLock to ensure that no queries are
70 	 * going on that might depend on this rule.  (Note: a weaker lock would
71 	 * suffice if it's not an ON SELECT rule.)
72 	 */
73 	eventRelationOid = ((Form_pg_rewrite) GETSTRUCT(tuple))->ev_class;
74 	event_relation = heap_open(eventRelationOid, AccessExclusiveLock);
75 
76 	/*
77 	 * Now delete the pg_rewrite tuple for the rule
78 	 */
79 	CatalogTupleDelete(RewriteRelation, &tuple->t_self);
80 
81 	systable_endscan(rcscan);
82 
83 	heap_close(RewriteRelation, RowExclusiveLock);
84 
85 	/*
86 	 * Issue shared-inval notice to force all backends (including me!) to
87 	 * update relcache entries with the new rule set.
88 	 */
89 	CacheInvalidateRelcache(event_relation);
90 
91 	/* Close rel, but keep lock till commit... */
92 	heap_close(event_relation, NoLock);
93 }
94