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;
132 def->collOid = exprCollation((Node *) tle->expr);
135 * It's possible that the column is of a collatable type but the
136 * collation could not be resolved, so double-check.
138 if (type_is_collatable(exprType((Node *) tle->expr)))
140 if (!OidIsValid(def->collOid))
142 (errcode(ERRCODE_INDETERMINATE_COLLATION),
143 errmsg("could not determine which collation to use for view column \"%s\"",
145 errhint("Use the COLLATE clause to set the collation explicitly.")));
148 Assert(!OidIsValid(def->collOid));
149 def->constraints = NIL;
151 attrList = lappend(attrList, def);
157 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
158 errmsg("view must have at least one column")));
161 * Check to see if we want to replace an existing view.
163 namespaceId = RangeVarGetCreationNamespace(relation);
164 viewOid = get_relname_relid(relation->relname, namespaceId);
166 if (OidIsValid(viewOid) && replace)
169 TupleDesc descriptor;
172 * Yes. Get exclusive lock on the existing view ...
174 rel = relation_open(viewOid, AccessExclusiveLock);
177 * Make sure it *is* a view, and do permissions checks.
179 if (rel->rd_rel->relkind != RELKIND_VIEW)
181 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
182 errmsg("\"%s\" is not a view",
183 RelationGetRelationName(rel))));
185 if (!pg_class_ownercheck(viewOid, GetUserId()))
186 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
187 RelationGetRelationName(rel));
189 /* Also check it's not in use already */
190 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
193 * Due to the namespace visibility rules for temporary objects, we
194 * should only end up replacing a temporary view with another
195 * temporary view, and similarly for permanent views.
197 Assert(relation->relpersistence == rel->rd_rel->relpersistence);
200 * Create a tuple descriptor to compare against the existing view, and
201 * verify that the old column list is an initial prefix of the new
204 descriptor = BuildDescForRelation(attrList);
205 checkViewTupleDesc(descriptor, rel->rd_att);
208 * If new attributes have been added, we must add pg_attribute entries
209 * for them. It is convenient (although overkill) to use the ALTER
210 * TABLE ADD COLUMN infrastructure for this.
212 if (list_length(attrList) > rel->rd_att->natts)
216 int skip = rel->rd_att->natts;
220 AlterTableCmd *atcmd;
227 atcmd = makeNode(AlterTableCmd);
228 atcmd->subtype = AT_AddColumnToView;
229 atcmd->def = (Node *) lfirst(c);
230 atcmds = lappend(atcmds, atcmd);
232 AlterTableInternal(viewOid, atcmds, true);
236 * Seems okay, so return the OID of the pre-existing view.
238 relation_close(rel, NoLock); /* keep the lock! */
247 * now set the parameters for keys/inheritance etc. All of these are
248 * uninteresting for views...
250 createStmt->relation = (RangeVar *) relation;
251 createStmt->tableElts = attrList;
252 createStmt->inhRelations = NIL;
253 createStmt->constraints = NIL;
254 createStmt->options = list_make1(defWithOids(false));
255 createStmt->oncommit = ONCOMMIT_NOOP;
256 createStmt->tablespacename = NULL;
257 createStmt->if_not_exists = false;
260 * finally create the relation (this will error out if there's an
261 * existing view, so we don't need more code to complain if "replace"
264 relid = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid);
265 Assert(relid != InvalidOid);
271 * Verify that tupledesc associated with proposed new view definition
272 * matches tupledesc of old view. This is basically a cut-down version
273 * of equalTupleDescs(), with code added to generate specific complaints.
274 * Also, we allow the new tupledesc to have more columns than the old.
277 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
281 if (newdesc->natts < olddesc->natts)
283 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
284 errmsg("cannot drop columns from view")));
285 /* we can ignore tdhasoid */
287 for (i = 0; i < olddesc->natts; i++)
289 Form_pg_attribute newattr = newdesc->attrs[i];
290 Form_pg_attribute oldattr = olddesc->attrs[i];
292 /* XXX msg not right, but we don't support DROP COL on view anyway */
293 if (newattr->attisdropped != oldattr->attisdropped)
295 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
296 errmsg("cannot drop columns from view")));
298 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
300 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
301 errmsg("cannot change name of view column \"%s\" to \"%s\"",
302 NameStr(oldattr->attname),
303 NameStr(newattr->attname))));
304 /* XXX would it be safe to allow atttypmod to change? Not sure */
305 if (newattr->atttypid != oldattr->atttypid ||
306 newattr->atttypmod != oldattr->atttypmod)
308 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
309 errmsg("cannot change data type of view column \"%s\" from %s to %s",
310 NameStr(oldattr->attname),
311 format_type_with_typemod(oldattr->atttypid,
313 format_type_with_typemod(newattr->atttypid,
314 newattr->atttypmod))));
315 /* We can ignore the remaining attributes of an attribute... */
319 * We ignore the constraint fields. The new view desc can't have any
320 * constraints, and the only ones that could be on the old view are
321 * defaults, which we are happy to leave in place.
326 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
329 * Set up the ON SELECT rule. Since the query has already been through
330 * parse analysis, we use DefineQueryRewrite() directly.
332 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
338 list_make1(viewParse));
341 * Someday: automatic ON INSERT, etc
345 /*---------------------------------------------------------------
346 * UpdateRangeTableOfViewParse
348 * Update the range table of the given parsetree.
349 * This update consists of adding two new entries IN THE BEGINNING
350 * of the range table (otherwise the rule system will die a slow,
351 * horrible and painful death, and we do not want that now, do we?)
352 * one for the OLD relation and one for the NEW one (both of
353 * them refer in fact to the "view" relation).
355 * Of course we must also increase the 'varnos' of all the Var nodes
358 * These extra RT entries are not actually used in the query,
359 * except for run-time permission checking.
360 *---------------------------------------------------------------
363 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
367 RangeTblEntry *rt_entry1,
371 * Make a copy of the given parsetree. It's not so much that we don't
372 * want to scribble on our input, it's that the parser has a bad habit of
373 * outputting multiple links to the same subtree for constructs like
374 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
375 * Var node twice. copyObject will expand any multiply-referenced subtree
376 * into multiple copies.
378 viewParse = (Query *) copyObject(viewParse);
380 /* need to open the rel for addRangeTableEntryForRelation */
381 viewRel = relation_open(viewOid, AccessShareLock);
384 * Create the 2 new range table entries and form the new range table...
385 * OLD first, then NEW....
387 rt_entry1 = addRangeTableEntryForRelation(NULL, viewRel,
388 makeAlias("old", NIL),
390 rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
391 makeAlias("new", NIL),
393 /* Must override addRangeTableEntry's default access-check flags */
394 rt_entry1->requiredPerms = 0;
395 rt_entry2->requiredPerms = 0;
397 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
399 viewParse->rtable = new_rt;
402 * Now offset all var nodes by 2, and jointree RT indexes too.
404 OffsetVarNodes((Node *) viewParse, 2, 0);
406 relation_close(viewRel, AccessShareLock);
413 * Execute a CREATE VIEW command.
416 DefineView(ViewStmt *stmt, const char *queryString)
423 * Run parse analysis to convert the raw parse tree to a Query. Note this
424 * also acquires sufficient locks on the source table(s).
426 * Since parse analysis scribbles on its input, copy the raw parse tree;
427 * this ensures we don't corrupt a prepared statement, for example.
429 viewParse = parse_analyze((Node *) copyObject(stmt->query),
430 queryString, NULL, 0);
433 * The grammar should ensure that the result is a single SELECT Query.
435 if (!IsA(viewParse, Query) ||
436 viewParse->commandType != CMD_SELECT)
437 elog(ERROR, "unexpected parse analysis result");
440 * Check for unsupported cases. These tests are redundant with ones in
441 * DefineQueryRewrite(), but that function will complain about a bogus ON
442 * SELECT rule, and we'd rather the message complain about a view.
444 if (viewParse->intoClause != NULL)
446 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
447 errmsg("views must not contain SELECT INTO")));
448 if (viewParse->hasModifyingCTE)
450 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
451 errmsg("views must not contain data-modifying statements in WITH")));
454 * If a list of column names was given, run through and insert these into
455 * the actual query tree. - thomas 2000-03-08
457 if (stmt->aliases != NIL)
459 ListCell *alist_item = list_head(stmt->aliases);
460 ListCell *targetList;
462 foreach(targetList, viewParse->targetList)
464 TargetEntry *te = (TargetEntry *) lfirst(targetList);
466 Assert(IsA(te, TargetEntry));
467 /* junk columns don't get aliases */
470 te->resname = pstrdup(strVal(lfirst(alist_item)));
471 alist_item = lnext(alist_item);
472 if (alist_item == NULL)
473 break; /* done assigning aliases */
476 if (alist_item != NULL)
478 (errcode(ERRCODE_SYNTAX_ERROR),
479 errmsg("CREATE VIEW specifies more column "
480 "names than columns")));
484 * If the user didn't explicitly ask for a temporary view, check whether
485 * we need one implicitly. We allow TEMP to be inserted automatically as
486 * long as the CREATE command is consistent with that --- no explicit
490 if (view->relpersistence == RELPERSISTENCE_PERMANENT
491 && isViewOnTempTable(viewParse))
493 view = copyObject(view); /* don't corrupt original command */
494 view->relpersistence = RELPERSISTENCE_TEMP;
496 (errmsg("view \"%s\" will be a temporary view",
500 /* Unlogged views are not sensible. */
501 if (view->relpersistence == RELPERSISTENCE_UNLOGGED)
503 (errcode(ERRCODE_SYNTAX_ERROR),
504 errmsg("views cannot be unlogged because they do not have storage")));
507 * Create the view relation
509 * NOTE: if it already exists and replace is false, the xact will be
512 viewOid = DefineVirtualRelation(view, viewParse->targetList,
516 * The relation we have just created is not visible to any other commands
517 * running with the same transaction & command id. So, increment the
518 * command id counter (but do NOT pfree any memory!!!!)
520 CommandCounterIncrement();
523 * The range table of 'viewParse' does not contain entries for the "OLD"
524 * and "NEW" relations. So... add them!
526 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
529 * Now create the rules associated with the view.
531 DefineViewRules(viewOid, viewParse, stmt->replace);