1/*-------------------------------------------------------------------------
2 *
3 * view.c
4 * use rewrite rules to construct views
5 *
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/commands/view.c
12 *
13 *-------------------------------------------------------------------------
14 */
15#include "postgres.h"
16
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"
37
38
39static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
40
41/*---------------------------------------------------------------------
42 * Validator for "check_option" reloption on views. The allowed values
43 * are "local" and "cascaded".
44 */
45void
46validateWithCheckOption(const char *value)
47{
48 if (value == NULL ||
49 (strcmp(value, "local") != 0 &&
50 strcmp(value, "cascaded") != 0))
51 {
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\".")));
56 }
57}
58
59/*---------------------------------------------------------------------
60 * DefineVirtualRelation
61 *
62 * Create a view relation and use the rules system to store the query
63 * for the view.
64 *
65 * EventTriggerAlterTableStart must have been called already.
66 *---------------------------------------------------------------------
67 */
68static ObjectAddress
69DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace,
70 List *options, Query *viewParse)
71{
72 Oid viewOid;
73 LOCKMODE lockmode;
74 CreateStmt *createStmt = makeNode(CreateStmt);
75 List *attrList;
76 ListCell *t;
77
78 /*
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.
81 */
82 attrList = NIL;
83 foreach(t, tlist)
84 {
85 TargetEntry *tle = (TargetEntry *) lfirst(t);
86
87 if (!tle->resjunk)
88 {
89 ColumnDef *def = makeColumnDef(tle->resname,
90 exprType((Node *) tle->expr),
91 exprTypmod((Node *) tle->expr),
92 exprCollation((Node *) tle->expr));
93
94 /*
95 * It's possible that the column is of a collatable type but the
96 * collation could not be resolved, so double-check.
97 */
98 if (type_is_collatable(exprType((Node *) tle->expr)))
99 {
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.")));
106 }
107 else
108 Assert(!OidIsValid(def->collOid));
109
110 attrList = lappend(attrList, def);
111 }
112 }
113
114 /*
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.
119 */
120 lockmode = replace ? AccessExclusiveLock : NoLock;
121 (void) RangeVarGetAndCheckCreationNamespace(relation, lockmode, &viewOid);
122
123 if (OidIsValid(viewOid) && replace)
124 {
125 Relation rel;
126 TupleDesc descriptor;
127 List *atcmds = NIL;
128 AlterTableCmd *atcmd;
129 ObjectAddress address;
130
131 /* Relation is already locked, but we must build a relcache entry. */
132 rel = relation_open(viewOid, NoLock);
133
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))));
140
141 /* Also check it's not in use already */
142 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
143
144 /*
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.
148 */
149 Assert(relation->relpersistence == rel->rd_rel->relpersistence);
150
151 /*
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.
155 */
156 descriptor = BuildDescForRelation(attrList);
157 checkViewTupleDesc(descriptor, rel->rd_att);
158
159 /*
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.
163 *
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.
167 */
168 if (list_length(attrList) > rel->rd_att->natts)
169 {
170 ListCell *c;
171 int skip = rel->rd_att->natts;
172
173 foreach(c, attrList)
174 {
175 if (skip > 0)
176 {
177 skip--;
178 continue;
179 }
180 atcmd = makeNode(AlterTableCmd);
181 atcmd->subtype = AT_AddColumnToView;
182 atcmd->def = (Node *) lfirst(c);
183 atcmds = lappend(atcmds, atcmd);
184 }
185
186 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
187 AlterTableInternal(viewOid, atcmds, true);
188
189 /* Make the new view columns visible */
190 CommandCounterIncrement();
191 }
192
193 /*
194 * Update the query for the view.
195 *
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).
201 */
202 StoreViewQuery(viewOid, viewParse, replace);
203
204 /* Make the new view query visible */
205 CommandCounterIncrement();
206
207 /*
208 * Finally update the view options.
209 *
210 * The new options list replaces the existing options list, even if
211 * it's empty.
212 */
213 atcmd = makeNode(AlterTableCmd);
214 atcmd->subtype = AT_ReplaceRelOptions;
215 atcmd->def = (Node *) options;
216 atcmds = list_make1(atcmd);
217
218 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
219 AlterTableInternal(viewOid, atcmds, true);
220
221 ObjectAddressSet(address, RelationRelationId, viewOid);
222
223 /*
224 * Seems okay, so return the OID of the pre-existing view.
225 */
226 relation_close(rel, NoLock); /* keep the lock! */
227
228 return address;
229 }
230 else
231 {
232 ObjectAddress address;
233
234 /*
235 * Set the parameters for keys/inheritance etc. All of these are
236 * uninteresting for views...
237 */
238 createStmt->relation = relation;
239 createStmt->tableElts = attrList;
240 createStmt->inhRelations = NIL;
241 createStmt->constraints = NIL;
242 createStmt->options = options;
243 createStmt->oncommit = ONCOMMIT_NOOP;
244 createStmt->tablespacename = NULL;
245 createStmt->if_not_exists = false;
246
247 /*
248 * Create the relation (this will error out if there's an existing
249 * view, so we don't need more code to complain if "replace" is
250 * false).
251 */
252 address = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid, NULL,
253 NULL);
254 Assert(address.objectId != InvalidOid);
255
256 /* Make the new view relation visible */
257 CommandCounterIncrement();
258
259 /* Store the query for the view */
260 StoreViewQuery(address.objectId, viewParse, replace);
261
262 return address;
263 }
264}
265
266/*
267 * Verify that tupledesc associated with proposed new view definition
268 * matches tupledesc of old view. This is basically a cut-down version
269 * of equalTupleDescs(), with code added to generate specific complaints.
270 * Also, we allow the new tupledesc to have more columns than the old.
271 */
272static void
273checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
274{
275 int i;
276
277 if (newdesc->natts < olddesc->natts)
278 ereport(ERROR,
279 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
280 errmsg("cannot drop columns from view")));
281
282 for (i = 0; i < olddesc->natts; i++)
283 {
284 Form_pg_attribute newattr = TupleDescAttr(newdesc, i);
285 Form_pg_attribute oldattr = TupleDescAttr(olddesc, i);
286
287 /* XXX msg not right, but we don't support DROP COL on view anyway */
288 if (newattr->attisdropped != oldattr->attisdropped)
289 ereport(ERROR,
290 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
291 errmsg("cannot drop columns from view")));
292
293 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
294 ereport(ERROR,
295 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
296 errmsg("cannot change name of view column \"%s\" to \"%s\"",
297 NameStr(oldattr->attname),
298 NameStr(newattr->attname))));
299 /* XXX would it be safe to allow atttypmod to change? Not sure */
300 if (newattr->atttypid != oldattr->atttypid ||
301 newattr->atttypmod != oldattr->atttypmod)
302 ereport(ERROR,
303 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
304 errmsg("cannot change data type of view column \"%s\" from %s to %s",
305 NameStr(oldattr->attname),
306 format_type_with_typemod(oldattr->atttypid,
307 oldattr->atttypmod),
308 format_type_with_typemod(newattr->atttypid,
309 newattr->atttypmod))));
310 /* We can ignore the remaining attributes of an attribute... */
311 }
312
313 /*
314 * We ignore the constraint fields. The new view desc can't have any
315 * constraints, and the only ones that could be on the old view are
316 * defaults, which we are happy to leave in place.
317 */
318}
319
320static void
321DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
322{
323 /*
324 * Set up the ON SELECT rule. Since the query has already been through
325 * parse analysis, we use DefineQueryRewrite() directly.
326 */
327 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
328 viewOid,
329 NULL,
330 CMD_SELECT,
331 true,
332 replace,
333 list_make1(viewParse));
334
335 /*
336 * Someday: automatic ON INSERT, etc
337 */
338}
339
340/*---------------------------------------------------------------
341 * UpdateRangeTableOfViewParse
342 *
343 * Update the range table of the given parsetree.
344 * This update consists of adding two new entries IN THE BEGINNING
345 * of the range table (otherwise the rule system will die a slow,
346 * horrible and painful death, and we do not want that now, do we?)
347 * one for the OLD relation and one for the NEW one (both of
348 * them refer in fact to the "view" relation).
349 *
350 * Of course we must also increase the 'varnos' of all the Var nodes
351 * by 2...
352 *
353 * These extra RT entries are not actually used in the query,
354 * except for run-time locking and permission checking.
355 *---------------------------------------------------------------
356 */
357static Query *
358UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
359{
360 Relation viewRel;
361 List *new_rt;
362 RangeTblEntry *rt_entry1,
363 *rt_entry2;
364 ParseState *pstate;
365
366 /*
367 * Make a copy of the given parsetree. It's not so much that we don't
368 * want to scribble on our input, it's that the parser has a bad habit of
369 * outputting multiple links to the same subtree for constructs like
370 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
371 * Var node twice. copyObject will expand any multiply-referenced subtree
372 * into multiple copies.
373 */
374 viewParse = copyObject(viewParse);
375
376 /* Create a dummy ParseState for addRangeTableEntryForRelation */
377 pstate = make_parsestate(NULL);
378
379 /* need to open the rel for addRangeTableEntryForRelation */
380 viewRel = relation_open(viewOid, AccessShareLock);
381
382 /*
383 * Create the 2 new range table entries and form the new range table...
384 * OLD first, then NEW....
385 */
386 rt_entry1 = addRangeTableEntryForRelation(pstate, viewRel,
387 AccessShareLock,
388 makeAlias("old", NIL),
389 false, false);
390 rt_entry2 = addRangeTableEntryForRelation(pstate, viewRel,
391 AccessShareLock,
392 makeAlias("new", NIL),
393 false, false);
394 /* Must override addRangeTableEntry's default access-check flags */
395 rt_entry1->requiredPerms = 0;
396 rt_entry2->requiredPerms = 0;
397
398 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
399
400 viewParse->rtable = new_rt;
401
402 /*
403 * Now offset all var nodes by 2, and jointree RT indexes too.
404 */
405 OffsetVarNodes((Node *) viewParse, 2, 0);
406
407 relation_close(viewRel, AccessShareLock);
408
409 return viewParse;
410}
411
412/*
413 * DefineView
414 * Execute a CREATE VIEW command.
415 */
416ObjectAddress
417DefineView(ViewStmt *stmt, const char *queryString,
418 int stmt_location, int stmt_len)
419{
420 RawStmt *rawstmt;
421 Query *viewParse;
422 RangeVar *view;
423 ListCell *cell;
424 bool check_option;
425 ObjectAddress address;
426
427 /*
428 * Run parse analysis to convert the raw parse tree to a Query. Note this
429 * also acquires sufficient locks on the source table(s).
430 *
431 * Since parse analysis scribbles on its input, copy the raw parse tree;
432 * this ensures we don't corrupt a prepared statement, for example.
433 */
434 rawstmt = makeNode(RawStmt);
435 rawstmt->stmt = (Node *) copyObject(stmt->query);
436 rawstmt->stmt_location = stmt_location;
437 rawstmt->stmt_len = stmt_len;
438
439 viewParse = parse_analyze(rawstmt, queryString, NULL, 0, NULL);
440
441 /*
442 * The grammar should ensure that the result is a single SELECT Query.
443 * However, it doesn't forbid SELECT INTO, so we have to check for that.
444 */
445 if (!IsA(viewParse, Query))
446 elog(ERROR, "unexpected parse analysis result");
447 if (viewParse->utilityStmt != NULL &&
448 IsA(viewParse->utilityStmt, CreateTableAsStmt))
449 ereport(ERROR,
450 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
451 errmsg("views must not contain SELECT INTO")));
452 if (viewParse->commandType != CMD_SELECT)
453 elog(ERROR, "unexpected parse analysis result");
454
455 /*
456 * Check for unsupported cases. These tests are redundant with ones in
457 * DefineQueryRewrite(), but that function will complain about a bogus ON
458 * SELECT rule, and we'd rather the message complain about a view.
459 */
460 if (viewParse->hasModifyingCTE)
461 ereport(ERROR,
462 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
463 errmsg("views must not contain data-modifying statements in WITH")));
464
465 /*
466 * If the user specified the WITH CHECK OPTION, add it to the list of
467 * reloptions.
468 */
469 if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
470 stmt->options = lappend(stmt->options,
471 makeDefElem("check_option",
472 (Node *) makeString("local"), -1));
473 else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
474 stmt->options = lappend(stmt->options,
475 makeDefElem("check_option",
476 (Node *) makeString("cascaded"), -1));
477
478 /*
479 * Check that the view is auto-updatable if WITH CHECK OPTION was
480 * specified.
481 */
482 check_option = false;
483
484 foreach(cell, stmt->options)
485 {
486 DefElem *defel = (DefElem *) lfirst(cell);
487
488 if (strcmp(defel->defname, "check_option") == 0)
489 check_option = true;
490 }
491
492 /*
493 * If the check option is specified, look to see if the view is actually
494 * auto-updatable or not.
495 */
496 if (check_option)
497 {
498 const char *view_updatable_error =
499 view_query_is_auto_updatable(viewParse, true);
500
501 if (view_updatable_error)
502 ereport(ERROR,
503 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
504 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
505 errhint("%s", _(view_updatable_error))));
506 }
507
508 /*
509 * If a list of column names was given, run through and insert these into
510 * the actual query tree. - thomas 2000-03-08
511 */
512 if (stmt->aliases != NIL)
513 {
514 ListCell *alist_item = list_head(stmt->aliases);
515 ListCell *targetList;
516
517 foreach(targetList, viewParse->targetList)
518 {
519 TargetEntry *te = lfirst_node(TargetEntry, targetList);
520
521 /* junk columns don't get aliases */
522 if (te->resjunk)
523 continue;
524 te->resname = pstrdup(strVal(lfirst(alist_item)));
525 alist_item = lnext(alist_item);
526 if (alist_item == NULL)
527 break; /* done assigning aliases */
528 }
529
530 if (alist_item != NULL)
531 ereport(ERROR,
532 (errcode(ERRCODE_SYNTAX_ERROR),
533 errmsg("CREATE VIEW specifies more column "
534 "names than columns")));
535 }
536
537 /* Unlogged views are not sensible. */
538 if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
539 ereport(ERROR,
540 (errcode(ERRCODE_SYNTAX_ERROR),
541 errmsg("views cannot be unlogged because they do not have storage")));
542
543 /*
544 * If the user didn't explicitly ask for a temporary view, check whether
545 * we need one implicitly. We allow TEMP to be inserted automatically as
546 * long as the CREATE command is consistent with that --- no explicit
547 * schema name.
548 */
549 view = copyObject(stmt->view); /* don't corrupt original command */
550 if (view->relpersistence == RELPERSISTENCE_PERMANENT
551 && isQueryUsingTempRelation(viewParse))
552 {
553 view->relpersistence = RELPERSISTENCE_TEMP;
554 ereport(NOTICE,
555 (errmsg("view \"%s\" will be a temporary view",
556 view->relname)));
557 }
558
559 /*
560 * Create the view relation
561 *
562 * NOTE: if it already exists and replace is false, the xact will be
563 * aborted.
564 */
565 address = DefineVirtualRelation(view, viewParse->targetList,
566 stmt->replace, stmt->options, viewParse);
567
568 return address;
569}
570
571/*
572 * Use the rules system to store the query for the view.
573 */
574void
575StoreViewQuery(Oid viewOid, Query *viewParse, bool replace)
576{
577 /*
578 * The range table of 'viewParse' does not contain entries for the "OLD"
579 * and "NEW" relations. So... add them!
580 */
581 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
582
583 /*
584 * Now create the rules associated with the view.
585 */
586 DefineViewRules(viewOid, viewParse, replace);
587}
588