1 /*-------------------------------------------------------------------------
2  *
3  * rewriteDefine.c
4  *	  routines for defining a rewrite rule
5  *
6  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/rewrite/rewriteDefine.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "access/heapam.h"
18 #include "access/htup_details.h"
19 #include "access/multixact.h"
20 #include "access/tableam.h"
21 #include "access/transam.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/heap.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/objectaccess.h"
29 #include "catalog/pg_inherits.h"
30 #include "catalog/pg_rewrite.h"
31 #include "catalog/storage.h"
32 #include "commands/policy.h"
33 #include "miscadmin.h"
34 #include "nodes/nodeFuncs.h"
35 #include "parser/parse_utilcmd.h"
36 #include "rewrite/rewriteDefine.h"
37 #include "rewrite/rewriteManip.h"
38 #include "rewrite/rewriteSupport.h"
39 #include "utils/acl.h"
40 #include "utils/builtins.h"
41 #include "utils/inval.h"
42 #include "utils/lsyscache.h"
43 #include "utils/rel.h"
44 #include "utils/snapmgr.h"
45 #include "utils/syscache.h"
46 
47 
48 static void checkRuleResultList(List *targetList, TupleDesc resultDesc,
49 								bool isSelect, bool requireColumnNameMatch);
50 static bool setRuleCheckAsUser_walker(Node *node, Oid *context);
51 static void setRuleCheckAsUser_Query(Query *qry, Oid userid);
52 
53 
54 /*
55  * InsertRule -
56  *	  takes the arguments and inserts them as a row into the system
57  *	  relation "pg_rewrite"
58  */
59 static Oid
InsertRule(const char * rulname,int evtype,Oid eventrel_oid,bool evinstead,Node * event_qual,List * action,bool replace)60 InsertRule(const char *rulname,
61 		   int evtype,
62 		   Oid eventrel_oid,
63 		   bool evinstead,
64 		   Node *event_qual,
65 		   List *action,
66 		   bool replace)
67 {
68 	char	   *evqual = nodeToString(event_qual);
69 	char	   *actiontree = nodeToString((Node *) action);
70 	Datum		values[Natts_pg_rewrite];
71 	bool		nulls[Natts_pg_rewrite];
72 	bool		replaces[Natts_pg_rewrite];
73 	NameData	rname;
74 	Relation	pg_rewrite_desc;
75 	HeapTuple	tup,
76 				oldtup;
77 	Oid			rewriteObjectId;
78 	ObjectAddress myself,
79 				referenced;
80 	bool		is_update = false;
81 
82 	/*
83 	 * Set up *nulls and *values arrays
84 	 */
85 	MemSet(nulls, false, sizeof(nulls));
86 
87 	namestrcpy(&rname, rulname);
88 	values[Anum_pg_rewrite_rulename - 1] = NameGetDatum(&rname);
89 	values[Anum_pg_rewrite_ev_class - 1] = ObjectIdGetDatum(eventrel_oid);
90 	values[Anum_pg_rewrite_ev_type - 1] = CharGetDatum(evtype + '0');
91 	values[Anum_pg_rewrite_ev_enabled - 1] = CharGetDatum(RULE_FIRES_ON_ORIGIN);
92 	values[Anum_pg_rewrite_is_instead - 1] = BoolGetDatum(evinstead);
93 	values[Anum_pg_rewrite_ev_qual - 1] = CStringGetTextDatum(evqual);
94 	values[Anum_pg_rewrite_ev_action - 1] = CStringGetTextDatum(actiontree);
95 
96 	/*
97 	 * Ready to store new pg_rewrite tuple
98 	 */
99 	pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
100 
101 	/*
102 	 * Check to see if we are replacing an existing tuple
103 	 */
104 	oldtup = SearchSysCache2(RULERELNAME,
105 							 ObjectIdGetDatum(eventrel_oid),
106 							 PointerGetDatum(rulname));
107 
108 	if (HeapTupleIsValid(oldtup))
109 	{
110 		if (!replace)
111 			ereport(ERROR,
112 					(errcode(ERRCODE_DUPLICATE_OBJECT),
113 					 errmsg("rule \"%s\" for relation \"%s\" already exists",
114 							rulname, get_rel_name(eventrel_oid))));
115 
116 		/*
117 		 * When replacing, we don't need to replace every attribute
118 		 */
119 		MemSet(replaces, false, sizeof(replaces));
120 		replaces[Anum_pg_rewrite_ev_type - 1] = true;
121 		replaces[Anum_pg_rewrite_is_instead - 1] = true;
122 		replaces[Anum_pg_rewrite_ev_qual - 1] = true;
123 		replaces[Anum_pg_rewrite_ev_action - 1] = true;
124 
125 		tup = heap_modify_tuple(oldtup, RelationGetDescr(pg_rewrite_desc),
126 								values, nulls, replaces);
127 
128 		CatalogTupleUpdate(pg_rewrite_desc, &tup->t_self, tup);
129 
130 		ReleaseSysCache(oldtup);
131 
132 		rewriteObjectId = ((Form_pg_rewrite) GETSTRUCT(tup))->oid;
133 		is_update = true;
134 	}
135 	else
136 	{
137 		rewriteObjectId = GetNewOidWithIndex(pg_rewrite_desc,
138 											 RewriteOidIndexId,
139 											 Anum_pg_rewrite_oid);
140 		values[Anum_pg_rewrite_oid - 1] = ObjectIdGetDatum(rewriteObjectId);
141 
142 		tup = heap_form_tuple(pg_rewrite_desc->rd_att, values, nulls);
143 
144 		CatalogTupleInsert(pg_rewrite_desc, tup);
145 	}
146 
147 
148 	heap_freetuple(tup);
149 
150 	/* If replacing, get rid of old dependencies and make new ones */
151 	if (is_update)
152 		deleteDependencyRecordsFor(RewriteRelationId, rewriteObjectId, false);
153 
154 	/*
155 	 * Install dependency on rule's relation to ensure it will go away on
156 	 * relation deletion.  If the rule is ON SELECT, make the dependency
157 	 * implicit --- this prevents deleting a view's SELECT rule.  Other kinds
158 	 * of rules can be AUTO.
159 	 */
160 	myself.classId = RewriteRelationId;
161 	myself.objectId = rewriteObjectId;
162 	myself.objectSubId = 0;
163 
164 	referenced.classId = RelationRelationId;
165 	referenced.objectId = eventrel_oid;
166 	referenced.objectSubId = 0;
167 
168 	recordDependencyOn(&myself, &referenced,
169 					   (evtype == CMD_SELECT) ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO);
170 
171 	/*
172 	 * Also install dependencies on objects referenced in action and qual.
173 	 */
174 	recordDependencyOnExpr(&myself, (Node *) action, NIL,
175 						   DEPENDENCY_NORMAL);
176 
177 	if (event_qual != NULL)
178 	{
179 		/* Find query containing OLD/NEW rtable entries */
180 		Query	   *qry = linitial_node(Query, action);
181 
182 		qry = getInsertSelectQuery(qry, NULL);
183 		recordDependencyOnExpr(&myself, event_qual, qry->rtable,
184 							   DEPENDENCY_NORMAL);
185 	}
186 
187 	/* Post creation hook for new rule */
188 	InvokeObjectPostCreateHook(RewriteRelationId, rewriteObjectId, 0);
189 
190 	table_close(pg_rewrite_desc, RowExclusiveLock);
191 
192 	return rewriteObjectId;
193 }
194 
195 /*
196  * DefineRule
197  *		Execute a CREATE RULE command.
198  */
199 ObjectAddress
DefineRule(RuleStmt * stmt,const char * queryString)200 DefineRule(RuleStmt *stmt, const char *queryString)
201 {
202 	List	   *actions;
203 	Node	   *whereClause;
204 	Oid			relId;
205 
206 	/* Parse analysis. */
207 	transformRuleStmt(stmt, queryString, &actions, &whereClause);
208 
209 	/*
210 	 * Find and lock the relation.  Lock level should match
211 	 * DefineQueryRewrite.
212 	 */
213 	relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
214 
215 	/* ... and execute */
216 	return DefineQueryRewrite(stmt->rulename,
217 							  relId,
218 							  whereClause,
219 							  stmt->event,
220 							  stmt->instead,
221 							  stmt->replace,
222 							  actions);
223 }
224 
225 
226 /*
227  * DefineQueryRewrite
228  *		Create a rule
229  *
230  * This is essentially the same as DefineRule() except that the rule's
231  * action and qual have already been passed through parse analysis.
232  */
233 ObjectAddress
DefineQueryRewrite(const char * rulename,Oid event_relid,Node * event_qual,CmdType event_type,bool is_instead,bool replace,List * action)234 DefineQueryRewrite(const char *rulename,
235 				   Oid event_relid,
236 				   Node *event_qual,
237 				   CmdType event_type,
238 				   bool is_instead,
239 				   bool replace,
240 				   List *action)
241 {
242 	Relation	event_relation;
243 	ListCell   *l;
244 	Query	   *query;
245 	bool		RelisBecomingView = false;
246 	Oid			ruleId = InvalidOid;
247 	ObjectAddress address;
248 
249 	/*
250 	 * If we are installing an ON SELECT rule, we had better grab
251 	 * AccessExclusiveLock to ensure no SELECTs are currently running on the
252 	 * event relation. For other types of rules, it would be sufficient to
253 	 * grab ShareRowExclusiveLock to lock out insert/update/delete actions and
254 	 * to ensure that we lock out current CREATE RULE statements; but because
255 	 * of race conditions in access to catalog entries, we can't do that yet.
256 	 *
257 	 * Note that this lock level should match the one used in DefineRule.
258 	 */
259 	event_relation = table_open(event_relid, AccessExclusiveLock);
260 
261 	/*
262 	 * Verify relation is of a type that rules can sensibly be applied to.
263 	 * Internal callers can target materialized views, but transformRuleStmt()
264 	 * blocks them for users.  Don't mention them in the error message.
265 	 */
266 	if (event_relation->rd_rel->relkind != RELKIND_RELATION &&
267 		event_relation->rd_rel->relkind != RELKIND_MATVIEW &&
268 		event_relation->rd_rel->relkind != RELKIND_VIEW &&
269 		event_relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
270 		ereport(ERROR,
271 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
272 				 errmsg("\"%s\" is not a table or view",
273 						RelationGetRelationName(event_relation))));
274 
275 	if (!allowSystemTableMods && IsSystemRelation(event_relation))
276 		ereport(ERROR,
277 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
278 				 errmsg("permission denied: \"%s\" is a system catalog",
279 						RelationGetRelationName(event_relation))));
280 
281 	/*
282 	 * Check user has permission to apply rules to this relation.
283 	 */
284 	if (!pg_class_ownercheck(event_relid, GetUserId()))
285 		aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(event_relation->rd_rel->relkind),
286 					   RelationGetRelationName(event_relation));
287 
288 	/*
289 	 * No rule actions that modify OLD or NEW
290 	 */
291 	foreach(l, action)
292 	{
293 		query = lfirst_node(Query, l);
294 		if (query->resultRelation == 0)
295 			continue;
296 		/* Don't be fooled by INSERT/SELECT */
297 		if (query != getInsertSelectQuery(query, NULL))
298 			continue;
299 		if (query->resultRelation == PRS2_OLD_VARNO)
300 			ereport(ERROR,
301 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
302 					 errmsg("rule actions on OLD are not implemented"),
303 					 errhint("Use views or triggers instead.")));
304 		if (query->resultRelation == PRS2_NEW_VARNO)
305 			ereport(ERROR,
306 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
307 					 errmsg("rule actions on NEW are not implemented"),
308 					 errhint("Use triggers instead.")));
309 	}
310 
311 	if (event_type == CMD_SELECT)
312 	{
313 		/*
314 		 * Rules ON SELECT are restricted to view definitions
315 		 *
316 		 * So there cannot be INSTEAD NOTHING, ...
317 		 */
318 		if (list_length(action) == 0)
319 			ereport(ERROR,
320 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
321 					 errmsg("INSTEAD NOTHING rules on SELECT are not implemented"),
322 					 errhint("Use views instead.")));
323 
324 		/*
325 		 * ... there cannot be multiple actions, ...
326 		 */
327 		if (list_length(action) > 1)
328 			ereport(ERROR,
329 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
330 					 errmsg("multiple actions for rules on SELECT are not implemented")));
331 
332 		/*
333 		 * ... the one action must be a SELECT, ...
334 		 */
335 		query = linitial_node(Query, action);
336 		if (!is_instead ||
337 			query->commandType != CMD_SELECT)
338 			ereport(ERROR,
339 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
340 					 errmsg("rules on SELECT must have action INSTEAD SELECT")));
341 
342 		/*
343 		 * ... it cannot contain data-modifying WITH ...
344 		 */
345 		if (query->hasModifyingCTE)
346 			ereport(ERROR,
347 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
348 					 errmsg("rules on SELECT must not contain data-modifying statements in WITH")));
349 
350 		/*
351 		 * ... there can be no rule qual, ...
352 		 */
353 		if (event_qual != NULL)
354 			ereport(ERROR,
355 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
356 					 errmsg("event qualifications are not implemented for rules on SELECT")));
357 
358 		/*
359 		 * ... the targetlist of the SELECT action must exactly match the
360 		 * event relation, ...
361 		 */
362 		checkRuleResultList(query->targetList,
363 							RelationGetDescr(event_relation),
364 							true,
365 							event_relation->rd_rel->relkind !=
366 							RELKIND_MATVIEW);
367 
368 		/*
369 		 * ... there must not be another ON SELECT rule already ...
370 		 */
371 		if (!replace && event_relation->rd_rules != NULL)
372 		{
373 			int			i;
374 
375 			for (i = 0; i < event_relation->rd_rules->numLocks; i++)
376 			{
377 				RewriteRule *rule;
378 
379 				rule = event_relation->rd_rules->rules[i];
380 				if (rule->event == CMD_SELECT)
381 					ereport(ERROR,
382 							(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
383 							 errmsg("\"%s\" is already a view",
384 									RelationGetRelationName(event_relation))));
385 			}
386 		}
387 
388 		/*
389 		 * ... and finally the rule must be named _RETURN.
390 		 */
391 		if (strcmp(rulename, ViewSelectRuleName) != 0)
392 		{
393 			/*
394 			 * In versions before 7.3, the expected name was _RETviewname. For
395 			 * backwards compatibility with old pg_dump output, accept that
396 			 * and silently change it to _RETURN.  Since this is just a quick
397 			 * backwards-compatibility hack, limit the number of characters
398 			 * checked to a few less than NAMEDATALEN; this saves having to
399 			 * worry about where a multibyte character might have gotten
400 			 * truncated.
401 			 */
402 			if (strncmp(rulename, "_RET", 4) != 0 ||
403 				strncmp(rulename + 4, RelationGetRelationName(event_relation),
404 						NAMEDATALEN - 4 - 4) != 0)
405 				ereport(ERROR,
406 						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
407 						 errmsg("view rule for \"%s\" must be named \"%s\"",
408 								RelationGetRelationName(event_relation),
409 								ViewSelectRuleName)));
410 			rulename = pstrdup(ViewSelectRuleName);
411 		}
412 
413 		/*
414 		 * Are we converting a relation to a view?
415 		 *
416 		 * If so, check that the relation is empty because the storage for the
417 		 * relation is going to be deleted.  Also insist that the rel not be
418 		 * involved in partitioning, nor have any triggers, indexes, child or
419 		 * parent tables, RLS policies, or RLS enabled.  (Note: some of these
420 		 * tests are too strict, because they will reject relations that once
421 		 * had such but don't anymore.  But we don't really care, because this
422 		 * whole business of converting relations to views is just an obsolete
423 		 * kluge to allow dump/reload of views that participate in circular
424 		 * dependencies.)
425 		 */
426 		if (event_relation->rd_rel->relkind != RELKIND_VIEW &&
427 			event_relation->rd_rel->relkind != RELKIND_MATVIEW)
428 		{
429 			TableScanDesc scanDesc;
430 			Snapshot	snapshot;
431 			TupleTableSlot *slot;
432 
433 			if (event_relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
434 				ereport(ERROR,
435 						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
436 						 errmsg("cannot convert partitioned table \"%s\" to a view",
437 								RelationGetRelationName(event_relation))));
438 
439 			/* only case left: */
440 			Assert(event_relation->rd_rel->relkind == RELKIND_RELATION);
441 
442 			if (event_relation->rd_rel->relispartition)
443 				ereport(ERROR,
444 						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
445 						 errmsg("cannot convert partition \"%s\" to a view",
446 								RelationGetRelationName(event_relation))));
447 
448 			snapshot = RegisterSnapshot(GetLatestSnapshot());
449 			scanDesc = table_beginscan(event_relation, snapshot, 0, NULL);
450 			slot = table_slot_create(event_relation, NULL);
451 			if (table_scan_getnextslot(scanDesc, ForwardScanDirection, slot))
452 				ereport(ERROR,
453 						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
454 						 errmsg("could not convert table \"%s\" to a view because it is not empty",
455 								RelationGetRelationName(event_relation))));
456 			ExecDropSingleTupleTableSlot(slot);
457 			table_endscan(scanDesc);
458 			UnregisterSnapshot(snapshot);
459 
460 			if (event_relation->rd_rel->relhastriggers)
461 				ereport(ERROR,
462 						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
463 						 errmsg("could not convert table \"%s\" to a view because it has triggers",
464 								RelationGetRelationName(event_relation)),
465 						 errhint("In particular, the table cannot be involved in any foreign key relationships.")));
466 
467 			if (event_relation->rd_rel->relhasindex)
468 				ereport(ERROR,
469 						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
470 						 errmsg("could not convert table \"%s\" to a view because it has indexes",
471 								RelationGetRelationName(event_relation))));
472 
473 			if (event_relation->rd_rel->relhassubclass)
474 				ereport(ERROR,
475 						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
476 						 errmsg("could not convert table \"%s\" to a view because it has child tables",
477 								RelationGetRelationName(event_relation))));
478 
479 			if (has_superclass(RelationGetRelid(event_relation)))
480 				ereport(ERROR,
481 						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
482 						 errmsg("could not convert table \"%s\" to a view because it has parent tables",
483 								RelationGetRelationName(event_relation))));
484 
485 			if (event_relation->rd_rel->relrowsecurity)
486 				ereport(ERROR,
487 						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
488 						 errmsg("could not convert table \"%s\" to a view because it has row security enabled",
489 								RelationGetRelationName(event_relation))));
490 
491 			if (relation_has_policies(event_relation))
492 				ereport(ERROR,
493 						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
494 						 errmsg("could not convert table \"%s\" to a view because it has row security policies",
495 								RelationGetRelationName(event_relation))));
496 
497 			RelisBecomingView = true;
498 		}
499 	}
500 	else
501 	{
502 		/*
503 		 * For non-SELECT rules, a RETURNING list can appear in at most one of
504 		 * the actions ... and there can't be any RETURNING list at all in a
505 		 * conditional or non-INSTEAD rule.  (Actually, there can be at most
506 		 * one RETURNING list across all rules on the same event, but it seems
507 		 * best to enforce that at rule expansion time.)  If there is a
508 		 * RETURNING list, it must match the event relation.
509 		 */
510 		bool		haveReturning = false;
511 
512 		foreach(l, action)
513 		{
514 			query = lfirst_node(Query, l);
515 
516 			if (!query->returningList)
517 				continue;
518 			if (haveReturning)
519 				ereport(ERROR,
520 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
521 						 errmsg("cannot have multiple RETURNING lists in a rule")));
522 			haveReturning = true;
523 			if (event_qual != NULL)
524 				ereport(ERROR,
525 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
526 						 errmsg("RETURNING lists are not supported in conditional rules")));
527 			if (!is_instead)
528 				ereport(ERROR,
529 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
530 						 errmsg("RETURNING lists are not supported in non-INSTEAD rules")));
531 			checkRuleResultList(query->returningList,
532 								RelationGetDescr(event_relation),
533 								false, false);
534 		}
535 	}
536 
537 	/*
538 	 * This rule is allowed - prepare to install it.
539 	 */
540 
541 	/* discard rule if it's null action and not INSTEAD; it's a no-op */
542 	if (action != NIL || is_instead)
543 	{
544 		ruleId = InsertRule(rulename,
545 							event_type,
546 							event_relid,
547 							is_instead,
548 							event_qual,
549 							action,
550 							replace);
551 
552 		/*
553 		 * Set pg_class 'relhasrules' field true for event relation.
554 		 *
555 		 * Important side effect: an SI notice is broadcast to force all
556 		 * backends (including me!) to update relcache entries with the new
557 		 * rule.
558 		 */
559 		SetRelationRuleStatus(event_relid, true);
560 	}
561 
562 	/* ---------------------------------------------------------------------
563 	 * If the relation is becoming a view:
564 	 * - delete the associated storage files
565 	 * - get rid of any system attributes in pg_attribute; a view shouldn't
566 	 *	 have any of those
567 	 * - remove the toast table; there is no need for it anymore, and its
568 	 *	 presence would make vacuum slightly more complicated
569 	 * - set relkind to RELKIND_VIEW, and adjust other pg_class fields
570 	 *	 to be appropriate for a view
571 	 *
572 	 * NB: we had better have AccessExclusiveLock to do this ...
573 	 * ---------------------------------------------------------------------
574 	 */
575 	if (RelisBecomingView)
576 	{
577 		Relation	relationRelation;
578 		Oid			toastrelid;
579 		HeapTuple	classTup;
580 		Form_pg_class classForm;
581 
582 		relationRelation = table_open(RelationRelationId, RowExclusiveLock);
583 		toastrelid = event_relation->rd_rel->reltoastrelid;
584 
585 		/* drop storage while table still looks like a table  */
586 		RelationDropStorage(event_relation);
587 		DeleteSystemAttributeTuples(event_relid);
588 
589 		/*
590 		 * Drop the toast table if any.  (This won't take care of updating the
591 		 * toast fields in the relation's own pg_class entry; we handle that
592 		 * below.)
593 		 */
594 		if (OidIsValid(toastrelid))
595 		{
596 			ObjectAddress toastobject;
597 
598 			/*
599 			 * Delete the dependency of the toast relation on the main
600 			 * relation so we can drop the former without dropping the latter.
601 			 */
602 			deleteDependencyRecordsFor(RelationRelationId, toastrelid,
603 									   false);
604 
605 			/* Make deletion of dependency record visible */
606 			CommandCounterIncrement();
607 
608 			/* Now drop toast table, including its index */
609 			toastobject.classId = RelationRelationId;
610 			toastobject.objectId = toastrelid;
611 			toastobject.objectSubId = 0;
612 			performDeletion(&toastobject, DROP_RESTRICT,
613 							PERFORM_DELETION_INTERNAL);
614 		}
615 
616 		/*
617 		 * SetRelationRuleStatus may have updated the pg_class row, so we must
618 		 * advance the command counter before trying to update it again.
619 		 */
620 		CommandCounterIncrement();
621 
622 		/*
623 		 * Fix pg_class entry to look like a normal view's, including setting
624 		 * the correct relkind and removal of reltoastrelid of the toast table
625 		 * we potentially removed above.
626 		 */
627 		classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(event_relid));
628 		if (!HeapTupleIsValid(classTup))
629 			elog(ERROR, "cache lookup failed for relation %u", event_relid);
630 		classForm = (Form_pg_class) GETSTRUCT(classTup);
631 
632 		classForm->relam = InvalidOid;
633 		classForm->reltablespace = InvalidOid;
634 		classForm->relpages = 0;
635 		classForm->reltuples = 0;
636 		classForm->relallvisible = 0;
637 		classForm->reltoastrelid = InvalidOid;
638 		classForm->relhasindex = false;
639 		classForm->relkind = RELKIND_VIEW;
640 		classForm->relfrozenxid = InvalidTransactionId;
641 		classForm->relminmxid = InvalidMultiXactId;
642 		classForm->relreplident = REPLICA_IDENTITY_NOTHING;
643 
644 		CatalogTupleUpdate(relationRelation, &classTup->t_self, classTup);
645 
646 		heap_freetuple(classTup);
647 		table_close(relationRelation, RowExclusiveLock);
648 	}
649 
650 	ObjectAddressSet(address, RewriteRelationId, ruleId);
651 
652 	/* Close rel, but keep lock till commit... */
653 	table_close(event_relation, NoLock);
654 
655 	return address;
656 }
657 
658 /*
659  * checkRuleResultList
660  *		Verify that targetList produces output compatible with a tupledesc
661  *
662  * The targetList might be either a SELECT targetlist, or a RETURNING list;
663  * isSelect tells which.  This is used for choosing error messages.
664  *
665  * A SELECT targetlist may optionally require that column names match.
666  */
667 static void
checkRuleResultList(List * targetList,TupleDesc resultDesc,bool isSelect,bool requireColumnNameMatch)668 checkRuleResultList(List *targetList, TupleDesc resultDesc, bool isSelect,
669 					bool requireColumnNameMatch)
670 {
671 	ListCell   *tllist;
672 	int			i;
673 
674 	/* Only a SELECT may require a column name match. */
675 	Assert(isSelect || !requireColumnNameMatch);
676 
677 	i = 0;
678 	foreach(tllist, targetList)
679 	{
680 		TargetEntry *tle = (TargetEntry *) lfirst(tllist);
681 		Oid			tletypid;
682 		int32		tletypmod;
683 		Form_pg_attribute attr;
684 		char	   *attname;
685 
686 		/* resjunk entries may be ignored */
687 		if (tle->resjunk)
688 			continue;
689 		i++;
690 		if (i > resultDesc->natts)
691 			ereport(ERROR,
692 					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
693 					 isSelect ?
694 					 errmsg("SELECT rule's target list has too many entries") :
695 					 errmsg("RETURNING list has too many entries")));
696 
697 		attr = TupleDescAttr(resultDesc, i - 1);
698 		attname = NameStr(attr->attname);
699 
700 		/*
701 		 * Disallow dropped columns in the relation.  This is not really
702 		 * expected to happen when creating an ON SELECT rule.  It'd be
703 		 * possible if someone tried to convert a relation with dropped
704 		 * columns to a view, but the only case we care about supporting
705 		 * table-to-view conversion for is pg_dump, and pg_dump won't do that.
706 		 *
707 		 * Unfortunately, the situation is also possible when adding a rule
708 		 * with RETURNING to a regular table, and rejecting that case is
709 		 * altogether more annoying.  In principle we could support it by
710 		 * modifying the targetlist to include dummy NULL columns
711 		 * corresponding to the dropped columns in the tupdesc.  However,
712 		 * places like ruleutils.c would have to be fixed to not process such
713 		 * entries, and that would take an uncertain and possibly rather large
714 		 * amount of work.  (Note we could not dodge that by marking the dummy
715 		 * columns resjunk, since it's precisely the non-resjunk tlist columns
716 		 * that are expected to correspond to table columns.)
717 		 */
718 		if (attr->attisdropped)
719 			ereport(ERROR,
720 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
721 					 isSelect ?
722 					 errmsg("cannot convert relation containing dropped columns to view") :
723 					 errmsg("cannot create a RETURNING list for a relation containing dropped columns")));
724 
725 		/* Check name match if required; no need for two error texts here */
726 		if (requireColumnNameMatch && strcmp(tle->resname, attname) != 0)
727 			ereport(ERROR,
728 					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
729 					 errmsg("SELECT rule's target entry %d has different column name from column \"%s\"",
730 							i, attname),
731 					 errdetail("SELECT target entry is named \"%s\".",
732 							   tle->resname)));
733 
734 		/* Check type match. */
735 		tletypid = exprType((Node *) tle->expr);
736 		if (attr->atttypid != tletypid)
737 			ereport(ERROR,
738 					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
739 					 isSelect ?
740 					 errmsg("SELECT rule's target entry %d has different type from column \"%s\"",
741 							i, attname) :
742 					 errmsg("RETURNING list's entry %d has different type from column \"%s\"",
743 							i, attname),
744 					 isSelect ?
745 					 errdetail("SELECT target entry has type %s, but column has type %s.",
746 							   format_type_be(tletypid),
747 							   format_type_be(attr->atttypid)) :
748 					 errdetail("RETURNING list entry has type %s, but column has type %s.",
749 							   format_type_be(tletypid),
750 							   format_type_be(attr->atttypid))));
751 
752 		/*
753 		 * Allow typmods to be different only if one of them is -1, ie,
754 		 * "unspecified".  This is necessary for cases like "numeric", where
755 		 * the table will have a filled-in default length but the select
756 		 * rule's expression will probably have typmod = -1.
757 		 */
758 		tletypmod = exprTypmod((Node *) tle->expr);
759 		if (attr->atttypmod != tletypmod &&
760 			attr->atttypmod != -1 && tletypmod != -1)
761 			ereport(ERROR,
762 					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
763 					 isSelect ?
764 					 errmsg("SELECT rule's target entry %d has different size from column \"%s\"",
765 							i, attname) :
766 					 errmsg("RETURNING list's entry %d has different size from column \"%s\"",
767 							i, attname),
768 					 isSelect ?
769 					 errdetail("SELECT target entry has type %s, but column has type %s.",
770 							   format_type_with_typemod(tletypid, tletypmod),
771 							   format_type_with_typemod(attr->atttypid,
772 														attr->atttypmod)) :
773 					 errdetail("RETURNING list entry has type %s, but column has type %s.",
774 							   format_type_with_typemod(tletypid, tletypmod),
775 							   format_type_with_typemod(attr->atttypid,
776 														attr->atttypmod))));
777 	}
778 
779 	if (i != resultDesc->natts)
780 		ereport(ERROR,
781 				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
782 				 isSelect ?
783 				 errmsg("SELECT rule's target list has too few entries") :
784 				 errmsg("RETURNING list has too few entries")));
785 }
786 
787 /*
788  * setRuleCheckAsUser
789  *		Recursively scan a query or expression tree and set the checkAsUser
790  *		field to the given userid in all rtable entries.
791  *
792  * Note: for a view (ON SELECT rule), the checkAsUser field of the OLD
793  * RTE entry will be overridden when the view rule is expanded, and the
794  * checkAsUser field of the NEW entry is irrelevant because that entry's
795  * requiredPerms bits will always be zero.  However, for other types of rules
796  * it's important to set these fields to match the rule owner.  So we just set
797  * them always.
798  */
799 void
setRuleCheckAsUser(Node * node,Oid userid)800 setRuleCheckAsUser(Node *node, Oid userid)
801 {
802 	(void) setRuleCheckAsUser_walker(node, &userid);
803 }
804 
805 static bool
setRuleCheckAsUser_walker(Node * node,Oid * context)806 setRuleCheckAsUser_walker(Node *node, Oid *context)
807 {
808 	if (node == NULL)
809 		return false;
810 	if (IsA(node, Query))
811 	{
812 		setRuleCheckAsUser_Query((Query *) node, *context);
813 		return false;
814 	}
815 	return expression_tree_walker(node, setRuleCheckAsUser_walker,
816 								  (void *) context);
817 }
818 
819 static void
setRuleCheckAsUser_Query(Query * qry,Oid userid)820 setRuleCheckAsUser_Query(Query *qry, Oid userid)
821 {
822 	ListCell   *l;
823 
824 	/* Set all the RTEs in this query node */
825 	foreach(l, qry->rtable)
826 	{
827 		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
828 
829 		if (rte->rtekind == RTE_SUBQUERY)
830 		{
831 			/* Recurse into subquery in FROM */
832 			setRuleCheckAsUser_Query(rte->subquery, userid);
833 		}
834 		else
835 			rte->checkAsUser = userid;
836 	}
837 
838 	/* Recurse into subquery-in-WITH */
839 	foreach(l, qry->cteList)
840 	{
841 		CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
842 
843 		setRuleCheckAsUser_Query(castNode(Query, cte->ctequery), userid);
844 	}
845 
846 	/* If there are sublinks, search for them and process their RTEs */
847 	if (qry->hasSubLinks)
848 		query_tree_walker(qry, setRuleCheckAsUser_walker, (void *) &userid,
849 						  QTW_IGNORE_RC_SUBQUERIES);
850 }
851 
852 
853 /*
854  * Change the firing semantics of an existing rule.
855  */
856 void
EnableDisableRule(Relation rel,const char * rulename,char fires_when)857 EnableDisableRule(Relation rel, const char *rulename,
858 				  char fires_when)
859 {
860 	Relation	pg_rewrite_desc;
861 	Oid			owningRel = RelationGetRelid(rel);
862 	Oid			eventRelationOid;
863 	HeapTuple	ruletup;
864 	Form_pg_rewrite ruleform;
865 	bool		changed = false;
866 
867 	/*
868 	 * Find the rule tuple to change.
869 	 */
870 	pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
871 	ruletup = SearchSysCacheCopy2(RULERELNAME,
872 								  ObjectIdGetDatum(owningRel),
873 								  PointerGetDatum(rulename));
874 	if (!HeapTupleIsValid(ruletup))
875 		ereport(ERROR,
876 				(errcode(ERRCODE_UNDEFINED_OBJECT),
877 				 errmsg("rule \"%s\" for relation \"%s\" does not exist",
878 						rulename, get_rel_name(owningRel))));
879 
880 	ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
881 
882 	/*
883 	 * Verify that the user has appropriate permissions.
884 	 */
885 	eventRelationOid = ruleform->ev_class;
886 	Assert(eventRelationOid == owningRel);
887 	if (!pg_class_ownercheck(eventRelationOid, GetUserId()))
888 		aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(eventRelationOid)),
889 					   get_rel_name(eventRelationOid));
890 
891 	/*
892 	 * Change ev_enabled if it is different from the desired new state.
893 	 */
894 	if (DatumGetChar(ruleform->ev_enabled) !=
895 		fires_when)
896 	{
897 		ruleform->ev_enabled = CharGetDatum(fires_when);
898 		CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
899 
900 		changed = true;
901 	}
902 
903 	InvokeObjectPostAlterHook(RewriteRelationId, ruleform->oid, 0);
904 
905 	heap_freetuple(ruletup);
906 	table_close(pg_rewrite_desc, RowExclusiveLock);
907 
908 	/*
909 	 * If we changed anything, broadcast a SI inval message to force each
910 	 * backend (including our own!) to rebuild relation's relcache entry.
911 	 * Otherwise they will fail to apply the change promptly.
912 	 */
913 	if (changed)
914 		CacheInvalidateRelcache(rel);
915 }
916 
917 
918 /*
919  * Perform permissions and integrity checks before acquiring a relation lock.
920  */
921 static void
RangeVarCallbackForRenameRule(const RangeVar * rv,Oid relid,Oid oldrelid,void * arg)922 RangeVarCallbackForRenameRule(const RangeVar *rv, Oid relid, Oid oldrelid,
923 							  void *arg)
924 {
925 	HeapTuple	tuple;
926 	Form_pg_class form;
927 
928 	tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
929 	if (!HeapTupleIsValid(tuple))
930 		return;					/* concurrently dropped */
931 	form = (Form_pg_class) GETSTRUCT(tuple);
932 
933 	/* only tables and views can have rules */
934 	if (form->relkind != RELKIND_RELATION &&
935 		form->relkind != RELKIND_VIEW &&
936 		form->relkind != RELKIND_PARTITIONED_TABLE)
937 		ereport(ERROR,
938 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
939 				 errmsg("\"%s\" is not a table or view", rv->relname)));
940 
941 	if (!allowSystemTableMods && IsSystemClass(relid, form))
942 		ereport(ERROR,
943 				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
944 				 errmsg("permission denied: \"%s\" is a system catalog",
945 						rv->relname)));
946 
947 	/* you must own the table to rename one of its rules */
948 	if (!pg_class_ownercheck(relid, GetUserId()))
949 		aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
950 
951 	ReleaseSysCache(tuple);
952 }
953 
954 /*
955  * Rename an existing rewrite rule.
956  */
957 ObjectAddress
RenameRewriteRule(RangeVar * relation,const char * oldName,const char * newName)958 RenameRewriteRule(RangeVar *relation, const char *oldName,
959 				  const char *newName)
960 {
961 	Oid			relid;
962 	Relation	targetrel;
963 	Relation	pg_rewrite_desc;
964 	HeapTuple	ruletup;
965 	Form_pg_rewrite ruleform;
966 	Oid			ruleOid;
967 	ObjectAddress address;
968 
969 	/*
970 	 * Look up name, check permissions, and acquire lock (which we will NOT
971 	 * release until end of transaction).
972 	 */
973 	relid = RangeVarGetRelidExtended(relation, AccessExclusiveLock,
974 									 0,
975 									 RangeVarCallbackForRenameRule,
976 									 NULL);
977 
978 	/* Have lock already, so just need to build relcache entry. */
979 	targetrel = relation_open(relid, NoLock);
980 
981 	/* Prepare to modify pg_rewrite */
982 	pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
983 
984 	/* Fetch the rule's entry (it had better exist) */
985 	ruletup = SearchSysCacheCopy2(RULERELNAME,
986 								  ObjectIdGetDatum(relid),
987 								  PointerGetDatum(oldName));
988 	if (!HeapTupleIsValid(ruletup))
989 		ereport(ERROR,
990 				(errcode(ERRCODE_UNDEFINED_OBJECT),
991 				 errmsg("rule \"%s\" for relation \"%s\" does not exist",
992 						oldName, RelationGetRelationName(targetrel))));
993 	ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
994 	ruleOid = ruleform->oid;
995 
996 	/* rule with the new name should not already exist */
997 	if (IsDefinedRewriteRule(relid, newName))
998 		ereport(ERROR,
999 				(errcode(ERRCODE_DUPLICATE_OBJECT),
1000 				 errmsg("rule \"%s\" for relation \"%s\" already exists",
1001 						newName, RelationGetRelationName(targetrel))));
1002 
1003 	/*
1004 	 * We disallow renaming ON SELECT rules, because they should always be
1005 	 * named "_RETURN".
1006 	 */
1007 	if (ruleform->ev_type == CMD_SELECT + '0')
1008 		ereport(ERROR,
1009 				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1010 				 errmsg("renaming an ON SELECT rule is not allowed")));
1011 
1012 	/* OK, do the update */
1013 	namestrcpy(&(ruleform->rulename), newName);
1014 
1015 	CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
1016 
1017 	heap_freetuple(ruletup);
1018 	table_close(pg_rewrite_desc, RowExclusiveLock);
1019 
1020 	/*
1021 	 * Invalidate relation's relcache entry so that other backends (and this
1022 	 * one too!) are sent SI message to make them rebuild relcache entries.
1023 	 * (Ideally this should happen automatically...)
1024 	 */
1025 	CacheInvalidateRelcache(targetrel);
1026 
1027 	ObjectAddressSet(address, RewriteRelationId, ruleOid);
1028 
1029 	/*
1030 	 * Close rel, but keep exclusive lock!
1031 	 */
1032 	relation_close(targetrel, NoLock);
1033 
1034 	return address;
1035 }
1036