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  if (event_relation->rd_rel->relispartition)
432  ereport(ERROR,
433  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
434  errmsg("could not convert partition \"%s\" to a view",
435  RelationGetRelationName(event_relation))));
436 
437  snapshot = RegisterSnapshot(GetLatestSnapshot());
438  scanDesc = heap_beginscan(event_relation, snapshot, 0, NULL);
439  if (heap_getnext(scanDesc, ForwardScanDirection) != NULL)
440  ereport(ERROR,
441  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
442  errmsg("could not convert table \"%s\" to a view because it is not empty",
443  RelationGetRelationName(event_relation))));
444  heap_endscan(scanDesc);
445  UnregisterSnapshot(snapshot);
446 
447  if (event_relation->rd_rel->relhastriggers)
448  ereport(ERROR,
449  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
450  errmsg("could not convert table \"%s\" to a view because it has triggers",
451  RelationGetRelationName(event_relation)),
452  errhint("In particular, the table cannot be involved in any foreign key relationships.")));
453 
454  if (event_relation->rd_rel->relhasindex)
455  ereport(ERROR,
456  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
457  errmsg("could not convert table \"%s\" to a view because it has indexes",
458  RelationGetRelationName(event_relation))));
459 
460  if (event_relation->rd_rel->relhassubclass)
461  ereport(ERROR,
462  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
463  errmsg("could not convert table \"%s\" to a view because it has child tables",
464  RelationGetRelationName(event_relation))));
465 
466  if (event_relation->rd_rel->relrowsecurity)
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 enabled",
470  RelationGetRelationName(event_relation))));
471 
472  if (relation_has_policies(event_relation))
473  ereport(ERROR,
474  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
475  errmsg("could not convert table \"%s\" to a view because it has row security policies",
476  RelationGetRelationName(event_relation))));
477 
478  RelisBecomingView = true;
479  }
480  }
481  else
482  {
483  /*
484  * For non-SELECT rules, a RETURNING list can appear in at most one of
485  * the actions ... and there can't be any RETURNING list at all in a
486  * conditional or non-INSTEAD rule. (Actually, there can be at most
487  * one RETURNING list across all rules on the same event, but it seems
488  * best to enforce that at rule expansion time.) If there is a
489  * RETURNING list, it must match the event relation.
490  */
491  bool haveReturning = false;
492 
493  foreach(l, action)
494  {
495  query = lfirst_node(Query, l);
496 
497  if (!query->returningList)
498  continue;
499  if (haveReturning)
500  ereport(ERROR,
501  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
502  errmsg("cannot have multiple RETURNING lists in a rule")));
503  haveReturning = true;
504  if (event_qual != NULL)
505  ereport(ERROR,
506  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
507  errmsg("RETURNING lists are not supported in conditional rules")));
508  if (!is_instead)
509  ereport(ERROR,
510  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
511  errmsg("RETURNING lists are not supported in non-INSTEAD rules")));
513  RelationGetDescr(event_relation),
514  false, false);
515  }
516  }
517 
518  /*
519  * This rule is allowed - prepare to install it.
520  */
521 
522  /* discard rule if it's null action and not INSTEAD; it's a no-op */
523  if (action != NIL || is_instead)
524  {
525  ruleId = InsertRule(rulename,
526  event_type,
527  event_relid,
528  is_instead,
529  event_qual,
530  action,
531  replace);
532 
533  /*
534  * Set pg_class 'relhasrules' field TRUE for event relation.
535  *
536  * Important side effect: an SI notice is broadcast to force all
537  * backends (including me!) to update relcache entries with the new
538  * rule.
539  */
540  SetRelationRuleStatus(event_relid, true);
541  }
542 
543  /* ---------------------------------------------------------------------
544  * If the relation is becoming a view:
545  * - delete the associated storage files
546  * - get rid of any system attributes in pg_attribute; a view shouldn't
547  * have any of those
548  * - remove the toast table; there is no need for it anymore, and its
549  * presence would make vacuum slightly more complicated
550  * - set relkind to RELKIND_VIEW, and adjust other pg_class fields
551  * to be appropriate for a view
552  *
553  * NB: we had better have AccessExclusiveLock to do this ...
554  * ---------------------------------------------------------------------
555  */
556  if (RelisBecomingView)
557  {
558  Relation relationRelation;
559  Oid toastrelid;
560  HeapTuple classTup;
561  Form_pg_class classForm;
562 
563  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
564  toastrelid = event_relation->rd_rel->reltoastrelid;
565 
566  /* drop storage while table still looks like a table */
567  RelationDropStorage(event_relation);
568  DeleteSystemAttributeTuples(event_relid);
569 
570  /*
571  * Drop the toast table if any. (This won't take care of updating the
572  * toast fields in the relation's own pg_class entry; we handle that
573  * below.)
574  */
575  if (OidIsValid(toastrelid))
576  {
577  ObjectAddress toastobject;
578 
579  /*
580  * Delete the dependency of the toast relation on the main
581  * relation so we can drop the former without dropping the latter.
582  */
584  false);
585 
586  /* Make deletion of dependency record visible */
588 
589  /* Now drop toast table, including its index */
590  toastobject.classId = RelationRelationId;
591  toastobject.objectId = toastrelid;
592  toastobject.objectSubId = 0;
593  performDeletion(&toastobject, DROP_RESTRICT,
595  }
596 
597  /*
598  * SetRelationRuleStatus may have updated the pg_class row, so we must
599  * advance the command counter before trying to update it again.
600  */
602 
603  /*
604  * Fix pg_class entry to look like a normal view's, including setting
605  * the correct relkind and removal of reltoastrelid of the toast table
606  * we potentially removed above.
607  */
608  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(event_relid));
609  if (!HeapTupleIsValid(classTup))
610  elog(ERROR, "cache lookup failed for relation %u", event_relid);
611  classForm = (Form_pg_class) GETSTRUCT(classTup);
612 
613  classForm->reltablespace = InvalidOid;
614  classForm->relpages = 0;
615  classForm->reltuples = 0;
616  classForm->relallvisible = 0;
617  classForm->reltoastrelid = InvalidOid;
618  classForm->relhasindex = false;
619  classForm->relkind = RELKIND_VIEW;
620  classForm->relhasoids = false;
621  classForm->relhaspkey = false;
622  classForm->relfrozenxid = InvalidTransactionId;
623  classForm->relminmxid = InvalidMultiXactId;
624  classForm->relreplident = REPLICA_IDENTITY_NOTHING;
625 
626  CatalogTupleUpdate(relationRelation, &classTup->t_self, classTup);
627 
628  heap_freetuple(classTup);
629  heap_close(relationRelation, RowExclusiveLock);
630  }
631 
632  ObjectAddressSet(address, RewriteRelationId, ruleId);
633 
634  /* Close rel, but keep lock till commit... */
635  heap_close(event_relation, NoLock);
636 
637  return address;
638 }
#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:63
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:863
#define RelationGetDescr(relation)
Definition: rel.h:428
Oid GetUserId(void)
Definition: miscinit.c:284
#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:436
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:905
#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:112
#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:379
#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:45
bool relation_has_policies(Relation rel)
Definition: policy.c:1363
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:2869
bool replace
Definition: parsenodes.h:2871
char * rulename
Definition: parsenodes.h:2866
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:2868
#define AccessExclusiveLock
Definition: lockdefs.h:45
RangeVar * relation
Definition: parsenodes.h:2865
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 839 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().

841 {
842  Relation pg_rewrite_desc;
843  Oid owningRel = RelationGetRelid(rel);
844  Oid eventRelationOid;
845  HeapTuple ruletup;
846  bool changed = false;
847 
848  /*
849  * Find the rule tuple to change.
850  */
851  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
853  ObjectIdGetDatum(owningRel),
854  PointerGetDatum(rulename));
855  if (!HeapTupleIsValid(ruletup))
856  ereport(ERROR,
857  (errcode(ERRCODE_UNDEFINED_OBJECT),
858  errmsg("rule \"%s\" for relation \"%s\" does not exist",
859  rulename, get_rel_name(owningRel))));
860 
861  /*
862  * Verify that the user has appropriate permissions.
863  */
864  eventRelationOid = ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_class;
865  Assert(eventRelationOid == owningRel);
866  if (!pg_class_ownercheck(eventRelationOid, GetUserId()))
868  get_rel_name(eventRelationOid));
869 
870  /*
871  * Change ev_enabled if it is different from the desired new state.
872  */
873  if (DatumGetChar(((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled) !=
874  fires_when)
875  {
876  ((Form_pg_rewrite) GETSTRUCT(ruletup))->ev_enabled =
877  CharGetDatum(fires_when);
878  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
879 
880  changed = true;
881  }
882 
884  HeapTupleGetOid(ruletup), 0);
885 
886  heap_freetuple(ruletup);
887  heap_close(pg_rewrite_desc, RowExclusiveLock);
888 
889  /*
890  * If we changed anything, broadcast a SI inval message to force each
891  * backend (including our own!) to rebuild relation's relcache entry.
892  * Otherwise they will fail to apply the change promptly.
893  */
894  if (changed)
896 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:284
#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:416
ObjectAddress RenameRewriteRule ( RangeVar relation,
const char *  oldName,
const char *  newName 
)

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

941 {
942  Oid relid;
943  Relation targetrel;
944  Relation pg_rewrite_desc;
945  HeapTuple ruletup;
946  Form_pg_rewrite ruleform;
947  Oid ruleOid;
948  ObjectAddress address;
949 
950  /*
951  * Look up name, check permissions, and acquire lock (which we will NOT
952  * release until end of transaction).
953  */
955  false, false,
957  NULL);
958 
959  /* Have lock already, so just need to build relcache entry. */
960  targetrel = relation_open(relid, NoLock);
961 
962  /* Prepare to modify pg_rewrite */
963  pg_rewrite_desc = heap_open(RewriteRelationId, RowExclusiveLock);
964 
965  /* Fetch the rule's entry (it had better exist) */
967  ObjectIdGetDatum(relid),
968  PointerGetDatum(oldName));
969  if (!HeapTupleIsValid(ruletup))
970  ereport(ERROR,
971  (errcode(ERRCODE_UNDEFINED_OBJECT),
972  errmsg("rule \"%s\" for relation \"%s\" does not exist",
973  oldName, RelationGetRelationName(targetrel))));
974  ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
975  ruleOid = HeapTupleGetOid(ruletup);
976 
977  /* rule with the new name should not already exist */
978  if (IsDefinedRewriteRule(relid, newName))
979  ereport(ERROR,
981  errmsg("rule \"%s\" for relation \"%s\" already exists",
982  newName, RelationGetRelationName(targetrel))));
983 
984  /*
985  * We disallow renaming ON SELECT rules, because they should always be
986  * named "_RETURN".
987  */
988  if (ruleform->ev_type == CMD_SELECT + '0')
989  ereport(ERROR,
990  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
991  errmsg("renaming an ON SELECT rule is not allowed")));
992 
993  /* OK, do the update */
994  namestrcpy(&(ruleform->rulename), newName);
995 
996  CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
997 
998  heap_freetuple(ruletup);
999  heap_close(pg_rewrite_desc, RowExclusiveLock);
1000 
1001  /*
1002  * Invalidate relation's relcache entry so that other backends (and this
1003  * one too!) are sent SI message to make them rebuild relcache entries.
1004  * (Ideally this should happen automatically...)
1005  */
1006  CacheInvalidateRelcache(targetrel);
1007 
1008  ObjectAddressSet(address, RewriteRelationId, ruleOid);
1009 
1010  /*
1011  * Close rel, but keep exclusive lock!
1012  */
1013  relation_close(targetrel, NoLock);
1014 
1015  return address;
1016 }
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:216
#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:436
#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:45
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:32
void setRuleCheckAsUser ( Node node,
Oid  userid 
)

Definition at line 782 of file rewriteDefine.c.

References setRuleCheckAsUser_walker().

Referenced by RelationBuildRuleLock().

783 {
784  (void) setRuleCheckAsUser_walker(node, &userid);
785 }
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)