1 /*-------------------------------------------------------------------------
4 * use rewrite rules to construct views
6 * Portions Copyright (c) 1996-2010, 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.121 2010/07/25 23:21:21 rhaas Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "access/xact.h"
19 #include "catalog/namespace.h"
20 #include "commands/defrem.h"
21 #include "commands/tablecmds.h"
22 #include "commands/view.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "nodes/nodeFuncs.h"
26 #include "parser/analyze.h"
27 #include "parser/parse_relation.h"
28 #include "rewrite/rewriteDefine.h"
29 #include "rewrite/rewriteManip.h"
30 #include "rewrite/rewriteSupport.h"
31 #include "utils/acl.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/rel.h"
37 static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
38 static bool isViewOnTempTable_walker(Node *node, void *context);
40 /*---------------------------------------------------------------------
43 * Returns true iff any of the relations underlying this view are
45 *---------------------------------------------------------------------
48 isViewOnTempTable(Query *viewParse)
50 return isViewOnTempTable_walker((Node *) viewParse, NULL);
54 isViewOnTempTable_walker(Node *node, void *context)
61 Query *query = (Query *) node;
64 foreach(rtable, query->rtable)
66 RangeTblEntry *rte = lfirst(rtable);
68 if (rte->rtekind == RTE_RELATION)
70 Relation rel = heap_open(rte->relid, AccessShareLock);
71 bool istemp = rel->rd_istemp;
73 heap_close(rel, AccessShareLock);
79 return query_tree_walker(query,
80 isViewOnTempTable_walker,
82 QTW_IGNORE_JOINALIASES);
85 return expression_tree_walker(node,
86 isViewOnTempTable_walker,
90 /*---------------------------------------------------------------------
91 * DefineVirtualRelation
93 * Create the "view" relation. `DefineRelation' does all the work,
94 * we just provide the correct arguments ... at least when we're
95 * creating a view. If we're updating an existing view, we have to
97 *---------------------------------------------------------------------
100 DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
104 CreateStmt *createStmt = makeNode(CreateStmt);
109 * create a list of ColumnDef nodes based on the names and types of the
110 * (non-junk) targetlist items from the view's SELECT list.
115 TargetEntry *tle = lfirst(t);
119 ColumnDef *def = makeNode(ColumnDef);
121 def->colname = pstrdup(tle->resname);
122 def->typeName = makeTypeNameFromOid(exprType((Node *) tle->expr),
123 exprTypmod((Node *) tle->expr));
125 def->is_local = true;
126 def->is_not_null = false;
128 def->raw_default = NULL;
129 def->cooked_default = NULL;
130 def->constraints = NIL;
132 attrList = lappend(attrList, def);
138 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
139 errmsg("view must have at least one column")));
142 * Check to see if we want to replace an existing view.
144 namespaceId = RangeVarGetCreationNamespace(relation);
145 viewOid = get_relname_relid(relation->relname, namespaceId);
147 if (OidIsValid(viewOid) && replace)
150 TupleDesc descriptor;
153 * Yes. Get exclusive lock on the existing view ...
155 rel = relation_open(viewOid, AccessExclusiveLock);
158 * Make sure it *is* a view, and do permissions checks.
160 if (rel->rd_rel->relkind != RELKIND_VIEW)
162 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
163 errmsg("\"%s\" is not a view",
164 RelationGetRelationName(rel))));
166 if (!pg_class_ownercheck(viewOid, GetUserId()))
167 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
168 RelationGetRelationName(rel));
170 /* Also check it's not in use already */
171 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
174 * Due to the namespace visibility rules for temporary objects, we
175 * should only end up replacing a temporary view with another
176 * temporary view, and vice versa.
178 Assert(relation->istemp == rel->rd_istemp);
181 * Create a tuple descriptor to compare against the existing view, and
182 * verify that the old column list is an initial prefix of the new
185 descriptor = BuildDescForRelation(attrList);
186 checkViewTupleDesc(descriptor, rel->rd_att);
189 * If new attributes have been added, we must add pg_attribute entries
190 * for them. It is convenient (although overkill) to use the ALTER
191 * TABLE ADD COLUMN infrastructure for this.
193 if (list_length(attrList) > rel->rd_att->natts)
197 int skip = rel->rd_att->natts;
201 AlterTableCmd *atcmd;
208 atcmd = makeNode(AlterTableCmd);
209 atcmd->subtype = AT_AddColumnToView;
210 atcmd->def = (Node *) lfirst(c);
211 atcmds = lappend(atcmds, atcmd);
213 AlterTableInternal(viewOid, atcmds, true);
217 * Seems okay, so return the OID of the pre-existing view.
219 relation_close(rel, NoLock); /* keep the lock! */
228 * now set the parameters for keys/inheritance etc. All of these are
229 * uninteresting for views...
231 createStmt->relation = (RangeVar *) relation;
232 createStmt->tableElts = attrList;
233 createStmt->inhRelations = NIL;
234 createStmt->constraints = NIL;
235 createStmt->options = list_make1(defWithOids(false));
236 createStmt->oncommit = ONCOMMIT_NOOP;
237 createStmt->tablespacename = NULL;
238 createStmt->if_not_exists = false;
241 * finally create the relation (this will error out if there's an
242 * existing view, so we don't need more code to complain if "replace"
245 relid = DefineRelation(createStmt, RELKIND_VIEW);
246 Assert(relid != InvalidOid);
252 * Verify that tupledesc associated with proposed new view definition
253 * matches tupledesc of old view. This is basically a cut-down version
254 * of equalTupleDescs(), with code added to generate specific complaints.
255 * Also, we allow the new tupledesc to have more columns than the old.
258 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
262 if (newdesc->natts < olddesc->natts)
264 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
265 errmsg("cannot drop columns from view")));
266 /* we can ignore tdhasoid */
268 for (i = 0; i < olddesc->natts; i++)
270 Form_pg_attribute newattr = newdesc->attrs[i];
271 Form_pg_attribute oldattr = olddesc->attrs[i];
273 /* XXX msg not right, but we don't support DROP COL on view anyway */
274 if (newattr->attisdropped != oldattr->attisdropped)
276 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
277 errmsg("cannot drop columns from view")));
279 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
281 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
282 errmsg("cannot change name of view column \"%s\" to \"%s\"",
283 NameStr(oldattr->attname),
284 NameStr(newattr->attname))));
285 /* XXX would it be safe to allow atttypmod to change? Not sure */
286 if (newattr->atttypid != oldattr->atttypid ||
287 newattr->atttypmod != oldattr->atttypmod)
289 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
290 errmsg("cannot change data type of view column \"%s\" from %s to %s",
291 NameStr(oldattr->attname),
292 format_type_with_typemod(oldattr->atttypid,
294 format_type_with_typemod(newattr->atttypid,
295 newattr->atttypmod))));
296 /* We can ignore the remaining attributes of an attribute... */
300 * We ignore the constraint fields. The new view desc can't have any
301 * constraints, and the only ones that could be on the old view are
302 * defaults, which we are happy to leave in place.
307 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
310 * Set up the ON SELECT rule. Since the query has already been through
311 * parse analysis, we use DefineQueryRewrite() directly.
313 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
319 list_make1(viewParse));
322 * Someday: automatic ON INSERT, etc
326 /*---------------------------------------------------------------
327 * UpdateRangeTableOfViewParse
329 * Update the range table of the given parsetree.
330 * This update consists of adding two new entries IN THE BEGINNING
331 * of the range table (otherwise the rule system will die a slow,
332 * horrible and painful death, and we do not want that now, do we?)
333 * one for the OLD relation and one for the NEW one (both of
334 * them refer in fact to the "view" relation).
336 * Of course we must also increase the 'varnos' of all the Var nodes
339 * These extra RT entries are not actually used in the query,
340 * except for run-time permission checking.
341 *---------------------------------------------------------------
344 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
348 RangeTblEntry *rt_entry1,
352 * Make a copy of the given parsetree. It's not so much that we don't
353 * want to scribble on our input, it's that the parser has a bad habit of
354 * outputting multiple links to the same subtree for constructs like
355 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
356 * Var node twice. copyObject will expand any multiply-referenced subtree
357 * into multiple copies.
359 viewParse = (Query *) copyObject(viewParse);
361 /* need to open the rel for addRangeTableEntryForRelation */
362 viewRel = relation_open(viewOid, AccessShareLock);
365 * Create the 2 new range table entries and form the new range table...
366 * OLD first, then NEW....
368 rt_entry1 = addRangeTableEntryForRelation(NULL, viewRel,
369 makeAlias("old", NIL),
371 rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
372 makeAlias("new", NIL),
374 /* Must override addRangeTableEntry's default access-check flags */
375 rt_entry1->requiredPerms = 0;
376 rt_entry2->requiredPerms = 0;
378 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
380 viewParse->rtable = new_rt;
383 * Now offset all var nodes by 2, and jointree RT indexes too.
385 OffsetVarNodes((Node *) viewParse, 2, 0);
387 relation_close(viewRel, AccessShareLock);
394 * Execute a CREATE VIEW command.
397 DefineView(ViewStmt *stmt, const char *queryString)
404 * Run parse analysis to convert the raw parse tree to a Query. Note this
405 * also acquires sufficient locks on the source table(s).
407 * Since parse analysis scribbles on its input, copy the raw parse tree;
408 * this ensures we don't corrupt a prepared statement, for example.
410 viewParse = parse_analyze((Node *) copyObject(stmt->query),
411 queryString, NULL, 0);
414 * The grammar should ensure that the result is a single SELECT Query.
416 if (!IsA(viewParse, Query) ||
417 viewParse->commandType != CMD_SELECT)
418 elog(ERROR, "unexpected parse analysis result");
421 * If a list of column names was given, run through and insert these into
422 * the actual query tree. - thomas 2000-03-08
424 if (stmt->aliases != NIL)
426 ListCell *alist_item = list_head(stmt->aliases);
427 ListCell *targetList;
429 foreach(targetList, viewParse->targetList)
431 TargetEntry *te = (TargetEntry *) lfirst(targetList);
433 Assert(IsA(te, TargetEntry));
434 /* junk columns don't get aliases */
437 te->resname = pstrdup(strVal(lfirst(alist_item)));
438 alist_item = lnext(alist_item);
439 if (alist_item == NULL)
440 break; /* done assigning aliases */
443 if (alist_item != NULL)
445 (errcode(ERRCODE_SYNTAX_ERROR),
446 errmsg("CREATE VIEW specifies more column "
447 "names than columns")));
451 * If the user didn't explicitly ask for a temporary view, check whether
452 * we need one implicitly. We allow TEMP to be inserted automatically as
453 * long as the CREATE command is consistent with that --- no explicit
457 if (!view->istemp && isViewOnTempTable(viewParse))
459 view = copyObject(view); /* don't corrupt original command */
462 (errmsg("view \"%s\" will be a temporary view",
467 * Create the view relation
469 * NOTE: if it already exists and replace is false, the xact will be
472 viewOid = DefineVirtualRelation(view, viewParse->targetList,
476 * The relation we have just created is not visible to any other commands
477 * running with the same transaction & command id. So, increment the
478 * command id counter (but do NOT pfree any memory!!!!)
480 CommandCounterIncrement();
483 * The range table of 'viewParse' does not contain entries for the "OLD"
484 * and "NEW" relations. So... add them!
486 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
489 * Now create the rules associated with the view.
491 DefineViewRules(viewOid, viewParse, stmt->replace);