1 /*-------------------------------------------------------------------------
4 * use rewrite rules to construct views
6 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/commands/view.c,v 1.90 2005/04/14 01:38:17 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "catalog/dependency.h"
19 #include "catalog/namespace.h"
20 #include "commands/tablecmds.h"
21 #include "commands/view.h"
22 #include "miscadmin.h"
23 #include "nodes/makefuncs.h"
24 #include "optimizer/clauses.h"
25 #include "parser/parse_expr.h"
26 #include "parser/parse_relation.h"
27 #include "rewrite/rewriteDefine.h"
28 #include "rewrite/rewriteManip.h"
29 #include "rewrite/rewriteSupport.h"
30 #include "utils/acl.h"
31 #include "utils/lsyscache.h"
34 static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
35 static bool isViewOnTempTable_walker(Node *node, void *context);
37 /*---------------------------------------------------------------------
40 * Returns true iff any of the relations underlying this view are
42 *---------------------------------------------------------------------
45 isViewOnTempTable(Query *viewParse)
47 return isViewOnTempTable_walker((Node *) viewParse, NULL);
51 isViewOnTempTable_walker(Node *node, void *context)
58 Query *query = (Query *) node;
61 foreach (rtable, query->rtable)
63 RangeTblEntry *rte = lfirst(rtable);
64 if (rte->rtekind == RTE_RELATION)
66 Relation rel = heap_open(rte->relid, AccessShareLock);
67 bool istemp = rel->rd_istemp;
68 heap_close(rel, AccessShareLock);
74 return query_tree_walker(query,
75 isViewOnTempTable_walker,
77 QTW_IGNORE_JOINALIASES);
80 return expression_tree_walker(node,
81 isViewOnTempTable_walker,
85 /*---------------------------------------------------------------------
86 * DefineVirtualRelation
88 * Create the "view" relation. `DefineRelation' does all the work,
89 * we just provide the correct arguments ... at least when we're
90 * creating a view. If we're updating an existing view, we have to
92 *---------------------------------------------------------------------
95 DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
99 CreateStmt *createStmt = makeNode(CreateStmt);
104 * create a list of ColumnDef nodes based on the names and types of
105 * the (non-junk) targetlist items from the view's SELECT list.
110 TargetEntry *tle = lfirst(t);
114 ColumnDef *def = makeNode(ColumnDef);
115 TypeName *typename = makeNode(TypeName);
117 def->colname = pstrdup(tle->resname);
119 typename->typeid = exprType((Node *) tle->expr);
120 typename->typmod = exprTypmod((Node *) tle->expr);
121 def->typename = typename;
124 def->is_local = true;
125 def->is_not_null = false;
126 def->raw_default = NULL;
127 def->cooked_default = NULL;
128 def->constraints = NIL;
131 attrList = lappend(attrList, def);
137 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
138 errmsg("view must have at least one column")));
141 * Check to see if we want to replace an existing view.
143 namespaceId = RangeVarGetCreationNamespace(relation);
144 viewOid = get_relname_relid(relation->relname, namespaceId);
146 if (OidIsValid(viewOid) && replace)
149 TupleDesc descriptor;
152 * Yes. Get exclusive lock on the existing view ...
154 rel = relation_open(viewOid, AccessExclusiveLock);
157 * Make sure it *is* a view, and do permissions checks.
159 if (rel->rd_rel->relkind != RELKIND_VIEW)
161 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
162 errmsg("\"%s\" is not a view",
163 RelationGetRelationName(rel))));
165 if (!pg_class_ownercheck(viewOid, GetUserId()))
166 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
167 RelationGetRelationName(rel));
170 * Due to the namespace visibility rules for temporary
171 * objects, we should only end up replacing a temporary view
172 * with another temporary view, and vice versa.
174 Assert(relation->istemp == rel->rd_istemp);
177 * Create a tuple descriptor to compare against the existing view,
178 * and verify it matches.
180 descriptor = BuildDescForRelation(attrList);
181 checkViewTupleDesc(descriptor, rel->rd_att);
184 * Seems okay, so return the OID of the pre-existing view.
186 relation_close(rel, NoLock); /* keep the lock! */
193 * now set the parameters for keys/inheritance etc. All of these
194 * are uninteresting for views...
196 createStmt->relation = (RangeVar *) relation;
197 createStmt->tableElts = attrList;
198 createStmt->inhRelations = NIL;
199 createStmt->constraints = NIL;
200 createStmt->hasoids = MUST_NOT_HAVE_OIDS;
201 createStmt->oncommit = ONCOMMIT_NOOP;
202 createStmt->tablespacename = NULL;
205 * finally create the relation (this will error out if there's an
206 * existing view, so we don't need more code to complain if
207 * "replace" is false).
209 return DefineRelation(createStmt, RELKIND_VIEW);
214 * Verify that tupledesc associated with proposed new view definition
215 * matches tupledesc of old view. This is basically a cut-down version
216 * of equalTupleDescs(), with code added to generate specific complaints.
219 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
223 if (newdesc->natts != olddesc->natts)
225 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
226 errmsg("cannot change number of columns in view")));
227 /* we can ignore tdhasoid */
229 for (i = 0; i < newdesc->natts; i++)
231 Form_pg_attribute newattr = newdesc->attrs[i];
232 Form_pg_attribute oldattr = olddesc->attrs[i];
234 /* XXX not right, but we don't support DROP COL on view anyway */
235 if (newattr->attisdropped != oldattr->attisdropped)
237 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
238 errmsg("cannot change number of columns in view")));
240 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
242 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
243 errmsg("cannot change name of view column \"%s\"",
244 NameStr(oldattr->attname))));
245 /* XXX would it be safe to allow atttypmod to change? Not sure */
246 if (newattr->atttypid != oldattr->atttypid ||
247 newattr->atttypmod != oldattr->atttypmod)
249 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
250 errmsg("cannot change data type of view column \"%s\"",
251 NameStr(oldattr->attname))));
252 /* We can ignore the remaining attributes of an attribute... */
256 * We ignore the constraint fields. The new view desc can't have any
257 * constraints, and the only ones that could be on the old view are
258 * defaults, which we are happy to leave in place.
263 FormViewRetrieveRule(const RangeVar *view, Query *viewParse, bool replace)
268 * Create a RuleStmt that corresponds to the suitable rewrite rule
269 * args for DefineQueryRewrite();
271 rule = makeNode(RuleStmt);
272 rule->relation = copyObject((RangeVar *) view);
273 rule->rulename = pstrdup(ViewSelectRuleName);
274 rule->whereClause = NULL;
275 rule->event = CMD_SELECT;
276 rule->instead = true;
277 rule->actions = list_make1(viewParse);
278 rule->replace = replace;
284 DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
286 RuleStmt *retrieve_rule;
289 RuleStmt *replace_rule;
290 RuleStmt *append_rule;
291 RuleStmt *delete_rule;
294 retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
297 replace_rule = FormViewReplaceRule(view, viewParse);
298 append_rule = FormViewAppendRule(view, viewParse);
299 delete_rule = FormViewDeleteRule(view, viewParse);
302 DefineQueryRewrite(retrieve_rule);
305 DefineQueryRewrite(replace_rule);
306 DefineQueryRewrite(append_rule);
307 DefineQueryRewrite(delete_rule);
312 /*---------------------------------------------------------------
313 * UpdateRangeTableOfViewParse
315 * Update the range table of the given parsetree.
316 * This update consists of adding two new entries IN THE BEGINNING
317 * of the range table (otherwise the rule system will die a slow,
318 * horrible and painful death, and we do not want that now, do we?)
319 * one for the OLD relation and one for the NEW one (both of
320 * them refer in fact to the "view" relation).
322 * Of course we must also increase the 'varnos' of all the Var nodes
325 * These extra RT entries are not actually used in the query,
326 * except for run-time permission checking.
327 *---------------------------------------------------------------
330 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
334 RangeTblEntry *rt_entry1,
338 * Make a copy of the given parsetree. It's not so much that we don't
339 * want to scribble on our input, it's that the parser has a bad habit
340 * of outputting multiple links to the same subtree for constructs
341 * like BETWEEN, and we mustn't have OffsetVarNodes increment the
342 * varno of a Var node twice. copyObject will expand any
343 * multiply-referenced subtree into multiple copies.
345 viewParse = (Query *) copyObject(viewParse);
347 /* need to open the rel for addRangeTableEntryForRelation */
348 viewRel = relation_open(viewOid, AccessShareLock);
351 * Create the 2 new range table entries and form the new range
352 * table... OLD first, then NEW....
354 rt_entry1 = addRangeTableEntryForRelation(NULL, viewRel,
355 makeAlias("*OLD*", NIL),
357 rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
358 makeAlias("*NEW*", NIL),
360 /* Must override addRangeTableEntry's default access-check flags */
361 rt_entry1->requiredPerms = 0;
362 rt_entry2->requiredPerms = 0;
364 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
366 viewParse->rtable = new_rt;
369 * Now offset all var nodes by 2, and jointree RT indexes too.
371 OffsetVarNodes((Node *) viewParse, 2, 0);
373 relation_close(viewRel, AccessShareLock);
378 /*-------------------------------------------------------------------
381 * - takes a "viewname", "parsetree" pair and then
382 * 1) construct the "virtual" relation
383 * 2) commit the command but NOT the transaction,
384 * so that the relation exists
385 * before the rules are defined.
386 * 2) define the "n" rules specified in the PRS2 paper
387 * over the "virtual" relation
388 *-------------------------------------------------------------------
391 DefineView(RangeVar *view, Query *viewParse, bool replace)
396 * If the user didn't explicitly ask for a temporary view, check
397 * whether we need one implicitly.
401 view->istemp = isViewOnTempTable(viewParse);
404 (errmsg("view \"%s\" will be a temporary view",
409 * Create the view relation
411 * NOTE: if it already exists and replace is false, the xact will be
414 viewOid = DefineVirtualRelation(view, viewParse->targetList, replace);
417 * The relation we have just created is not visible to any other
418 * commands running with the same transaction & command id. So,
419 * increment the command id counter (but do NOT pfree any memory!!!!)
421 CommandCounterIncrement();
424 * The range table of 'viewParse' does not contain entries for the
425 * "OLD" and "NEW" relations. So... add them!
427 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
430 * Now create the rules associated with the view.
432 DefineViewRules(view, viewParse, replace);
438 * Remove a view given its name
440 * We just have to drop the relation; the associated rules will be
441 * cleaned up automatically.
444 RemoveView(const RangeVar *view, DropBehavior behavior)
447 ObjectAddress object;
449 viewOid = RangeVarGetRelid(view, false);
451 object.classId = RelationRelationId;
452 object.objectId = viewOid;
453 object.objectSubId = 0;
455 performDeletion(&object, behavior);