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