PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
rewriteDefine.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.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 "utils/tqual.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 (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 (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

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

Definition at line 650 of file rewriteDefine.c.

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

Referenced by DefineQueryRewrite().

652 {
653  ListCell *tllist;
654  int i;
655 
656  /* Only a SELECT may require a column name match. */
657  Assert(isSelect || !requireColumnNameMatch);
658 
659  i = 0;
660  foreach(tllist, targetList)
661  {
662  TargetEntry *tle = (TargetEntry *) lfirst(tllist);
663  Oid tletypid;
664  int32 tletypmod;
665  Form_pg_attribute attr;
666  char *attname;
667 
668  /* resjunk entries may be ignored */
669  if (tle->resjunk)
670  continue;
671  i++;
672  if (i > resultDesc->natts)
673  ereport(ERROR,
674  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
675  isSelect ?
676  errmsg("SELECT rule's target list has too many entries") :
677  errmsg("RETURNING list has too many entries")));
678 
679  attr = TupleDescAttr(resultDesc, i - 1);
680  attname = NameStr(attr->attname);
681 
682  /*
683  * Disallow dropped columns in the relation. This is not really
684  * expected to happen when creating an ON SELECT rule. It'd be
685  * possible if someone tried to convert a relation with dropped
686  * columns to a view, but the only case we care about supporting
687  * table-to-view conversion for is pg_dump, and pg_dump won't do that.
688  *
689  * Unfortunately, the situation is also possible when adding a rule
690  * with RETURNING to a regular table, and rejecting that case is
691  * altogether more annoying. In principle we could support it by
692  * modifying the targetlist to include dummy NULL columns
693  * corresponding to the dropped columns in the tupdesc. However,
694  * places like ruleutils.c would have to be fixed to not process such
695  * entries, and that would take an uncertain and possibly rather large
696  * amount of work. (Note we could not dodge that by marking the dummy
697  * columns resjunk, since it's precisely the non-resjunk tlist columns
698  * that are expected to correspond to table columns.)
699  */
700  if (attr->attisdropped)
701  ereport(ERROR,
702  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
703  isSelect ?
704  errmsg("cannot convert relation containing dropped columns to view") :
705  errmsg("cannot create a RETURNING list for a relation containing dropped columns")));
706 
707  /* Check name match if required; no need for two error texts here */
708  if (requireColumnNameMatch && strcmp(tle->resname, attname) != 0)
709  ereport(ERROR,
710  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
711  errmsg("SELECT rule's target entry %d has different column name from column \"%s\"",
712  i, attname),
713  errdetail("SELECT target entry is named \"%s\".",
714  tle->resname)));
715 
716  /* Check type match. */
717  tletypid = exprType((Node *) tle->expr);
718  if (attr->atttypid != tletypid)
719  ereport(ERROR,
720  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
721  isSelect ?
722  errmsg("SELECT rule's target entry %d has different type from column \"%s\"",
723  i, attname) :
724  errmsg("RETURNING list's entry %d has different type from column \"%s\"",
725  i, attname),
726  isSelect ?
727  errdetail("SELECT target entry has type %s, but column has type %s.",
728  format_type_be(tletypid),
729  format_type_be(attr->atttypid)) :
730  errdetail("RETURNING list entry has type %s, but column has type %s.",
731  format_type_be(tletypid),
732  format_type_be(attr->atttypid))));
733 
734  /*
735  * Allow typmods to be different only if one of them is -1, ie,
736  * "unspecified". This is necessary for cases like "numeric", where
737  * the table will have a filled-in default length but the select
738  * rule's expression will probably have typmod = -1.
739  */
740  tletypmod = exprTypmod((Node *) tle->expr);
741  if (attr->atttypmod != tletypmod &&
742  attr->atttypmod != -1 && tletypmod != -1)
743  ereport(ERROR,
744  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
745  isSelect ?
746  errmsg("SELECT rule's target entry %d has different size from column \"%s\"",
747  i, attname) :
748  errmsg("RETURNING list's entry %d has different size from column \"%s\"",
749  i, attname),
750  isSelect ?
751  errdetail("SELECT target entry has type %s, but column has type %s.",
752  format_type_with_typemod(tletypid, tletypmod),
753  format_type_with_typemod(attr->atttypid,
754  attr->atttypmod)) :
755  errdetail("RETURNING list entry has type %s, but column has type %s.",
756  format_type_with_typemod(tletypid, tletypmod),
757  format_type_with_typemod(attr->atttypid,
758  attr->atttypmod))));
759  }
760 
761  if (i != resultDesc->natts)
762  ereport(ERROR,
763  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
764  isSelect ?
765  errmsg("SELECT rule's target list has too few entries") :
766  errmsg("RETURNING list has too few entries")));
767 }
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
Definition: nodes.h:510
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1370
int natts
Definition: tupdesc.h:73
signed int int32
Definition: c.h:246
bool resjunk
Definition: primnodes.h:1375
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:113
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1368
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:493
ObjectAddress DefineQueryRewrite ( char *  rulename,
Oid  event_relid,
Node event_qual,
CmdType  event_type,
bool  is_instead,
bool  replace,
List action 
)

Definition at line 228 of file rewriteDefine.c.

References AccessExclusiveLock, ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, allowSystemTableMods, CatalogTupleUpdate(), checkRuleResultList(), ObjectAddress::classId, CMD_SELECT, CommandCounterIncrement(), Query::commandType, deleteDependencyRecordsFor(), DeleteSystemAttributeTuples(), DROP_RESTRICT, elog, ereport, errcode(), errhint(), errmsg(), ERROR, RewriteRule::event, ForwardScanDirection, getInsertSelectQuery(), GetLatestSnapshot(), GETSTRUCT, GetUserId(), Query::hasModifyingCTE, heap_beginscan(), heap_close, heap_endscan(), heap_freetuple(), heap_getnext(), heap_open(), 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, RelationRelationId, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_VIEW, RELOID, REPLICA_IDENTITY_NOTHING, Query::resultRelation, Query::returningList, RewriteRelationId, RowExclusiveLock, RuleLock::rules, SearchSysCacheCopy1, SetRelationRuleStatus(), HeapTupleData::t_self, Query::targetList, UnregisterSnapshot(), and ViewSelectRuleName.

Referenced by DefineRule(), and DefineViewRules().

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

Definition at line 194 of file rewriteDefine.c.

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

Referenced by ProcessUtilitySlow().

195 {
196  List *actions;
197  Node *whereClause;
198  Oid relId;
199 
200  /* Parse analysis. */
201  transformRuleStmt(stmt, queryString, &actions, &whereClause);
202 
203  /*
204  * Find and lock the relation. Lock level should match
205  * DefineQueryRewrite.
206  */
207  relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
208 
209  /* ... and execute */
210  return DefineQueryRewrite(stmt->rulename,
211  relId,
212  whereClause,
213  stmt->event,
214  stmt->instead,
215  stmt->replace,
216  actions);
217 }
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:53
Definition: nodes.h:510
unsigned int Oid
Definition: postgres_ext.h:31
bool instead
Definition: parsenodes.h:2877
bool replace
Definition: parsenodes.h:2879
char * rulename
Definition: parsenodes.h:2874
ObjectAddress DefineQueryRewrite(char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)
CmdType event
Definition: parsenodes.h:2876
#define AccessExclusiveLock
Definition: lockdefs.h:45
RangeVar * relation
Definition: parsenodes.h:2873
Definition: pg_list.h:45
void transformRuleStmt(RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
void EnableDisableRule ( Relation  rel,
const char *  rulename,
char  fires_when 
)

Definition at line 839 of file rewriteDefine.c.

References ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, Assert, CacheInvalidateRelcache(), CatalogTupleUpdate(), CharGetDatum, DatumGetChar, ereport, errcode(), errmsg(), ERROR, get_rel_name(), GETSTRUCT, GetUserId(), heap_close, heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, ObjectIdGetDatum, pg_class_ownercheck(), PointerGetDatum, RelationGetRelid, RewriteRelationId, RowExclusiveLock, RULERELNAME, SearchSysCacheCopy2, and HeapTupleData::t_self.

Referenced by ATExecEnableDisableRule().

841 {
842  Relation pg_rewrite_desc;
843  Oid owningRel = RelationGetRelid(rel);
844  Oid eventRelationOid;
845  HeapTuple ruletup;
846  bool changed = false;
847 
848  /*
849  * Find the rule tuple to change.
850  */
851  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
853  ObjectIdGetDatum(owningRel),
854  PointerGetDatum(rulename));
855  if (!HeapTupleIsValid(ruletup))
856  ereport(ERROR,
857  (errcode(ERRCODE_UNDEFINED_OBJECT),
858  errmsg("rule \"%s\" for relation \"%s\" does not exist",
859  rulename, get_rel_name(owningRel))));
860 
861  /*
862  * Verify that the user has appropriate permissions.
863  */
864  eventRelationOid = ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_class;
865  Assert(eventRelationOid == owningRel);
866  if (!pg_class_ownercheck(eventRelationOid, GetUserId()))
868  get_rel_name(eventRelationOid));
869 
870  /*
871  * Change ev_enabled if it is different from the desired new state.
872  */
873  if (DatumGetChar(((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled) !=
874  fires_when)
875  {
876  ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled =
877  CharGetDatum(fires_when);
878  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
879 
880  changed = true;
881  }
882 
884  HeapTupleGetOid(ruletup), 0);
885 
886  heap_freetuple(ruletup);
887  heap_close(pg_rewrite_desc, RowExclusiveLock);
888 
889  /*
890  * If we changed anything, broadcast a SI inval message to force each
891  * backend (including our own!) to rebuild relation's relcache entry.
892  * Otherwise they will fail to apply the change promptly.
893  */
894  if (changed)
896 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:284
#define PointerGetDatum(X)
Definition: postgres.h:562
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define DatumGetChar(X)
Definition: postgres.h:415
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RewriteRelationId
Definition: pg_rewrite.h:32
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:681
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define CharGetDatum(X)
Definition: postgres.h:422
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:53
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1233
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:175
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define RelationGetRelid(relation)
Definition: rel.h:416
static Oid InsertRule ( 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 Anum_pg_rewrite_ev_action, Anum_pg_rewrite_ev_class, Anum_pg_rewrite_ev_enabled, Anum_pg_rewrite_ev_qual, Anum_pg_rewrite_ev_type, Anum_pg_rewrite_is_instead, Anum_pg_rewrite_rulename, 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(), heap_close, heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostCreateHook, linitial_node, MemSet, NameGetDatum, namestrcpy(), Natts_pg_rewrite, NIL, nodeToString(), ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, PointerGetDatum, RelationData::rd_att, recordDependencyOn(), recordDependencyOnExpr(), RelationGetDescr, RelationRelationId, ReleaseSysCache(), RewriteRelationId, RowExclusiveLock, Query::rtable, RULE_FIRES_ON_ORIGIN, RULERELNAME, SearchSysCache2(), HeapTupleData::t_self, and values.

Referenced by DefineQueryRewrite().

66 {
67  char *evqual = nodeToString(event_qual);
68  char *actiontree = nodeToString((Node *) action);
70  bool nulls[Natts_pg_rewrite];
71  bool replaces[Natts_pg_rewrite];
72  NameData rname;
73  Relation pg_rewrite_desc;
74  HeapTuple tup,
75  oldtup;
76  Oid rewriteObjectId;
77  ObjectAddress myself,
78  referenced;
79  bool is_update = false;
80 
81  /*
82  * Set up *nulls and *values arrays
83  */
84  MemSet(nulls, false, sizeof(nulls));
85 
86  namestrcpy(&rname, rulname);
87  values[Anum_pg_rewrite_rulename - 1] = NameGetDatum(&rname);
88  values[Anum_pg_rewrite_ev_class - 1] = ObjectIdGetDatum(eventrel_oid);
89  values[Anum_pg_rewrite_ev_type - 1] = CharGetDatum(evtype + '0');
91  values[Anum_pg_rewrite_is_instead - 1] = BoolGetDatum(evinstead);
92  values[Anum_pg_rewrite_ev_qual - 1] = CStringGetTextDatum(evqual);
93  values[Anum_pg_rewrite_ev_action - 1] = CStringGetTextDatum(actiontree);
94 
95  /*
96  * Ready to store new pg_rewrite tuple
97  */
98  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
99 
100  /*
101  * Check to see if we are replacing an existing tuple
102  */
103  oldtup = SearchSysCache2(RULERELNAME,
104  ObjectIdGetDatum(eventrel_oid),
105  PointerGetDatum(rulname));
106 
107  if (HeapTupleIsValid(oldtup))
108  {
109  if (!replace)
110  ereport(ERROR,
112  errmsg("rule \"%s\" for relation \"%s\" already exists",
113  rulname, get_rel_name(eventrel_oid))));
114 
115  /*
116  * When replacing, we don't need to replace every attribute
117  */
118  MemSet(replaces, false, sizeof(replaces));
119  replaces[Anum_pg_rewrite_ev_type - 1] = true;
120  replaces[Anum_pg_rewrite_is_instead - 1] = true;
121  replaces[Anum_pg_rewrite_ev_qual - 1] = true;
122  replaces[Anum_pg_rewrite_ev_action - 1] = true;
123 
124  tup = heap_modify_tuple(oldtup, RelationGetDescr(pg_rewrite_desc),
125  values, nulls, replaces);
126 
127  CatalogTupleUpdate(pg_rewrite_desc, &tup->t_self, tup);
128 
129  ReleaseSysCache(oldtup);
130 
131  rewriteObjectId = HeapTupleGetOid(tup);
132  is_update = true;
133  }
134  else
135  {
136  tup = heap_form_tuple(pg_rewrite_desc->rd_att, values, nulls);
137 
138  rewriteObjectId = CatalogTupleInsert(pg_rewrite_desc, tup);
139  }
140 
141 
142  heap_freetuple(tup);
143 
144  /* If replacing, get rid of old dependencies and make new ones */
145  if (is_update)
146  deleteDependencyRecordsFor(RewriteRelationId, rewriteObjectId, false);
147 
148  /*
149  * Install dependency on rule's relation to ensure it will go away on
150  * relation deletion. If the rule is ON SELECT, make the dependency
151  * implicit --- this prevents deleting a view's SELECT rule. Other kinds
152  * of rules can be AUTO.
153  */
154  myself.classId = RewriteRelationId;
155  myself.objectId = rewriteObjectId;
156  myself.objectSubId = 0;
157 
158  referenced.classId = RelationRelationId;
159  referenced.objectId = eventrel_oid;
160  referenced.objectSubId = 0;
161 
162  recordDependencyOn(&myself, &referenced,
164 
165  /*
166  * Also install dependencies on objects referenced in action and qual.
167  */
168  recordDependencyOnExpr(&myself, (Node *) action, NIL,
170 
171  if (event_qual != NULL)
172  {
173  /* Find query containing OLD/NEW rtable entries */
174  Query *qry = linitial_node(Query, action);
175 
176  qry = getInsertSelectQuery(qry, NULL);
177  recordDependencyOnExpr(&myself, event_qual, qry->rtable,
179  }
180 
181  /* Post creation hook for new rule */
182  InvokeObjectPostCreateHook(RewriteRelationId, rewriteObjectId, 0);
183 
184  heap_close(pg_rewrite_desc, RowExclusiveLock);
185 
186  return rewriteObjectId;
187 }
#define NIL
Definition: pg_list.h:69
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
#define NameGetDatum(X)
Definition: postgres.h:601
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define Anum_pg_rewrite_ev_action
Definition: pg_rewrite.h:66
#define RelationGetDescr(relation)
Definition: rel.h:428
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationRelationId
Definition: pg_class.h:29
#define Natts_pg_rewrite
Definition: pg_rewrite.h:59
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:191
Definition: nodes.h:510
#define Anum_pg_rewrite_ev_class
Definition: pg_rewrite.h:61
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:863
#define Anum_pg_rewrite_is_instead
Definition: pg_rewrite.h:64
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:695
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
int namestrcpy(Name name, const char *str)
Definition: name.c:216
#define Anum_pg_rewrite_ev_enabled
Definition: pg_rewrite.h:63
#define Anum_pg_rewrite_rulename
Definition: pg_rewrite.h:60
List * rtable
Definition: parsenodes.h:135
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
ItemPointerData t_self
Definition: htup.h:65
Definition: c.h:487
#define RowExclusiveLock
Definition: lockdefs.h:38
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1351
#define ereport(elevel, rest)
Definition: elog.h:122
#define Anum_pg_rewrite_ev_type
Definition: pg_rewrite.h:62
#define RULE_FIRES_ON_ORIGIN
Definition: rewriteDefine.h:21
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
#define BoolGetDatum(X)
Definition: postgres.h:408
#define RewriteRelationId
Definition: pg_rewrite.h:32
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1123
#define CharGetDatum(X)
Definition: postgres.h:422
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CStringGetTextDatum(s)
Definition: builtins.h:91
char * nodeToString(const void *obj)
Definition: outfuncs.c:4259
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define Anum_pg_rewrite_ev_qual
Definition: pg_rewrite.h:65
static void RangeVarCallbackForRenameRule ( const RangeVar rv,
Oid  relid,
Oid  oldrelid,
void *  arg 
)
static

Definition at line 903 of file rewriteDefine.c.

References ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, allowSystemTableMods, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetUserId(), HeapTupleIsValid, IsSystemClass(), ObjectIdGetDatum, pg_class_ownercheck(), ReleaseSysCache(), RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_VIEW, RangeVar::relname, RELOID, and SearchSysCache1().

Referenced by RenameRewriteRule().

905 {
906  HeapTuple tuple;
907  Form_pg_class form;
908 
909  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
910  if (!HeapTupleIsValid(tuple))
911  return; /* concurrently dropped */
912  form = (Form_pg_class) GETSTRUCT(tuple);
913 
914  /* only tables and views can have rules */
915  if (form->relkind != RELKIND_RELATION &&
916  form->relkind != RELKIND_VIEW &&
917  form->relkind != RELKIND_PARTITIONED_TABLE)
918  ereport(ERROR,
919  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
920  errmsg("\"%s\" is not a table or view", rv->relname)));
921 
922  if (!allowSystemTableMods && IsSystemClass(relid, form))
923  ereport(ERROR,
924  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
925  errmsg("permission denied: \"%s\" is a system catalog",
926  rv->relname)));
927 
928  /* you must own the table to rename one of its rules */
929  if (!pg_class_ownercheck(relid, GetUserId()))
931 
932  ReleaseSysCache(tuple);
933 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:284
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:75
char * relname
Definition: primnodes.h:68
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
bool allowSystemTableMods
Definition: globals.c:112
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_VIEW
Definition: pg_class.h:164
#define RELKIND_RELATION
Definition: pg_class.h:160
ObjectAddress RenameRewriteRule ( RangeVar relation,
const char *  oldName,
const char *  newName 
)

Definition at line 939 of file rewriteDefine.c.

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

Referenced by ExecRenameStmt().

941 {
942  Oid relid;
943  Relation targetrel;
944  Relation pg_rewrite_desc;
945  HeapTuple ruletup;
946  Form_pg_rewrite ruleform;
947  Oid ruleOid;
948  ObjectAddress address;
949 
950  /*
951  * Look up name, check permissions, and acquire lock (which we will NOT
952  * release until end of transaction).
953  */
955  false, false,
957  NULL);
958 
959  /* Have lock already, so just need to build relcache entry. */
960  targetrel = relation_open(relid, NoLock);
961 
962  /* Prepare to modify pg_rewrite */
963  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
964 
965  /* Fetch the rule's entry (it had better exist) */
967  ObjectIdGetDatum(relid),
968  PointerGetDatum(oldName));
969  if (!HeapTupleIsValid(ruletup))
970  ereport(ERROR,
971  (errcode(ERRCODE_UNDEFINED_OBJECT),
972  errmsg("rule \"%s\" for relation \"%s\" does not exist",
973  oldName, RelationGetRelationName(targetrel))));
974  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
975  ruleOid = HeapTupleGetOid(ruletup);
976 
977  /* rule with the new name should not already exist */
978  if (IsDefinedRewriteRule(relid, newName))
979  ereport(ERROR,
981  errmsg("rule \"%s\" for relation \"%s\" already exists",
982  newName, RelationGetRelationName(targetrel))));
983 
984  /*
985  * We disallow renaming ON SELECT rules, because they should always be
986  * named "_RETURN".
987  */
988  if (ruleform->ev_type == CMD_SELECT + '0')
989  ereport(ERROR,
990  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
991  errmsg("renaming an ON SELECT rule is not allowed")));
992 
993  /* OK, do the update */
994  namestrcpy(&(ruleform->rulename), newName);
995 
996  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
997 
998  heap_freetuple(ruletup);
999  heap_close(pg_rewrite_desc, RowExclusiveLock);
1000 
1001  /*
1002  * Invalidate relation's relcache entry so that other backends (and this
1003  * one too!) are sent SI message to make them rebuild relcache entries.
1004  * (Ideally this should happen automatically...)
1005  */
1006  CacheInvalidateRelcache(targetrel);
1007 
1008  ObjectAddressSet(address, RewriteRelationId, ruleOid);
1009 
1010  /*
1011  * Close rel, but keep exclusive lock!
1012  */
1013  relation_close(targetrel, NoLock);
1014 
1015  return address;
1016 }
bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName)
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define PointerGetDatum(X)
Definition: postgres.h:562
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:216
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
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:436
#define ereport(elevel, rest)
Definition: elog.h:122
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RewriteRelationId
Definition: pg_rewrite.h:32
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:53
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1233
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void RangeVarCallbackForRenameRule(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:175
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
void setRuleCheckAsUser ( Node node,
Oid  userid 
)

Definition at line 782 of file rewriteDefine.c.

References setRuleCheckAsUser_walker().

Referenced by RelationBuildRuleLock().

783 {
784  (void) setRuleCheckAsUser_walker(node, &userid);
785 }
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
static void setRuleCheckAsUser_Query ( Query qry,
Oid  userid 
)
static

Definition at line 802 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().

803 {
804  ListCell *l;
805 
806  /* Set all the RTEs in this query node */
807  foreach(l, qry->rtable)
808  {
809  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
810 
811  if (rte->rtekind == RTE_SUBQUERY)
812  {
813  /* Recurse into subquery in FROM */
814  setRuleCheckAsUser_Query(rte->subquery, userid);
815  }
816  else
817  rte->checkAsUser = userid;
818  }
819 
820  /* Recurse into subquery-in-WITH */
821  foreach(l, qry->cteList)
822  {
823  CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
824 
826  }
827 
828  /* If there are sublinks, search for them and process their RTEs */
829  if (qry->hasSubLinks)
830  query_tree_walker(qry, setRuleCheckAsUser_walker, (void *) &userid,
832 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2245
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:22
List * rtable
Definition: parsenodes.h:135
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:945
List * cteList
Definition: parsenodes.h:133
Query * subquery
Definition: parsenodes.h:968
bool hasSubLinks
Definition: parsenodes.h:126
static bool setRuleCheckAsUser_walker ( Node node,
Oid context 
)
static

Definition at line 788 of file rewriteDefine.c.

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

Referenced by setRuleCheckAsUser(), and setRuleCheckAsUser_Query().

789 {
790  if (node == NULL)
791  return false;
792  if (IsA(node, Query))
793  {
794  setRuleCheckAsUser_Query((Query *) node, *context);
795  return false;
796  }
798  (void *) context);
799 }
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834