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 * Validator for "check_option" reloption on views. The allowed values
43 * are "local" and "cascaded".
46 validateWithCheckOption(const char *value
)
49 (strcmp(value
, "local") != 0 &&
50 strcmp(value
, "cascaded") != 0))
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
65 * EventTriggerAlterTableStart must have been called already.
66 *---------------------------------------------------------------------
69 DefineVirtualRelation(RangeVar
*relation
, List
*tlist
, bool replace
,
70 List
*options
, Query
*viewParse
)
74 CreateStmt
*createStmt
= makeNode(CreateStmt
);
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.
85 TargetEntry
*tle
= (TargetEntry
*) lfirst(t
);
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
))
102 (errcode(ERRCODE_INDETERMINATE_COLLATION
),
103 errmsg("could not determine which collation to use for view column \"%s\"",
105 errhint("Use the COLLATE clause to set the collation explicitly.")));
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
)
126 TupleDesc descriptor
;
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
)
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
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
)
171 int skip
= rel
->rd_att
->natts
;
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
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
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! */
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
266 address
= DefineRelation(createStmt
, RELKIND_VIEW
, InvalidOid
, 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
);
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.
287 checkViewTupleDesc(TupleDesc newdesc
, TupleDesc olddesc
)
291 if (newdesc
->natts
< olddesc
->natts
)
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
)
304 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
305 errmsg("cannot drop columns from view")));
307 if (strcmp(NameStr(newattr
->attname
), NameStr(oldattr
->attname
)) != 0)
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
)
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
,
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.
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
),
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
367 * These extra RT entries are not actually used in the query,
368 * except for run-time locking and permission checking.
369 *---------------------------------------------------------------
372 UpdateRangeTableOfViewParse(Oid viewOid
, Query
*viewParse
)
376 RangeTblEntry
*rt_entry1
,
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
,
402 makeAlias("old", NIL
),
404 rt_entry2
= addRangeTableEntryForRelation(pstate
, viewRel
,
406 makeAlias("new", NIL
),
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
);
428 * Execute a CREATE VIEW command.
431 DefineView(ViewStmt
*stmt
, const char *queryString
,
432 int stmt_location
, int stmt_len
)
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
))
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
)
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
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
496 check_option
= false;
498 foreach(cell
, stmt
->options
)
500 DefElem
*defel
= (DefElem
*) lfirst(cell
);
502 if (strcmp(defel
->defname
, "check_option") == 0)
507 * If the check option is specified, look to see if the view is actually
508 * auto-updatable or not.
512 const char *view_updatable_error
=
513 view_query_is_auto_updatable(viewParse
, true);
515 if (view_updatable_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 */
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
)
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
)
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
563 view
= copyObject(stmt
->view
); /* don't corrupt original command */
564 if (view
->relpersistence
== RELPERSISTENCE_PERMANENT
565 && isQueryUsingTempRelation(viewParse
))
567 view
->relpersistence
= RELPERSISTENCE_TEMP
;
569 (errmsg("view \"%s\" will be a temporary view",
574 * Create the view relation
576 * NOTE: if it already exists and replace is false, the xact will be
579 address
= DefineVirtualRelation(view
, viewParse
->targetList
,
580 stmt
->replace
, stmt
->options
, viewParse
);
586 * Use the rules system to store the query for the view.
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
);