1 /*-------------------------------------------------------------------------
4 * use rewrite rules to construct views
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/view.c
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 char relpersistence = rel->rd_rel->relpersistence;
73 heap_close(rel, AccessShareLock);
74 if (relpersistence == RELPERSISTENCE_TEMP)
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;
127 def->is_from_type = false;
129 def->raw_default = NULL;
130 def->cooked_default = NULL;
131 def->collClause = NULL;
133 * XXX Temporary kluge to make regression tests pass. We should
134 * be able to trust the result of exprCollation more than this.
136 if (type_is_collatable(exprType((Node *) tle->expr)))
137 def->collOid = exprCollation((Node *) tle->expr);
139 def->collOid = InvalidOid;
140 def->constraints = NIL;
142 attrList = lappend(attrList, def);
148 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
149 errmsg("view must have at least one column")));
152 * Check to see if we want to replace an existing view.
154 namespaceId = RangeVarGetCreationNamespace(relation);
155 viewOid = get_relname_relid(relation->relname, namespaceId);
157 if (OidIsValid(viewOid) && replace)
160 TupleDesc descriptor;
163 * Yes. Get exclusive lock on the existing view ...
165 rel = relation_open(viewOid, AccessExclusiveLock);
168 * Make sure it *is* a view, and do permissions checks.
170 if (rel->rd_rel->relkind != RELKIND_VIEW)
172 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
173 errmsg("\"%s\" is not a view",
174 RelationGetRelationName(rel))));
176 if (!pg_class_ownercheck(viewOid, GetUserId()))
177 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
178 RelationGetRelationName(rel));
180 /* Also check it's not in use already */
181 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
184 * Due to the namespace visibility rules for temporary objects, we
185 * should only end up replacing a temporary view with another
186 * temporary view, and similarly for permanent views.
188 Assert(relation->relpersistence == rel->rd_rel->relpersistence);
191 * Create a tuple descriptor to compare against the existing view, and
192 * verify that the old column list is an initial prefix of the new
195 descriptor = BuildDescForRelation(attrList);
196 checkViewTupleDesc(descriptor, rel->rd_att);
199 * If new attributes have been added, we must add pg_attribute entries
200 * for them. It is convenient (although overkill) to use the ALTER
201 * TABLE ADD COLUMN infrastructure for this.
203 if (list_length(attrList) > rel->rd_att->natts)
207 int skip = rel->rd_att->natts;
211 AlterTableCmd *atcmd;
218 atcmd = makeNode(AlterTableCmd);
219 atcmd->subtype = AT_AddColumnToView;
220 atcmd->def = (Node *) lfirst(c);
221 atcmds = lappend(atcmds, atcmd);
223 AlterTableInternal(viewOid, atcmds, true);
227 * Seems okay, so return the OID of the pre-existing view.
229 relation_close(rel, NoLock); /* keep the lock! */
238 * now set the parameters for keys/inheritance etc. All of these are
239 * uninteresting for views...
241 createStmt->relation = (RangeVar *) relation;
242 createStmt->tableElts = attrList;
243 createStmt->inhRelations = NIL;
244 createStmt->constraints = NIL;
245 createStmt->options = list_make1(defWithOids(false));
246 createStmt->oncommit = ONCOMMIT_NOOP;
247 createStmt->tablespacename = NULL;
248 createStmt->if_not_exists = false;
251 * finally create the relation (this will error out if there's an
252 * existing view, so we don't need more code to complain if "replace"
255 relid = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid);
256 Assert(relid != InvalidOid);
262 * Verify that tupledesc associated with proposed new view definition
263 * matches tupledesc of old view. This is basically a cut-down version
264 * of equalTupleDescs(), with code added to generate specific complaints.
265 * Also, we allow the new tupledesc to have more columns than the old.
268 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
272 if (newdesc->natts < olddesc->natts)
274 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
275 errmsg("cannot drop columns from view")));
276 /* we can ignore tdhasoid */
278 for (i = 0; i < olddesc->natts; i++)
280 Form_pg_attribute newattr = newdesc->attrs[i];
281 Form_pg_attribute oldattr = olddesc->attrs[i];
283 /* XXX msg not right, but we don't support DROP COL on view anyway */
284 if (newattr->attisdropped != oldattr->attisdropped)
286 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
287 errmsg("cannot drop columns from view")));
289 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
291 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
292 errmsg("cannot change name of view column \"%s\" to \"%s\"",
293 NameStr(oldattr->attname),
294 NameStr(newattr->attname))));
295 /* XXX would it be safe to allow atttypmod to change? Not sure */
296 if (newattr->atttypid != oldattr->atttypid ||
297 newattr->atttypmod != oldattr->atttypmod)
299 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
300 errmsg("cannot change data type of view column \"%s\" from %s to %s",
301 NameStr(oldattr->attname),
302 format_type_with_typemod(oldattr->atttypid,
304 format_type_with_typemod(newattr->atttypid,
305 newattr->atttypmod))));
306 /* We can ignore the remaining attributes of an attribute... */
310 * We ignore the constraint fields. The new view desc can't have any
311 * constraints, and the only ones that could be on the old view are
312 * defaults, which we are happy to leave in place.
317 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
320 * Set up the ON SELECT rule. Since the query has already been through
321 * parse analysis, we use DefineQueryRewrite() directly.
323 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
329 list_make1(viewParse));
332 * Someday: automatic ON INSERT, etc
336 /*---------------------------------------------------------------
337 * UpdateRangeTableOfViewParse
339 * Update the range table of the given parsetree.
340 * This update consists of adding two new entries IN THE BEGINNING
341 * of the range table (otherwise the rule system will die a slow,
342 * horrible and painful death, and we do not want that now, do we?)
343 * one for the OLD relation and one for the NEW one (both of
344 * them refer in fact to the "view" relation).
346 * Of course we must also increase the 'varnos' of all the Var nodes
349 * These extra RT entries are not actually used in the query,
350 * except for run-time permission checking.
351 *---------------------------------------------------------------
354 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
358 RangeTblEntry *rt_entry1,
362 * Make a copy of the given parsetree. It's not so much that we don't
363 * want to scribble on our input, it's that the parser has a bad habit of
364 * outputting multiple links to the same subtree for constructs like
365 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
366 * Var node twice. copyObject will expand any multiply-referenced subtree
367 * into multiple copies.
369 viewParse = (Query *) copyObject(viewParse);
371 /* need to open the rel for addRangeTableEntryForRelation */
372 viewRel = relation_open(viewOid, AccessShareLock);
375 * Create the 2 new range table entries and form the new range table...
376 * OLD first, then NEW....
378 rt_entry1 = addRangeTableEntryForRelation(NULL, viewRel,
379 makeAlias("old", NIL),
381 rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
382 makeAlias("new", NIL),
384 /* Must override addRangeTableEntry's default access-check flags */
385 rt_entry1->requiredPerms = 0;
386 rt_entry2->requiredPerms = 0;
388 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
390 viewParse->rtable = new_rt;
393 * Now offset all var nodes by 2, and jointree RT indexes too.
395 OffsetVarNodes((Node *) viewParse, 2, 0);
397 relation_close(viewRel, AccessShareLock);
404 * Execute a CREATE VIEW command.
407 DefineView(ViewStmt *stmt, const char *queryString)
414 * Run parse analysis to convert the raw parse tree to a Query. Note this
415 * also acquires sufficient locks on the source table(s).
417 * Since parse analysis scribbles on its input, copy the raw parse tree;
418 * this ensures we don't corrupt a prepared statement, for example.
420 viewParse = parse_analyze((Node *) copyObject(stmt->query),
421 queryString, NULL, 0);
424 * The grammar should ensure that the result is a single SELECT Query.
426 if (!IsA(viewParse, Query) ||
427 viewParse->commandType != CMD_SELECT)
428 elog(ERROR, "unexpected parse analysis result");
431 * Check for unsupported cases. These tests are redundant with ones in
432 * DefineQueryRewrite(), but that function will complain about a bogus
433 * ON SELECT rule, and we'd rather the message complain about a view.
435 if (viewParse->intoClause != NULL)
437 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
438 errmsg("views must not contain SELECT INTO")));
439 if (viewParse->hasModifyingCTE)
441 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
442 errmsg("views must not contain data-modifying statements in WITH")));
445 * If a list of column names was given, run through and insert these into
446 * the actual query tree. - thomas 2000-03-08
448 if (stmt->aliases != NIL)
450 ListCell *alist_item = list_head(stmt->aliases);
451 ListCell *targetList;
453 foreach(targetList, viewParse->targetList)
455 TargetEntry *te = (TargetEntry *) lfirst(targetList);
457 Assert(IsA(te, TargetEntry));
458 /* junk columns don't get aliases */
461 te->resname = pstrdup(strVal(lfirst(alist_item)));
462 alist_item = lnext(alist_item);
463 if (alist_item == NULL)
464 break; /* done assigning aliases */
467 if (alist_item != NULL)
469 (errcode(ERRCODE_SYNTAX_ERROR),
470 errmsg("CREATE VIEW specifies more column "
471 "names than columns")));
475 * If the user didn't explicitly ask for a temporary view, check whether
476 * we need one implicitly. We allow TEMP to be inserted automatically as
477 * long as the CREATE command is consistent with that --- no explicit
481 if (view->relpersistence == RELPERSISTENCE_PERMANENT
482 && isViewOnTempTable(viewParse))
484 view = copyObject(view); /* don't corrupt original command */
485 view->relpersistence = RELPERSISTENCE_TEMP;
487 (errmsg("view \"%s\" will be a temporary view",
491 /* Unlogged views are not sensible. */
492 if (view->relpersistence == RELPERSISTENCE_UNLOGGED)
494 (errcode(ERRCODE_SYNTAX_ERROR),
495 errmsg("views cannot be unlogged because they do not have storage")));
498 * Create the view relation
500 * NOTE: if it already exists and replace is false, the xact will be
503 viewOid = DefineVirtualRelation(view, viewParse->targetList,
507 * The relation we have just created is not visible to any other commands
508 * running with the same transaction & command id. So, increment the
509 * command id counter (but do NOT pfree any memory!!!!)
511 CommandCounterIncrement();
514 * The range table of 'viewParse' does not contain entries for the "OLD"
515 * and "NEW" relations. So... add them!
517 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
520 * Now create the rules associated with the view.
522 DefineViewRules(viewOid, viewParse, stmt->replace);