PostgreSQL Source Code  git master
rewriteDefine.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_rewrite.h"
#include "catalog/storage.h"
#include "commands/policy.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_utilcmd.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteManip.h"
#include "rewrite/rewriteSupport.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for rewriteDefine.c:

Go to the source code of this file.

Functions

static void checkRuleResultList (List *targetList, TupleDesc resultDesc, bool isSelect, bool requireColumnNameMatch)
 
static bool setRuleCheckAsUser_walker (Node *node, Oid *context)
 
static void setRuleCheckAsUser_Query (Query *qry, Oid userid)
 
static Oid InsertRule (const char *rulname, int evtype, Oid eventrel_oid, bool evinstead, Node *event_qual, List *action, bool replace)
 
ObjectAddress DefineRule (RuleStmt *stmt, const char *queryString)
 
ObjectAddress DefineQueryRewrite (const char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)
 
void setRuleCheckAsUser (Node *node, Oid userid)
 
void EnableDisableRule (Relation rel, const char *rulename, char fires_when)
 
static void RangeVarCallbackForRenameRule (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
ObjectAddress RenameRewriteRule (RangeVar *relation, const char *oldName, const char *newName)
 

Function Documentation

◆ checkRuleResultList()

static void checkRuleResultList ( List targetList,
TupleDesc  resultDesc,
bool  isSelect,
bool  requireColumnNameMatch 
)
static

Definition at line 668 of file rewriteDefine.c.

References Assert, attname, ereport, errcode(), errdetail(), errmsg(), ERROR, TargetEntry::expr, exprType(), exprTypmod(), format_type_be(), format_type_with_typemod(), i, lfirst, NameStr, TupleDescData::natts, TargetEntry::resjunk, TargetEntry::resname, and TupleDescAttr.

Referenced by DefineQueryRewrite().

670 {
671  ListCell *tllist;
672  int i;
673 
674  /* Only a SELECT may require a column name match. */
675  Assert(isSelect || !requireColumnNameMatch);
676 
677  i = 0;
678  foreach(tllist, targetList)
679  {
680  TargetEntry *tle = (TargetEntry *) lfirst(tllist);
681  Oid tletypid;
682  int32 tletypmod;
683  Form_pg_attribute attr;
684  char *attname;
685 
686  /* resjunk entries may be ignored */
687  if (tle->resjunk)
688  continue;
689  i++;
690  if (i > resultDesc->natts)
691  ereport(ERROR,
692  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
693  isSelect ?
694  errmsg("SELECT rule's target list has too many entries") :
695  errmsg("RETURNING list has too many entries")));
696 
697  attr = TupleDescAttr(resultDesc, i - 1);
698  attname = NameStr(attr->attname);
699 
700  /*
701  * Disallow dropped columns in the relation. This is not really
702  * expected to happen when creating an ON SELECT rule. It'd be
703  * possible if someone tried to convert a relation with dropped
704  * columns to a view, but the only case we care about supporting
705  * table-to-view conversion for is pg_dump, and pg_dump won't do that.
706  *
707  * Unfortunately, the situation is also possible when adding a rule
708  * with RETURNING to a regular table, and rejecting that case is
709  * altogether more annoying. In principle we could support it by
710  * modifying the targetlist to include dummy NULL columns
711  * corresponding to the dropped columns in the tupdesc. However,
712  * places like ruleutils.c would have to be fixed to not process such
713  * entries, and that would take an uncertain and possibly rather large
714  * amount of work. (Note we could not dodge that by marking the dummy
715  * columns resjunk, since it's precisely the non-resjunk tlist columns
716  * that are expected to correspond to table columns.)
717  */
718  if (attr->attisdropped)
719  ereport(ERROR,
720  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
721  isSelect ?
722  errmsg("cannot convert relation containing dropped columns to view") :
723  errmsg("cannot create a RETURNING list for a relation containing dropped columns")));
724 
725  /* Check name match if required; no need for two error texts here */
726  if (requireColumnNameMatch && strcmp(tle->resname, attname) != 0)
727  ereport(ERROR,
728  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
729  errmsg("SELECT rule's target entry %d has different column name from column \"%s\"",
730  i, attname),
731  errdetail("SELECT target entry is named \"%s\".",
732  tle->resname)));
733 
734  /* Check type match. */
735  tletypid = exprType((Node *) tle->expr);
736  if (attr->atttypid != tletypid)
737  ereport(ERROR,
738  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
739  isSelect ?
740  errmsg("SELECT rule's target entry %d has different type from column \"%s\"",
741  i, attname) :
742  errmsg("RETURNING list's entry %d has different type from column \"%s\"",
743  i, attname),
744  isSelect ?
745  errdetail("SELECT target entry has type %s, but column has type %s.",
746  format_type_be(tletypid),
747  format_type_be(attr->atttypid)) :
748  errdetail("RETURNING list entry has type %s, but column has type %s.",
749  format_type_be(tletypid),
750  format_type_be(attr->atttypid))));
751 
752  /*
753  * Allow typmods to be different only if one of them is -1, ie,
754  * "unspecified". This is necessary for cases like "numeric", where
755  * the table will have a filled-in default length but the select
756  * rule's expression will probably have typmod = -1.
757  */
758  tletypmod = exprTypmod((Node *) tle->expr);
759  if (attr->atttypmod != tletypmod &&
760  attr->atttypmod != -1 && tletypmod != -1)
761  ereport(ERROR,
762  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
763  isSelect ?
764  errmsg("SELECT rule's target entry %d has different size from column \"%s\"",
765  i, attname) :
766  errmsg("RETURNING list's entry %d has different size from column \"%s\"",
767  i, attname),
768  isSelect ?
769  errdetail("SELECT target entry has type %s, but column has type %s.",
770  format_type_with_typemod(tletypid, tletypmod),
771  format_type_with_typemod(attr->atttypid,
772  attr->atttypmod)) :
773  errdetail("RETURNING list entry has type %s, but column has type %s.",
774  format_type_with_typemod(tletypid, tletypmod),
775  format_type_with_typemod(attr->atttypid,
776  attr->atttypmod))));
777  }
778 
779  if (i != resultDesc->natts)
780  ereport(ERROR,
781  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
782  isSelect ?
783  errmsg("SELECT rule's target list has too few entries") :
784  errmsg("RETURNING list has too few entries")));
785 }
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1456
signed int int32
Definition: c.h:429
bool resjunk
Definition: primnodes.h:1461
#define ERROR
Definition: elog.h:46
NameData attname
Definition: pg_attribute.h:41
int errdetail(const char *fmt,...)
Definition: elog.c:1042
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:358
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1454
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
#define NameStr(name)
Definition: c.h:681

◆ DefineQueryRewrite()

ObjectAddress DefineQueryRewrite ( const char *  rulename,
Oid  event_relid,
Node event_qual,
CmdType  event_type,
bool  is_instead,
bool  replace,
List action 
)

Definition at line 233 of file rewriteDefine.c.

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, allowSystemTableMods, Assert, CatalogTupleUpdate(), checkRuleResultList(), ObjectAddress::classId, CMD_SELECT, CommandCounterIncrement(), Query::commandType, deleteDependencyRecordsFor(), DeleteSystemAttributeTuples(), DROP_RESTRICT, elog, ereport, errcode(), errdetail_relkind_not_supported(), errhint(), errmsg(), ERROR, RewriteRule::event, ExecDropSingleTupleTableSlot(), ForwardScanDirection, get_relkind_objtype(), getInsertSelectQuery(), GetLatestSnapshot(), GETSTRUCT, GetUserId(), has_superclass(), Query::hasModifyingCTE, heap_freetuple(), HeapTupleIsValid, i, InsertRule(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, IsSystemRelation(), lfirst_node, linitial_node, list_length(), NAMEDATALEN, NIL, NoLock, RuleLock::numLocks, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, PERFORM_DELETION_INTERNAL, performDeletion(), pg_class_ownercheck(), PRS2_NEW_VARNO, PRS2_OLD_VARNO, pstrdup(), RelationData::rd_rel, RelationData::rd_rules, RegisterSnapshot(), relation_has_policies(), RelationDropStorage(), RelationGetDescr, RelationGetRelationName, RelationGetRelid, RELOID, Query::resultRelation, Query::returningList, RowExclusiveLock, RuleLock::rules, SearchSysCacheCopy1, SetRelationRuleStatus(), HeapTupleData::t_self, table_beginscan(), table_close(), table_endscan(), table_open(), table_scan_getnextslot(), table_slot_create(), Query::targetList, UnregisterSnapshot(), and ViewSelectRuleName.

Referenced by DefineRule(), and DefineViewRules().

240 {
241  Relation event_relation;
242  ListCell *l;
243  Query *query;
244  bool RelisBecomingView = false;
245  Oid ruleId = InvalidOid;
246  ObjectAddress address;
247 
248  /*
249  * If we are installing an ON SELECT rule, we had better grab
250  * AccessExclusiveLock to ensure no SELECTs are currently running on the
251  * event relation. For other types of rules, it would be sufficient to
252  * grab ShareRowExclusiveLock to lock out insert/update/delete actions and
253  * to ensure that we lock out current CREATE RULE statements; but because
254  * of race conditions in access to catalog entries, we can't do that yet.
255  *
256  * Note that this lock level should match the one used in DefineRule.
257  */
258  event_relation = table_open(event_relid, AccessExclusiveLock);
259 
260  /*
261  * Verify relation is of a type that rules can sensibly be applied to.
262  * Internal callers can target materialized views, but transformRuleStmt()
263  * blocks them for users. Don't mention them in the error message.
264  */
265  if (event_relation->rd_rel->relkind != RELKIND_RELATION &&
266  event_relation->rd_rel->relkind != RELKIND_MATVIEW &&
267  event_relation->rd_rel->relkind != RELKIND_VIEW &&
268  event_relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
269  ereport(ERROR,
270  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
271  errmsg("relation \"%s\" cannot have rules",
272  RelationGetRelationName(event_relation)),
273  errdetail_relkind_not_supported(event_relation->rd_rel->relkind)));
274 
275  if (!allowSystemTableMods && IsSystemRelation(event_relation))
276  ereport(ERROR,
277  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
278  errmsg("permission denied: \"%s\" is a system catalog",
279  RelationGetRelationName(event_relation))));
280 
281  /*
282  * Check user has permission to apply rules to this relation.
283  */
284  if (!pg_class_ownercheck(event_relid, GetUserId()))
285  aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(event_relation->rd_rel->relkind),
286  RelationGetRelationName(event_relation));
287 
288  /*
289  * No rule actions that modify OLD or NEW
290  */
291  foreach(l, action)
292  {
293  query = lfirst_node(Query, l);
294  if (query->resultRelation == 0)
295  continue;
296  /* Don't be fooled by INSERT/SELECT */
297  if (query != getInsertSelectQuery(query, NULL))
298  continue;
299  if (query->resultRelation == PRS2_OLD_VARNO)
300  ereport(ERROR,
301  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
302  errmsg("rule actions on OLD are not implemented"),
303  errhint("Use views or triggers instead.")));
304  if (query->resultRelation == PRS2_NEW_VARNO)
305  ereport(ERROR,
306  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
307  errmsg("rule actions on NEW are not implemented"),
308  errhint("Use triggers instead.")));
309  }
310 
311  if (event_type == CMD_SELECT)
312  {
313  /*
314  * Rules ON SELECT are restricted to view definitions
315  *
316  * So there cannot be INSTEAD NOTHING, ...
317  */
318  if (list_length(action) == 0)
319  ereport(ERROR,
320  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
321  errmsg("INSTEAD NOTHING rules on SELECT are not implemented"),
322  errhint("Use views instead.")));
323 
324  /*
325  * ... there cannot be multiple actions, ...
326  */
327  if (list_length(action) > 1)
328  ereport(ERROR,
329  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
330  errmsg("multiple actions for rules on SELECT are not implemented")));
331 
332  /*
333  * ... the one action must be a SELECT, ...
334  */
335  query = linitial_node(Query, action);
336  if (!is_instead ||
337  query->commandType != CMD_SELECT)
338  ereport(ERROR,
339  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
340  errmsg("rules on SELECT must have action INSTEAD SELECT")));
341 
342  /*
343  * ... it cannot contain data-modifying WITH ...
344  */
345  if (query->hasModifyingCTE)
346  ereport(ERROR,
347  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
348  errmsg("rules on SELECT must not contain data-modifying statements in WITH")));
349 
350  /*
351  * ... there can be no rule qual, ...
352  */
353  if (event_qual != NULL)
354  ereport(ERROR,
355  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
356  errmsg("event qualifications are not implemented for rules on SELECT")));
357 
358  /*
359  * ... the targetlist of the SELECT action must exactly match the
360  * event relation, ...
361  */
363  RelationGetDescr(event_relation),
364  true,
365  event_relation->rd_rel->relkind !=
366  RELKIND_MATVIEW);
367 
368  /*
369  * ... there must not be another ON SELECT rule already ...
370  */
371  if (!replace && event_relation->rd_rules != NULL)
372  {
373  int i;
374 
375  for (i = 0; i < event_relation->rd_rules->numLocks; i++)
376  {
377  RewriteRule *rule;
378 
379  rule = event_relation->rd_rules->rules[i];
380  if (rule->event == CMD_SELECT)
381  ereport(ERROR,
382  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
383  errmsg("\"%s\" is already a view",
384  RelationGetRelationName(event_relation))));
385  }
386  }
387 
388  /*
389  * ... and finally the rule must be named _RETURN.
390  */
391  if (strcmp(rulename, ViewSelectRuleName) != 0)
392  {
393  /*
394  * In versions before 7.3, the expected name was _RETviewname. For
395  * backwards compatibility with old pg_dump output, accept that
396  * and silently change it to _RETURN. Since this is just a quick
397  * backwards-compatibility hack, limit the number of characters
398  * checked to a few less than NAMEDATALEN; this saves having to
399  * worry about where a multibyte character might have gotten
400  * truncated.
401  */
402  if (strncmp(rulename, "_RET", 4) != 0 ||
403  strncmp(rulename + 4, RelationGetRelationName(event_relation),
404  NAMEDATALEN - 4 - 4) != 0)
405  ereport(ERROR,
406  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
407  errmsg("view rule for \"%s\" must be named \"%s\"",
408  RelationGetRelationName(event_relation),
410  rulename = pstrdup(ViewSelectRuleName);
411  }
412 
413  /*
414  * Are we converting a relation to a view?
415  *
416  * If so, check that the relation is empty because the storage for the
417  * relation is going to be deleted. Also insist that the rel not be
418  * involved in partitioning, nor have any triggers, indexes, child or
419  * parent tables, RLS policies, or RLS enabled. (Note: some of these
420  * tests are too strict, because they will reject relations that once
421  * had such but don't anymore. But we don't really care, because this
422  * whole business of converting relations to views is just an obsolete
423  * kluge to allow dump/reload of views that participate in circular
424  * dependencies.)
425  */
426  if (event_relation->rd_rel->relkind != RELKIND_VIEW &&
427  event_relation->rd_rel->relkind != RELKIND_MATVIEW)
428  {
429  TableScanDesc scanDesc;
430  Snapshot snapshot;
431  TupleTableSlot *slot;
432 
433  if (event_relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
434  ereport(ERROR,
435  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
436  errmsg("cannot convert partitioned table \"%s\" to a view",
437  RelationGetRelationName(event_relation))));
438 
439  /* only case left: */
440  Assert(event_relation->rd_rel->relkind == RELKIND_RELATION);
441 
442  if (event_relation->rd_rel->relispartition)
443  ereport(ERROR,
444  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
445  errmsg("cannot convert partition \"%s\" to a view",
446  RelationGetRelationName(event_relation))));
447 
448  snapshot = RegisterSnapshot(GetLatestSnapshot());
449  scanDesc = table_beginscan(event_relation, snapshot, 0, NULL);
450  slot = table_slot_create(event_relation, NULL);
451  if (table_scan_getnextslot(scanDesc, ForwardScanDirection, slot))
452  ereport(ERROR,
453  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
454  errmsg("could not convert table \"%s\" to a view because it is not empty",
455  RelationGetRelationName(event_relation))));
457  table_endscan(scanDesc);
458  UnregisterSnapshot(snapshot);
459 
460  if (event_relation->rd_rel->relhastriggers)
461  ereport(ERROR,
462  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
463  errmsg("could not convert table \"%s\" to a view because it has triggers",
464  RelationGetRelationName(event_relation)),
465  errhint("In particular, the table cannot be involved in any foreign key relationships.")));
466 
467  if (event_relation->rd_rel->relhasindex)
468  ereport(ERROR,
469  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
470  errmsg("could not convert table \"%s\" to a view because it has indexes",
471  RelationGetRelationName(event_relation))));
472 
473  if (event_relation->rd_rel->relhassubclass)
474  ereport(ERROR,
475  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
476  errmsg("could not convert table \"%s\" to a view because it has child tables",
477  RelationGetRelationName(event_relation))));
478 
479  if (has_superclass(RelationGetRelid(event_relation)))
480  ereport(ERROR,
481  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
482  errmsg("could not convert table \"%s\" to a view because it has parent tables",
483  RelationGetRelationName(event_relation))));
484 
485  if (event_relation->rd_rel->relrowsecurity)
486  ereport(ERROR,
487  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
488  errmsg("could not convert table \"%s\" to a view because it has row security enabled",
489  RelationGetRelationName(event_relation))));
490 
491  if (relation_has_policies(event_relation))
492  ereport(ERROR,
493  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
494  errmsg("could not convert table \"%s\" to a view because it has row security policies",
495  RelationGetRelationName(event_relation))));
496 
497  RelisBecomingView = true;
498  }
499  }
500  else
501  {
502  /*
503  * For non-SELECT rules, a RETURNING list can appear in at most one of
504  * the actions ... and there can't be any RETURNING list at all in a
505  * conditional or non-INSTEAD rule. (Actually, there can be at most
506  * one RETURNING list across all rules on the same event, but it seems
507  * best to enforce that at rule expansion time.) If there is a
508  * RETURNING list, it must match the event relation.
509  */
510  bool haveReturning = false;
511 
512  foreach(l, action)
513  {
514  query = lfirst_node(Query, l);
515 
516  if (!query->returningList)
517  continue;
518  if (haveReturning)
519  ereport(ERROR,
520  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
521  errmsg("cannot have multiple RETURNING lists in a rule")));
522  haveReturning = true;
523  if (event_qual != NULL)
524  ereport(ERROR,
525  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
526  errmsg("RETURNING lists are not supported in conditional rules")));
527  if (!is_instead)
528  ereport(ERROR,
529  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
530  errmsg("RETURNING lists are not supported in non-INSTEAD rules")));
532  RelationGetDescr(event_relation),
533  false, false);
534  }
535  }
536 
537  /*
538  * This rule is allowed - prepare to install it.
539  */
540 
541  /* discard rule if it's null action and not INSTEAD; it's a no-op */
542  if (action != NIL || is_instead)
543  {
544  ruleId = InsertRule(rulename,
545  event_type,
546  event_relid,
547  is_instead,
548  event_qual,
549  action,
550  replace);
551 
552  /*
553  * Set pg_class 'relhasrules' field true for event relation.
554  *
555  * Important side effect: an SI notice is broadcast to force all
556  * backends (including me!) to update relcache entries with the new
557  * rule.
558  */
559  SetRelationRuleStatus(event_relid, true);
560  }
561 
562  /* ---------------------------------------------------------------------
563  * If the relation is becoming a view:
564  * - delete the associated storage files
565  * - get rid of any system attributes in pg_attribute; a view shouldn't
566  * have any of those
567  * - remove the toast table; there is no need for it anymore, and its
568  * presence would make vacuum slightly more complicated
569  * - set relkind to RELKIND_VIEW, and adjust other pg_class fields
570  * to be appropriate for a view
571  *
572  * NB: we had better have AccessExclusiveLock to do this ...
573  * ---------------------------------------------------------------------
574  */
575  if (RelisBecomingView)
576  {
577  Relation relationRelation;
578  Oid toastrelid;
579  HeapTuple classTup;
580  Form_pg_class classForm;
581 
582  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
583  toastrelid = event_relation->rd_rel->reltoastrelid;
584 
585  /* drop storage while table still looks like a table */
586  RelationDropStorage(event_relation);
587  DeleteSystemAttributeTuples(event_relid);
588 
589  /*
590  * Drop the toast table if any. (This won't take care of updating the
591  * toast fields in the relation's own pg_class entry; we handle that
592  * below.)
593  */
594  if (OidIsValid(toastrelid))
595  {
596  ObjectAddress toastobject;
597 
598  /*
599  * Delete the dependency of the toast relation on the main
600  * relation so we can drop the former without dropping the latter.
601  */
602  deleteDependencyRecordsFor(RelationRelationId, toastrelid,
603  false);
604 
605  /* Make deletion of dependency record visible */
607 
608  /* Now drop toast table, including its index */
609  toastobject.classId = RelationRelationId;
610  toastobject.objectId = toastrelid;
611  toastobject.objectSubId = 0;
612  performDeletion(&toastobject, DROP_RESTRICT,
614  }
615 
616  /*
617  * SetRelationRuleStatus may have updated the pg_class row, so we must
618  * advance the command counter before trying to update it again.
619  */
621 
622  /*
623  * Fix pg_class entry to look like a normal view's, including setting
624  * the correct relkind and removal of reltoastrelid of the toast table
625  * we potentially removed above.
626  */
627  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(event_relid));
628  if (!HeapTupleIsValid(classTup))
629  elog(ERROR, "cache lookup failed for relation %u", event_relid);
630  classForm = (Form_pg_class) GETSTRUCT(classTup);
631 
632  classForm->relam = InvalidOid;
633  classForm->reltablespace = InvalidOid;
634  classForm->relpages = 0;
635  classForm->reltuples = -1;
636  classForm->relallvisible = 0;
637  classForm->reltoastrelid = InvalidOid;
638  classForm->relhasindex = false;
639  classForm->relkind = RELKIND_VIEW;
640  classForm->relfrozenxid = InvalidTransactionId;
641  classForm->relminmxid = InvalidMultiXactId;
642  classForm->relreplident = REPLICA_IDENTITY_NOTHING;
643 
644  CatalogTupleUpdate(relationRelation, &classTup->t_self, classTup);
645 
646  heap_freetuple(classTup);
647  table_close(relationRelation, RowExclusiveLock);
648  }
649 
650  ObjectAddressSet(address, RewriteRelationId, ruleId);
651 
652  /* Close rel, but keep lock till commit... */
653  table_close(event_relation, NoLock);
654 
655  return address;
656 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
#define NIL
Definition: pg_list.h:65
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:924
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
int numLocks
Definition: prs2lock.h:42
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int resultRelation
Definition: parsenodes.h:130
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:236
int errcode(int sqlerrcode)
Definition: elog.c:698
static void checkRuleResultList(List *targetList, TupleDesc resultDesc, bool isSelect, bool requireColumnNameMatch)
#define ViewSelectRuleName
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1032
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:177
#define OidIsValid(objectId)
Definition: c.h:710
void SetRelationRuleStatus(Oid relationId, bool relHasRules)
Definition: localtime.c:72
List * targetList
Definition: parsenodes.h:150
#define NAMEDATALEN
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:883
ItemPointerData t_self
Definition: htup.h:65
bool has_superclass(Oid relationId)
Definition: pg_inherits.c:378
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define NoLock
Definition: lockdefs.h:34
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
#define RowExclusiveLock
Definition: lockdefs.h:38
CmdType event
Definition: prs2lock.h:27
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:511
RewriteRule ** rules
Definition: prs2lock.h:43
List * returningList
Definition: parsenodes.h:156
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
#define PRS2_OLD_VARNO
Definition: primnodes.h:183
void RelationDropStorage(Relation rel)
Definition: storage.c:195
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define InvalidMultiXactId
Definition: multixact.h:24
bool allowSystemTableMods
Definition: globals.c:123
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
CmdType commandType
Definition: parsenodes.h:120
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4818
RuleLock * rd_rules
Definition: rel.h:113
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static int list_length(const List *l)
Definition: pg_list.h:149
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define AccessExclusiveLock
Definition: lockdefs.h:45
bool relation_has_policies(Relation rel)
Definition: policy.c:1262
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
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 DeleteSystemAttributeTuples(Oid relid)
Definition: heap.c:1620
int i
ObjectType get_relkind_objtype(char relkind)
bool hasModifyingCTE
Definition: parsenodes.h:139
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:477
#define PRS2_NEW_VARNO
Definition: primnodes.h:184
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:133

◆ DefineRule()

ObjectAddress DefineRule ( RuleStmt stmt,
const char *  queryString 
)

Definition at line 199 of file rewriteDefine.c.

References AccessExclusiveLock, DefineQueryRewrite(), RuleStmt::event, RuleStmt::instead, RangeVarGetRelid, RuleStmt::relation, RuleStmt::replace, RuleStmt::rulename, and transformRuleStmt().

Referenced by ProcessUtilitySlow().

200 {
201  List *actions;
202  Node *whereClause;
203  Oid relId;
204 
205  /* Parse analysis. */
206  transformRuleStmt(stmt, queryString, &actions, &whereClause);
207 
208  /*
209  * Find and lock the relation. Lock level should match
210  * DefineQueryRewrite.
211  */
212  relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
213 
214  /* ... and execute */
215  return DefineQueryRewrite(stmt->rulename,
216  relId,
217  whereClause,
218  stmt->event,
219  stmt->instead,
220  stmt->replace,
221  actions);
222 }
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
Definition: nodes.h:539
unsigned int Oid
Definition: postgres_ext.h:31
bool instead
Definition: parsenodes.h:3128
bool replace
Definition: parsenodes.h:3130
char * rulename
Definition: parsenodes.h:3125
CmdType event
Definition: parsenodes.h:3127
#define AccessExclusiveLock
Definition: lockdefs.h:45
RangeVar * relation
Definition: parsenodes.h:3124
Definition: pg_list.h:50
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)

◆ EnableDisableRule()

void EnableDisableRule ( Relation  rel,
const char *  rulename,
char  fires_when 
)

Definition at line 857 of file rewriteDefine.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, Assert, CacheInvalidateRelcache(), CatalogTupleUpdate(), CharGetDatum, DatumGetChar, ereport, errcode(), errmsg(), ERROR, get_rel_name(), get_rel_relkind(), get_relkind_objtype(), GETSTRUCT, GetUserId(), heap_freetuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, ObjectIdGetDatum, pg_class_ownercheck(), PointerGetDatum, RelationGetRelid, RowExclusiveLock, RULERELNAME, SearchSysCacheCopy2, HeapTupleData::t_self, table_close(), and table_open().

Referenced by ATExecEnableDisableRule().

859 {
860  Relation pg_rewrite_desc;
861  Oid owningRel = RelationGetRelid(rel);
862  Oid eventRelationOid;
863  HeapTuple ruletup;
864  Form_pg_rewrite ruleform;
865  bool changed = false;
866 
867  /*
868  * Find the rule tuple to change.
869  */
870  pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
872  ObjectIdGetDatum(owningRel),
873  PointerGetDatum(rulename));
874  if (!HeapTupleIsValid(ruletup))
875  ereport(ERROR,
876  (errcode(ERRCODE_UNDEFINED_OBJECT),
877  errmsg("rule \"%s\" for relation \"%s\" does not exist",
878  rulename, get_rel_name(owningRel))));
879 
880  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
881 
882  /*
883  * Verify that the user has appropriate permissions.
884  */
885  eventRelationOid = ruleform->ev_class;
886  Assert(eventRelationOid == owningRel);
887  if (!pg_class_ownercheck(eventRelationOid, GetUserId()))
889  get_rel_name(eventRelationOid));
890 
891  /*
892  * Change ev_enabled if it is different from the desired new state.
893  */
894  if (DatumGetChar(ruleform->ev_enabled) !=
895  fires_when)
896  {
897  ruleform->ev_enabled = CharGetDatum(fires_when);
898  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
899 
900  changed = true;
901  }
902 
903  InvokeObjectPostAlterHook(RewriteRelationId, ruleform->oid, 0);
904 
905  heap_freetuple(ruletup);
906  table_close(pg_rewrite_desc, RowExclusiveLock);
907 
908  /*
909  * If we changed anything, broadcast a SI inval message to force each
910  * backend (including our own!) to rebuild relation's relcache entry.
911  * Otherwise they will fail to apply the change promptly.
912  */
913  if (changed)
915 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Oid GetUserId(void)
Definition: miscinit.c:478
#define PointerGetDatum(X)
Definition: postgres.h:600
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
int errcode(int sqlerrcode)
Definition: elog.c:698
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define DatumGetChar(X)
Definition: postgres.h:453
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4818
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define CharGetDatum(X)
Definition: postgres.h:460
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:52
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1279
int errmsg(const char *fmt,...)
Definition: elog.c:909
ObjectType get_relkind_objtype(char relkind)
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ InsertRule()

static Oid InsertRule ( const char *  rulname,
int  evtype,
Oid  eventrel_oid,
bool  evinstead,
Node event_qual,
List action,
bool  replace 
)
static

Definition at line 59 of file rewriteDefine.c.

References BoolGetDatum, CatalogTupleInsert(), CatalogTupleUpdate(), CharGetDatum, ObjectAddress::classId, CMD_SELECT, CStringGetTextDatum, deleteDependencyRecordsFor(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, DEPENDENCY_NORMAL, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, get_rel_name(), getInsertSelectQuery(), GetNewOidWithIndex(), GETSTRUCT, heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostCreateHook, linitial_node, MemSet, NameGetDatum, namestrcpy(), NIL, nodeToString(), ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, PointerGetDatum, RelationData::rd_att, recordDependencyOn(), recordDependencyOnExpr(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, Query::rtable, RULE_FIRES_ON_ORIGIN, RULERELNAME, SearchSysCache2(), HeapTupleData::t_self, table_close(), table_open(), and values.

Referenced by DefineQueryRewrite().

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];
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');
90  values[Anum_pg_rewrite_ev_enabled - 1] = CharGetDatum(RULE_FIRES_ON_ORIGIN);
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 = table_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 = ((Form_pg_rewrite) GETSTRUCT(tup))->oid;
132  is_update = true;
133  }
134  else
135  {
136  rewriteObjectId = GetNewOidWithIndex(pg_rewrite_desc,
137  RewriteOidIndexId,
138  Anum_pg_rewrite_oid);
139  values[Anum_pg_rewrite_oid - 1] = ObjectIdGetDatum(rewriteObjectId);
140 
141  tup = heap_form_tuple(pg_rewrite_desc->rd_att, values, nulls);
142 
143  CatalogTupleInsert(pg_rewrite_desc, tup);
144  }
145 
146 
147  heap_freetuple(tup);
148 
149  /* If replacing, get rid of old dependencies and make new ones */
150  if (is_update)
151  deleteDependencyRecordsFor(RewriteRelationId, rewriteObjectId, false);
152 
153  /*
154  * Install dependency on rule's relation to ensure it will go away on
155  * relation deletion. If the rule is ON SELECT, make the dependency
156  * implicit --- this prevents deleting a view's SELECT rule. Other kinds
157  * of rules can be AUTO.
158  */
159  myself.classId = RewriteRelationId;
160  myself.objectId = rewriteObjectId;
161  myself.objectSubId = 0;
162 
163  referenced.classId = RelationRelationId;
164  referenced.objectId = eventrel_oid;
165  referenced.objectSubId = 0;
166 
167  recordDependencyOn(&myself, &referenced,
169 
170  /*
171  * Also install dependencies on objects referenced in action and qual.
172  */
173  recordDependencyOnExpr(&myself, (Node *) action, NIL,
175 
176  if (event_qual != NULL)
177  {
178  /* Find query containing OLD/NEW rtable entries */
179  Query *qry = linitial_node(Query, action);
180 
181  qry = getInsertSelectQuery(qry, NULL);
182  recordDependencyOnExpr(&myself, event_qual, qry->rtable,
184  }
185 
186  /* Post creation hook for new rule */
187  InvokeObjectPostCreateHook(RewriteRelationId, rewriteObjectId, 0);
188 
189  table_close(pg_rewrite_desc, RowExclusiveLock);
190 
191  return rewriteObjectId;
192 }
#define NIL
Definition: pg_list.h:65
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:924
#define NameGetDatum(X)
Definition: postgres.h:639
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
#define RelationGetDescr(relation)
Definition: rel.h:503
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define PointerGetDatum(X)
Definition: postgres.h:600
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:236
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
#define MemSet(start, val, len)
Definition: c.h:1008
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:1020
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:177
List * rtable
Definition: parsenodes.h:147
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
Definition: c.h:675
#define RowExclusiveLock
Definition: lockdefs.h:38
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1568
#define RULE_FIRES_ON_ORIGIN
Definition: rewriteDefine.h:21
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
TupleDesc rd_att
Definition: rel.h:110
#define BoolGetDatum(X)
Definition: postgres.h:446
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1138
#define CharGetDatum(X)
Definition: postgres.h:460
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:52
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define CStringGetTextDatum(s)
Definition: builtins.h:82
char * nodeToString(const void *obj)
Definition: outfuncs.c:4543
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
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221

◆ RangeVarCallbackForRenameRule()

static void RangeVarCallbackForRenameRule ( const RangeVar rv,
Oid  relid,
Oid  oldrelid,
void *  arg 
)
static

Definition at line 922 of file rewriteDefine.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, allowSystemTableMods, ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, get_rel_relkind(), get_relkind_objtype(), GETSTRUCT, GetUserId(), HeapTupleIsValid, IsSystemClass(), ObjectIdGetDatum, pg_class_ownercheck(), ReleaseSysCache(), RangeVar::relname, RELOID, and SearchSysCache1().

Referenced by RenameRewriteRule().

924 {
925  HeapTuple tuple;
926  Form_pg_class form;
927 
928  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
929  if (!HeapTupleIsValid(tuple))
930  return; /* concurrently dropped */
931  form = (Form_pg_class) GETSTRUCT(tuple);
932 
933  /* only tables and views can have rules */
934  if (form->relkind != RELKIND_RELATION &&
935  form->relkind != RELKIND_VIEW &&
936  form->relkind != RELKIND_PARTITIONED_TABLE)
937  ereport(ERROR,
938  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
939  errmsg("relation \"%s\" cannot have rules", rv->relname),
940  errdetail_relkind_not_supported(form->relkind)));
941 
942  if (!allowSystemTableMods && IsSystemClass(relid, form))
943  ereport(ERROR,
944  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
945  errmsg("permission denied: \"%s\" is a system catalog",
946  rv->relname)));
947 
948  /* you must own the table to rename one of its rules */
949  if (!pg_class_ownercheck(relid, GetUserId()))
951 
952  ReleaseSysCache(tuple);
953 }
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Oid GetUserId(void)
Definition: miscinit.c:478
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
int errcode(int sqlerrcode)
Definition: elog.c:698
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:86
char * relname
Definition: primnodes.h:68
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
bool allowSystemTableMods
Definition: globals.c:123
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4818
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
int errmsg(const char *fmt,...)
Definition: elog.c:909
ObjectType get_relkind_objtype(char relkind)

◆ RenameRewriteRule()

ObjectAddress RenameRewriteRule ( RangeVar relation,
const char *  oldName,
const char *  newName 
)

Definition at line 959 of file rewriteDefine.c.

References AccessExclusiveLock, CacheInvalidateRelcache(), CatalogTupleUpdate(), CMD_SELECT, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, IsDefinedRewriteRule(), namestrcpy(), NoLock, ObjectAddressSet, ObjectIdGetDatum, PointerGetDatum, RangeVarCallbackForRenameRule(), RangeVarGetRelidExtended(), relation_close(), relation_open(), RelationGetRelationName, RowExclusiveLock, RULERELNAME, SearchSysCacheCopy2, HeapTupleData::t_self, table_close(), and table_open().

Referenced by ExecRenameStmt().

961 {
962  Oid relid;
963  Relation targetrel;
964  Relation pg_rewrite_desc;
965  HeapTuple ruletup;
966  Form_pg_rewrite ruleform;
967  Oid ruleOid;
968  ObjectAddress address;
969 
970  /*
971  * Look up name, check permissions, and acquire lock (which we will NOT
972  * release until end of transaction).
973  */
975  0,
977  NULL);
978 
979  /* Have lock already, so just need to build relcache entry. */
980  targetrel = relation_open(relid, NoLock);
981 
982  /* Prepare to modify pg_rewrite */
983  pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
984 
985  /* Fetch the rule's entry (it had better exist) */
987  ObjectIdGetDatum(relid),
988  PointerGetDatum(oldName));
989  if (!HeapTupleIsValid(ruletup))
990  ereport(ERROR,
991  (errcode(ERRCODE_UNDEFINED_OBJECT),
992  errmsg("rule \"%s\" for relation \"%s\" does not exist",
993  oldName, RelationGetRelationName(targetrel))));
994  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
995  ruleOid = ruleform->oid;
996 
997  /* rule with the new name should not already exist */
998  if (IsDefinedRewriteRule(relid, newName))
999  ereport(ERROR,
1001  errmsg("rule \"%s\" for relation \"%s\" already exists",
1002  newName, RelationGetRelationName(targetrel))));
1003 
1004  /*
1005  * We disallow renaming ON SELECT rules, because they should always be
1006  * named "_RETURN".
1007  */
1008  if (ruleform->ev_type == CMD_SELECT + '0')
1009  ereport(ERROR,
1010  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1011  errmsg("renaming an ON SELECT rule is not allowed")));
1012 
1013  /* OK, do the update */
1014  namestrcpy(&(ruleform->rulename), newName);
1015 
1016  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
1017 
1018  InvokeObjectPostAlterHook(RewriteRelationId, ruleOid, 0);
1019 
1020  heap_freetuple(ruletup);
1021  table_close(pg_rewrite_desc, RowExclusiveLock);
1022 
1023  /*
1024  * Invalidate relation's relcache entry so that other backends (and this
1025  * one too!) are sent SI message to make them rebuild relcache entries.
1026  * (Ideally this should happen automatically...)
1027  */
1028  CacheInvalidateRelcache(targetrel);
1029 
1030  ObjectAddressSet(address, RewriteRelationId, ruleOid);
1031 
1032  /*
1033  * Close rel, but keep exclusive lock!
1034  */
1035  relation_close(targetrel, NoLock);
1036 
1037  return address;
1038 }
bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName)
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define PointerGetDatum(X)
Definition: postgres.h:600
int errcode(int sqlerrcode)
Definition: elog.c:698
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:511
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:237
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:52
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1279
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void RangeVarCallbackForRenameRule(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

◆ setRuleCheckAsUser()

void setRuleCheckAsUser ( Node node,
Oid  userid 
)

Definition at line 800 of file rewriteDefine.c.

References setRuleCheckAsUser_walker().

Referenced by get_row_security_policies(), and RelationBuildRuleLock().

801 {
802  (void) setRuleCheckAsUser_walker(node, &userid);
803 }
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)

◆ setRuleCheckAsUser_Query()

static void setRuleCheckAsUser_Query ( Query qry,
Oid  userid 
)
static

Definition at line 820 of file rewriteDefine.c.

References castNode, RangeTblEntry::checkAsUser, Query::cteList, CommonTableExpr::ctequery, Query::hasSubLinks, lfirst, QTW_IGNORE_RC_SUBQUERIES, query_tree_walker(), Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, setRuleCheckAsUser_walker(), and RangeTblEntry::subquery.

Referenced by setRuleCheckAsUser_walker().

821 {
822  ListCell *l;
823 
824  /* Set all the RTEs in this query node */
825  foreach(l, qry->rtable)
826  {
827  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
828 
829  if (rte->rtekind == RTE_SUBQUERY)
830  {
831  /* Recurse into subquery in FROM */
832  setRuleCheckAsUser_Query(rte->subquery, userid);
833  }
834  else
835  rte->checkAsUser = userid;
836  }
837 
838  /* Recurse into subquery-in-WITH */
839  foreach(l, qry->cteList)
840  {
841  CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
842 
844  }
845 
846  /* If there are sublinks, search for them and process their RTEs */
847  if (qry->hasSubLinks)
848  query_tree_walker(qry, setRuleCheckAsUser_walker, (void *) &userid,
850 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2355
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:22
List * rtable
Definition: parsenodes.h:147
#define lfirst(lc)
Definition: pg_list.h:169
RTEKind rtekind
Definition: parsenodes.h:995
List * cteList
Definition: parsenodes.h:145
Query * subquery
Definition: parsenodes.h:1030
bool hasSubLinks
Definition: parsenodes.h:136

◆ setRuleCheckAsUser_walker()

static bool setRuleCheckAsUser_walker ( Node node,
Oid context 
)
static

Definition at line 806 of file rewriteDefine.c.

References expression_tree_walker(), IsA, and setRuleCheckAsUser_Query().

Referenced by setRuleCheckAsUser(), and setRuleCheckAsUser_Query().

807 {
808  if (node == NULL)
809  return false;
810  if (IsA(node, Query))
811  {
812  setRuleCheckAsUser_Query((Query *) node, *context);
813  return false;
814  }
816  (void *) context);
817 }
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904