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.75 2003/08/01 00:15:20 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 "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;
76 def->is_not_null = false;
77 def->raw_default = NULL;
78 def->cooked_default = NULL;
79 def->constraints = NIL;
82 attrList = lappend(attrList, def);
88 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
89 errmsg("view must have at least one attribute")));
92 * Check to see if we want to replace an existing view.
94 namespaceId = RangeVarGetCreationNamespace(relation);
95 viewOid = get_relname_relid(relation->relname, namespaceId);
97 if (OidIsValid(viewOid) && replace)
100 TupleDesc descriptor;
103 * Yes. Get exclusive lock on the existing view ...
105 rel = relation_open(viewOid, AccessExclusiveLock);
108 * Make sure it *is* a view, and do permissions checks.
110 if (rel->rd_rel->relkind != RELKIND_VIEW)
112 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
113 errmsg("\"%s\" is not a view",
114 RelationGetRelationName(rel))));
116 if (!pg_class_ownercheck(viewOid, GetUserId()))
117 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
118 RelationGetRelationName(rel));
121 * Create a tuple descriptor to compare against the existing view,
122 * and verify it matches.
124 descriptor = BuildDescForRelation(attrList);
125 checkViewTupleDesc(descriptor, rel->rd_att);
128 * Seems okay, so return the OID of the pre-existing view.
130 relation_close(rel, NoLock); /* keep the lock! */
137 * now create the parameters for keys/inheritance etc. All of them
140 createStmt->relation = (RangeVar *) relation;
141 createStmt->tableElts = attrList;
142 createStmt->inhRelations = NIL;
143 createStmt->constraints = NIL;
144 createStmt->hasoids = false;
145 createStmt->oncommit = ONCOMMIT_NOOP;
148 * finally create the relation (this will error out if there's an
149 * existing view, so we don't need more code to complain if
150 * "replace" is false).
152 return DefineRelation(createStmt, RELKIND_VIEW);
157 * Verify that tupledesc associated with proposed new view definition
158 * matches tupledesc of old view. This is basically a cut-down version
159 * of equalTupleDescs(), with code added to generate specific complaints.
162 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
166 if (newdesc->natts != olddesc->natts)
168 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
169 errmsg("cannot change number of columns in view")));
170 /* we can ignore tdhasoid */
172 for (i = 0; i < newdesc->natts; i++)
174 Form_pg_attribute newattr = newdesc->attrs[i];
175 Form_pg_attribute oldattr = olddesc->attrs[i];
177 /* XXX not right, but we don't support DROP COL on view anyway */
178 if (newattr->attisdropped != oldattr->attisdropped)
180 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
181 errmsg("cannot change number of columns in view")));
183 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
185 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
186 errmsg("cannot change name of view column \"%s\"",
187 NameStr(oldattr->attname))));
188 /* XXX would it be safe to allow atttypmod to change? Not sure */
189 if (newattr->atttypid != oldattr->atttypid ||
190 newattr->atttypmod != oldattr->atttypmod)
192 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
193 errmsg("cannot change datatype of view column \"%s\"",
194 NameStr(oldattr->attname))));
195 /* We can ignore the remaining attributes of an attribute... */
199 * We ignore the constraint fields. The new view desc can't have any
200 * constraints, and the only ones that could be on the old view are
201 * defaults, which we are happy to leave in place.
206 FormViewRetrieveRule(const RangeVar *view, Query *viewParse, bool replace)
211 * Create a RuleStmt that corresponds to the suitable rewrite rule
212 * args for DefineQueryRewrite();
214 rule = makeNode(RuleStmt);
215 rule->relation = copyObject((RangeVar *) view);
216 rule->rulename = pstrdup(ViewSelectRuleName);
217 rule->whereClause = NULL;
218 rule->event = CMD_SELECT;
219 rule->instead = true;
220 rule->actions = makeList1(viewParse);
221 rule->replace = replace;
227 DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
229 RuleStmt *retrieve_rule;
232 RuleStmt *replace_rule;
233 RuleStmt *append_rule;
234 RuleStmt *delete_rule;
237 retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
240 replace_rule = FormViewReplaceRule(view, viewParse);
241 append_rule = FormViewAppendRule(view, viewParse);
242 delete_rule = FormViewDeleteRule(view, viewParse);
245 DefineQueryRewrite(retrieve_rule);
248 DefineQueryRewrite(replace_rule);
249 DefineQueryRewrite(append_rule);
250 DefineQueryRewrite(delete_rule);
255 /*---------------------------------------------------------------
256 * UpdateRangeTableOfViewParse
258 * Update the range table of the given parsetree.
259 * This update consists of adding two new entries IN THE BEGINNING
260 * of the range table (otherwise the rule system will die a slow,
261 * horrible and painful death, and we do not want that now, do we?)
262 * one for the OLD relation and one for the NEW one (both of
263 * them refer in fact to the "view" relation).
265 * Of course we must also increase the 'varnos' of all the Var nodes
268 * These extra RT entries are not actually used in the query,
269 * except for run-time permission checking.
270 *---------------------------------------------------------------
273 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
276 RangeTblEntry *rt_entry1,
280 * Make a copy of the given parsetree. It's not so much that we don't
281 * want to scribble on our input, it's that the parser has a bad habit
282 * of outputting multiple links to the same subtree for constructs
283 * like BETWEEN, and we mustn't have OffsetVarNodes increment the
284 * varno of a Var node twice. copyObject will expand any
285 * multiply-referenced subtree into multiple copies.
287 viewParse = (Query *) copyObject(viewParse);
290 * Create the 2 new range table entries and form the new range
291 * table... OLD first, then NEW....
293 rt_entry1 = addRangeTableEntryForRelation(NULL, viewOid,
294 makeAlias("*OLD*", NIL),
296 rt_entry2 = addRangeTableEntryForRelation(NULL, viewOid,
297 makeAlias("*NEW*", NIL),
299 /* Must override addRangeTableEntry's default access-check flags */
300 rt_entry1->checkForRead = false;
301 rt_entry2->checkForRead = false;
303 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
305 viewParse->rtable = new_rt;
308 * Now offset all var nodes by 2, and jointree RT indexes too.
310 OffsetVarNodes((Node *) viewParse, 2, 0);
315 /*-------------------------------------------------------------------
318 * - takes a "viewname", "parsetree" pair and then
319 * 1) construct the "virtual" relation
320 * 2) commit the command but NOT the transaction,
321 * so that the relation exists
322 * before the rules are defined.
323 * 2) define the "n" rules specified in the PRS2 paper
324 * over the "virtual" relation
325 *-------------------------------------------------------------------
328 DefineView(const RangeVar *view, Query *viewParse, bool replace)
333 * Create the view relation
335 * NOTE: if it already exists and replace is false, the xact will be
339 viewOid = DefineVirtualRelation(view, viewParse->targetList, replace);
342 * The relation we have just created is not visible to any other
343 * commands running with the same transaction & command id. So,
344 * increment the command id counter (but do NOT pfree any memory!!!!)
346 CommandCounterIncrement();
349 * The range table of 'viewParse' does not contain entries for the
350 * "OLD" and "NEW" relations. So... add them!
352 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
355 * Now create the rules associated with the view.
357 DefineViewRules(view, viewParse, replace);
363 * Remove a view given its name
365 * We just have to drop the relation; the associated rules will be
366 * cleaned up automatically.
369 RemoveView(const RangeVar *view, DropBehavior behavior)
372 ObjectAddress object;
374 viewOid = RangeVarGetRelid(view, false);
376 object.classId = RelOid_pg_class;
377 object.objectId = viewOid;
378 object.objectSubId = 0;
380 performDeletion(&object, behavior);