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 644 of file rewriteDefine.c.

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

Referenced by DefineQueryRewrite().

646 {
647  ListCell *tllist;
648  int i;
649 
650  /* Only a SELECT may require a column name match. */
651  Assert(isSelect || !requireColumnNameMatch);
652 
653  i = 0;
654  foreach(tllist, targetList)
655  {
656  TargetEntry *tle = (TargetEntry *) lfirst(tllist);
657  Oid tletypid;
658  int32 tletypmod;
659  Form_pg_attribute attr;
660  char *attname;
661 
662  /* resjunk entries may be ignored */
663  if (tle->resjunk)
664  continue;
665  i++;
666  if (i > resultDesc->natts)
667  ereport(ERROR,
668  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
669  isSelect ?
670  errmsg("SELECT rule's target list has too many entries") :
671  errmsg("RETURNING list has too many entries")));
672 
673  attr = resultDesc->attrs[i - 1];
674  attname = NameStr(attr->attname);
675 
676  /*
677  * Disallow dropped columns in the relation. This is not really
678  * expected to happen when creating an ON SELECT rule. It'd be
679  * possible if someone tried to convert a relation with dropped
680  * columns to a view, but the only case we care about supporting
681  * table-to-view conversion for is pg_dump, and pg_dump won't do that.
682  *
683  * Unfortunately, the situation is also possible when adding a rule
684  * with RETURNING to a regular table, and rejecting that case is
685  * altogether more annoying. In principle we could support it by
686  * modifying the targetlist to include dummy NULL columns
687  * corresponding to the dropped columns in the tupdesc. However,
688  * places like ruleutils.c would have to be fixed to not process such
689  * entries, and that would take an uncertain and possibly rather large
690  * amount of work. (Note we could not dodge that by marking the dummy
691  * columns resjunk, since it's precisely the non-resjunk tlist columns
692  * that are expected to correspond to table columns.)
693  */
694  if (attr->attisdropped)
695  ereport(ERROR,
696  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
697  isSelect ?
698  errmsg("cannot convert relation containing dropped columns to view") :
699  errmsg("cannot create a RETURNING list for a relation containing dropped columns")));
700 
701  /* Check name match if required; no need for two error texts here */
702  if (requireColumnNameMatch && strcmp(tle->resname, attname) != 0)
703  ereport(ERROR,
704  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
705  errmsg("SELECT rule's target entry %d has different column name from column \"%s\"",
706  i, attname),
707  errdetail("SELECT target entry is named \"%s\".",
708  tle->resname)));
709 
710  /* Check type match. */
711  tletypid = exprType((Node *) tle->expr);
712  if (attr->atttypid != tletypid)
713  ereport(ERROR,
714  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
715  isSelect ?
716  errmsg("SELECT rule's target entry %d has different type from column \"%s\"",
717  i, attname) :
718  errmsg("RETURNING list's entry %d has different type from column \"%s\"",
719  i, attname),
720  isSelect ?
721  errdetail("SELECT target entry has type %s, but column has type %s.",
722  format_type_be(tletypid),
723  format_type_be(attr->atttypid)) :
724  errdetail("RETURNING list entry has type %s, but column has type %s.",
725  format_type_be(tletypid),
726  format_type_be(attr->atttypid))));
727 
728  /*
729  * Allow typmods to be different only if one of them is -1, ie,
730  * "unspecified". This is necessary for cases like "numeric", where
731  * the table will have a filled-in default length but the select
732  * rule's expression will probably have typmod = -1.
733  */
734  tletypmod = exprTypmod((Node *) tle->expr);
735  if (attr->atttypmod != tletypmod &&
736  attr->atttypmod != -1 && tletypmod != -1)
737  ereport(ERROR,
738  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
739  isSelect ?
740  errmsg("SELECT rule's target entry %d has different size from column \"%s\"",
741  i, attname) :
742  errmsg("RETURNING list's entry %d has different size from column \"%s\"",
743  i, attname),
744  isSelect ?
745  errdetail("SELECT target entry has type %s, but column has type %s.",
746  format_type_with_typemod(tletypid, tletypmod),
747  format_type_with_typemod(attr->atttypid,
748  attr->atttypmod)) :
749  errdetail("RETURNING list entry has type %s, but column has type %s.",
750  format_type_with_typemod(tletypid, tletypmod),
751  format_type_with_typemod(attr->atttypid,
752  attr->atttypmod))));
753  }
754 
755  if (i != resultDesc->natts)
756  ereport(ERROR,
757  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
758  isSelect ?
759  errmsg("SELECT rule's target list has too few entries") :
760  errmsg("RETURNING list has too few entries")));
761 }
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Definition: nodes.h:509
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:1369
int natts
Definition: tupdesc.h:73
signed int int32
Definition: c.h:256
bool resjunk
Definition: primnodes.h:1374
#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:675
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1367
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:499
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, NULL, 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("could not convert partitioned table \"%s\" to a view",
429  RelationGetRelationName(event_relation))));
430 
431  snapshot = RegisterSnapshot(GetLatestSnapshot());
432  scanDesc = heap_beginscan(event_relation, snapshot, 0, NULL);
433  if (heap_getnext(scanDesc, ForwardScanDirection) != NULL)
434  ereport(ERROR,
435  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
436  errmsg("could not convert table \"%s\" to a view because it is not empty",
437  RelationGetRelationName(event_relation))));
438  heap_endscan(scanDesc);
439  UnregisterSnapshot(snapshot);
440 
441  if (event_relation->rd_rel->relhastriggers)
442  ereport(ERROR,
443  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
444  errmsg("could not convert table \"%s\" to a view because it has triggers",
445  RelationGetRelationName(event_relation)),
446  errhint("In particular, the table cannot be involved in any foreign key relationships.")));
447 
448  if (event_relation->rd_rel->relhasindex)
449  ereport(ERROR,
450  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
451  errmsg("could not convert table \"%s\" to a view because it has indexes",
452  RelationGetRelationName(event_relation))));
453 
454  if (event_relation->rd_rel->relhassubclass)
455  ereport(ERROR,
456  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
457  errmsg("could not convert table \"%s\" to a view because it has child tables",
458  RelationGetRelationName(event_relation))));
459 
460  if (event_relation->rd_rel->relrowsecurity)
461  ereport(ERROR,
462  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
463  errmsg("could not convert table \"%s\" to a view because it has row security enabled",
464  RelationGetRelationName(event_relation))));
465 
466  if (relation_has_policies(event_relation))
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 policies",
470  RelationGetRelationName(event_relation))));
471 
472  RelisBecomingView = true;
473  }
474  }
475  else
476  {
477  /*
478  * For non-SELECT rules, a RETURNING list can appear in at most one of
479  * the actions ... and there can't be any RETURNING list at all in a
480  * conditional or non-INSTEAD rule. (Actually, there can be at most
481  * one RETURNING list across all rules on the same event, but it seems
482  * best to enforce that at rule expansion time.) If there is a
483  * RETURNING list, it must match the event relation.
484  */
485  bool haveReturning = false;
486 
487  foreach(l, action)
488  {
489  query = lfirst_node(Query, l);
490 
491  if (!query->returningList)
492  continue;
493  if (haveReturning)
494  ereport(ERROR,
495  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
496  errmsg("cannot have multiple RETURNING lists in a rule")));
497  haveReturning = true;
498  if (event_qual != NULL)
499  ereport(ERROR,
500  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
501  errmsg("RETURNING lists are not supported in conditional rules")));
502  if (!is_instead)
503  ereport(ERROR,
504  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
505  errmsg("RETURNING lists are not supported in non-INSTEAD rules")));
507  RelationGetDescr(event_relation),
508  false, false);
509  }
510  }
511 
512  /*
513  * This rule is allowed - prepare to install it.
514  */
515 
516  /* discard rule if it's null action and not INSTEAD; it's a no-op */
517  if (action != NIL || is_instead)
518  {
519  ruleId = InsertRule(rulename,
520  event_type,
521  event_relid,
522  is_instead,
523  event_qual,
524  action,
525  replace);
526 
527  /*
528  * Set pg_class 'relhasrules' field TRUE for event relation.
529  *
530  * Important side effect: an SI notice is broadcast to force all
531  * backends (including me!) to update relcache entries with the new
532  * rule.
533  */
534  SetRelationRuleStatus(event_relid, true);
535  }
536 
537  /* ---------------------------------------------------------------------
538  * If the relation is becoming a view:
539  * - delete the associated storage files
540  * - get rid of any system attributes in pg_attribute; a view shouldn't
541  * have any of those
542  * - remove the toast table; there is no need for it anymore, and its
543  * presence would make vacuum slightly more complicated
544  * - set relkind to RELKIND_VIEW, and adjust other pg_class fields
545  * to be appropriate for a view
546  *
547  * NB: we had better have AccessExclusiveLock to do this ...
548  * ---------------------------------------------------------------------
549  */
550  if (RelisBecomingView)
551  {
552  Relation relationRelation;
553  Oid toastrelid;
554  HeapTuple classTup;
555  Form_pg_class classForm;
556 
557  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
558  toastrelid = event_relation->rd_rel->reltoastrelid;
559 
560  /* drop storage while table still looks like a table */
561  RelationDropStorage(event_relation);
562  DeleteSystemAttributeTuples(event_relid);
563 
564  /*
565  * Drop the toast table if any. (This won't take care of updating the
566  * toast fields in the relation's own pg_class entry; we handle that
567  * below.)
568  */
569  if (OidIsValid(toastrelid))
570  {
571  ObjectAddress toastobject;
572 
573  /*
574  * Delete the dependency of the toast relation on the main
575  * relation so we can drop the former without dropping the latter.
576  */
578  false);
579 
580  /* Make deletion of dependency record visible */
582 
583  /* Now drop toast table, including its index */
584  toastobject.classId = RelationRelationId;
585  toastobject.objectId = toastrelid;
586  toastobject.objectSubId = 0;
587  performDeletion(&toastobject, DROP_RESTRICT,
589  }
590 
591  /*
592  * SetRelationRuleStatus may have updated the pg_class row, so we must
593  * advance the command counter before trying to update it again.
594  */
596 
597  /*
598  * Fix pg_class entry to look like a normal view's, including setting
599  * the correct relkind and removal of reltoastrelid of the toast table
600  * we potentially removed above.
601  */
602  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(event_relid));
603  if (!HeapTupleIsValid(classTup))
604  elog(ERROR, "cache lookup failed for relation %u", event_relid);
605  classForm = (Form_pg_class) GETSTRUCT(classTup);
606 
607  classForm->reltablespace = InvalidOid;
608  classForm->relpages = 0;
609  classForm->reltuples = 0;
610  classForm->relallvisible = 0;
611  classForm->reltoastrelid = InvalidOid;
612  classForm->relhasindex = false;
613  classForm->relkind = RELKIND_VIEW;
614  classForm->relhasoids = false;
615  classForm->relhaspkey = false;
616  classForm->relfrozenxid = InvalidTransactionId;
617  classForm->relminmxid = InvalidMultiXactId;
618  classForm->relreplident = REPLICA_IDENTITY_NOTHING;
619 
620  CatalogTupleUpdate(relationRelation, &classTup->t_self, classTup);
621 
622  heap_freetuple(classTup);
623  heap_close(relationRelation, RowExclusiveLock);
624  }
625 
626  ObjectAddressSet(address, RewriteRelationId, ruleId);
627 
628  /* Close rel, but keep lock till commit... */
629  heap_close(event_relation, NoLock);
630 
631  return address;
632 }
#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:1578
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:858
#define RelationGetDescr(relation)
Definition: rel.h:429
Oid GetUserId(void)
Definition: miscinit.c:283
#define REPLICA_IDENTITY_NOTHING
Definition: pg_class.h:177
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#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:1372
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
#define OidIsValid(objectId)
Definition: c.h:538
void SetRelationRuleStatus(Oid relationId, bool relHasRules)
Definition: localtime.c:82
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:437
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:900
#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:922
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define InvalidMultiXactId
Definition: multixact.h:23
bool allowSystemTableMods
Definition: globals.c:111
#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
#define NULL
Definition: c.h:229
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:375
#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:165
#define AccessExclusiveLock
Definition: lockdefs.h:46
bool relation_has_policies(Relation rel)
Definition: policy.c:1362
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_VIEW
Definition: pg_class.h:164
void DeleteSystemAttributeTuples(Oid relid)
Definition: heap.c:1500
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:1391
#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:509
unsigned int Oid
Definition: postgres_ext.h:31
bool instead
Definition: parsenodes.h:2841
bool replace
Definition: parsenodes.h:2843
char * rulename
Definition: parsenodes.h:2838
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:2840
#define AccessExclusiveLock
Definition: lockdefs.h:46
RangeVar * relation
Definition: parsenodes.h:2837
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 833 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().

835 {
836  Relation pg_rewrite_desc;
837  Oid owningRel = RelationGetRelid(rel);
838  Oid eventRelationOid;
839  HeapTuple ruletup;
840  bool changed = false;
841 
842  /*
843  * Find the rule tuple to change.
844  */
845  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
847  ObjectIdGetDatum(owningRel),
848  PointerGetDatum(rulename));
849  if (!HeapTupleIsValid(ruletup))
850  ereport(ERROR,
851  (errcode(ERRCODE_UNDEFINED_OBJECT),
852  errmsg("rule \"%s\" for relation \"%s\" does not exist",
853  rulename, get_rel_name(owningRel))));
854 
855  /*
856  * Verify that the user has appropriate permissions.
857  */
858  eventRelationOid = ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_class;
859  Assert(eventRelationOid == owningRel);
860  if (!pg_class_ownercheck(eventRelationOid, GetUserId()))
862  get_rel_name(eventRelationOid));
863 
864  /*
865  * Change ev_enabled if it is different from the desired new state.
866  */
867  if (DatumGetChar(((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled) !=
868  fires_when)
869  {
870  ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled =
871  CharGetDatum(fires_when);
872  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
873 
874  changed = true;
875  }
876 
878  HeapTupleGetOid(ruletup), 0);
879 
880  heap_freetuple(ruletup);
881  heap_close(pg_rewrite_desc, RowExclusiveLock);
882 
883  /*
884  * If we changed anything, broadcast a SI inval message to force each
885  * backend (including our own!) to rebuild relation's relcache entry.
886  * Otherwise they will fail to apply the change promptly.
887  */
888  if (changed)
890 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:283
#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:1372
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:1284
#define RewriteRelationId
Definition: pg_rewrite.h:32
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:675
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:167
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define RelationGetRelid(relation)
Definition: rel.h:417
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(), NULL, 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:429
#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:509
#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:857
#define Anum_pg_rewrite_is_instead
Definition: pg_rewrite.h:64
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
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:217
#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:493
#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:1117
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
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
#define NULL
Definition: c.h:229
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define CharGetDatum(X)
Definition: postgres.h:422
static Datum values[MAXATTR]
Definition: bootstrap.c:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CStringGetTextDatum(s)
Definition: builtins.h:91
char * nodeToString(const void *obj)
Definition: outfuncs.c:4219
#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:791
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define Anum_pg_rewrite_ev_qual
Definition: pg_rewrite.h:65
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:158
static void RangeVarCallbackForRenameRule ( const RangeVar rv,
Oid  relid,
Oid  oldrelid,
void *  arg 
)
static

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

899 {
900  HeapTuple tuple;
901  Form_pg_class form;
902 
903  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
904  if (!HeapTupleIsValid(tuple))
905  return; /* concurrently dropped */
906  form = (Form_pg_class) GETSTRUCT(tuple);
907 
908  /* only tables and views can have rules */
909  if (form->relkind != RELKIND_RELATION &&
910  form->relkind != RELKIND_VIEW &&
911  form->relkind != RELKIND_PARTITIONED_TABLE)
912  ereport(ERROR,
913  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
914  errmsg("\"%s\" is not a table or view", rv->relname)));
915 
916  if (!allowSystemTableMods && IsSystemClass(relid, form))
917  ereport(ERROR,
918  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
919  errmsg("permission denied: \"%s\" is a system catalog",
920  rv->relname)));
921 
922  /* you must own the table to rename one of its rules */
923  if (!pg_class_ownercheck(relid, GetUserId()))
925 
926  ReleaseSysCache(tuple);
927 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:283
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:74
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
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
bool allowSystemTableMods
Definition: globals.c:111
#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 933 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, NULL, ObjectAddressSet, ObjectIdGetDatum, PointerGetDatum, RangeVarCallbackForRenameRule(), RangeVarGetRelidExtended(), relation_close(), relation_open(), RelationGetRelationName, RewriteRelationId, RowExclusiveLock, RULERELNAME, SearchSysCacheCopy2, and HeapTupleData::t_self.

Referenced by ExecRenameStmt().

935 {
936  Oid relid;
937  Relation targetrel;
938  Relation pg_rewrite_desc;
939  HeapTuple ruletup;
940  Form_pg_rewrite ruleform;
941  Oid ruleOid;
942  ObjectAddress address;
943 
944  /*
945  * Look up name, check permissions, and acquire lock (which we will NOT
946  * release until end of transaction).
947  */
949  false, false,
951  NULL);
952 
953  /* Have lock already, so just need to build relcache entry. */
954  targetrel = relation_open(relid, NoLock);
955 
956  /* Prepare to modify pg_rewrite */
957  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
958 
959  /* Fetch the rule's entry (it had better exist) */
961  ObjectIdGetDatum(relid),
962  PointerGetDatum(oldName));
963  if (!HeapTupleIsValid(ruletup))
964  ereport(ERROR,
965  (errcode(ERRCODE_UNDEFINED_OBJECT),
966  errmsg("rule \"%s\" for relation \"%s\" does not exist",
967  oldName, RelationGetRelationName(targetrel))));
968  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
969  ruleOid = HeapTupleGetOid(ruletup);
970 
971  /* rule with the new name should not already exist */
972  if (IsDefinedRewriteRule(relid, newName))
973  ereport(ERROR,
975  errmsg("rule \"%s\" for relation \"%s\" already exists",
976  newName, RelationGetRelationName(targetrel))));
977 
978  /*
979  * We disallow renaming ON SELECT rules, because they should always be
980  * named "_RETURN".
981  */
982  if (ruleform->ev_type == CMD_SELECT + '0')
983  ereport(ERROR,
984  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
985  errmsg("renaming an ON SELECT rule is not allowed")));
986 
987  /* OK, do the update */
988  namestrcpy(&(ruleform->rulename), newName);
989 
990  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
991 
992  heap_freetuple(ruletup);
993  heap_close(pg_rewrite_desc, RowExclusiveLock);
994 
995  /*
996  * Invalidate relation's relcache entry so that other backends (and this
997  * one too!) are sent SI message to make them rebuild relcache entries.
998  * (Ideally this should happen automatically...)
999  */
1000  CacheInvalidateRelcache(targetrel);
1001 
1002  ObjectAddressSet(address, RewriteRelationId, ruleOid);
1003 
1004  /*
1005  * Close rel, but keep exclusive lock!
1006  */
1007  relation_close(targetrel, NoLock);
1008 
1009  return address;
1010 }
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:1260
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:217
#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:437
#define ereport(elevel, rest)
Definition: elog.h:122
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RewriteRelationId
Definition: pg_rewrite.h:32
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
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:46
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:1114
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:167
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
void setRuleCheckAsUser ( Node node,
Oid  userid 
)

Definition at line 776 of file rewriteDefine.c.

References setRuleCheckAsUser_walker().

Referenced by RelationBuildRuleLock().

777 {
778  (void) setRuleCheckAsUser_walker(node, &userid);
779 }
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
static void setRuleCheckAsUser_Query ( Query qry,
Oid  userid 
)
static

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

797 {
798  ListCell *l;
799 
800  /* Set all the RTEs in this query node */
801  foreach(l, qry->rtable)
802  {
803  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
804 
805  if (rte->rtekind == RTE_SUBQUERY)
806  {
807  /* Recurse into subquery in FROM */
808  setRuleCheckAsUser_Query(rte->subquery, userid);
809  }
810  else
811  rte->checkAsUser = userid;
812  }
813 
814  /* Recurse into subquery-in-WITH */
815  foreach(l, qry->cteList)
816  {
817  CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
818 
820  }
821 
822  /* If there are sublinks, search for them and process their RTEs */
823  if (qry->hasSubLinks)
824  query_tree_walker(qry, setRuleCheckAsUser_walker, (void *) &userid,
826 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2268
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
#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:929
List * cteList
Definition: parsenodes.h:133
Query * subquery
Definition: parsenodes.h:947
bool hasSubLinks
Definition: parsenodes.h:126
static bool setRuleCheckAsUser_walker ( Node node,
Oid context 
)
static

Definition at line 782 of file rewriteDefine.c.

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

Referenced by setRuleCheckAsUser(), and setRuleCheckAsUser_Query().

783 {
784  if (node == NULL)
785  return false;
786  if (IsA(node, Query))
787  {
788  setRuleCheckAsUser_Query((Query *) node, *context);
789  return false;
790  }
792  (void *) context);
793 }
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
#define NULL
Definition: c.h:229
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1865