PostgreSQL Source Code  git master
rewriteDefine.h File Reference
Include dependency graph for rewriteDefine.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define RULE_FIRES_ON_ORIGIN   'O'
 
#define RULE_FIRES_ALWAYS   'A'
 
#define RULE_FIRES_ON_REPLICA   'R'
 
#define RULE_DISABLED   'D'
 

Functions

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)
 
ObjectAddress RenameRewriteRule (RangeVar *relation, const char *oldName, const char *newName)
 
void setRuleCheckAsUser (Node *node, Oid userid)
 
void EnableDisableRule (Relation rel, const char *rulename, char fires_when)
 

Macro Definition Documentation

◆ RULE_DISABLED

#define RULE_DISABLED   'D'

Definition at line 24 of file rewriteDefine.h.

Referenced by ATExecCmd(), and matchLocks().

◆ RULE_FIRES_ALWAYS

#define RULE_FIRES_ALWAYS   'A'

Definition at line 22 of file rewriteDefine.h.

Referenced by ATExecCmd().

◆ RULE_FIRES_ON_ORIGIN

#define RULE_FIRES_ON_ORIGIN   'O'

Definition at line 21 of file rewriteDefine.h.

Referenced by ATExecCmd(), InsertRule(), and matchLocks().

◆ RULE_FIRES_ON_REPLICA

#define RULE_FIRES_ON_REPLICA   'R'

Definition at line 23 of file rewriteDefine.h.

Referenced by ATExecCmd(), and matchLocks().

Function Documentation

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

References AccessExclusiveLock, 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, ExecDropSingleTupleTableSlot(), ForwardScanDirection, get_relkind_objtype(), getInsertSelectQuery(), GetLatestSnapshot(), GETSTRUCT, GetUserId(), Query::hasModifyingCTE, heap_freetuple(), HeapTupleIsValid, i, InsertRule(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, IsSystemRelation(), lfirst_node, linitial_node, list_length(), NAMEDATALEN, NIL, NoLock, RuleLock::numLocks, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, PERFORM_DELETION_INTERNAL, performDeletion(), pg_class_ownercheck(), PRS2_NEW_VARNO, PRS2_OLD_VARNO, pstrdup(), RelationData::rd_rel, RelationData::rd_rules, RegisterSnapshot(), relation_has_policies(), RelationDropStorage(), RelationGetDescr, RelationGetRelationName, RELOID, Query::resultRelation, Query::returningList, RowExclusiveLock, RuleLock::rules, SearchSysCacheCopy1, SetRelationRuleStatus(), HeapTupleData::t_self, table_beginscan(), table_close(), table_endscan(), table_open(), table_scan_getnextslot(), table_slot_create(), Query::targetList, UnregisterSnapshot(), and ViewSelectRuleName.

Referenced by DefineRule(), and DefineViewRules().

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

◆ DefineRule()

ObjectAddress DefineRule ( RuleStmt stmt,
const char *  queryString 
)

Definition at line 198 of file rewriteDefine.c.

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

Referenced by ProcessUtilitySlow().

199 {
200  List *actions;
201  Node *whereClause;
202  Oid relId;
203 
204  /* Parse analysis. */
205  transformRuleStmt(stmt, queryString, &actions, &whereClause);
206 
207  /*
208  * Find and lock the relation. Lock level should match
209  * DefineQueryRewrite.
210  */
211  relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
212 
213  /* ... and execute */
214  return DefineQueryRewrite(stmt->rulename,
215  relId,
216  whereClause,
217  stmt->event,
218  stmt->instead,
219  stmt->replace,
220  actions);
221 }
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:78
Definition: nodes.h:528
unsigned int Oid
Definition: postgres_ext.h:31
bool instead
Definition: parsenodes.h:3019
bool replace
Definition: parsenodes.h:3021
char * rulename
Definition: parsenodes.h:3016
CmdType event
Definition: parsenodes.h:3018
#define AccessExclusiveLock
Definition: lockdefs.h:45
RangeVar * relation
Definition: parsenodes.h:3015
Definition: pg_list.h:50
ObjectAddress DefineQueryRewrite(const char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)
void transformRuleStmt(RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)

◆ EnableDisableRule()

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

Definition at line 845 of file rewriteDefine.c.

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

Referenced by ATExecEnableDisableRule().

847 {
848  Relation pg_rewrite_desc;
849  Oid owningRel = RelationGetRelid(rel);
850  Oid eventRelationOid;
851  HeapTuple ruletup;
852  Form_pg_rewrite ruleform;
853  bool changed = false;
854 
855  /*
856  * Find the rule tuple to change.
857  */
858  pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
860  ObjectIdGetDatum(owningRel),
861  PointerGetDatum(rulename));
862  if (!HeapTupleIsValid(ruletup))
863  ereport(ERROR,
864  (errcode(ERRCODE_UNDEFINED_OBJECT),
865  errmsg("rule \"%s\" for relation \"%s\" does not exist",
866  rulename, get_rel_name(owningRel))));
867 
868  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
869 
870  /*
871  * Verify that the user has appropriate permissions.
872  */
873  eventRelationOid = ruleform->ev_class;
874  Assert(eventRelationOid == owningRel);
875  if (!pg_class_ownercheck(eventRelationOid, GetUserId()))
877  get_rel_name(eventRelationOid));
878 
879  /*
880  * Change ev_enabled if it is different from the desired new state.
881  */
882  if (DatumGetChar(ruleform->ev_enabled) !=
883  fires_when)
884  {
885  ruleform->ev_enabled = CharGetDatum(fires_when);
886  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
887 
888  changed = true;
889  }
890 
891  InvokeObjectPostAlterHook(RewriteRelationId, ruleform->oid, 0);
892 
893  heap_freetuple(ruletup);
894  table_close(pg_rewrite_desc, RowExclusiveLock);
895 
896  /*
897  * If we changed anything, broadcast a SI inval message to force each
898  * backend (including our own!) to rebuild relation's relcache entry.
899  * Otherwise they will fail to apply the change promptly.
900  */
901  if (changed)
903 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:476
#define PointerGetDatum(X)
Definition: postgres.h:556
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1947
int errcode(int sqlerrcode)
Definition: elog.c:704
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3297
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define DatumGetChar(X)
Definition: postgres.h:409
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:792
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4690
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
#define CharGetDatum(X)
Definition: postgres.h:416
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:52
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
int errmsg(const char *fmt,...)
Definition: elog.c:915
ObjectType get_relkind_objtype(char relkind)
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1872
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ RenameRewriteRule()

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

Definition at line 946 of file rewriteDefine.c.

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

Referenced by ExecRenameStmt().

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

◆ setRuleCheckAsUser()

void setRuleCheckAsUser ( Node node,
Oid  userid 
)

Definition at line 788 of file rewriteDefine.c.

References setRuleCheckAsUser_walker().

Referenced by get_row_security_policies(), and RelationBuildRuleLock().

789 {
790  (void) setRuleCheckAsUser_walker(node, &userid);
791 }
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)