Debian Codegraph @

src/backend/rewrite/rewriteDefine.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * rewriteDefine.c
4 * routines for defining a rewrite rule
5 *
6 * Portions Copyright (c) 1996-2025, 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/htup_details.h"
18 #include "access/relation.h"
19 #include "access/table.h"
20 #include "catalog/catalog.h"
21 #include "catalog/dependency.h"
22 #include "catalog/indexing.h"
23 #include "catalog/namespace.h"
24 #include "catalog/objectaccess.h"
25 #include "catalog/pg_rewrite.h"
26 #include "miscadmin.h"
27 #include "nodes/nodeFuncs.h"
28 #include "parser/parse_utilcmd.h"
29 #include "rewrite/rewriteDefine.h"
30 #include "rewrite/rewriteManip.h"
31 #include "rewrite/rewriteSupport.h"
32 #include "utils/acl.h"
33 #include "utils/builtins.h"
34 #include "utils/inval.h"
35 #include "utils/lsyscache.h"
36 #include "utils/rel.h"
37 #include "utils/syscache.h"
38
39
40 static void checkRuleResultList(List *targetList, TupleDesc resultDesc,
41 bool isSelect, bool requireColumnNameMatch);
42 static bool setRuleCheckAsUser_walker(Node *node, Oid *context);
43 static void setRuleCheckAsUser_Query(Query *qry, Oid userid);
44
45
46 /*
47 * InsertRule -
48 * takes the arguments and inserts them as a row into the system
49 * relation "pg_rewrite"
50 */
51 static Oid
52 InsertRule(const char *rulname,
53 int evtype,
54 Oid eventrel_oid,
55 bool evinstead,
56 Node *event_qual,
57 List *action,
58 bool replace)
59 {
60 char *evqual = nodeToString(event_qual);
61 char *actiontree = nodeToString((Node *) action);
62 Datum values[Natts_pg_rewrite];
63 bool nulls[Natts_pg_rewrite] = {0};
64 NameData rname;
65 Relation pg_rewrite_desc;
66 HeapTuple tup,
67 oldtup;
68 Oid rewriteObjectId;
69 ObjectAddress myself,
70 referenced;
71 bool is_update = false;
72
73 /*
74 * Set up *nulls and *values arrays
75 */
76 namestrcpy(&rname, rulname);
77 values[Anum_pg_rewrite_rulename - 1] = NameGetDatum(&rname);
78 values[Anum_pg_rewrite_ev_class - 1] = ObjectIdGetDatum(eventrel_oid);
79 values[Anum_pg_rewrite_ev_type - 1] = CharGetDatum(evtype + '0');
80 values[Anum_pg_rewrite_ev_enabled - 1] = CharGetDatum(RULE_FIRES_ON_ORIGIN);
81 values[Anum_pg_rewrite_is_instead - 1] = BoolGetDatum(evinstead);
82 values[Anum_pg_rewrite_ev_qual - 1] = CStringGetTextDatum(evqual);
83 values[Anum_pg_rewrite_ev_action - 1] = CStringGetTextDatum(actiontree);
84
85 /*
86 * Ready to store new pg_rewrite tuple
87 */
88 pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
89
90 /*
91 * Check to see if we are replacing an existing tuple
92 */
93 oldtup = SearchSysCache2(RULERELNAME,
94 ObjectIdGetDatum(eventrel_oid),
95 PointerGetDatum(rulname));
96
97 if (HeapTupleIsValid(oldtup))
98 {
99 bool replaces[Natts_pg_rewrite] = {0};
100
101 if (!replace)
102 ereport(ERROR,
103 (errcode(ERRCODE_DUPLICATE_OBJECT),
104 errmsg("rule \"%s\" for relation \"%s\" already exists",
105 rulname, get_rel_name(eventrel_oid))));
106
107 /*
108 * When replacing, we don't need to replace every attribute
109 */
110 replaces[Anum_pg_rewrite_ev_type - 1] = true;
111 replaces[Anum_pg_rewrite_is_instead - 1] = true;
112 replaces[Anum_pg_rewrite_ev_qual - 1] = true;
113 replaces[Anum_pg_rewrite_ev_action - 1] = true;
114
115 tup = heap_modify_tuple(oldtup, RelationGetDescr(pg_rewrite_desc),
116 values, nulls, replaces);
117
118 CatalogTupleUpdate(pg_rewrite_desc, &tup->t_self, tup);
119
120 ReleaseSysCache(oldtup);
121
122 rewriteObjectId = ((Form_pg_rewrite) GETSTRUCT(tup))->oid;
123 is_update = true;
124 }
125 else
126 {
127 rewriteObjectId = GetNewOidWithIndex(pg_rewrite_desc,
128 RewriteOidIndexId,
129 Anum_pg_rewrite_oid);
130 values[Anum_pg_rewrite_oid - 1] = ObjectIdGetDatum(rewriteObjectId);
131
132 tup = heap_form_tuple(pg_rewrite_desc->rd_att, values, nulls);
133
134 CatalogTupleInsert(pg_rewrite_desc, tup);
135 }
136
137
138 heap_freetuple(tup);
139
140 /* If replacing, get rid of old dependencies and make new ones */
141 if (is_update)
142 deleteDependencyRecordsFor(RewriteRelationId, rewriteObjectId, false);
143
144 /*
145 * Install dependency on rule's relation to ensure it will go away on
146 * relation deletion. If the rule is ON SELECT, make the dependency
147 * implicit --- this prevents deleting a view's SELECT rule. Other kinds
148 * of rules can be AUTO.
149 */
150 myself.classId = RewriteRelationId;
151 myself.objectId = rewriteObjectId;
152 myself.objectSubId = 0;
153
154 referenced.classId = RelationRelationId;
155 referenced.objectId = eventrel_oid;
156 referenced.objectSubId = 0;
157
158 recordDependencyOn(&myself, &referenced,
159 (evtype == CMD_SELECT) ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO);
160
161 /*
162 * Also install dependencies on objects referenced in action and qual.
163 */
164 CheckUsageOnTypesInExpr((Node *) action, NIL, GetUserId());
165 recordDependencyOnExpr(&myself, (Node *) action, NIL,
166 DEPENDENCY_NORMAL);
167
168 if (event_qual != NULL)
169 {
170 /* Find query containing OLD/NEW rtable entries */
171 Query *qry = linitial_node(Query, action);
172
173 qry = getInsertSelectQuery(qry, NULL);
174 CheckUsageOnTypesInExpr(event_qual, qry->rtable, GetUserId());
175 recordDependencyOnExpr(&myself, event_qual, qry->rtable,
176 DEPENDENCY_NORMAL);
177 }
178
179 /* Post creation hook for new rule */
180 InvokeObjectPostCreateHook(RewriteRelationId, rewriteObjectId, 0);
181
182 table_close(pg_rewrite_desc, RowExclusiveLock);
183
184 return rewriteObjectId;
185 }
186
187 /*
188 * DefineRule
189 * Execute a CREATE RULE command.
190 */
191 ObjectAddress
192 DefineRule(RuleStmt *stmt, const char *queryString)
193 {
194 List *actions;
195 Node *whereClause;
196 Oid relId;
197
198 /* Parse analysis. */
199 transformRuleStmt(stmt, queryString, &actions, &whereClause);
200
201 /*
202 * Find and lock the relation. Lock level should match
203 * DefineQueryRewrite.
204 */
205 relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
206
207 /* ... and execute */
208 return DefineQueryRewrite(stmt->rulename,
209 relId,
210 whereClause,
211 stmt->event,
212 stmt->instead,
213 stmt->replace,
214 actions);
215 }
216
217
218 /*
219 * DefineQueryRewrite
220 * Create a rule
221 *
222 * This is essentially the same as DefineRule() except that the rule's
223 * action and qual have already been passed through parse analysis.
224 */
225 ObjectAddress
226 DefineQueryRewrite(const char *rulename,
227 Oid event_relid,
228 Node *event_qual,
229 CmdType event_type,
230 bool is_instead,
231 bool replace,
232 List *action)
233 {
234 Relation event_relation;
235 ListCell *l;
236 Query *query;
237 Oid ruleId = InvalidOid;
238 ObjectAddress address;
239
240 /*
241 * If we are installing an ON SELECT rule, we had better grab
242 * AccessExclusiveLock to ensure no SELECTs are currently running on the
243 * event relation. For other types of rules, it would be sufficient to
244 * grab ShareRowExclusiveLock to lock out insert/update/delete actions and
245 * to ensure that we lock out current CREATE RULE statements; but because
246 * of race conditions in access to catalog entries, we can't do that yet.
247 *
248 * Note that this lock level should match the one used in DefineRule.
249 */
250 event_relation = table_open(event_relid, AccessExclusiveLock);
251
252 /*
253 * Verify relation is of a type that rules can sensibly be applied to.
254 * Internal callers can target materialized views, but transformRuleStmt()
255 * blocks them for users. Don't mention them in the error message.
256 */
257 if (event_relation->rd_rel->relkind != RELKIND_RELATION &&
258 event_relation->rd_rel->relkind != RELKIND_MATVIEW &&
259 event_relation->rd_rel->relkind != RELKIND_VIEW &&
260 event_relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
261 ereport(ERROR,
262 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
263 errmsg("relation \"%s\" cannot have rules",
264 RelationGetRelationName(event_relation)),
265 errdetail_relkind_not_supported(event_relation->rd_rel->relkind)));
266
267 if (!allowSystemTableMods && IsSystemRelation(event_relation))
268 ereport(ERROR,
269 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
270 errmsg("permission denied: \"%s\" is a system catalog",
271 RelationGetRelationName(event_relation))));
272
273 /*
274 * Check user has permission to apply rules to this relation.
275 */
276 if (!object_ownercheck(RelationRelationId, event_relid, GetUserId()))
277 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(event_relation->rd_rel->relkind),
278 RelationGetRelationName(event_relation));
279
280 /*
281 * No rule actions that modify OLD or NEW
282 */
283 foreach(l, action)
284 {
285 query = lfirst_node(Query, l);
286 if (query->resultRelation == 0)
287 continue;
288 /* Don't be fooled by INSERT/SELECT */
289 if (query != getInsertSelectQuery(query, NULL))
290 continue;
291 if (query->resultRelation == PRS2_OLD_VARNO)
292 ereport(ERROR,
293 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
294 errmsg("rule actions on OLD are not implemented"),
295 errhint("Use views or triggers instead.")));
296 if (query->resultRelation == PRS2_NEW_VARNO)
297 ereport(ERROR,
298 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
299 errmsg("rule actions on NEW are not implemented"),
300 errhint("Use triggers instead.")));
301 }
302
303 if (event_type == CMD_SELECT)
304 {
305 /*
306 * Rules ON SELECT are restricted to view definitions
307 *
308 * So this had better be a view, ...
309 */
310 if (event_relation->rd_rel->relkind != RELKIND_VIEW &&
311 event_relation->rd_rel->relkind != RELKIND_MATVIEW)
312 ereport(ERROR,
313 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
314 errmsg("relation \"%s\" cannot have ON SELECT rules",
315 RelationGetRelationName(event_relation)),
316 errdetail_relkind_not_supported(event_relation->rd_rel->relkind)));
317
318 /*
319 * ... there cannot be INSTEAD NOTHING, ...
320 */
321 if (action == NIL)
322 ereport(ERROR,
323 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
324 errmsg("INSTEAD NOTHING rules on SELECT are not implemented"),
325 errhint("Use views instead.")));
326
327 /*
328 * ... there cannot be multiple actions, ...
329 */
330 if (list_length(action) > 1)
331 ereport(ERROR,
332 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
333 errmsg("multiple actions for rules on SELECT are not implemented")));
334
335 /*
336 * ... the one action must be a SELECT, ...
337 */
338 query = linitial_node(Query, action);
339 if (!is_instead ||
340 query->commandType != CMD_SELECT)
341 ereport(ERROR,
342 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
343 errmsg("rules on SELECT must have action INSTEAD SELECT")));
344
345 /*
346 * ... it cannot contain data-modifying WITH ...
347 */
348 if (query->hasModifyingCTE)
349 ereport(ERROR,
350 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
351 errmsg("rules on SELECT must not contain data-modifying statements in WITH")));
352
353 /*
354 * ... there can be no rule qual, ...
355 */
356 if (event_qual != NULL)
357 ereport(ERROR,
358 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
359 errmsg("event qualifications are not implemented for rules on SELECT")));
360
361 /*
362 * ... the targetlist of the SELECT action must exactly match the
363 * event relation, ...
364 */
365 checkRuleResultList(query->targetList,
366 RelationGetDescr(event_relation),
367 true,
368 event_relation->rd_rel->relkind !=
369 RELKIND_MATVIEW);
370
371 /*
372 * ... there must not be another ON SELECT rule already ...
373 */
374 if (!replace && event_relation->rd_rules != NULL)
375 {
376 int i;
377
378 for (i = 0; i < event_relation->rd_rules->numLocks; i++)
379 {
380 RewriteRule *rule;
381
382 rule = event_relation->rd_rules->rules[i];
383 if (rule->event == CMD_SELECT)
384 ereport(ERROR,
385 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
386 errmsg("\"%s\" is already a view",
387 RelationGetRelationName(event_relation))));
388 }
389 }
390
391 /*
392 * ... and finally the rule must be named _RETURN.
393 */
394 if (strcmp(rulename, ViewSelectRuleName) != 0)
395 ereport(ERROR,
396 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
397 errmsg("view rule for \"%s\" must be named \"%s\"",
398 RelationGetRelationName(event_relation),
399 ViewSelectRuleName)));
400 }
401 else
402 {
403 /*
404 * For non-SELECT rules, a RETURNING list can appear in at most one of
405 * the actions ... and there can't be any RETURNING list at all in a
406 * conditional or non-INSTEAD rule. (Actually, there can be at most
407 * one RETURNING list across all rules on the same event, but it seems
408 * best to enforce that at rule expansion time.) If there is a
409 * RETURNING list, it must match the event relation.
410 */
411 bool haveReturning = false;
412
413 foreach(l, action)
414 {
415 query = lfirst_node(Query, l);
416
417 if (!query->returningList)
418 continue;
419 if (haveReturning)
420 ereport(ERROR,
421 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
422 errmsg("cannot have multiple RETURNING lists in a rule")));
423 haveReturning = true;
424 if (event_qual != NULL)
425 ereport(ERROR,
426 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
427 errmsg("RETURNING lists are not supported in conditional rules")));
428 if (!is_instead)
429 ereport(ERROR,
430 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
431 errmsg("RETURNING lists are not supported in non-INSTEAD rules")));
432 checkRuleResultList(query->returningList,
433 RelationGetDescr(event_relation),
434 false, false);
435 }
436
437 /*
438 * And finally, if it's not an ON SELECT rule then it must *not* be
439 * named _RETURN. This prevents accidentally or maliciously replacing
440 * a view's ON SELECT rule with some other kind of rule.
441 */
442 if (strcmp(rulename, ViewSelectRuleName) == 0)
443 ereport(ERROR,
444 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
445 errmsg("non-view rule for \"%s\" must not be named \"%s\"",
446 RelationGetRelationName(event_relation),
447 ViewSelectRuleName)));
448 }
449
450 /*
451 * This rule is allowed - prepare to install it.
452 */
453
454 /* discard rule if it's null action and not INSTEAD; it's a no-op */
455 if (action != NIL || is_instead)
456 {
457 ruleId = InsertRule(rulename,
458 event_type,
459 event_relid,
460 is_instead,
461 event_qual,
462 action,
463 replace);
464
465 /*
466 * Set pg_class 'relhasrules' field true for event relation.
467 *
468 * Important side effect: an SI notice is broadcast to force all
469 * backends (including me!) to update relcache entries with the new
470 * rule.
471 */
472 SetRelationRuleStatus(event_relid, true);
473 }
474
475 ObjectAddressSet(address, RewriteRelationId, ruleId);
476
477 /* Close rel, but keep lock till commit... */
478 table_close(event_relation, NoLock);
479
480 return address;
481 }
482
483 /*
484 * checkRuleResultList
485 * Verify that targetList produces output compatible with a tupledesc
486 *
487 * The targetList might be either a SELECT targetlist, or a RETURNING list;
488 * isSelect tells which. This is used for choosing error messages.
489 *
490 * A SELECT targetlist may optionally require that column names match.
491 */
492 static void
493 checkRuleResultList(List *targetList, TupleDesc resultDesc, bool isSelect,
494 bool requireColumnNameMatch)
495 {
496 ListCell *tllist;
497 int i;
498
499 /* Only a SELECT may require a column name match. */
500 Assert(isSelect || !requireColumnNameMatch);
501
502 i = 0;
503 foreach(tllist, targetList)
504 {
505 TargetEntry *tle = (TargetEntry *) lfirst(tllist);
506 Oid tletypid;
507 int32 tletypmod;
508 Form_pg_attribute attr;
509 char *attname;
510
511 /* resjunk entries may be ignored */
512 if (tle->resjunk)
513 continue;
514 i++;
515 if (i > resultDesc->natts)
516 ereport(ERROR,
517 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
518 isSelect ?
519 errmsg("SELECT rule's target list has too many entries") :
520 errmsg("RETURNING list has too many entries")));
521
522 attr = TupleDescAttr(resultDesc, i - 1);
523 attname = NameStr(attr->attname);
524
525 /*
526 * Disallow dropped columns in the relation. This is not really
527 * expected to happen when creating an ON SELECT rule. It'd be
528 * possible if someone tried to convert a relation with dropped
529 * columns to a view, but the only case we care about supporting
530 * table-to-view conversion for is pg_dump, and pg_dump won't do that.
531 *
532 * Unfortunately, the situation is also possible when adding a rule
533 * with RETURNING to a regular table, and rejecting that case is
534 * altogether more annoying. In principle we could support it by
535 * modifying the targetlist to include dummy NULL columns
536 * corresponding to the dropped columns in the tupdesc. However,
537 * places like ruleutils.c would have to be fixed to not process such
538 * entries, and that would take an uncertain and possibly rather large
539 * amount of work. (Note we could not dodge that by marking the dummy
540 * columns resjunk, since it's precisely the non-resjunk tlist columns
541 * that are expected to correspond to table columns.)
542 */
543 if (attr->attisdropped)
544 ereport(ERROR,
545 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
546 isSelect ?
547 errmsg("cannot convert relation containing dropped columns to view") :
548 errmsg("cannot create a RETURNING list for a relation containing dropped columns")));
549
550 /* Check name match if required; no need for two error texts here */
551 if (requireColumnNameMatch && strcmp(tle->resname, attname) != 0)
552 ereport(ERROR,
553 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
554 errmsg("SELECT rule's target entry %d has different column name from column \"%s\"",
555 i, attname),
556 errdetail("SELECT target entry is named \"%s\".",
557 tle->resname)));
558
559 /* Check type match. */
560 tletypid = exprType((Node *) tle->expr);
561 if (attr->atttypid != tletypid)
562 ereport(ERROR,
563 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
564 isSelect ?
565 errmsg("SELECT rule's target entry %d has different type from column \"%s\"",
566 i, attname) :
567 errmsg("RETURNING list's entry %d has different type from column \"%s\"",
568 i, attname),
569 isSelect ?
570 errdetail("SELECT target entry has type %s, but column has type %s.",
571 format_type_be(tletypid),
572 format_type_be(attr->atttypid)) :
573 errdetail("RETURNING list entry has type %s, but column has type %s.",
574 format_type_be(tletypid),
575 format_type_be(attr->atttypid))));
576
577 /*
578 * Allow typmods to be different only if one of them is -1, ie,
579 * "unspecified". This is necessary for cases like "numeric", where
580 * the table will have a filled-in default length but the select
581 * rule's expression will probably have typmod = -1.
582 */
583 tletypmod = exprTypmod((Node *) tle->expr);
584 if (attr->atttypmod != tletypmod &&
585 attr->atttypmod != -1 && tletypmod != -1)
586 ereport(ERROR,
587 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
588 isSelect ?
589 errmsg("SELECT rule's target entry %d has different size from column \"%s\"",
590 i, attname) :
591 errmsg("RETURNING list's entry %d has different size from column \"%s\"",
592 i, attname),
593 isSelect ?
594 errdetail("SELECT target entry has type %s, but column has type %s.",
595 format_type_with_typemod(tletypid, tletypmod),
596 format_type_with_typemod(attr->atttypid,
597 attr->atttypmod)) :
598 errdetail("RETURNING list entry has type %s, but column has type %s.",
599 format_type_with_typemod(tletypid, tletypmod),
600 format_type_with_typemod(attr->atttypid,
601 attr->atttypmod))));
602 }
603
604 if (i != resultDesc->natts)
605 ereport(ERROR,
606 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
607 isSelect ?
608 errmsg("SELECT rule's target list has too few entries") :
609 errmsg("RETURNING list has too few entries")));
610 }
611
612 /*
613 * setRuleCheckAsUser
614 * Recursively scan a query or expression tree and set the checkAsUser
615 * field to the given userid in all RTEPermissionInfos of the query.
616 */
617 void
618 setRuleCheckAsUser(Node *node, Oid userid)
619 {
620 (void) setRuleCheckAsUser_walker(node, &userid);
621 }
622
623 static bool
624 setRuleCheckAsUser_walker(Node *node, Oid *context)
625 {
626 if (node == NULL)
627 return false;
628 if (IsA(node, Query))
629 {
630 setRuleCheckAsUser_Query((Query *) node, *context);
631 return false;
632 }
633 return expression_tree_walker(node, setRuleCheckAsUser_walker,
634 context);
635 }
636
637 static void
638 setRuleCheckAsUser_Query(Query *qry, Oid userid)
639 {
640 ListCell *l;
641
642 /* Set in all RTEPermissionInfos for this query. */
643 foreach(l, qry->rteperminfos)
644 {
645 RTEPermissionInfo *perminfo = lfirst_node(RTEPermissionInfo, l);
646
647 perminfo->checkAsUser = userid;
648 }
649
650 /* Now recurse to any subquery RTEs */
651 foreach(l, qry->rtable)
652 {
653 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
654
655 if (rte->rtekind == RTE_SUBQUERY)
656 setRuleCheckAsUser_Query(rte->subquery, userid);
657 }
658
659 /* Recurse into subquery-in-WITH */
660 foreach(l, qry->cteList)
661 {
662 CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
663
664 setRuleCheckAsUser_Query(castNode(Query, cte->ctequery), userid);
665 }
666
667 /* If there are sublinks, search for them and process their RTEs */
668 if (qry->hasSubLinks)
669 query_tree_walker(qry, setRuleCheckAsUser_walker, &userid,
670 QTW_IGNORE_RC_SUBQUERIES);
671 }
672
673
674 /*
675 * Change the firing semantics of an existing rule.
676 */
677 void
678 EnableDisableRule(Relation rel, const char *rulename,
679 char fires_when)
680 {
681 Relation pg_rewrite_desc;
682 Oid owningRel = RelationGetRelid(rel);
683 Oid eventRelationOid;
684 HeapTuple ruletup;
685 Form_pg_rewrite ruleform;
686 bool changed = false;
687
688 /*
689 * Find the rule tuple to change.
690 */
691 pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
692 ruletup = SearchSysCacheCopy2(RULERELNAME,
693 ObjectIdGetDatum(owningRel),
694 PointerGetDatum(rulename));
695 if (!HeapTupleIsValid(ruletup))
696 ereport(ERROR,
697 (errcode(ERRCODE_UNDEFINED_OBJECT),
698 errmsg("rule \"%s\" for relation \"%s\" does not exist",
699 rulename, get_rel_name(owningRel))));
700
701 ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
702
703 /*
704 * Verify that the user has appropriate permissions.
705 */
706 eventRelationOid = ruleform->ev_class;
707 Assert(eventRelationOid == owningRel);
708 if (!object_ownercheck(RelationRelationId, eventRelationOid, GetUserId()))
709 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(eventRelationOid)),
710 get_rel_name(eventRelationOid));
711
712 /*
713 * Change ev_enabled if it is different from the desired new state.
714 */
715 if (DatumGetChar(ruleform->ev_enabled) !=
716 fires_when)
717 {
718 ruleform->ev_enabled = CharGetDatum(fires_when);
719 CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
720
721 changed = true;
722 }
723
724 InvokeObjectPostAlterHook(RewriteRelationId, ruleform->oid, 0);
725
726 heap_freetuple(ruletup);
727 table_close(pg_rewrite_desc, RowExclusiveLock);
728
729 /*
730 * If we changed anything, broadcast a SI inval message to force each
731 * backend (including our own!) to rebuild relation's relcache entry.
732 * Otherwise they will fail to apply the change promptly.
733 */
734 if (changed)
735 CacheInvalidateRelcache(rel);
736 }
737
738
739 /*
740 * Perform permissions and integrity checks before acquiring a relation lock.
741 */
742 static void
743 RangeVarCallbackForRenameRule(const RangeVar *rv, Oid relid, Oid oldrelid,
744 void *arg)
745 {
746 HeapTuple tuple;
747 Form_pg_class form;
748
749 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
750 if (!HeapTupleIsValid(tuple))
751 return; /* concurrently dropped */
752 form = (Form_pg_class) GETSTRUCT(tuple);
753
754 /* only tables and views can have rules */
755 if (form->relkind != RELKIND_RELATION &&
756 form->relkind != RELKIND_VIEW &&
757 form->relkind != RELKIND_PARTITIONED_TABLE)
758 ereport(ERROR,
759 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
760 errmsg("relation \"%s\" cannot have rules", rv->relname),
761 errdetail_relkind_not_supported(form->relkind)));
762
763 if (!allowSystemTableMods && IsSystemClass(relid, form))
764 ereport(ERROR,
765 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
766 errmsg("permission denied: \"%s\" is a system catalog",
767 rv->relname)));
768
769 /* you must own the table to rename one of its rules */
770 if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
771 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
772
773 ReleaseSysCache(tuple);
774 }
775
776 /*
777 * Rename an existing rewrite rule.
778 */
779 ObjectAddress
780 RenameRewriteRule(RangeVar *relation, const char *oldName,
781 const char *newName)
782 {
783 Oid relid;
784 Relation targetrel;
785 Relation pg_rewrite_desc;
786 HeapTuple ruletup;
787 Form_pg_rewrite ruleform;
788 Oid ruleOid;
789 ObjectAddress address;
790
791 /*
792 * Look up name, check permissions, and acquire lock (which we will NOT
793 * release until end of transaction).
794 */
795 relid = RangeVarGetRelidExtended(relation, AccessExclusiveLock,
796 0,
797 RangeVarCallbackForRenameRule,
798 NULL);
799
800 /* Have lock already, so just need to build relcache entry. */
801 targetrel = relation_open(relid, NoLock);
802
803 /* Prepare to modify pg_rewrite */
804 pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
805
806 /* Fetch the rule's entry (it had better exist) */
807 ruletup = SearchSysCacheCopy2(RULERELNAME,
808 ObjectIdGetDatum(relid),
809 PointerGetDatum(oldName));
810 if (!HeapTupleIsValid(ruletup))
811 ereport(ERROR,
812 (errcode(ERRCODE_UNDEFINED_OBJECT),
813 errmsg("rule \"%s\" for relation \"%s\" does not exist",
814 oldName, RelationGetRelationName(targetrel))));
815 ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
816 ruleOid = ruleform->oid;
817
818 /* rule with the new name should not already exist */
819 if (IsDefinedRewriteRule(relid, newName))
820 ereport(ERROR,
821 (errcode(ERRCODE_DUPLICATE_OBJECT),
822 errmsg("rule \"%s\" for relation \"%s\" already exists",
823 newName, RelationGetRelationName(targetrel))));
824
825 /*
826 * We disallow renaming ON SELECT rules, because they should always be
827 * named "_RETURN".
828 */
829 if (ruleform->ev_type == CMD_SELECT + '0')
830 ereport(ERROR,
831 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
832 errmsg("renaming an ON SELECT rule is not allowed")));
833
834 /*
835 * Conversely, if it's not an ON SELECT rule then it must *not* be named
836 * _RETURN.
837 */
838 if (strcmp(newName, ViewSelectRuleName) == 0)
839 ereport(ERROR,
840 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
841 errmsg("non-view rule for \"%s\" must not be named \"%s\"",
842 RelationGetRelationName(targetrel),
843 ViewSelectRuleName)));
844
845 /* OK, do the update */
846 namestrcpy(&(ruleform->rulename), newName);
847
848 CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
849
850 InvokeObjectPostAlterHook(RewriteRelationId, ruleOid, 0);
851
852 heap_freetuple(ruletup);
853 table_close(pg_rewrite_desc, RowExclusiveLock);
854
855 /*
856 * Invalidate relation's relcache entry so that other backends (and this
857 * one too!) are sent SI message to make them rebuild relcache entries.
858 * (Ideally this should happen automatically...)
859 */
860 CacheInvalidateRelcache(targetrel);
861
862 ObjectAddressSet(address, RewriteRelationId, ruleOid);
863
864 /*
865 * Close rel, but keep exclusive lock!
866 */
867 relation_close(targetrel, NoLock);
868
869 return address;
870 }