PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 (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

#define RULE_DISABLED   'D'

Definition at line 24 of file rewriteDefine.h.

Referenced by ATExecCmd(), and matchLocks().

#define RULE_FIRES_ALWAYS   'A'

Definition at line 22 of file rewriteDefine.h.

Referenced by ATExecCmd().

#define RULE_FIRES_ON_ORIGIN   'O'

Definition at line 21 of file rewriteDefine.h.

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

#define RULE_FIRES_ON_REPLICA   'R'

Definition at line 23 of file rewriteDefine.h.

Referenced by ATExecCmd(), and matchLocks().

Function Documentation

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

Definition at line 228 of file rewriteDefine.c.

References AccessExclusiveLock, ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, allowSystemTableMods, CatalogTupleUpdate(), checkRuleResultList(), ObjectAddress::classId, CMD_SELECT, CommandCounterIncrement(), Query::commandType, deleteDependencyRecordsFor(), DeleteSystemAttributeTuples(), DROP_RESTRICT, elog, ereport, errcode(), errhint(), errmsg(), ERROR, RewriteRule::event, ForwardScanDirection, getInsertSelectQuery(), GetLatestSnapshot(), GETSTRUCT, GetUserId(), Query::hasModifyingCTE, heap_beginscan(), heap_close, heap_endscan(), heap_freetuple(), heap_getnext(), heap_open(), HeapTupleIsValid, i, InsertRule(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, IsSystemRelation(), lfirst_node, linitial_node, list_length(), NAMEDATALEN, NIL, NoLock, NULL, RuleLock::numLocks, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, PERFORM_DELETION_INTERNAL, performDeletion(), pg_class_ownercheck(), PRS2_NEW_VARNO, PRS2_OLD_VARNO, pstrdup(), RelationData::rd_rel, RelationData::rd_rules, RegisterSnapshot(), relation_has_policies(), RelationDropStorage(), RelationGetDescr, RelationGetRelationName, RelationRelationId, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_VIEW, RELOID, REPLICA_IDENTITY_NOTHING, Query::resultRelation, Query::returningList, RewriteRelationId, RowExclusiveLock, RuleLock::rules, SearchSysCacheCopy1, SetRelationRuleStatus(), HeapTupleData::t_self, Query::targetList, UnregisterSnapshot(), and ViewSelectRuleName.

Referenced by DefineRule(), and DefineViewRules().

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

Definition at line 194 of file rewriteDefine.c.

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

Referenced by ProcessUtilitySlow().

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

Definition at line 833 of file rewriteDefine.c.

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

Referenced by ATExecEnableDisableRule().

835 {
836  Relation pg_rewrite_desc;
837  Oid owningRel = RelationGetRelid(rel);
838  Oid eventRelationOid;
839  HeapTuple ruletup;
840  bool changed = false;
841 
842  /*
843  * Find the rule tuple to change.
844  */
845  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
847  ObjectIdGetDatum(owningRel),
848  PointerGetDatum(rulename));
849  if (!HeapTupleIsValid(ruletup))
850  ereport(ERROR,
851  (errcode(ERRCODE_UNDEFINED_OBJECT),
852  errmsg("rule \"%s\" for relation \"%s\" does not exist",
853  rulename, get_rel_name(owningRel))));
854 
855  /*
856  * Verify that the user has appropriate permissions.
857  */
858  eventRelationOid = ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_class;
859  Assert(eventRelationOid == owningRel);
860  if (!pg_class_ownercheck(eventRelationOid, GetUserId()))
862  get_rel_name(eventRelationOid));
863 
864  /*
865  * Change ev_enabled if it is different from the desired new state.
866  */
867  if (DatumGetChar(((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled) !=
868  fires_when)
869  {
870  ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled =
871  CharGetDatum(fires_when);
872  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
873 
874  changed = true;
875  }
876 
878  HeapTupleGetOid(ruletup), 0);
879 
880  heap_freetuple(ruletup);
881  heap_close(pg_rewrite_desc, RowExclusiveLock);
882 
883  /*
884  * If we changed anything, broadcast a SI inval message to force each
885  * backend (including our own!) to rebuild relation's relcache entry.
886  * Otherwise they will fail to apply the change promptly.
887  */
888  if (changed)
890 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:283
#define PointerGetDatum(X)
Definition: postgres.h:562
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define DatumGetChar(X)
Definition: postgres.h:415
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RewriteRelationId
Definition: pg_rewrite.h:32
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:675
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define CharGetDatum(X)
Definition: postgres.h:422
FormData_pg_rewrite * Form_pg_rewrite
Definition: pg_rewrite.h:53
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1233
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:167
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define RelationGetRelid(relation)
Definition: rel.h:417
ObjectAddress RenameRewriteRule ( RangeVar relation,
const char *  oldName,
const char *  newName 
)

Definition at line 933 of file rewriteDefine.c.

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

Referenced by ExecRenameStmt().

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

Definition at line 776 of file rewriteDefine.c.

References setRuleCheckAsUser_walker().

Referenced by RelationBuildRuleLock().

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