1 /*-------------------------------------------------------------------------
4 * use rewrite rules to construct views
6 * Portions Copyright (c) 1996-2019, 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/relation.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/rewriteHandler.h"
31 #include "rewrite/rewriteSupport.h"
32 #include "utils/acl.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/rel.h"
36 #include "utils/syscache.h"
39 static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
41 /*---------------------------------------------------------------------
42 * DefineVirtualRelation
44 * Create a view relation and use the rules system to store the query
47 * EventTriggerAlterTableStart must have been called already.
48 *---------------------------------------------------------------------
51 DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace,
52 List *options, Query *viewParse)
56 CreateStmt *createStmt = makeNode(CreateStmt);
61 * create a list of ColumnDef nodes based on the names and types of the
62 * (non-junk) targetlist items from the view's SELECT list.
67 TargetEntry *tle = (TargetEntry *) lfirst(t);
71 ColumnDef *def = makeColumnDef(tle->resname,
72 exprType((Node *) tle->expr),
73 exprTypmod((Node *) tle->expr),
74 exprCollation((Node *) tle->expr));
77 * It's possible that the column is of a collatable type but the
78 * collation could not be resolved, so double-check.
80 if (type_is_collatable(exprType((Node *) tle->expr)))
82 if (!OidIsValid(def->collOid))
84 (errcode(ERRCODE_INDETERMINATE_COLLATION),
85 errmsg("could not determine which collation to use for view column \"%s\"",
87 errhint("Use the COLLATE clause to set the collation explicitly.")));
90 Assert(!OidIsValid(def->collOid));
92 attrList = lappend(attrList, def);
97 * Look up, check permissions on, and lock the creation namespace; also
98 * check for a preexisting view with the same name. This will also set
99 * relation->relpersistence to RELPERSISTENCE_TEMP if the selected
100 * namespace is temporary.
102 lockmode = replace ? AccessExclusiveLock : NoLock;
103 (void) RangeVarGetAndCheckCreationNamespace(relation, lockmode, &viewOid);
105 if (OidIsValid(viewOid) && replace)
108 TupleDesc descriptor;
110 AlterTableCmd *atcmd;
111 ObjectAddress address;
113 /* Relation is already locked, but we must build a relcache entry. */
114 rel = relation_open(viewOid, NoLock);
116 /* Make sure it *is* a view. */
117 if (rel->rd_rel->relkind != RELKIND_VIEW)
119 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
120 errmsg("\"%s\" is not a view",
121 RelationGetRelationName(rel))));
123 /* Also check it's not in use already */
124 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
127 * Due to the namespace visibility rules for temporary objects, we
128 * should only end up replacing a temporary view with another
129 * temporary view, and similarly for permanent views.
131 Assert(relation->relpersistence == rel->rd_rel->relpersistence);
134 * Create a tuple descriptor to compare against the existing view, and
135 * verify that the old column list is an initial prefix of the new
138 descriptor = BuildDescForRelation(attrList);
139 checkViewTupleDesc(descriptor, rel->rd_att);
142 * If new attributes have been added, we must add pg_attribute entries
143 * for them. It is convenient (although overkill) to use the ALTER
144 * TABLE ADD COLUMN infrastructure for this.
146 * Note that we must do this before updating the query for the view,
147 * since the rules system requires that the correct view columns be in
148 * place when defining the new rules.
150 if (list_length(attrList) > rel->rd_att->natts)
153 int skip = rel->rd_att->natts;
162 atcmd = makeNode(AlterTableCmd);
163 atcmd->subtype = AT_AddColumnToView;
164 atcmd->def = (Node *) lfirst(c);
165 atcmds = lappend(atcmds, atcmd);
168 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
169 AlterTableInternal(viewOid, atcmds, true);
171 /* Make the new view columns visible */
172 CommandCounterIncrement();
176 * Update the query for the view.
178 * Note that we must do this before updating the view options, because
179 * the new options may not be compatible with the old view query (for
180 * example if we attempt to add the WITH CHECK OPTION, we require that
181 * the new view be automatically updatable, but the old view may not
184 StoreViewQuery(viewOid, viewParse, replace);
186 /* Make the new view query visible */
187 CommandCounterIncrement();
190 * Finally update the view options.
192 * The new options list replaces the existing options list, even if
195 atcmd = makeNode(AlterTableCmd);
196 atcmd->subtype = AT_ReplaceRelOptions;
197 atcmd->def = (Node *) options;
198 atcmds = list_make1(atcmd);
200 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
201 AlterTableInternal(viewOid, atcmds, true);
203 ObjectAddressSet(address, RelationRelationId, viewOid);
206 * Seems okay, so return the OID of the pre-existing view.
208 relation_close(rel, NoLock); /* keep the lock! */
214 ObjectAddress address;
217 * Set the parameters for keys/inheritance etc. All of these are
218 * uninteresting for views...
220 createStmt->relation = relation;
221 createStmt->tableElts = attrList;
222 createStmt->inhRelations = NIL;
223 createStmt->constraints = NIL;
224 createStmt->options = options;
225 createStmt->oncommit = ONCOMMIT_NOOP;
226 createStmt->tablespacename = NULL;
227 createStmt->if_not_exists = false;
230 * Create the relation (this will error out if there's an existing
231 * view, so we don't need more code to complain if "replace" is
234 address = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid, NULL,
236 Assert(address.objectId != InvalidOid);
238 /* Make the new view relation visible */
239 CommandCounterIncrement();
241 /* Store the query for the view */
242 StoreViewQuery(address.objectId, viewParse, replace);
249 * Verify that tupledesc associated with proposed new view definition
250 * matches tupledesc of old view. This is basically a cut-down version
251 * of equalTupleDescs(), with code added to generate specific complaints.
252 * Also, we allow the new tupledesc to have more columns than the old.
255 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
259 if (newdesc->natts < olddesc->natts)
261 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
262 errmsg("cannot drop columns from view")));
264 for (i = 0; i < olddesc->natts; i++)
266 Form_pg_attribute newattr = TupleDescAttr(newdesc, i);
267 Form_pg_attribute oldattr = TupleDescAttr(olddesc, i);
269 /* XXX msg not right, but we don't support DROP COL on view anyway */
270 if (newattr->attisdropped != oldattr->attisdropped)
272 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
273 errmsg("cannot drop columns from view")));
275 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
277 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
278 errmsg("cannot change name of view column \"%s\" to \"%s\"",
279 NameStr(oldattr->attname),
280 NameStr(newattr->attname))));
281 /* XXX would it be safe to allow atttypmod to change? Not sure */
282 if (newattr->atttypid != oldattr->atttypid ||
283 newattr->atttypmod != oldattr->atttypmod)
285 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
286 errmsg("cannot change data type of view column \"%s\" from %s to %s",
287 NameStr(oldattr->attname),
288 format_type_with_typemod(oldattr->atttypid,
290 format_type_with_typemod(newattr->atttypid,
291 newattr->atttypmod))));
292 /* We can ignore the remaining attributes of an attribute... */
296 * We ignore the constraint fields. The new view desc can't have any
297 * constraints, and the only ones that could be on the old view are
298 * defaults, which we are happy to leave in place.
303 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
306 * Set up the ON SELECT rule. Since the query has already been through
307 * parse analysis, we use DefineQueryRewrite() directly.
309 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
315 list_make1(viewParse));
318 * Someday: automatic ON INSERT, etc
322 /*---------------------------------------------------------------
323 * UpdateRangeTableOfViewParse
325 * Update the range table of the given parsetree.
326 * This update consists of adding two new entries IN THE BEGINNING
327 * of the range table (otherwise the rule system will die a slow,
328 * horrible and painful death, and we do not want that now, do we?)
329 * one for the OLD relation and one for the NEW one (both of
330 * them refer in fact to the "view" relation).
332 * Of course we must also increase the 'varnos' of all the Var nodes
335 * These extra RT entries are not actually used in the query,
336 * except for run-time locking and permission checking.
337 *---------------------------------------------------------------
340 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
344 RangeTblEntry *rt_entry1,
349 * Make a copy of the given parsetree. It's not so much that we don't
350 * want to scribble on our input, it's that the parser has a bad habit of
351 * outputting multiple links to the same subtree for constructs like
352 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
353 * Var node twice. copyObject will expand any multiply-referenced subtree
354 * into multiple copies.
356 viewParse = copyObject(viewParse);
358 /* Create a dummy ParseState for addRangeTableEntryForRelation */
359 pstate = make_parsestate(NULL);
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(pstate, viewRel,
370 makeAlias("old", NIL),
372 rt_entry2 = addRangeTableEntryForRelation(pstate, viewRel,
374 makeAlias("new", NIL),
376 /* Must override addRangeTableEntry's default access-check flags */
377 rt_entry1->requiredPerms = 0;
378 rt_entry2->requiredPerms = 0;
380 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
382 viewParse->rtable = new_rt;
385 * Now offset all var nodes by 2, and jointree RT indexes too.
387 OffsetVarNodes((Node *) viewParse, 2, 0);
389 relation_close(viewRel, AccessShareLock);
396 * Execute a CREATE VIEW command.
399 DefineView(ViewStmt *stmt, const char *queryString,
400 int stmt_location, int stmt_len)
407 ObjectAddress address;
410 * Run parse analysis to convert the raw parse tree to a Query. Note this
411 * also acquires sufficient locks on the source table(s).
413 * Since parse analysis scribbles on its input, copy the raw parse tree;
414 * this ensures we don't corrupt a prepared statement, for example.
416 rawstmt = makeNode(RawStmt);
417 rawstmt->stmt = (Node *) copyObject(stmt->query);
418 rawstmt->stmt_location = stmt_location;
419 rawstmt->stmt_len = stmt_len;
421 viewParse = parse_analyze(rawstmt, queryString, NULL, 0, NULL);
424 * The grammar should ensure that the result is a single SELECT Query.
425 * However, it doesn't forbid SELECT INTO, so we have to check for that.
427 if (!IsA(viewParse, Query))
428 elog(ERROR, "unexpected parse analysis result");
429 if (viewParse->utilityStmt != NULL &&
430 IsA(viewParse->utilityStmt, CreateTableAsStmt))
432 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
433 errmsg("views must not contain SELECT INTO")));
434 if (viewParse->commandType != CMD_SELECT)
435 elog(ERROR, "unexpected parse analysis result");
438 * Check for unsupported cases. These tests are redundant with ones in
439 * DefineQueryRewrite(), but that function will complain about a bogus ON
440 * SELECT rule, and we'd rather the message complain about a view.
442 if (viewParse->hasModifyingCTE)
444 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
445 errmsg("views must not contain data-modifying statements in WITH")));
448 * If the user specified the WITH CHECK OPTION, add it to the list of
451 if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
452 stmt->options = lappend(stmt->options,
453 makeDefElem("check_option",
454 (Node *) makeString("local"), -1));
455 else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
456 stmt->options = lappend(stmt->options,
457 makeDefElem("check_option",
458 (Node *) makeString("cascaded"), -1));
461 * Check that the view is auto-updatable if WITH CHECK OPTION was
464 check_option = false;
466 foreach(cell, stmt->options)
468 DefElem *defel = (DefElem *) lfirst(cell);
470 if (strcmp(defel->defname, "check_option") == 0)
475 * If the check option is specified, look to see if the view is actually
476 * auto-updatable or not.
480 const char *view_updatable_error =
481 view_query_is_auto_updatable(viewParse, true);
483 if (view_updatable_error)
485 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
486 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
487 errhint("%s", _(view_updatable_error))));
491 * If a list of column names was given, run through and insert these into
492 * the actual query tree. - thomas 2000-03-08
494 if (stmt->aliases != NIL)
496 ListCell *alist_item = list_head(stmt->aliases);
497 ListCell *targetList;
499 foreach(targetList, viewParse->targetList)
501 TargetEntry *te = lfirst_node(TargetEntry, targetList);
503 /* junk columns don't get aliases */
506 te->resname = pstrdup(strVal(lfirst(alist_item)));
507 alist_item = lnext(stmt->aliases, alist_item);
508 if (alist_item == NULL)
509 break; /* done assigning aliases */
512 if (alist_item != NULL)
514 (errcode(ERRCODE_SYNTAX_ERROR),
515 errmsg("CREATE VIEW specifies more column "
516 "names than columns")));
519 /* Unlogged views are not sensible. */
520 if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
522 (errcode(ERRCODE_SYNTAX_ERROR),
523 errmsg("views cannot be unlogged because they do not have storage")));
526 * If the user didn't explicitly ask for a temporary view, check whether
527 * we need one implicitly. We allow TEMP to be inserted automatically as
528 * long as the CREATE command is consistent with that --- no explicit
531 view = copyObject(stmt->view); /* don't corrupt original command */
532 if (view->relpersistence == RELPERSISTENCE_PERMANENT
533 && isQueryUsingTempRelation(viewParse))
535 view->relpersistence = RELPERSISTENCE_TEMP;
537 (errmsg("view \"%s\" will be a temporary view",
542 * Create the view relation
544 * NOTE: if it already exists and replace is false, the xact will be
547 address = DefineVirtualRelation(view, viewParse->targetList,
548 stmt->replace, stmt->options, viewParse);
554 * Use the rules system to store the query for the view.
557 StoreViewQuery(Oid viewOid, Query *viewParse, bool replace)
560 * The range table of 'viewParse' does not contain entries for the "OLD"
561 * and "NEW" relations. So... add them!
563 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
566 * Now create the rules associated with the view.
568 DefineViewRules(viewOid, viewParse, replace);