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

Go to the source code of this file.

Functions

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

Function Documentation

◆ checkRuleResultList()

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

Definition at line 513 of file rewriteDefine.c.

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

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

198 {
199  List *actions;
200  Node *whereClause;
201  Oid relId;
202 
203  /* Parse analysis. */
204  transformRuleStmt(stmt, queryString, &actions, &whereClause);
205 
206  /*
207  * Find and lock the relation. Lock level should match
208  * DefineQueryRewrite.
209  */
210  relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
211 
212  /* ... and execute */
213  return DefineQueryRewrite(stmt->rulename,
214  relId,
215  whereClause,
216  stmt->event,
217  stmt->instead,
218  stmt->replace,
219  actions);
220 }
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
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:52
char * rulename
Definition: parsenodes.h:3222
bool instead
Definition: parsenodes.h:3225
RangeVar * relation
Definition: parsenodes.h:3221
bool replace
Definition: parsenodes.h:3227
CmdType event
Definition: parsenodes.h:3224

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

Referenced by ProcessUtilitySlow().

◆ EnableDisableRule()

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

Definition at line 702 of file rewriteDefine.c.

704 {
705  Relation pg_rewrite_desc;
706  Oid owningRel = RelationGetRelid(rel);
707  Oid eventRelationOid;
708  HeapTuple ruletup;
709  Form_pg_rewrite ruleform;
710  bool changed = false;
711 
712  /*
713  * Find the rule tuple to change.
714  */
715  pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
717  ObjectIdGetDatum(owningRel),
718  PointerGetDatum(rulename));
719  if (!HeapTupleIsValid(ruletup))
720  ereport(ERROR,
721  (errcode(ERRCODE_UNDEFINED_OBJECT),
722  errmsg("rule \"%s\" for relation \"%s\" does not exist",
723  rulename, get_rel_name(owningRel))));
724 
725  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
726 
727  /*
728  * Verify that the user has appropriate permissions.
729  */
730  eventRelationOid = ruleform->ev_class;
731  Assert(eventRelationOid == owningRel);
732  if (!object_ownercheck(RelationRelationId, eventRelationOid, GetUserId()))
734  get_rel_name(eventRelationOid));
735 
736  /*
737  * Change ev_enabled if it is different from the desired new state.
738  */
739  if (DatumGetChar(ruleform->ev_enabled) !=
740  fires_when)
741  {
742  ruleform->ev_enabled = CharGetDatum(fires_when);
743  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
744 
745  changed = true;
746  }
747 
748  InvokeObjectPostAlterHook(RewriteRelationId, ruleform->oid, 0);
749 
750  heap_freetuple(ruletup);
751  table_close(pg_rewrite_desc, RowExclusiveLock);
752 
753  /*
754  * If we changed anything, broadcast a SI inval message to force each
755  * backend (including our own!) to rebuild relation's relcache entry.
756  * Otherwise they will fail to apply the change promptly.
757  */
758  if (changed)
760 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1363
#define RowExclusiveLock
Definition: lockdefs.h:38
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910
#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:670
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static char DatumGetChar(Datum X)
Definition: postgres.h:460
static Datum CharGetDatum(char X)
Definition: postgres.h:470
#define RelationGetRelid(relation)
Definition: rel.h:501
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:181
@ RULERELNAME
Definition: syscache.h:92

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, RULERELNAME, 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 59 of file rewriteDefine.c.

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

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, RULERELNAME, 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 767 of file rewriteDefine.c.

769 {
770  HeapTuple tuple;
771  Form_pg_class form;
772 
773  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
774  if (!HeapTupleIsValid(tuple))
775  return; /* concurrently dropped */
776  form = (Form_pg_class) GETSTRUCT(tuple);
777 
778  /* only tables and views can have rules */
779  if (form->relkind != RELKIND_RELATION &&
780  form->relkind != RELKIND_VIEW &&
781  form->relkind != RELKIND_PARTITIONED_TABLE)
782  ereport(ERROR,
783  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
784  errmsg("relation \"%s\" cannot have rules", rv->relname),
785  errdetail_relkind_not_supported(form->relkind)));
786 
787  if (!allowSystemTableMods && IsSystemClass(relid, form))
788  ereport(ERROR,
789  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
790  errmsg("permission denied: \"%s\" is a system catalog",
791  rv->relname)));
792 
793  /* you must own the table to rename one of its rules */
794  if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
796 
797  ReleaseSysCache(tuple);
798 }
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:87
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
char * relname
Definition: primnodes.h:77
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ RELOID
Definition: syscache.h:89

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, RELOID, and SearchSysCache1().

Referenced by RenameRewriteRule().

◆ RenameRewriteRule()

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

Definition at line 804 of file rewriteDefine.c.

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

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

Referenced by ExecRenameStmt().

◆ setRuleCheckAsUser()

void setRuleCheckAsUser ( Node node,
Oid  userid 
)

Definition at line 645 of file rewriteDefine.c.

646 {
647  (void) setRuleCheckAsUser_walker(node, &userid);
648 }
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 665 of file rewriteDefine.c.

666 {
667  ListCell *l;
668 
669  /* Set all the RTEs in this query node */
670  foreach(l, qry->rtable)
671  {
672  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
673 
674  if (rte->rtekind == RTE_SUBQUERY)
675  {
676  /* Recurse into subquery in FROM */
677  setRuleCheckAsUser_Query(rte->subquery, userid);
678  }
679  else
680  rte->checkAsUser = userid;
681  }
682 
683  /* Recurse into subquery-in-WITH */
684  foreach(l, qry->cteList)
685  {
686  CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
687 
689  }
690 
691  /* If there are sublinks, search for them and process their RTEs */
692  if (qry->hasSubLinks)
693  query_tree_walker(qry, setRuleCheckAsUser_walker, (void *) &userid,
695 }
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:24
#define castNode(_type_, nodeptr)
Definition: nodes.h:186
@ RTE_SUBQUERY
Definition: parsenodes.h:1012
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
List * cteList
Definition: parsenodes.h:153
bool hasSubLinks
Definition: parsenodes.h:144
Query * subquery
Definition: parsenodes.h:1065
RTEKind rtekind
Definition: parsenodes.h:1030

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().

◆ setRuleCheckAsUser_walker()

static bool setRuleCheckAsUser_walker ( Node node,
Oid context 
)
static

Definition at line 651 of file rewriteDefine.c.

652 {
653  if (node == NULL)
654  return false;
655  if (IsA(node, Query))
656  {
657  setRuleCheckAsUser_Query((Query *) node, *context);
658  return false;
659  }
661  (void *) context);
662 }
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define IsA(nodeptr, _type_)
Definition: nodes.h:168

References expression_tree_walker, IsA, and setRuleCheckAsUser_Query().

Referenced by setRuleCheckAsUser(), and setRuleCheckAsUser_Query().