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