PostgreSQL Source Code  git master
rewriteDefine.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/table.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_rewrite.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/syscache.h"
Include dependency graph for rewriteDefine.c:

Go to the source code of this file.

Functions

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

Function Documentation

◆ checkRuleResultList()

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

Definition at line 506 of file rewriteDefine.c.

508 {
509  ListCell *tllist;
510  int i;
511 
512  /* Only a SELECT may require a column name match. */
513  Assert(isSelect || !requireColumnNameMatch);
514 
515  i = 0;
516  foreach(tllist, targetList)
517  {
518  TargetEntry *tle = (TargetEntry *) lfirst(tllist);
519  Oid tletypid;
520  int32 tletypmod;
521  Form_pg_attribute attr;
522  char *attname;
523 
524  /* resjunk entries may be ignored */
525  if (tle->resjunk)
526  continue;
527  i++;
528  if (i > resultDesc->natts)
529  ereport(ERROR,
530  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
531  isSelect ?
532  errmsg("SELECT rule's target list has too many entries") :
533  errmsg("RETURNING list has too many entries")));
534 
535  attr = TupleDescAttr(resultDesc, i - 1);
536  attname = NameStr(attr->attname);
537 
538  /*
539  * Disallow dropped columns in the relation. This is not really
540  * expected to happen when creating an ON SELECT rule. It'd be
541  * possible if someone tried to convert a relation with dropped
542  * columns to a view, but the only case we care about supporting
543  * table-to-view conversion for is pg_dump, and pg_dump won't do that.
544  *
545  * Unfortunately, the situation is also possible when adding a rule
546  * with RETURNING to a regular table, and rejecting that case is
547  * altogether more annoying. In principle we could support it by
548  * modifying the targetlist to include dummy NULL columns
549  * corresponding to the dropped columns in the tupdesc. However,
550  * places like ruleutils.c would have to be fixed to not process such
551  * entries, and that would take an uncertain and possibly rather large
552  * amount of work. (Note we could not dodge that by marking the dummy
553  * columns resjunk, since it's precisely the non-resjunk tlist columns
554  * that are expected to correspond to table columns.)
555  */
556  if (attr->attisdropped)
557  ereport(ERROR,
558  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
559  isSelect ?
560  errmsg("cannot convert relation containing dropped columns to view") :
561  errmsg("cannot create a RETURNING list for a relation containing dropped columns")));
562 
563  /* Check name match if required; no need for two error texts here */
564  if (requireColumnNameMatch && strcmp(tle->resname, attname) != 0)
565  ereport(ERROR,
566  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
567  errmsg("SELECT rule's target entry %d has different column name from column \"%s\"",
568  i, attname),
569  errdetail("SELECT target entry is named \"%s\".",
570  tle->resname)));
571 
572  /* Check type match. */
573  tletypid = exprType((Node *) tle->expr);
574  if (attr->atttypid != tletypid)
575  ereport(ERROR,
576  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
577  isSelect ?
578  errmsg("SELECT rule's target entry %d has different type from column \"%s\"",
579  i, attname) :
580  errmsg("RETURNING list's entry %d has different type from column \"%s\"",
581  i, attname),
582  isSelect ?
583  errdetail("SELECT target entry has type %s, but column has type %s.",
584  format_type_be(tletypid),
585  format_type_be(attr->atttypid)) :
586  errdetail("RETURNING list entry has type %s, but column has type %s.",
587  format_type_be(tletypid),
588  format_type_be(attr->atttypid))));
589 
590  /*
591  * Allow typmods to be different only if one of them is -1, ie,
592  * "unspecified". This is necessary for cases like "numeric", where
593  * the table will have a filled-in default length but the select
594  * rule's expression will probably have typmod = -1.
595  */
596  tletypmod = exprTypmod((Node *) tle->expr);
597  if (attr->atttypmod != tletypmod &&
598  attr->atttypmod != -1 && tletypmod != -1)
599  ereport(ERROR,
600  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
601  isSelect ?
602  errmsg("SELECT rule's target entry %d has different size from column \"%s\"",
603  i, attname) :
604  errmsg("RETURNING list's entry %d has different size from column \"%s\"",
605  i, attname),
606  isSelect ?
607  errdetail("SELECT target entry has type %s, but column has type %s.",
608  format_type_with_typemod(tletypid, tletypmod),
609  format_type_with_typemod(attr->atttypid,
610  attr->atttypmod)) :
611  errdetail("RETURNING list entry has type %s, but column has type %s.",
612  format_type_with_typemod(tletypid, tletypmod),
613  format_type_with_typemod(attr->atttypid,
614  attr->atttypmod))));
615  }
616 
617  if (i != resultDesc->natts)
618  ereport(ERROR,
619  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
620  isSelect ?
621  errmsg("SELECT rule's target list has too few entries") :
622  errmsg("RETURNING list has too few entries")));
623 }
#define NameStr(name)
Definition: c.h:749
signed int int32
Definition: c.h:497
#define Assert(condition)
Definition: c.h:861
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:362
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
int i
Definition: isn.c:73
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
NameData attname
Definition: pg_attribute.h:41
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define lfirst(lc)
Definition: pg_list.h:172
unsigned int Oid
Definition: postgres_ext.h:31
Definition: nodes.h:129
Expr * expr
Definition: primnodes.h:2186
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

Referenced by DefineQueryRewrite().

◆ DefineQueryRewrite()

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

Definition at line 224 of file rewriteDefine.c.

231 {
232  Relation event_relation;
233  ListCell *l;
234  Query *query;
235  Oid ruleId = InvalidOid;
236  ObjectAddress address;
237 
238  /*
239  * If we are installing an ON SELECT rule, we had better grab
240  * AccessExclusiveLock to ensure no SELECTs are currently running on the
241  * event relation. For other types of rules, it would be sufficient to
242  * grab ShareRowExclusiveLock to lock out insert/update/delete actions and
243  * to ensure that we lock out current CREATE RULE statements; but because
244  * of race conditions in access to catalog entries, we can't do that yet.
245  *
246  * Note that this lock level should match the one used in DefineRule.
247  */
248  event_relation = table_open(event_relid, AccessExclusiveLock);
249 
250  /*
251  * Verify relation is of a type that rules can sensibly be applied to.
252  * Internal callers can target materialized views, but transformRuleStmt()
253  * blocks them for users. Don't mention them in the error message.
254  */
255  if (event_relation->rd_rel->relkind != RELKIND_RELATION &&
256  event_relation->rd_rel->relkind != RELKIND_MATVIEW &&
257  event_relation->rd_rel->relkind != RELKIND_VIEW &&
258  event_relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
259  ereport(ERROR,
260  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
261  errmsg("relation \"%s\" cannot have rules",
262  RelationGetRelationName(event_relation)),
263  errdetail_relkind_not_supported(event_relation->rd_rel->relkind)));
264 
265  if (!allowSystemTableMods && IsSystemRelation(event_relation))
266  ereport(ERROR,
267  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
268  errmsg("permission denied: \"%s\" is a system catalog",
269  RelationGetRelationName(event_relation))));
270 
271  /*
272  * Check user has permission to apply rules to this relation.
273  */
274  if (!object_ownercheck(RelationRelationId, event_relid, GetUserId()))
275  aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(event_relation->rd_rel->relkind),
276  RelationGetRelationName(event_relation));
277 
278  /*
279  * No rule actions that modify OLD or NEW
280  */
281  foreach(l, action)
282  {
283  query = lfirst_node(Query, l);
284  if (query->resultRelation == 0)
285  continue;
286  /* Don't be fooled by INSERT/SELECT */
287  if (query != getInsertSelectQuery(query, NULL))
288  continue;
289  if (query->resultRelation == PRS2_OLD_VARNO)
290  ereport(ERROR,
291  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
292  errmsg("rule actions on OLD are not implemented"),
293  errhint("Use views or triggers instead.")));
294  if (query->resultRelation == PRS2_NEW_VARNO)
295  ereport(ERROR,
296  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
297  errmsg("rule actions on NEW are not implemented"),
298  errhint("Use triggers instead.")));
299  }
300 
301  if (event_type == CMD_SELECT)
302  {
303  /*
304  * Rules ON SELECT are restricted to view definitions
305  *
306  * So this had better be a view, ...
307  */
308  if (event_relation->rd_rel->relkind != RELKIND_VIEW &&
309  event_relation->rd_rel->relkind != RELKIND_MATVIEW)
310  ereport(ERROR,
311  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
312  errmsg("relation \"%s\" cannot have ON SELECT rules",
313  RelationGetRelationName(event_relation)),
314  errdetail_relkind_not_supported(event_relation->rd_rel->relkind)));
315 
316  /*
317  * ... there cannot be INSTEAD NOTHING, ...
318  */
319  if (action == NIL)
320  ereport(ERROR,
321  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
322  errmsg("INSTEAD NOTHING rules on SELECT are not implemented"),
323  errhint("Use views instead.")));
324 
325  /*
326  * ... there cannot be multiple actions, ...
327  */
328  if (list_length(action) > 1)
329  ereport(ERROR,
330  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
331  errmsg("multiple actions for rules on SELECT are not implemented")));
332 
333  /*
334  * ... the one action must be a SELECT, ...
335  */
336  query = linitial_node(Query, action);
337  if (!is_instead ||
338  query->commandType != CMD_SELECT)
339  ereport(ERROR,
340  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
341  errmsg("rules on SELECT must have action INSTEAD SELECT")));
342 
343  /*
344  * ... it cannot contain data-modifying WITH ...
345  */
346  if (query->hasModifyingCTE)
347  ereport(ERROR,
348  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
349  errmsg("rules on SELECT must not contain data-modifying statements in WITH")));
350 
351  /*
352  * ... there can be no rule qual, ...
353  */
354  if (event_qual != NULL)
355  ereport(ERROR,
356  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
357  errmsg("event qualifications are not implemented for rules on SELECT")));
358 
359  /*
360  * ... the targetlist of the SELECT action must exactly match the
361  * event relation, ...
362  */
364  RelationGetDescr(event_relation),
365  true,
366  event_relation->rd_rel->relkind !=
367  RELKIND_MATVIEW);
368 
369  /*
370  * ... there must not be another ON SELECT rule already ...
371  */
372  if (!replace && event_relation->rd_rules != NULL)
373  {
374  int i;
375 
376  for (i = 0; i < event_relation->rd_rules->numLocks; i++)
377  {
378  RewriteRule *rule;
379 
380  rule = event_relation->rd_rules->rules[i];
381  if (rule->event == CMD_SELECT)
382  ereport(ERROR,
383  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
384  errmsg("\"%s\" is already a view",
385  RelationGetRelationName(event_relation))));
386  }
387  }
388 
389  /*
390  * ... and finally the rule must be named _RETURN.
391  */
392  if (strcmp(rulename, ViewSelectRuleName) != 0)
393  {
394  /*
395  * In versions before 7.3, the expected name was _RETviewname. For
396  * backwards compatibility with old pg_dump output, accept that
397  * and silently change it to _RETURN. Since this is just a quick
398  * backwards-compatibility hack, limit the number of characters
399  * checked to a few less than NAMEDATALEN; this saves having to
400  * worry about where a multibyte character might have gotten
401  * truncated.
402  */
403  if (strncmp(rulename, "_RET", 4) != 0 ||
404  strncmp(rulename + 4, RelationGetRelationName(event_relation),
405  NAMEDATALEN - 4 - 4) != 0)
406  ereport(ERROR,
407  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
408  errmsg("view rule for \"%s\" must be named \"%s\"",
409  RelationGetRelationName(event_relation),
411  rulename = pstrdup(ViewSelectRuleName);
412  }
413  }
414  else
415  {
416  /*
417  * For non-SELECT rules, a RETURNING list can appear in at most one of
418  * the actions ... and there can't be any RETURNING list at all in a
419  * conditional or non-INSTEAD rule. (Actually, there can be at most
420  * one RETURNING list across all rules on the same event, but it seems
421  * best to enforce that at rule expansion time.) If there is a
422  * RETURNING list, it must match the event relation.
423  */
424  bool haveReturning = false;
425 
426  foreach(l, action)
427  {
428  query = lfirst_node(Query, l);
429 
430  if (!query->returningList)
431  continue;
432  if (haveReturning)
433  ereport(ERROR,
434  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
435  errmsg("cannot have multiple RETURNING lists in a rule")));
436  haveReturning = true;
437  if (event_qual != NULL)
438  ereport(ERROR,
439  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
440  errmsg("RETURNING lists are not supported in conditional rules")));
441  if (!is_instead)
442  ereport(ERROR,
443  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
444  errmsg("RETURNING lists are not supported in non-INSTEAD rules")));
446  RelationGetDescr(event_relation),
447  false, false);
448  }
449 
450  /*
451  * And finally, if it's not an ON SELECT rule then it must *not* be
452  * named _RETURN. This prevents accidentally or maliciously replacing
453  * a view's ON SELECT rule with some other kind of rule.
454  */
455  if (strcmp(rulename, ViewSelectRuleName) == 0)
456  ereport(ERROR,
457  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
458  errmsg("non-view rule for \"%s\" must not be named \"%s\"",
459  RelationGetRelationName(event_relation),
461  }
462 
463  /*
464  * This rule is allowed - prepare to install it.
465  */
466 
467  /* discard rule if it's null action and not INSTEAD; it's a no-op */
468  if (action != NIL || is_instead)
469  {
470  ruleId = InsertRule(rulename,
471  event_type,
472  event_relid,
473  is_instead,
474  event_qual,
475  action,
476  replace);
477 
478  /*
479  * Set pg_class 'relhasrules' field true for event relation.
480  *
481  * Important side effect: an SI notice is broadcast to force all
482  * backends (including me!) to update relcache entries with the new
483  * rule.
484  */
485  SetRelationRuleStatus(event_relid, true);
486  }
487 
488  ObjectAddressSet(address, RewriteRelationId, ruleId);
489 
490  /* Close rel, but keep lock till commit... */
491  table_close(event_relation, NoLock);
492 
493  return address;
494 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2703
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4145
bool IsSystemRelation(Relation relation)
Definition: catalog.c:73
int errhint(const char *fmt,...)
Definition: elog.c:1317
bool allowSystemTableMods
Definition: globals.c:129
#define NoLock
Definition: lockdefs.h:34
#define AccessExclusiveLock
Definition: lockdefs.h:43
char * pstrdup(const char *in)
Definition: mcxt.c:1696
Oid GetUserId(void)
Definition: miscinit.c:514
@ CMD_SELECT
Definition: nodes.h:265
ObjectType get_relkind_objtype(char relkind)
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
#define NAMEDATALEN
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:36
#define PRS2_OLD_VARNO
Definition: primnodes.h:244
#define PRS2_NEW_VARNO
Definition: primnodes.h:245
#define RelationGetDescr(relation)
Definition: rel.h:531
#define RelationGetRelationName(relation)
Definition: rel.h:539
static Oid InsertRule(const char *rulname, int evtype, Oid eventrel_oid, bool evinstead, Node *event_qual, List *action, bool replace)
Definition: rewriteDefine.c:52
static void checkRuleResultList(List *targetList, TupleDesc resultDesc, bool isSelect, bool requireColumnNameMatch)
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:998
void SetRelationRuleStatus(Oid relationId, bool relHasRules)
#define ViewSelectRuleName
List * returningList
Definition: parsenodes.h:200
CmdType commandType
Definition: parsenodes.h:121
List * targetList
Definition: parsenodes.h:193
RuleLock * rd_rules
Definition: rel.h:115
Form_pg_class rd_rel
Definition: rel.h:111
RewriteRule ** rules
Definition: prs2lock.h:43
int numLocks
Definition: prs2lock.h:42
Definition: localtime.c:73
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, generate_unaccent_rules::action, allowSystemTableMods, checkRuleResultList(), CMD_SELECT, Query::commandType, ereport, errcode(), errdetail_relkind_not_supported(), errhint(), errmsg(), ERROR, get_relkind_objtype(), getInsertSelectQuery(), GetUserId(), i, InsertRule(), InvalidOid, IsSystemRelation(), lfirst_node, linitial_node, list_length(), NAMEDATALEN, NIL, NoLock, RuleLock::numLocks, object_ownercheck(), ObjectAddressSet, PRS2_NEW_VARNO, PRS2_OLD_VARNO, pstrdup(), RelationData::rd_rel, RelationData::rd_rules, RelationGetDescr, RelationGetRelationName, Query::returningList, RuleLock::rules, SetRelationRuleStatus(), table_close(), table_open(), Query::targetList, and ViewSelectRuleName.

Referenced by DefineRule(), and DefineViewRules().

◆ DefineRule()

ObjectAddress DefineRule ( RuleStmt stmt,
const char *  queryString 
)

Definition at line 190 of file rewriteDefine.c.

191 {
192  List *actions;
193  Node *whereClause;
194  Oid relId;
195 
196  /* Parse analysis. */
197  transformRuleStmt(stmt, queryString, &actions, &whereClause);
198 
199  /*
200  * Find and lock the relation. Lock level should match
201  * DefineQueryRewrite.
202  */
203  relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
204 
205  /* ... and execute */
206  return DefineQueryRewrite(stmt->rulename,
207  relId,
208  whereClause,
209  stmt->event,
210  stmt->instead,
211  stmt->replace,
212  actions);
213 }
#define stmt
Definition: indent_codes.h:59
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:80
void transformRuleStmt(RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
ObjectAddress DefineQueryRewrite(const char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)
Definition: pg_list.h:54

References AccessExclusiveLock, DefineQueryRewrite(), RangeVarGetRelid, stmt, and transformRuleStmt().

Referenced by ProcessUtilitySlow().

◆ EnableDisableRule()

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

Definition at line 691 of file rewriteDefine.c.

693 {
694  Relation pg_rewrite_desc;
695  Oid owningRel = RelationGetRelid(rel);
696  Oid eventRelationOid;
697  HeapTuple ruletup;
698  Form_pg_rewrite ruleform;
699  bool changed = false;
700 
701  /*
702  * Find the rule tuple to change.
703  */
704  pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
705  ruletup = SearchSysCacheCopy2(RULERELNAME,
706  ObjectIdGetDatum(owningRel),
707  PointerGetDatum(rulename));
708  if (!HeapTupleIsValid(ruletup))
709  ereport(ERROR,
710  (errcode(ERRCODE_UNDEFINED_OBJECT),
711  errmsg("rule \"%s\" for relation \"%s\" does not exist",
712  rulename, get_rel_name(owningRel))));
713 
714  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
715 
716  /*
717  * Verify that the user has appropriate permissions.
718  */
719  eventRelationOid = ruleform->ev_class;
720  Assert(eventRelationOid == owningRel);
721  if (!object_ownercheck(RelationRelationId, eventRelationOid, GetUserId()))
723  get_rel_name(eventRelationOid));
724 
725  /*
726  * Change ev_enabled if it is different from the desired new state.
727  */
728  if (DatumGetChar(ruleform->ev_enabled) !=
729  fires_when)
730  {
731  ruleform->ev_enabled = CharGetDatum(fires_when);
732  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
733 
734  changed = true;
735  }
736 
737  InvokeObjectPostAlterHook(RewriteRelationId, ruleform->oid, 0);
738 
739  heap_freetuple(ruletup);
740  table_close(pg_rewrite_desc, RowExclusiveLock);
741 
742  /*
743  * If we changed anything, broadcast a SI inval message to force each
744  * backend (including our own!) to rebuild relation's relcache entry.
745  * Otherwise they will fail to apply the change promptly.
746  */
747  if (changed)
749 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1360
#define RowExclusiveLock
Definition: lockdefs.h:38
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2003
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:52
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static char DatumGetChar(Datum X)
Definition: postgres.h:112
static Datum CharGetDatum(char X)
Definition: postgres.h:122
#define RelationGetRelid(relation)
Definition: rel.h:505
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:93

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

Referenced by ATExecEnableDisableRule().

◆ InsertRule()

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

Definition at line 52 of file rewriteDefine.c.

59 {
60  char *evqual = nodeToString(event_qual);
61  char *actiontree = nodeToString((Node *) action);
62  Datum values[Natts_pg_rewrite];
63  bool nulls[Natts_pg_rewrite] = {0};
64  NameData rname;
65  Relation pg_rewrite_desc;
66  HeapTuple tup,
67  oldtup;
68  Oid rewriteObjectId;
69  ObjectAddress myself,
70  referenced;
71  bool is_update = false;
72 
73  /*
74  * Set up *nulls and *values arrays
75  */
76  namestrcpy(&rname, rulname);
77  values[Anum_pg_rewrite_rulename - 1] = NameGetDatum(&rname);
78  values[Anum_pg_rewrite_ev_class - 1] = ObjectIdGetDatum(eventrel_oid);
79  values[Anum_pg_rewrite_ev_type - 1] = CharGetDatum(evtype + '0');
80  values[Anum_pg_rewrite_ev_enabled - 1] = CharGetDatum(RULE_FIRES_ON_ORIGIN);
81  values[Anum_pg_rewrite_is_instead - 1] = BoolGetDatum(evinstead);
82  values[Anum_pg_rewrite_ev_qual - 1] = CStringGetTextDatum(evqual);
83  values[Anum_pg_rewrite_ev_action - 1] = CStringGetTextDatum(actiontree);
84 
85  /*
86  * Ready to store new pg_rewrite tuple
87  */
88  pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
89 
90  /*
91  * Check to see if we are replacing an existing tuple
92  */
93  oldtup = SearchSysCache2(RULERELNAME,
94  ObjectIdGetDatum(eventrel_oid),
95  PointerGetDatum(rulname));
96 
97  if (HeapTupleIsValid(oldtup))
98  {
99  bool replaces[Natts_pg_rewrite] = {0};
100 
101  if (!replace)
102  ereport(ERROR,
104  errmsg("rule \"%s\" for relation \"%s\" already exists",
105  rulname, get_rel_name(eventrel_oid))));
106 
107  /*
108  * When replacing, we don't need to replace every attribute
109  */
110  replaces[Anum_pg_rewrite_ev_type - 1] = true;
111  replaces[Anum_pg_rewrite_is_instead - 1] = true;
112  replaces[Anum_pg_rewrite_ev_qual - 1] = true;
113  replaces[Anum_pg_rewrite_ev_action - 1] = true;
114 
115  tup = heap_modify_tuple(oldtup, RelationGetDescr(pg_rewrite_desc),
116  values, nulls, replaces);
117 
118  CatalogTupleUpdate(pg_rewrite_desc, &tup->t_self, tup);
119 
120  ReleaseSysCache(oldtup);
121 
122  rewriteObjectId = ((Form_pg_rewrite) GETSTRUCT(tup))->oid;
123  is_update = true;
124  }
125  else
126  {
127  rewriteObjectId = GetNewOidWithIndex(pg_rewrite_desc,
128  RewriteOidIndexId,
129  Anum_pg_rewrite_oid);
130  values[Anum_pg_rewrite_oid - 1] = ObjectIdGetDatum(rewriteObjectId);
131 
132  tup = heap_form_tuple(pg_rewrite_desc->rd_att, values, nulls);
133 
134  CatalogTupleInsert(pg_rewrite_desc, tup);
135  }
136 
137 
138  heap_freetuple(tup);
139 
140  /* If replacing, get rid of old dependencies and make new ones */
141  if (is_update)
142  deleteDependencyRecordsFor(RewriteRelationId, rewriteObjectId, false);
143 
144  /*
145  * Install dependency on rule's relation to ensure it will go away on
146  * relation deletion. If the rule is ON SELECT, make the dependency
147  * implicit --- this prevents deleting a view's SELECT rule. Other kinds
148  * of rules can be AUTO.
149  */
150  myself.classId = RewriteRelationId;
151  myself.objectId = rewriteObjectId;
152  myself.objectSubId = 0;
153 
154  referenced.classId = RelationRelationId;
155  referenced.objectId = eventrel_oid;
156  referenced.objectSubId = 0;
157 
158  recordDependencyOn(&myself, &referenced,
160 
161  /*
162  * Also install dependencies on objects referenced in action and qual.
163  */
164  recordDependencyOnExpr(&myself, (Node *) action, NIL,
166 
167  if (event_qual != NULL)
168  {
169  /* Find query containing OLD/NEW rtable entries */
170  Query *qry = linitial_node(Query, action);
171 
172  qry = getInsertSelectQuery(qry, NULL);
173  recordDependencyOnExpr(&myself, event_qual, qry->rtable,
175  }
176 
177  /* Post creation hook for new rule */
178  InvokeObjectPostCreateHook(RewriteRelationId, rewriteObjectId, 0);
179 
180  table_close(pg_rewrite_desc, RowExclusiveLock);
181 
182  return rewriteObjectId;
183 }
static Datum values[MAXATTR]
Definition: bootstrap.c:150
#define CStringGetTextDatum(s)
Definition: builtins.h:97
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:419
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1553
@ DEPENDENCY_AUTO
Definition: dependency.h:34
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
@ DEPENDENCY_NORMAL
Definition: dependency.h:33
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:233
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
char * nodeToString(const void *obj)
Definition: outfuncs.c:794
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:302
uintptr_t Datum
Definition: postgres.h:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum NameGetDatum(const NameData *X)
Definition: postgres.h:373
#define RULE_FIRES_ON_ORIGIN
Definition: rewriteDefine.h:21
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
List * rtable
Definition: parsenodes.h:170
TupleDesc rd_att
Definition: rel.h:112
Definition: c.h:744
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:232

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

Referenced by DefineQueryRewrite().

◆ RangeVarCallbackForRenameRule()

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

Definition at line 756 of file rewriteDefine.c.

758 {
759  HeapTuple tuple;
760  Form_pg_class form;
761 
762  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
763  if (!HeapTupleIsValid(tuple))
764  return; /* concurrently dropped */
765  form = (Form_pg_class) GETSTRUCT(tuple);
766 
767  /* only tables and views can have rules */
768  if (form->relkind != RELKIND_RELATION &&
769  form->relkind != RELKIND_VIEW &&
770  form->relkind != RELKIND_PARTITIONED_TABLE)
771  ereport(ERROR,
772  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
773  errmsg("relation \"%s\" cannot have rules", rv->relname),
774  errdetail_relkind_not_supported(form->relkind)));
775 
776  if (!allowSystemTableMods && IsSystemClass(relid, form))
777  ereport(ERROR,
778  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
779  errmsg("permission denied: \"%s\" is a system catalog",
780  rv->relname)));
781 
782  /* you must own the table to rename one of its rules */
783  if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
785 
786  ReleaseSysCache(tuple);
787 }
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:85
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
char * relname
Definition: primnodes.h:82
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

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

Referenced by RenameRewriteRule().

◆ RenameRewriteRule()

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

Definition at line 793 of file rewriteDefine.c.

795 {
796  Oid relid;
797  Relation targetrel;
798  Relation pg_rewrite_desc;
799  HeapTuple ruletup;
800  Form_pg_rewrite ruleform;
801  Oid ruleOid;
802  ObjectAddress address;
803 
804  /*
805  * Look up name, check permissions, and acquire lock (which we will NOT
806  * release until end of transaction).
807  */
809  0,
811  NULL);
812 
813  /* Have lock already, so just need to build relcache entry. */
814  targetrel = relation_open(relid, NoLock);
815 
816  /* Prepare to modify pg_rewrite */
817  pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
818 
819  /* Fetch the rule's entry (it had better exist) */
820  ruletup = SearchSysCacheCopy2(RULERELNAME,
821  ObjectIdGetDatum(relid),
822  PointerGetDatum(oldName));
823  if (!HeapTupleIsValid(ruletup))
824  ereport(ERROR,
825  (errcode(ERRCODE_UNDEFINED_OBJECT),
826  errmsg("rule \"%s\" for relation \"%s\" does not exist",
827  oldName, RelationGetRelationName(targetrel))));
828  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
829  ruleOid = ruleform->oid;
830 
831  /* rule with the new name should not already exist */
832  if (IsDefinedRewriteRule(relid, newName))
833  ereport(ERROR,
835  errmsg("rule \"%s\" for relation \"%s\" already exists",
836  newName, RelationGetRelationName(targetrel))));
837 
838  /*
839  * We disallow renaming ON SELECT rules, because they should always be
840  * named "_RETURN".
841  */
842  if (ruleform->ev_type == CMD_SELECT + '0')
843  ereport(ERROR,
844  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
845  errmsg("renaming an ON SELECT rule is not allowed")));
846 
847  /* OK, do the update */
848  namestrcpy(&(ruleform->rulename), newName);
849 
850  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
851 
852  InvokeObjectPostAlterHook(RewriteRelationId, ruleOid, 0);
853 
854  heap_freetuple(ruletup);
855  table_close(pg_rewrite_desc, RowExclusiveLock);
856 
857  /*
858  * Invalidate relation's relcache entry so that other backends (and this
859  * one too!) are sent SI message to make them rebuild relcache entries.
860  * (Ideally this should happen automatically...)
861  */
862  CacheInvalidateRelcache(targetrel);
863 
864  ObjectAddressSet(address, RewriteRelationId, ruleOid);
865 
866  /*
867  * Close rel, but keep exclusive lock!
868  */
869  relation_close(targetrel, NoLock);
870 
871  return address;
872 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:426
static void RangeVarCallbackForRenameRule(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName)
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47

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

Referenced by ExecRenameStmt().

◆ setRuleCheckAsUser()

void setRuleCheckAsUser ( Node node,
Oid  userid 
)

Definition at line 631 of file rewriteDefine.c.

632 {
633  (void) setRuleCheckAsUser_walker(node, &userid);
634 }
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)

References setRuleCheckAsUser_walker().

Referenced by get_row_security_policies(), and RelationBuildRuleLock().

◆ setRuleCheckAsUser_Query()

static void setRuleCheckAsUser_Query ( Query qry,
Oid  userid 
)
static

Definition at line 651 of file rewriteDefine.c.

652 {
653  ListCell *l;
654 
655  /* Set in all RTEPermissionInfos for this query. */
656  foreach(l, qry->rteperminfos)
657  {
659 
660  perminfo->checkAsUser = userid;
661  }
662 
663  /* Now recurse to any subquery RTEs */
664  foreach(l, qry->rtable)
665  {
666  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
667 
668  if (rte->rtekind == RTE_SUBQUERY)
669  setRuleCheckAsUser_Query(rte->subquery, userid);
670  }
671 
672  /* Recurse into subquery-in-WITH */
673  foreach(l, qry->cteList)
674  {
675  CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
676 
678  }
679 
680  /* If there are sublinks, search for them and process their RTEs */
681  if (qry->hasSubLinks)
682  query_tree_walker(qry, setRuleCheckAsUser_walker, (void *) &userid,
684 }
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:158
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:24
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
List * cteList
Definition: parsenodes.h:168
Query * subquery
Definition: parsenodes.h:1104
RTEKind rtekind
Definition: parsenodes.h:1047

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

Referenced by setRuleCheckAsUser_walker().

◆ setRuleCheckAsUser_walker()

static bool setRuleCheckAsUser_walker ( Node node,
Oid context 
)
static

Definition at line 637 of file rewriteDefine.c.

638 {
639  if (node == NULL)
640  return false;
641  if (IsA(node, Query))
642  {
644  return false;
645  }
647  (void *) context);
648 }
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
tree context
Definition: radixtree.h:1835

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

Referenced by setRuleCheckAsUser(), and setRuleCheckAsUser_Query().