1 /*-------------------------------------------------------------------------
4 * routines for defining a rewrite rule
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteDefine.c,v 1.67 2002/04/18 20:01:09 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "catalog/catname.h"
19 #include "catalog/indexing.h"
20 #include "catalog/pg_rewrite.h"
21 #include "commands/view.h"
22 #include "miscadmin.h"
23 #include "optimizer/clauses.h"
24 #include "parser/parse_relation.h"
25 #include "rewrite/rewriteDefine.h"
26 #include "rewrite/rewriteManip.h"
27 #include "rewrite/rewriteSupport.h"
28 #include "storage/smgr.h"
29 #include "utils/acl.h"
30 #include "utils/builtins.h"
31 #include "utils/syscache.h"
34 static void setRuleCheckAsUser(Query *qry, Oid userid);
35 static bool setRuleCheckAsUser_walker(Node *node, Oid *context);
40 * takes the arguments and inserts them as a row into the system
41 * relation "pg_rewrite"
44 InsertRule(char *rulname,
47 AttrNumber evslot_index,
53 Datum values[Natts_pg_rewrite];
54 char nulls[Natts_pg_rewrite];
56 Relation pg_rewrite_desc;
61 if (IsDefinedRewriteRule(eventrel_oid, rulname))
62 elog(ERROR, "Attempt to insert rule \"%s\" failed: already exists",
66 * Set up *nulls and *values arrays
68 MemSet(nulls, ' ', sizeof(nulls));
71 namestrcpy(&rname, rulname);
72 values[i++] = NameGetDatum(&rname); /* rulename */
73 values[i++] = ObjectIdGetDatum(eventrel_oid); /* ev_class */
74 values[i++] = Int16GetDatum(evslot_index); /* ev_attr */
75 values[i++] = CharGetDatum(evtype + '0'); /* ev_type */
76 values[i++] = BoolGetDatum(evinstead); /* is_instead */
77 values[i++] = DirectFunctionCall1(textin, CStringGetDatum(evqual)); /* ev_qual */
78 values[i++] = DirectFunctionCall1(textin, CStringGetDatum(actiontree)); /* ev_action */
81 * create a new pg_rewrite tuple
83 pg_rewrite_desc = heap_openr(RewriteRelationName, RowExclusiveLock);
85 tupDesc = pg_rewrite_desc->rd_att;
87 tup = heap_formtuple(tupDesc,
91 heap_insert(pg_rewrite_desc, tup);
93 rewriteObjectId = tup->t_data->t_oid;
95 if (RelationGetForm(pg_rewrite_desc)->relhasindex)
97 Relation idescs[Num_pg_rewrite_indices];
99 CatalogOpenIndices(Num_pg_rewrite_indices, Name_pg_rewrite_indices,
101 CatalogIndexInsert(idescs, Num_pg_rewrite_indices, pg_rewrite_desc,
103 CatalogCloseIndices(Num_pg_rewrite_indices, idescs);
108 heap_close(pg_rewrite_desc, RowExclusiveLock);
110 return rewriteObjectId;
114 DefineQueryRewrite(RuleStmt *stmt)
116 RangeVar *event_obj = stmt->relation;
117 Node *event_qual = stmt->whereClause;
118 CmdType event_type = stmt->event;
119 bool is_instead = stmt->instead;
120 List *action = stmt->actions;
121 Relation event_relation;
130 int32 aclcheck_result;
131 bool RelisBecomingView = false;
134 * If we are installing an ON SELECT rule, we had better grab
135 * AccessExclusiveLock to ensure no SELECTs are currently running on
136 * the event relation. For other types of rules, it might be
137 * sufficient to grab ShareLock to lock out insert/update/delete
138 * actions. But for now, let's just grab AccessExclusiveLock all the
141 event_relation = heap_openrv(event_obj, AccessExclusiveLock);
142 ev_relid = RelationGetRelid(event_relation);
145 * Check user has permission to apply rules to this relation.
147 aclcheck_result = pg_class_aclcheck(ev_relid, GetUserId(), ACL_RULE);
148 if (aclcheck_result != ACLCHECK_OK)
149 elog(ERROR, "%s: %s",
150 RelationGetRelationName(event_relation),
151 aclcheck_error_strings[aclcheck_result]);
154 * No rule actions that modify OLD or NEW
158 query = (Query *) lfirst(l);
159 if (query->resultRelation == 0)
161 /* Don't be fooled by INSERT/SELECT */
162 if (query != getInsertSelectQuery(query, NULL))
164 if (query->resultRelation == PRS2_OLD_VARNO)
165 elog(ERROR, "rule actions on OLD currently not supported"
166 "\n\tuse views or triggers instead");
167 if (query->resultRelation == PRS2_NEW_VARNO)
168 elog(ERROR, "rule actions on NEW currently not supported"
169 "\n\tuse triggers instead");
173 * Rules ON SELECT are restricted to view definitions
175 if (event_type == CMD_SELECT)
182 * So there cannot be INSTEAD NOTHING, ...
184 if (length(action) == 0)
186 elog(ERROR, "instead nothing rules on select currently not supported"
187 "\n\tuse views instead");
191 * ... there cannot be multiple actions, ...
193 if (length(action) > 1)
194 elog(ERROR, "multiple action rules on select currently not supported");
197 * ... the one action must be a SELECT, ...
199 query = (Query *) lfirst(action);
200 if (!is_instead || query->commandType != CMD_SELECT)
201 elog(ERROR, "only instead-select rules currently supported on select");
204 * ... there can be no rule qual, ...
206 if (event_qual != NULL)
207 elog(ERROR, "event qualifications not supported for rules on select");
210 * ... the targetlist of the SELECT action must exactly match the
211 * event relation, ...
214 foreach(tllist, query->targetList)
216 TargetEntry *tle = (TargetEntry *) lfirst(tllist);
217 Resdom *resdom = tle->resdom;
218 Form_pg_attribute attr;
224 if (i > event_relation->rd_att->natts)
225 elog(ERROR, "select rule's target list has too many entries");
227 attr = event_relation->rd_att->attrs[i - 1];
228 attname = NameStr(attr->attname);
230 if (strcmp(resdom->resname, attname) != 0)
231 elog(ERROR, "select rule's target entry %d has different column name from %s", i, attname);
233 if (attr->atttypid != resdom->restype)
234 elog(ERROR, "select rule's target entry %d has different type from attribute %s", i, attname);
237 * Allow typmods to be different only if one of them is -1,
238 * ie, "unspecified". This is necessary for cases like
239 * "numeric", where the table will have a filled-in default
240 * length but the select rule's expression will probably have
243 if (attr->atttypmod != resdom->restypmod &&
244 attr->atttypmod != -1 && resdom->restypmod != -1)
245 elog(ERROR, "select rule's target entry %d has different size from attribute %s", i, attname);
248 if (i != event_relation->rd_att->natts)
249 elog(ERROR, "select rule's target list has too few entries");
252 * ... there must not be another ON SELECT rule already ...
254 if (event_relation->rd_rules != NULL)
256 for (i = 0; i < event_relation->rd_rules->numLocks; i++)
260 rule = event_relation->rd_rules->rules[i];
261 if (rule->event == CMD_SELECT)
262 elog(ERROR, "\"%s\" is already a view",
263 RelationGetRelationName(event_relation));
268 * ... and finally the rule must be named _RETviewname.
270 expected_name = MakeRetrieveViewRuleName(event_obj->relname);
271 if (strcmp(expected_name, stmt->rulename) != 0)
273 elog(ERROR, "view rule for \"%s\" must be named \"%s\"",
274 event_obj->relname, expected_name);
276 pfree(expected_name);
279 * Are we converting a relation to a view?
281 * If so, check that the relation is empty because the storage for
282 * the relation is going to be deleted.
284 if (event_relation->rd_rel->relkind != RELKIND_VIEW)
286 HeapScanDesc scanDesc;
289 scanDesc = heap_beginscan(event_relation, 0, SnapshotNow, 0, NULL);
290 tuple = heap_getnext(scanDesc, 0);
291 if (HeapTupleIsValid(tuple))
292 elog(ERROR, "Relation \"%s\" is not empty. Cannot convert it to view",
296 * don't need heap_freetuple because we never got a valid
299 heap_endscan(scanDesc);
301 RelisBecomingView = true;
306 * This rule is allowed - prepare to install it.
309 event_attype = InvalidOid;
312 * We want the rule's table references to be checked as though by the
313 * rule owner, not the user referencing the rule. Therefore, scan
314 * through the rule's rtables and set the checkAsUser field on all
319 query = (Query *) lfirst(l);
320 setRuleCheckAsUser(query, GetUserId());
323 /* discard rule if it's null action and not INSTEAD; it's a no-op */
324 if (action != NIL || is_instead)
326 event_qualP = nodeToString(event_qual);
327 actionP = nodeToString(action);
329 ruleId = InsertRule(stmt->rulename,
338 * Set pg_class 'relhasrules' field TRUE for event relation. If
339 * appropriate, also modify the 'relkind' field to show that the
340 * relation is now a view.
342 * Important side effect: an SI notice is broadcast to force all
343 * backends (including me!) to update relcache entries with the
346 SetRelationRuleStatus(ev_relid, true, RelisBecomingView);
350 * IF the relation is becoming a view, delete the storage files
351 * associated with it. NB: we had better have AccessExclusiveLock to
354 if (RelisBecomingView)
355 smgrunlink(DEFAULT_SMGR, event_relation);
357 /* Close rel, but keep lock till commit... */
358 heap_close(event_relation, NoLock);
363 * Recursively scan a query and set the checkAsUser field to the
364 * given userid in all rtable entries.
366 * Note: for a view (ON SELECT rule), the checkAsUser field of the *OLD*
367 * RTE entry will be overridden when the view rule is expanded, and the
368 * checkAsUser field of the *NEW* entry is irrelevant because that entry's
369 * checkFor bits will never be set. However, for other types of rules it's
370 * important to set these fields to match the rule owner. So we just set
374 setRuleCheckAsUser(Query *qry, Oid userid)
378 /* Set all the RTEs in this query node */
379 foreach(l, qry->rtable)
381 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
385 /* Recurse into subquery in FROM */
386 setRuleCheckAsUser(rte->subquery, userid);
389 rte->checkAsUser = userid;
392 /* If there are sublinks, search for them and process their RTEs */
393 if (qry->hasSubLinks)
394 query_tree_walker(qry, setRuleCheckAsUser_walker, (void *) &userid,
395 false /* already did the ones in rtable */ );
399 * Expression-tree walker to find sublink queries
402 setRuleCheckAsUser_walker(Node *node, Oid *context)
406 if (IsA(node, Query))
408 Query *qry = (Query *) node;
410 setRuleCheckAsUser(qry, *context);
413 return expression_tree_walker(node, setRuleCheckAsUser_walker,
419 * Rename an existing rewrite rule.
421 * There is not currently a user command to invoke this directly
422 * (perhaps there should be). But we need it anyway to rename the
423 * ON SELECT rule associated with a view, when the view is renamed.
426 RenameRewriteRule(Oid owningRel, const char *oldName,
429 Relation pg_rewrite_desc;
432 pg_rewrite_desc = heap_openr(RewriteRelationName, RowExclusiveLock);
434 ruletup = SearchSysCacheCopy(RULERELNAME,
435 ObjectIdGetDatum(owningRel),
436 PointerGetDatum(oldName),
438 if (!HeapTupleIsValid(ruletup))
439 elog(ERROR, "RenameRewriteRule: rule \"%s\" does not exist", oldName);
441 /* should not already exist */
442 if (IsDefinedRewriteRule(owningRel, newName))
443 elog(ERROR, "Attempt to rename rule \"%s\" failed: \"%s\" already exists",
446 namestrcpy(&(((Form_pg_rewrite) GETSTRUCT(ruletup))->rulename), newName);
448 simple_heap_update(pg_rewrite_desc, &ruletup->t_self, ruletup);
450 /* keep system catalog indices current */
451 if (RelationGetForm(pg_rewrite_desc)->relhasindex)
453 Relation idescs[Num_pg_rewrite_indices];
455 CatalogOpenIndices(Num_pg_rewrite_indices, Name_pg_rewrite_indices,
457 CatalogIndexInsert(idescs, Num_pg_rewrite_indices, pg_rewrite_desc,
459 CatalogCloseIndices(Num_pg_rewrite_indices, idescs);
462 heap_freetuple(ruletup);
463 heap_close(pg_rewrite_desc, RowExclusiveLock);