In extensions, don't replace objects not belonging to the extension.
[pgsql.git] / src / backend / commands / view.c
blobdd7cc9703eca99fb4e2f0a9b1abdcd64d8ebda1d
1 /*-------------------------------------------------------------------------
3 * view.c
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
10 * IDENTIFICATION
11 * src/backend/commands/view.c
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
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 * Validator for "check_option" reloption on views. The allowed values
43 * are "local" and "cascaded".
45 void
46 validateWithCheckOption(const char *value)
48 if (value == NULL ||
49 (strcmp(value, "local") != 0 &&
50 strcmp(value, "cascaded") != 0))
52 ereport(ERROR,
53 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
54 errmsg("invalid value for \"check_option\" option"),
55 errdetail("Valid values are \"local\" and \"cascaded\".")));
59 /*---------------------------------------------------------------------
60 * DefineVirtualRelation
62 * Create a view relation and use the rules system to store the query
63 * for the view.
65 * EventTriggerAlterTableStart must have been called already.
66 *---------------------------------------------------------------------
68 static ObjectAddress
69 DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace,
70 List *options, Query *viewParse)
72 Oid viewOid;
73 LOCKMODE lockmode;
74 CreateStmt *createStmt = makeNode(CreateStmt);
75 List *attrList;
76 ListCell *t;
79 * create a list of ColumnDef nodes based on the names and types of the
80 * (non-junk) targetlist items from the view's SELECT list.
82 attrList = NIL;
83 foreach(t, tlist)
85 TargetEntry *tle = (TargetEntry *) lfirst(t);
87 if (!tle->resjunk)
89 ColumnDef *def = makeColumnDef(tle->resname,
90 exprType((Node *) tle->expr),
91 exprTypmod((Node *) tle->expr),
92 exprCollation((Node *) tle->expr));
95 * It's possible that the column is of a collatable type but the
96 * collation could not be resolved, so double-check.
98 if (type_is_collatable(exprType((Node *) tle->expr)))
100 if (!OidIsValid(def->collOid))
101 ereport(ERROR,
102 (errcode(ERRCODE_INDETERMINATE_COLLATION),
103 errmsg("could not determine which collation to use for view column \"%s\"",
104 def->colname),
105 errhint("Use the COLLATE clause to set the collation explicitly.")));
107 else
108 Assert(!OidIsValid(def->collOid));
110 attrList = lappend(attrList, def);
115 * Look up, check permissions on, and lock the creation namespace; also
116 * check for a preexisting view with the same name. This will also set
117 * relation->relpersistence to RELPERSISTENCE_TEMP if the selected
118 * namespace is temporary.
120 lockmode = replace ? AccessExclusiveLock : NoLock;
121 (void) RangeVarGetAndCheckCreationNamespace(relation, lockmode, &viewOid);
123 if (OidIsValid(viewOid) && replace)
125 Relation rel;
126 TupleDesc descriptor;
127 List *atcmds = NIL;
128 AlterTableCmd *atcmd;
129 ObjectAddress address;
131 /* Relation is already locked, but we must build a relcache entry. */
132 rel = relation_open(viewOid, NoLock);
134 /* Make sure it *is* a view. */
135 if (rel->rd_rel->relkind != RELKIND_VIEW)
136 ereport(ERROR,
137 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
138 errmsg("\"%s\" is not a view",
139 RelationGetRelationName(rel))));
141 /* Also check it's not in use already */
142 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
145 * Due to the namespace visibility rules for temporary objects, we
146 * should only end up replacing a temporary view with another
147 * temporary view, and similarly for permanent views.
149 Assert(relation->relpersistence == rel->rd_rel->relpersistence);
152 * Create a tuple descriptor to compare against the existing view, and
153 * verify that the old column list is an initial prefix of the new
154 * column list.
156 descriptor = BuildDescForRelation(attrList);
157 checkViewTupleDesc(descriptor, rel->rd_att);
160 * If new attributes have been added, we must add pg_attribute entries
161 * for them. It is convenient (although overkill) to use the ALTER
162 * TABLE ADD COLUMN infrastructure for this.
164 * Note that we must do this before updating the query for the view,
165 * since the rules system requires that the correct view columns be in
166 * place when defining the new rules.
168 if (list_length(attrList) > rel->rd_att->natts)
170 ListCell *c;
171 int skip = rel->rd_att->natts;
173 foreach(c, attrList)
175 if (skip > 0)
177 skip--;
178 continue;
180 atcmd = makeNode(AlterTableCmd);
181 atcmd->subtype = AT_AddColumnToView;
182 atcmd->def = (Node *) lfirst(c);
183 atcmds = lappend(atcmds, atcmd);
186 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
187 AlterTableInternal(viewOid, atcmds, true);
189 /* Make the new view columns visible */
190 CommandCounterIncrement();
194 * Update the query for the view.
196 * Note that we must do this before updating the view options, because
197 * the new options may not be compatible with the old view query (for
198 * example if we attempt to add the WITH CHECK OPTION, we require that
199 * the new view be automatically updatable, but the old view may not
200 * have been).
202 StoreViewQuery(viewOid, viewParse, replace);
204 /* Make the new view query visible */
205 CommandCounterIncrement();
208 * Update the view's options.
210 * The new options list replaces the existing options list, even if
211 * it's empty.
213 atcmd = makeNode(AlterTableCmd);
214 atcmd->subtype = AT_ReplaceRelOptions;
215 atcmd->def = (Node *) options;
216 atcmds = list_make1(atcmd);
218 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
219 AlterTableInternal(viewOid, atcmds, true);
222 * There is very little to do here to update the view's dependencies.
223 * Most view-level dependency relationships, such as those on the
224 * owner, schema, and associated composite type, aren't changing.
225 * Because we don't allow changing type or collation of an existing
226 * view column, those dependencies of the existing columns don't
227 * change either, while the AT_AddColumnToView machinery took care of
228 * adding such dependencies for new view columns. The dependencies of
229 * the view's query could have changed arbitrarily, but that was dealt
230 * with inside StoreViewQuery. What remains is only to check that
231 * view replacement is allowed when we're creating an extension.
233 ObjectAddressSet(address, RelationRelationId, viewOid);
235 recordDependencyOnCurrentExtension(&address, true);
238 * Seems okay, so return the OID of the pre-existing view.
240 relation_close(rel, NoLock); /* keep the lock! */
242 return address;
244 else
246 ObjectAddress address;
249 * Set the parameters for keys/inheritance etc. All of these are
250 * uninteresting for views...
252 createStmt->relation = relation;
253 createStmt->tableElts = attrList;
254 createStmt->inhRelations = NIL;
255 createStmt->constraints = NIL;
256 createStmt->options = options;
257 createStmt->oncommit = ONCOMMIT_NOOP;
258 createStmt->tablespacename = NULL;
259 createStmt->if_not_exists = false;
262 * Create the relation (this will error out if there's an existing
263 * view, so we don't need more code to complain if "replace" is
264 * false).
266 address = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid, NULL,
267 NULL);
268 Assert(address.objectId != InvalidOid);
270 /* Make the new view relation visible */
271 CommandCounterIncrement();
273 /* Store the query for the view */
274 StoreViewQuery(address.objectId, viewParse, replace);
276 return address;
281 * Verify that tupledesc associated with proposed new view definition
282 * matches tupledesc of old view. This is basically a cut-down version
283 * of equalTupleDescs(), with code added to generate specific complaints.
284 * Also, we allow the new tupledesc to have more columns than the old.
286 static void
287 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
289 int i;
291 if (newdesc->natts < olddesc->natts)
292 ereport(ERROR,
293 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
294 errmsg("cannot drop columns from view")));
296 for (i = 0; i < olddesc->natts; i++)
298 Form_pg_attribute newattr = TupleDescAttr(newdesc, i);
299 Form_pg_attribute oldattr = TupleDescAttr(olddesc, i);
301 /* XXX msg not right, but we don't support DROP COL on view anyway */
302 if (newattr->attisdropped != oldattr->attisdropped)
303 ereport(ERROR,
304 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
305 errmsg("cannot drop columns from view")));
307 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
308 ereport(ERROR,
309 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
310 errmsg("cannot change name of view column \"%s\" to \"%s\"",
311 NameStr(oldattr->attname),
312 NameStr(newattr->attname))));
313 /* XXX would it be safe to allow atttypmod to change? Not sure */
314 if (newattr->atttypid != oldattr->atttypid ||
315 newattr->atttypmod != oldattr->atttypmod)
316 ereport(ERROR,
317 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
318 errmsg("cannot change data type of view column \"%s\" from %s to %s",
319 NameStr(oldattr->attname),
320 format_type_with_typemod(oldattr->atttypid,
321 oldattr->atttypmod),
322 format_type_with_typemod(newattr->atttypid,
323 newattr->atttypmod))));
324 /* We can ignore the remaining attributes of an attribute... */
328 * We ignore the constraint fields. The new view desc can't have any
329 * constraints, and the only ones that could be on the old view are
330 * defaults, which we are happy to leave in place.
334 static void
335 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
338 * Set up the ON SELECT rule. Since the query has already been through
339 * parse analysis, we use DefineQueryRewrite() directly.
341 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
342 viewOid,
343 NULL,
344 CMD_SELECT,
345 true,
346 replace,
347 list_make1(viewParse));
350 * Someday: automatic ON INSERT, etc
354 /*---------------------------------------------------------------
355 * UpdateRangeTableOfViewParse
357 * Update the range table of the given parsetree.
358 * This update consists of adding two new entries IN THE BEGINNING
359 * of the range table (otherwise the rule system will die a slow,
360 * horrible and painful death, and we do not want that now, do we?)
361 * one for the OLD relation and one for the NEW one (both of
362 * them refer in fact to the "view" relation).
364 * Of course we must also increase the 'varnos' of all the Var nodes
365 * by 2...
367 * These extra RT entries are not actually used in the query,
368 * except for run-time locking and permission checking.
369 *---------------------------------------------------------------
371 static Query *
372 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
374 Relation viewRel;
375 List *new_rt;
376 RangeTblEntry *rt_entry1,
377 *rt_entry2;
378 ParseState *pstate;
381 * Make a copy of the given parsetree. It's not so much that we don't
382 * want to scribble on our input, it's that the parser has a bad habit of
383 * outputting multiple links to the same subtree for constructs like
384 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
385 * Var node twice. copyObject will expand any multiply-referenced subtree
386 * into multiple copies.
388 viewParse = copyObject(viewParse);
390 /* Create a dummy ParseState for addRangeTableEntryForRelation */
391 pstate = make_parsestate(NULL);
393 /* need to open the rel for addRangeTableEntryForRelation */
394 viewRel = relation_open(viewOid, AccessShareLock);
397 * Create the 2 new range table entries and form the new range table...
398 * OLD first, then NEW....
400 rt_entry1 = addRangeTableEntryForRelation(pstate, viewRel,
401 AccessShareLock,
402 makeAlias("old", NIL),
403 false, false);
404 rt_entry2 = addRangeTableEntryForRelation(pstate, viewRel,
405 AccessShareLock,
406 makeAlias("new", NIL),
407 false, false);
408 /* Must override addRangeTableEntry's default access-check flags */
409 rt_entry1->requiredPerms = 0;
410 rt_entry2->requiredPerms = 0;
412 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
414 viewParse->rtable = new_rt;
417 * Now offset all var nodes by 2, and jointree RT indexes too.
419 OffsetVarNodes((Node *) viewParse, 2, 0);
421 relation_close(viewRel, AccessShareLock);
423 return viewParse;
427 * DefineView
428 * Execute a CREATE VIEW command.
430 ObjectAddress
431 DefineView(ViewStmt *stmt, const char *queryString,
432 int stmt_location, int stmt_len)
434 RawStmt *rawstmt;
435 Query *viewParse;
436 RangeVar *view;
437 ListCell *cell;
438 bool check_option;
439 ObjectAddress address;
442 * Run parse analysis to convert the raw parse tree to a Query. Note this
443 * also acquires sufficient locks on the source table(s).
445 * Since parse analysis scribbles on its input, copy the raw parse tree;
446 * this ensures we don't corrupt a prepared statement, for example.
448 rawstmt = makeNode(RawStmt);
449 rawstmt->stmt = (Node *) copyObject(stmt->query);
450 rawstmt->stmt_location = stmt_location;
451 rawstmt->stmt_len = stmt_len;
453 viewParse = parse_analyze(rawstmt, queryString, NULL, 0, NULL);
456 * The grammar should ensure that the result is a single SELECT Query.
457 * However, it doesn't forbid SELECT INTO, so we have to check for that.
459 if (!IsA(viewParse, Query))
460 elog(ERROR, "unexpected parse analysis result");
461 if (viewParse->utilityStmt != NULL &&
462 IsA(viewParse->utilityStmt, CreateTableAsStmt))
463 ereport(ERROR,
464 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
465 errmsg("views must not contain SELECT INTO")));
466 if (viewParse->commandType != CMD_SELECT)
467 elog(ERROR, "unexpected parse analysis result");
470 * Check for unsupported cases. These tests are redundant with ones in
471 * DefineQueryRewrite(), but that function will complain about a bogus ON
472 * SELECT rule, and we'd rather the message complain about a view.
474 if (viewParse->hasModifyingCTE)
475 ereport(ERROR,
476 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
477 errmsg("views must not contain data-modifying statements in WITH")));
480 * If the user specified the WITH CHECK OPTION, add it to the list of
481 * reloptions.
483 if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
484 stmt->options = lappend(stmt->options,
485 makeDefElem("check_option",
486 (Node *) makeString("local"), -1));
487 else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
488 stmt->options = lappend(stmt->options,
489 makeDefElem("check_option",
490 (Node *) makeString("cascaded"), -1));
493 * Check that the view is auto-updatable if WITH CHECK OPTION was
494 * specified.
496 check_option = false;
498 foreach(cell, stmt->options)
500 DefElem *defel = (DefElem *) lfirst(cell);
502 if (strcmp(defel->defname, "check_option") == 0)
503 check_option = true;
507 * If the check option is specified, look to see if the view is actually
508 * auto-updatable or not.
510 if (check_option)
512 const char *view_updatable_error =
513 view_query_is_auto_updatable(viewParse, true);
515 if (view_updatable_error)
516 ereport(ERROR,
517 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
518 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
519 errhint("%s", _(view_updatable_error))));
523 * If a list of column names was given, run through and insert these into
524 * the actual query tree. - thomas 2000-03-08
526 if (stmt->aliases != NIL)
528 ListCell *alist_item = list_head(stmt->aliases);
529 ListCell *targetList;
531 foreach(targetList, viewParse->targetList)
533 TargetEntry *te = lfirst_node(TargetEntry, targetList);
535 /* junk columns don't get aliases */
536 if (te->resjunk)
537 continue;
538 te->resname = pstrdup(strVal(lfirst(alist_item)));
539 alist_item = lnext(alist_item);
540 if (alist_item == NULL)
541 break; /* done assigning aliases */
544 if (alist_item != NULL)
545 ereport(ERROR,
546 (errcode(ERRCODE_SYNTAX_ERROR),
547 errmsg("CREATE VIEW specifies more column "
548 "names than columns")));
551 /* Unlogged views are not sensible. */
552 if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
553 ereport(ERROR,
554 (errcode(ERRCODE_SYNTAX_ERROR),
555 errmsg("views cannot be unlogged because they do not have storage")));
558 * If the user didn't explicitly ask for a temporary view, check whether
559 * we need one implicitly. We allow TEMP to be inserted automatically as
560 * long as the CREATE command is consistent with that --- no explicit
561 * schema name.
563 view = copyObject(stmt->view); /* don't corrupt original command */
564 if (view->relpersistence == RELPERSISTENCE_PERMANENT
565 && isQueryUsingTempRelation(viewParse))
567 view->relpersistence = RELPERSISTENCE_TEMP;
568 ereport(NOTICE,
569 (errmsg("view \"%s\" will be a temporary view",
570 view->relname)));
574 * Create the view relation
576 * NOTE: if it already exists and replace is false, the xact will be
577 * aborted.
579 address = DefineVirtualRelation(view, viewParse->targetList,
580 stmt->replace, stmt->options, viewParse);
582 return address;
586 * Use the rules system to store the query for the view.
588 void
589 StoreViewQuery(Oid viewOid, Query *viewParse, bool replace)
592 * The range table of 'viewParse' does not contain entries for the "OLD"
593 * and "NEW" relations. So... add them!
595 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
598 * Now create the rules associated with the view.
600 DefineViewRules(viewOid, viewParse, replace);