1 /*-------------------------------------------------------------------------
4 * use rewrite rules to construct views
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/commands/view.c,v 1.71 2002/09/04 20:31:17 momjian 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 "parser/parse_relation.h"
25 #include "rewrite/rewriteDefine.h"
26 #include "rewrite/rewriteManip.h"
27 #include "rewrite/rewriteSupport.h"
28 #include "utils/acl.h"
29 #include "utils/lsyscache.h"
32 static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
35 /*---------------------------------------------------------------------
36 * DefineVirtualRelation
38 * Create the "view" relation. `DefineRelation' does all the work,
39 * we just provide the correct arguments ... at least when we're
40 * creating a view. If we're updating an existing view, we have to
42 *---------------------------------------------------------------------
45 DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
49 CreateStmt *createStmt = makeNode(CreateStmt);
54 * create a list of ColumnDef nodes based on the names and types of
55 * the (non-junk) targetlist items from the view's SELECT list.
60 TargetEntry *entry = lfirst(t);
61 Resdom *res = entry->resdom;
65 ColumnDef *def = makeNode(ColumnDef);
66 TypeName *typename = makeNode(TypeName);
68 def->colname = pstrdup(res->resname);
70 typename->typeid = res->restype;
71 typename->typmod = res->restypmod;
72 def->typename = typename;
74 def->is_inherited = false;
75 def->is_not_null = false;
76 def->raw_default = NULL;
77 def->cooked_default = NULL;
78 def->constraints = NIL;
81 attrList = lappend(attrList, def);
86 elog(ERROR, "attempted to define virtual relation with no attrs");
89 * Check to see if we want to replace an existing view.
91 namespaceId = RangeVarGetCreationNamespace(relation);
92 viewOid = get_relname_relid(relation->relname, namespaceId);
94 if (OidIsValid(viewOid) && replace)
100 * Yes. Get exclusive lock on the existing view ...
102 rel = relation_open(viewOid, AccessExclusiveLock);
105 * Make sure it *is* a view, and do permissions checks.
107 if (rel->rd_rel->relkind != RELKIND_VIEW)
108 elog(ERROR, "%s is not a view",
109 RelationGetRelationName(rel));
111 if (!pg_class_ownercheck(viewOid, GetUserId()))
112 aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
115 * Create a tuple descriptor to compare against the existing view,
116 * and verify it matches.
118 descriptor = BuildDescForRelation(attrList);
119 checkViewTupleDesc(descriptor, rel->rd_att);
122 * Seems okay, so return the OID of the pre-existing view.
124 relation_close(rel, NoLock); /* keep the lock! */
131 * now create the parameters for keys/inheritance etc. All of them
134 createStmt->relation = (RangeVar *) relation;
135 createStmt->tableElts = attrList;
136 createStmt->inhRelations = NIL;
137 createStmt->constraints = NIL;
138 createStmt->hasoids = false;
141 * finally create the relation (this will error out if there's an
142 * existing view, so we don't need more code to complain if
143 * "replace" is false).
145 return DefineRelation(createStmt, RELKIND_VIEW);
150 * Verify that tupledesc associated with proposed new view definition
151 * matches tupledesc of old view. This is basically a cut-down version
152 * of equalTupleDescs(), with code added to generate specific complaints.
155 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
159 if (newdesc->natts != olddesc->natts)
160 elog(ERROR, "Cannot change number of columns in view");
161 /* we can ignore tdhasoid */
163 for (i = 0; i < newdesc->natts; i++)
165 Form_pg_attribute newattr = newdesc->attrs[i];
166 Form_pg_attribute oldattr = olddesc->attrs[i];
168 /* XXX not right, but we don't support DROP COL on view anyway */
169 if (newattr->attisdropped != oldattr->attisdropped)
170 elog(ERROR, "Cannot change number of columns in view");
172 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
173 elog(ERROR, "Cannot change name of view column \"%s\"",
174 NameStr(oldattr->attname));
175 /* XXX would it be safe to allow atttypmod to change? Not sure */
176 if (newattr->atttypid != oldattr->atttypid ||
177 newattr->atttypmod != oldattr->atttypmod)
178 elog(ERROR, "Cannot change datatype of view column \"%s\"",
179 NameStr(oldattr->attname));
180 /* We can ignore the remaining attributes of an attribute... */
184 * We ignore the constraint fields. The new view desc can't have any
185 * constraints, and the only ones that could be on the old view are
186 * defaults, which we are happy to leave in place.
191 FormViewRetrieveRule(const RangeVar *view, Query *viewParse, bool replace)
196 * Create a RuleStmt that corresponds to the suitable rewrite rule
197 * args for DefineQueryRewrite();
199 rule = makeNode(RuleStmt);
200 rule->relation = copyObject((RangeVar *) view);
201 rule->rulename = pstrdup(ViewSelectRuleName);
202 rule->whereClause = NULL;
203 rule->event = CMD_SELECT;
204 rule->instead = true;
205 rule->actions = makeList1(viewParse);
206 rule->replace = replace;
212 DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
214 RuleStmt *retrieve_rule;
217 RuleStmt *replace_rule;
218 RuleStmt *append_rule;
219 RuleStmt *delete_rule;
222 retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
225 replace_rule = FormViewReplaceRule(view, viewParse);
226 append_rule = FormViewAppendRule(view, viewParse);
227 delete_rule = FormViewDeleteRule(view, viewParse);
230 DefineQueryRewrite(retrieve_rule);
233 DefineQueryRewrite(replace_rule);
234 DefineQueryRewrite(append_rule);
235 DefineQueryRewrite(delete_rule);
240 /*---------------------------------------------------------------
241 * UpdateRangeTableOfViewParse
243 * Update the range table of the given parsetree.
244 * This update consists of adding two new entries IN THE BEGINNING
245 * of the range table (otherwise the rule system will die a slow,
246 * horrible and painful death, and we do not want that now, do we?)
247 * one for the OLD relation and one for the NEW one (both of
248 * them refer in fact to the "view" relation).
250 * Of course we must also increase the 'varnos' of all the Var nodes
253 * These extra RT entries are not actually used in the query,
254 * except for run-time permission checking.
255 *---------------------------------------------------------------
258 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
261 RangeTblEntry *rt_entry1,
265 * Make a copy of the given parsetree. It's not so much that we don't
266 * want to scribble on our input, it's that the parser has a bad habit
267 * of outputting multiple links to the same subtree for constructs
268 * like BETWEEN, and we mustn't have OffsetVarNodes increment the
269 * varno of a Var node twice. copyObject will expand any
270 * multiply-referenced subtree into multiple copies.
272 viewParse = (Query *) copyObject(viewParse);
275 * Create the 2 new range table entries and form the new range
276 * table... OLD first, then NEW....
278 rt_entry1 = addRangeTableEntryForRelation(NULL, viewOid,
279 makeAlias("*OLD*", NIL),
281 rt_entry2 = addRangeTableEntryForRelation(NULL, viewOid,
282 makeAlias("*NEW*", NIL),
284 /* Must override addRangeTableEntry's default access-check flags */
285 rt_entry1->checkForRead = false;
286 rt_entry2->checkForRead = false;
288 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
290 viewParse->rtable = new_rt;
293 * Now offset all var nodes by 2, and jointree RT indexes too.
295 OffsetVarNodes((Node *) viewParse, 2, 0);
300 /*-------------------------------------------------------------------
303 * - takes a "viewname", "parsetree" pair and then
304 * 1) construct the "virtual" relation
305 * 2) commit the command but NOT the transaction,
306 * so that the relation exists
307 * before the rules are defined.
308 * 2) define the "n" rules specified in the PRS2 paper
309 * over the "virtual" relation
310 *-------------------------------------------------------------------
313 DefineView(const RangeVar *view, Query *viewParse, bool replace)
318 * Create the view relation
320 * NOTE: if it already exists and replace is false, the xact will be
324 viewOid = DefineVirtualRelation(view, viewParse->targetList, replace);
327 * The relation we have just created is not visible to any other
328 * commands running with the same transaction & command id. So,
329 * increment the command id counter (but do NOT pfree any memory!!!!)
331 CommandCounterIncrement();
334 * The range table of 'viewParse' does not contain entries for the
335 * "OLD" and "NEW" relations. So... add them!
337 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
340 * Now create the rules associated with the view.
342 DefineViewRules(view, viewParse, replace);
348 * Remove a view given its name
350 * We just have to drop the relation; the associated rules will be
351 * cleaned up automatically.
354 RemoveView(const RangeVar *view, DropBehavior behavior)
357 ObjectAddress object;
359 viewOid = RangeVarGetRelid(view, false);
361 object.classId = RelOid_pg_class;
362 object.objectId = viewOid;
363 object.objectSubId = 0;
365 performDeletion(&object, behavior);