1 /*-------------------------------------------------------------------------
4 * use rewrite rules to construct views
6 * Portions Copyright (c) 1996-2008, 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.110 2008/12/16 00:56:12 tgl 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;
127 def->raw_default = NULL;
128 def->cooked_default = NULL;
129 def->constraints = NIL;
131 attrList = lappend(attrList, def);
137 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
138 errmsg("view must have at least one column")));
141 * Check to see if we want to replace an existing view.
143 namespaceId = RangeVarGetCreationNamespace(relation);
144 viewOid = get_relname_relid(relation->relname, namespaceId);
146 if (OidIsValid(viewOid) && replace)
149 TupleDesc descriptor;
152 * Yes. Get exclusive lock on the existing view ...
154 rel = relation_open(viewOid, AccessExclusiveLock);
157 * Make sure it *is* a view, and do permissions checks.
159 if (rel->rd_rel->relkind != RELKIND_VIEW)
161 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
162 errmsg("\"%s\" is not a view",
163 RelationGetRelationName(rel))));
165 if (!pg_class_ownercheck(viewOid, GetUserId()))
166 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
167 RelationGetRelationName(rel));
169 /* Also check it's not in use already */
170 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
173 * Due to the namespace visibility rules for temporary objects, we
174 * should only end up replacing a temporary view with another
175 * temporary view, and vice versa.
177 Assert(relation->istemp == rel->rd_istemp);
180 * Create a tuple descriptor to compare against the existing view, and
181 * verify that the old column list is an initial prefix of the new
184 descriptor = BuildDescForRelation(attrList);
185 checkViewTupleDesc(descriptor, rel->rd_att);
188 * If new attributes have been added, we must add pg_attribute entries
189 * for them. It is convenient (although overkill) to use the ALTER
190 * TABLE ADD COLUMN infrastructure for this.
192 if (list_length(attrList) > rel->rd_att->natts)
196 int skip = rel->rd_att->natts;
200 AlterTableCmd *atcmd;
207 atcmd = makeNode(AlterTableCmd);
208 atcmd->subtype = AT_AddColumnToView;
209 atcmd->def = (Node *) lfirst(c);
210 atcmds = lappend(atcmds, atcmd);
212 AlterTableInternal(viewOid, atcmds, true);
216 * Seems okay, so return the OID of the pre-existing view.
218 relation_close(rel, NoLock); /* keep the lock! */
225 * now set the parameters for keys/inheritance etc. All of these are
226 * uninteresting for views...
228 createStmt->relation = (RangeVar *) relation;
229 createStmt->tableElts = attrList;
230 createStmt->inhRelations = NIL;
231 createStmt->constraints = NIL;
232 createStmt->options = list_make1(defWithOids(false));
233 createStmt->oncommit = ONCOMMIT_NOOP;
234 createStmt->tablespacename = NULL;
237 * finally create the relation (this will error out if there's an
238 * existing view, so we don't need more code to complain if "replace"
241 return DefineRelation(createStmt, RELKIND_VIEW);
246 * Verify that tupledesc associated with proposed new view definition
247 * matches tupledesc of old view. This is basically a cut-down version
248 * of equalTupleDescs(), with code added to generate specific complaints.
249 * Also, we allow the new tupledesc to have more columns than the old.
252 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
256 if (newdesc->natts < olddesc->natts)
258 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
259 errmsg("cannot drop columns from view")));
260 /* we can ignore tdhasoid */
262 for (i = 0; i < olddesc->natts; i++)
264 Form_pg_attribute newattr = newdesc->attrs[i];
265 Form_pg_attribute oldattr = olddesc->attrs[i];
267 /* XXX msg not right, but we don't support DROP COL on view anyway */
268 if (newattr->attisdropped != oldattr->attisdropped)
270 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
271 errmsg("cannot drop columns from view")));
273 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
275 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
276 errmsg("cannot change name of view column \"%s\" to \"%s\"",
277 NameStr(oldattr->attname),
278 NameStr(newattr->attname))));
279 /* XXX would it be safe to allow atttypmod to change? Not sure */
280 if (newattr->atttypid != oldattr->atttypid ||
281 newattr->atttypmod != oldattr->atttypmod)
283 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
284 errmsg("cannot change data type of view column \"%s\" from %s to %s",
285 NameStr(oldattr->attname),
286 format_type_with_typemod(oldattr->atttypid,
288 format_type_with_typemod(newattr->atttypid,
289 newattr->atttypmod))));
290 /* We can ignore the remaining attributes of an attribute... */
294 * We ignore the constraint fields. The new view desc can't have any
295 * constraints, and the only ones that could be on the old view are
296 * defaults, which we are happy to leave in place.
301 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
304 * Set up the ON SELECT rule. Since the query has already been through
305 * parse analysis, we use DefineQueryRewrite() directly.
307 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
313 list_make1(viewParse));
316 * Someday: automatic ON INSERT, etc
320 /*---------------------------------------------------------------
321 * UpdateRangeTableOfViewParse
323 * Update the range table of the given parsetree.
324 * This update consists of adding two new entries IN THE BEGINNING
325 * of the range table (otherwise the rule system will die a slow,
326 * horrible and painful death, and we do not want that now, do we?)
327 * one for the OLD relation and one for the NEW one (both of
328 * them refer in fact to the "view" relation).
330 * Of course we must also increase the 'varnos' of all the Var nodes
333 * These extra RT entries are not actually used in the query,
334 * except for run-time permission checking.
335 *---------------------------------------------------------------
338 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
342 RangeTblEntry *rt_entry1,
346 * Make a copy of the given parsetree. It's not so much that we don't
347 * want to scribble on our input, it's that the parser has a bad habit of
348 * outputting multiple links to the same subtree for constructs like
349 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
350 * Var node twice. copyObject will expand any multiply-referenced subtree
351 * into multiple copies.
353 viewParse = (Query *) copyObject(viewParse);
355 /* need to open the rel for addRangeTableEntryForRelation */
356 viewRel = relation_open(viewOid, AccessShareLock);
359 * Create the 2 new range table entries and form the new range table...
360 * OLD first, then NEW....
362 rt_entry1 = addRangeTableEntryForRelation(NULL, viewRel,
363 makeAlias("*OLD*", NIL),
365 rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
366 makeAlias("*NEW*", NIL),
368 /* Must override addRangeTableEntry's default access-check flags */
369 rt_entry1->requiredPerms = 0;
370 rt_entry2->requiredPerms = 0;
372 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
374 viewParse->rtable = new_rt;
377 * Now offset all var nodes by 2, and jointree RT indexes too.
379 OffsetVarNodes((Node *) viewParse, 2, 0);
381 relation_close(viewRel, AccessShareLock);
388 * Execute a CREATE VIEW command.
391 DefineView(ViewStmt *stmt, const char *queryString)
398 * Run parse analysis to convert the raw parse tree to a Query. Note this
399 * also acquires sufficient locks on the source table(s).
401 * Since parse analysis scribbles on its input, copy the raw parse tree;
402 * this ensures we don't corrupt a prepared statement, for example.
404 viewParse = parse_analyze((Node *) copyObject(stmt->query),
405 queryString, NULL, 0);
408 * The grammar should ensure that the result is a single SELECT Query.
410 if (!IsA(viewParse, Query) ||
411 viewParse->commandType != CMD_SELECT)
412 elog(ERROR, "unexpected parse analysis result");
415 * If a list of column names was given, run through and insert these into
416 * the actual query tree. - thomas 2000-03-08
418 if (stmt->aliases != NIL)
420 ListCell *alist_item = list_head(stmt->aliases);
421 ListCell *targetList;
423 foreach(targetList, viewParse->targetList)
425 TargetEntry *te = (TargetEntry *) lfirst(targetList);
427 Assert(IsA(te, TargetEntry));
428 /* junk columns don't get aliases */
431 te->resname = pstrdup(strVal(lfirst(alist_item)));
432 alist_item = lnext(alist_item);
433 if (alist_item == NULL)
434 break; /* done assigning aliases */
437 if (alist_item != NULL)
439 (errcode(ERRCODE_SYNTAX_ERROR),
440 errmsg("CREATE VIEW specifies more column "
441 "names than columns")));
445 * If the user didn't explicitly ask for a temporary view, check whether
446 * we need one implicitly. We allow TEMP to be inserted automatically as
447 * long as the CREATE command is consistent with that --- no explicit
451 if (!view->istemp && isViewOnTempTable(viewParse))
453 view = copyObject(view); /* don't corrupt original command */
456 (errmsg("view \"%s\" will be a temporary view",
461 * Create the view relation
463 * NOTE: if it already exists and replace is false, the xact will be
466 viewOid = DefineVirtualRelation(view, viewParse->targetList,
470 * The relation we have just created is not visible to any other commands
471 * running with the same transaction & command id. So, increment the
472 * command id counter (but do NOT pfree any memory!!!!)
474 CommandCounterIncrement();
477 * The range table of 'viewParse' does not contain entries for the "OLD"
478 * and "NEW" relations. So... add them!
480 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
483 * Now create the rules associated with the view.
485 DefineViewRules(viewOid, viewParse, stmt->replace);