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