1/*-------------------------------------------------------------------------
4 * routines for defining a rewrite rule
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/rewrite/rewriteDefine.c
13 *-------------------------------------------------------------------------
41 bool isSelect,
bool requireColumnNameMatch);
48 * takes the arguments and inserts them as a row into the system
49 * relation "pg_rewrite"
63 bool nulls[Natts_pg_rewrite] = {0};
71 bool is_update =
false;
74 * Set up *nulls and *values arrays
86 * Ready to store new pg_rewrite tuple
91 * Check to see if we are replacing an existing tuple
99 bool replaces[Natts_pg_rewrite] = {0};
104 errmsg(
"rule \"%s\" for relation \"%s\" already exists",
108 * When replacing, we don't need to replace every attribute
110 replaces[Anum_pg_rewrite_ev_type - 1] =
true;
111 replaces[Anum_pg_rewrite_is_instead - 1] =
true;
112 replaces[Anum_pg_rewrite_ev_qual - 1] =
true;
113 replaces[Anum_pg_rewrite_ev_action - 1] =
true;
129 Anum_pg_rewrite_oid);
140 /* If replacing, get rid of old dependencies and make new ones */
145 * Install dependency on rule's relation to ensure it will go away on
146 * relation deletion. If the rule is ON SELECT, make the dependency
147 * implicit --- this prevents deleting a view's SELECT rule. Other kinds
148 * of rules can be AUTO.
150 myself.
classId = RewriteRelationId;
154 referenced.
classId = RelationRelationId;
162 * Also install dependencies on objects referenced in action and qual.
167 if (event_qual != NULL)
169 /* Find query containing OLD/NEW rtable entries */
177 /* Post creation hook for new rule */
182 return rewriteObjectId;
187 * Execute a CREATE RULE command.
196 /* Parse analysis. */
200 * Find and lock the relation. Lock level should match
201 * DefineQueryRewrite.
205 /* ... and execute */
220 * This is essentially the same as DefineRule() except that the rule's
221 * action and qual have already been passed through parse analysis.
239 * If we are installing an ON SELECT rule, we had better grab
240 * AccessExclusiveLock to ensure no SELECTs are currently running on the
241 * event relation. For other types of rules, it would be sufficient to
242 * grab ShareRowExclusiveLock to lock out insert/update/delete actions and
243 * to ensure that we lock out current CREATE RULE statements; but because
244 * of race conditions in access to catalog entries, we can't do that yet.
246 * Note that this lock level should match the one used in DefineRule.
251 * Verify relation is of a type that rules can sensibly be applied to.
252 * Internal callers can target materialized views, but transformRuleStmt()
253 * blocks them for users. Don't mention them in the error message.
255 if (event_relation->
rd_rel->relkind != RELKIND_RELATION &&
256 event_relation->
rd_rel->relkind != RELKIND_MATVIEW &&
257 event_relation->
rd_rel->relkind != RELKIND_VIEW &&
258 event_relation->
rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
260 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
261 errmsg(
"relation \"%s\" cannot have rules",
267 (
errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
268 errmsg(
"permission denied: \"%s\" is a system catalog",
272 * Check user has permission to apply rules to this relation.
279 * No rule actions that modify OLD or NEW
284 if (query->resultRelation == 0)
286 /* Don't be fooled by INSERT/SELECT */
291 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
292 errmsg(
"rule actions on OLD are not implemented"),
293 errhint(
"Use views or triggers instead.")));
296 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
297 errmsg(
"rule actions on NEW are not implemented"),
298 errhint(
"Use triggers instead.")));
304 * Rules ON SELECT are restricted to view definitions
306 * So this had better be a view, ...
308 if (event_relation->
rd_rel->relkind != RELKIND_VIEW &&
309 event_relation->
rd_rel->relkind != RELKIND_MATVIEW)
311 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
312 errmsg(
"relation \"%s\" cannot have ON SELECT rules",
317 * ... there cannot be INSTEAD NOTHING, ...
321 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
322 errmsg(
"INSTEAD NOTHING rules on SELECT are not implemented"),
323 errhint(
"Use views instead.")));
326 * ... there cannot be multiple actions, ...
330 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
331 errmsg(
"multiple actions for rules on SELECT are not implemented")));
334 * ... the one action must be a SELECT, ...
340 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
341 errmsg(
"rules on SELECT must have action INSTEAD SELECT")));
344 * ... it cannot contain data-modifying WITH ...
346 if (query->hasModifyingCTE)
348 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
349 errmsg(
"rules on SELECT must not contain data-modifying statements in WITH")));
352 * ... there can be no rule qual, ...
354 if (event_qual != NULL)
356 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
357 errmsg(
"event qualifications are not implemented for rules on SELECT")));
360 * ... the targetlist of the SELECT action must exactly match the
361 * event relation, ...
366 event_relation->
rd_rel->relkind !=
370 * ... there must not be another ON SELECT rule already ...
372 if (!replace && event_relation->
rd_rules != NULL)
383 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
384 errmsg(
"\"%s\" is already a view",
390 * ... and finally the rule must be named _RETURN.
395 * In versions before 7.3, the expected name was _RETviewname. For
396 * backwards compatibility with old pg_dump output, accept that
397 * and silently change it to _RETURN. Since this is just a quick
398 * backwards-compatibility hack, limit the number of characters
399 * checked to a few less than NAMEDATALEN; this saves having to
400 * worry about where a multibyte character might have gotten
403 if (strncmp(rulename,
"_RET", 4) != 0 ||
407 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
408 errmsg(
"view rule for \"%s\" must be named \"%s\"",
417 * For non-SELECT rules, a RETURNING list can appear in at most one of
418 * the actions ... and there can't be any RETURNING list at all in a
419 * conditional or non-INSTEAD rule. (Actually, there can be at most
420 * one RETURNING list across all rules on the same event, but it seems
421 * best to enforce that at rule expansion time.) If there is a
422 * RETURNING list, it must match the event relation.
424 bool haveReturning =
false;
434 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
435 errmsg(
"cannot have multiple RETURNING lists in a rule")));
436 haveReturning =
true;
437 if (event_qual != NULL)
439 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
440 errmsg(
"RETURNING lists are not supported in conditional rules")));
443 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
444 errmsg(
"RETURNING lists are not supported in non-INSTEAD rules")));
451 * And finally, if it's not an ON SELECT rule then it must *not* be
452 * named _RETURN. This prevents accidentally or maliciously replacing
453 * a view's ON SELECT rule with some other kind of rule.
457 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
458 errmsg(
"non-view rule for \"%s\" must not be named \"%s\"",
464 * This rule is allowed - prepare to install it.
467 /* discard rule if it's null action and not INSTEAD; it's a no-op */
479 * Set pg_class 'relhasrules' field true for event relation.
481 * Important side effect: an SI notice is broadcast to force all
482 * backends (including me!) to update relcache entries with the new
490 /* Close rel, but keep lock till commit... */
497 * checkRuleResultList
498 * Verify that targetList produces output compatible with a tupledesc
500 * The targetList might be either a SELECT targetlist, or a RETURNING list;
501 * isSelect tells which. This is used for choosing error messages.
503 * A SELECT targetlist may optionally require that column names match.
507 bool requireColumnNameMatch)
512 /* Only a SELECT may require a column name match. */
513 Assert(isSelect || !requireColumnNameMatch);
516 foreach(tllist, targetList)
524 /* resjunk entries may be ignored */
528 if (
i > resultDesc->
natts)
530 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
532 errmsg(
"SELECT rule's target list has too many entries") :
533 errmsg(
"RETURNING list has too many entries")));
539 * Disallow dropped columns in the relation. This is not really
540 * expected to happen when creating an ON SELECT rule. It'd be
541 * possible if someone tried to convert a relation with dropped
542 * columns to a view, but the only case we care about supporting
543 * table-to-view conversion for is pg_dump, and pg_dump won't do that.
545 * Unfortunately, the situation is also possible when adding a rule
546 * with RETURNING to a regular table, and rejecting that case is
547 * altogether more annoying. In principle we could support it by
548 * modifying the targetlist to include dummy NULL columns
549 * corresponding to the dropped columns in the tupdesc. However,
550 * places like ruleutils.c would have to be fixed to not process such
551 * entries, and that would take an uncertain and possibly rather large
552 * amount of work. (Note we could not dodge that by marking the dummy
553 * columns resjunk, since it's precisely the non-resjunk tlist columns
554 * that are expected to correspond to table columns.)
556 if (attr->attisdropped)
558 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
560 errmsg(
"cannot convert relation containing dropped columns to view") :
561 errmsg(
"cannot create a RETURNING list for a relation containing dropped columns")));
563 /* Check name match if required; no need for two error texts here */
564 if (requireColumnNameMatch && strcmp(tle->resname,
attname) != 0)
566 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
567 errmsg(
"SELECT rule's target entry %d has different column name from column \"%s\"",
569 errdetail(
"SELECT target entry is named \"%s\".",
572 /* Check type match. */
574 if (attr->atttypid != tletypid)
576 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
578 errmsg(
"SELECT rule's target entry %d has different type from column \"%s\"",
580 errmsg(
"RETURNING list's entry %d has different type from column \"%s\"",
583 errdetail(
"SELECT target entry has type %s, but column has type %s.",
586 errdetail(
"RETURNING list entry has type %s, but column has type %s.",
591 * Allow typmods to be different only if one of them is -1, ie,
592 * "unspecified". This is necessary for cases like "numeric", where
593 * the table will have a filled-in default length but the select
594 * rule's expression will probably have typmod = -1.
597 if (attr->atttypmod != tletypmod &&
598 attr->atttypmod != -1 && tletypmod != -1)
600 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
602 errmsg(
"SELECT rule's target entry %d has different size from column \"%s\"",
604 errmsg(
"RETURNING list's entry %d has different size from column \"%s\"",
607 errdetail(
"SELECT target entry has type %s, but column has type %s.",
611 errdetail(
"RETURNING list entry has type %s, but column has type %s.",
617 if (
i != resultDesc->
natts)
619 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
621 errmsg(
"SELECT rule's target list has too few entries") :
622 errmsg(
"RETURNING list has too few entries")));
627 * Recursively scan a query or expression tree and set the checkAsUser
628 * field to the given userid in all RTEPermissionInfos of the query.
655 /* Set in all RTEPermissionInfos for this query. */
656 foreach(l, qry->rteperminfos)
663 /* Now recurse to any subquery RTEs */
672 /* Recurse into subquery-in-WITH */
680 /* If there are sublinks, search for them and process their RTEs */
681 if (qry->hasSubLinks)
688 * Change the firing semantics of an existing rule.
696 Oid eventRelationOid;
699 bool changed =
false;
702 * Find the rule tuple to change.
710 (
errcode(ERRCODE_UNDEFINED_OBJECT),
711 errmsg(
"rule \"%s\" for relation \"%s\" does not exist",
717 * Verify that the user has appropriate permissions.
719 eventRelationOid = ruleform->ev_class;
720 Assert(eventRelationOid == owningRel);
726 * Change ev_enabled if it is different from the desired new state.
728 if (ruleform->ev_enabled != fires_when)
730 ruleform->ev_enabled = fires_when;
742 * If we changed anything, broadcast a SI inval message to force each
743 * backend (including our own!) to rebuild relation's relcache entry.
744 * Otherwise they will fail to apply the change promptly.
752 * Perform permissions and integrity checks before acquiring a relation lock.
763 return;
/* concurrently dropped */
766 /* only tables and views can have rules */
767 if (form->relkind != RELKIND_RELATION &&
768 form->relkind != RELKIND_VIEW &&
769 form->relkind != RELKIND_PARTITIONED_TABLE)
771 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
777 (
errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
778 errmsg(
"permission denied: \"%s\" is a system catalog",
781 /* you must own the table to rename one of its rules */
789 * Rename an existing rewrite rule.
804 * Look up name, check permissions, and acquire lock (which we will NOT
805 * release until end of transaction).
812 /* Have lock already, so just need to build relcache entry. */
815 /* Prepare to modify pg_rewrite */
818 /* Fetch the rule's entry (it had better exist) */
824 (
errcode(ERRCODE_UNDEFINED_OBJECT),
825 errmsg(
"rule \"%s\" for relation \"%s\" does not exist",
828 ruleOid = ruleform->oid;
830 /* rule with the new name should not already exist */
834 errmsg(
"rule \"%s\" for relation \"%s\" already exists",
838 * We disallow renaming ON SELECT rules, because they should always be
843 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
844 errmsg(
"renaming an ON SELECT rule is not allowed")));
846 /* OK, do the update */
857 * Invalidate relation's relcache entry so that other backends (and this
858 * one too!) are sent SI message to make them rebuild relcache entries.
859 * (Ideally this should happen automatically...)
866 * Close rel, but keep exclusive lock!
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
static Datum values[MAXATTR]
#define CStringGetTextDatum(s)
bool IsSystemRelation(Relation relation)
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
int errdetail(const char *fmt,...)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
bool allowSystemTableMods
Assert(PointerIsAligned(start, uint64))
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
void heap_freetuple(HeapTuple htup)
#define HeapTupleIsValid(tuple)
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
void CacheInvalidateRelcache(Relation relation)
#define AccessExclusiveLock
char * get_rel_name(Oid relid)
char get_rel_relkind(Oid relid)
char * pstrdup(const char *in)
void namestrcpy(Name name, const char *str)
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Oid exprType(const Node *expr)
int32 exprTypmod(const Node *expr)
#define query_tree_walker(q, w, c, f)
#define expression_tree_walker(n, w, c)
#define QTW_IGNORE_RC_SUBQUERIES
#define IsA(nodeptr, _type_)
#define castNode(_type_, nodeptr)
#define InvokeObjectPostCreateHook(classId, objectId, subId)
#define InvokeObjectPostAlterHook(classId, objectId, subId)
ObjectType get_relkind_objtype(char relkind)
#define ObjectAddressSet(addr, class_id, object_id)
char * nodeToString(const void *obj)
void transformRuleStmt(RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
FormData_pg_attribute * Form_pg_attribute
int errdetail_relkind_not_supported(char relkind)
FormData_pg_class * Form_pg_class
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
#define lfirst_node(type, lc)
static int list_length(const List *l)
#define linitial_node(type, l)
FormData_pg_rewrite * Form_pg_rewrite
static Datum PointerGetDatum(const void *X)
static Datum BoolGetDatum(bool X)
static Datum ObjectIdGetDatum(Oid X)
static Datum NameGetDatum(const NameData *X)
static Datum CharGetDatum(char X)
#define RelationGetRelid(relation)
#define RelationGetDescr(relation)
#define RelationGetRelationName(relation)
static Oid InsertRule(const char *rulname, int evtype, Oid eventrel_oid, bool evinstead, Node *event_qual, List *action, bool replace)
void setRuleCheckAsUser(Node *node, Oid userid)
static bool setRuleCheckAsUser_walker(Node *node, Oid *context)
ObjectAddress DefineRule(RuleStmt *stmt, const char *queryString)
static void RangeVarCallbackForRenameRule(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
static void checkRuleResultList(List *targetList, TupleDesc resultDesc, bool isSelect, bool requireColumnNameMatch)
static void setRuleCheckAsUser_Query(Query *qry, Oid userid)
ObjectAddress DefineQueryRewrite(const char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)
void EnableDisableRule(Relation rel, const char *rulename, char fires_when)
ObjectAddress RenameRewriteRule(RangeVar *relation, const char *oldName, const char *newName)
#define RULE_FIRES_ON_ORIGIN
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
void SetRelationRuleStatus(Oid relationId, bool relHasRules)
bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName)
#define ViewSelectRuleName
void relation_close(Relation relation, LOCKMODE lockmode)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
#define ERRCODE_DUPLICATE_OBJECT
void ReleaseSysCache(HeapTuple tuple)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
#define SearchSysCacheCopy2(cacheId, key1, key2)
void table_close(Relation relation, LOCKMODE lockmode)
Relation table_open(Oid relationId, LOCKMODE lockmode)
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)