1 /*-------------------------------------------------------------------------
2 *
3 * view.c
4 * use rewrite rules to construct views
5 *
6 * Portions Copyright (c) 1996-2018, 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/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/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
39 static 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 */
45 void
validateWithCheckOption(const char * value)46 validateWithCheckOption(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 */
68 static ObjectAddress
DefineVirtualRelation(RangeVar * relation,List * tlist,bool replace,List * options,Query * viewParse)69 DefineVirtualRelation(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 */
272 static void
checkViewTupleDesc(TupleDesc newdesc,TupleDesc olddesc)273 checkViewTupleDesc(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 /* we can ignore tdhasoid */
282
283 for (i = 0; i < olddesc->natts; i++)
284 {
285 Form_pg_attribute newattr = TupleDescAttr(newdesc, i);
286 Form_pg_attribute oldattr = TupleDescAttr(olddesc, i);
287
288 /* XXX msg not right, but we don't support DROP COL on view anyway */
289 if (newattr->attisdropped != oldattr->attisdropped)
290 ereport(ERROR,
291 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
292 errmsg("cannot drop columns from view")));
293
294 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
295 ereport(ERROR,
296 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
297 errmsg("cannot change name of view column \"%s\" to \"%s\"",
298 NameStr(oldattr->attname),
299 NameStr(newattr->attname))));
300 /* XXX would it be safe to allow atttypmod to change? Not sure */
301 if (newattr->atttypid != oldattr->atttypid ||
302 newattr->atttypmod != oldattr->atttypmod)
303 ereport(ERROR,
304 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
305 errmsg("cannot change data type of view column \"%s\" from %s to %s",
306 NameStr(oldattr->attname),
307 format_type_with_typemod(oldattr->atttypid,
308 oldattr->atttypmod),
309 format_type_with_typemod(newattr->atttypid,
310 newattr->atttypmod))));
311 /* We can ignore the remaining attributes of an attribute... */
312 }
313
314 /*
315 * We ignore the constraint fields. The new view desc can't have any
316 * constraints, and the only ones that could be on the old view are
317 * defaults, which we are happy to leave in place.
318 */
319 }
320
321 static void
DefineViewRules(Oid viewOid,Query * viewParse,bool replace)322 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
323 {
324 /*
325 * Set up the ON SELECT rule. Since the query has already been through
326 * parse analysis, we use DefineQueryRewrite() directly.
327 */
328 DefineQueryRewrite(pstrdup(ViewSelectRuleName),
329 viewOid,
330 NULL,
331 CMD_SELECT,
332 true,
333 replace,
334 list_make1(viewParse));
335
336 /*
337 * Someday: automatic ON INSERT, etc
338 */
339 }
340
341 /*---------------------------------------------------------------
342 * UpdateRangeTableOfViewParse
343 *
344 * Update the range table of the given parsetree.
345 * This update consists of adding two new entries IN THE BEGINNING
346 * of the range table (otherwise the rule system will die a slow,
347 * horrible and painful death, and we do not want that now, do we?)
348 * one for the OLD relation and one for the NEW one (both of
349 * them refer in fact to the "view" relation).
350 *
351 * Of course we must also increase the 'varnos' of all the Var nodes
352 * by 2...
353 *
354 * These extra RT entries are not actually used in the query,
355 * except for run-time permission checking.
356 *---------------------------------------------------------------
357 */
358 static Query *
UpdateRangeTableOfViewParse(Oid viewOid,Query * viewParse)359 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
360 {
361 Relation viewRel;
362 List *new_rt;
363 RangeTblEntry *rt_entry1,
364 *rt_entry2;
365 ParseState *pstate;
366
367 /*
368 * Make a copy of the given parsetree. It's not so much that we don't
369 * want to scribble on our input, it's that the parser has a bad habit of
370 * outputting multiple links to the same subtree for constructs like
371 * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
372 * Var node twice. copyObject will expand any multiply-referenced subtree
373 * into multiple copies.
374 */
375 viewParse = copyObject(viewParse);
376
377 /* Create a dummy ParseState for addRangeTableEntryForRelation */
378 pstate = make_parsestate(NULL);
379
380 /* need to open the rel for addRangeTableEntryForRelation */
381 viewRel = relation_open(viewOid, AccessShareLock);
382
383 /*
384 * Create the 2 new range table entries and form the new range table...
385 * OLD first, then NEW....
386 */
387 rt_entry1 = addRangeTableEntryForRelation(pstate, viewRel,
388 makeAlias("old", NIL),
389 false, false);
390 rt_entry2 = addRangeTableEntryForRelation(pstate, viewRel,
391 makeAlias("new", NIL),
392 false, false);
393 /* Must override addRangeTableEntry's default access-check flags */
394 rt_entry1->requiredPerms = 0;
395 rt_entry2->requiredPerms = 0;
396
397 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
398
399 viewParse->rtable = new_rt;
400
401 /*
402 * Now offset all var nodes by 2, and jointree RT indexes too.
403 */
404 OffsetVarNodes((Node *) viewParse, 2, 0);
405
406 relation_close(viewRel, AccessShareLock);
407
408 return viewParse;
409 }
410
411 /*
412 * DefineView
413 * Execute a CREATE VIEW command.
414 */
415 ObjectAddress
DefineView(ViewStmt * stmt,const char * queryString,int stmt_location,int stmt_len)416 DefineView(ViewStmt *stmt, const char *queryString,
417 int stmt_location, int stmt_len)
418 {
419 RawStmt *rawstmt;
420 Query *viewParse;
421 RangeVar *view;
422 ListCell *cell;
423 bool check_option;
424 ObjectAddress address;
425
426 /*
427 * Run parse analysis to convert the raw parse tree to a Query. Note this
428 * also acquires sufficient locks on the source table(s).
429 *
430 * Since parse analysis scribbles on its input, copy the raw parse tree;
431 * this ensures we don't corrupt a prepared statement, for example.
432 */
433 rawstmt = makeNode(RawStmt);
434 rawstmt->stmt = (Node *) copyObject(stmt->query);
435 rawstmt->stmt_location = stmt_location;
436 rawstmt->stmt_len = stmt_len;
437
438 viewParse = parse_analyze(rawstmt, queryString, NULL, 0, NULL);
439
440 /*
441 * The grammar should ensure that the result is a single SELECT Query.
442 * However, it doesn't forbid SELECT INTO, so we have to check for that.
443 */
444 if (!IsA(viewParse, Query))
445 elog(ERROR, "unexpected parse analysis result");
446 if (viewParse->utilityStmt != NULL &&
447 IsA(viewParse->utilityStmt, CreateTableAsStmt))
448 ereport(ERROR,
449 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
450 errmsg("views must not contain SELECT INTO")));
451 if (viewParse->commandType != CMD_SELECT)
452 elog(ERROR, "unexpected parse analysis result");
453
454 /*
455 * Check for unsupported cases. These tests are redundant with ones in
456 * DefineQueryRewrite(), but that function will complain about a bogus ON
457 * SELECT rule, and we'd rather the message complain about a view.
458 */
459 if (viewParse->hasModifyingCTE)
460 ereport(ERROR,
461 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
462 errmsg("views must not contain data-modifying statements in WITH")));
463
464 /*
465 * If the user specified the WITH CHECK OPTION, add it to the list of
466 * reloptions.
467 */
468 if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
469 stmt->options = lappend(stmt->options,
470 makeDefElem("check_option",
471 (Node *) makeString("local"), -1));
472 else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
473 stmt->options = lappend(stmt->options,
474 makeDefElem("check_option",
475 (Node *) makeString("cascaded"), -1));
476
477 /*
478 * Check that the view is auto-updatable if WITH CHECK OPTION was
479 * specified.
480 */
481 check_option = false;
482
483 foreach(cell, stmt->options)
484 {
485 DefElem *defel = (DefElem *) lfirst(cell);
486
487 if (strcmp(defel->defname, "check_option") == 0)
488 check_option = true;
489 }
490
491 /*
492 * If the check option is specified, look to see if the view is actually
493 * auto-updatable or not.
494 */
495 if (check_option)
496 {
497 const char *view_updatable_error =
498 view_query_is_auto_updatable(viewParse, true);
499
500 if (view_updatable_error)
501 ereport(ERROR,
502 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
503 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
504 errhint("%s", _(view_updatable_error))));
505 }
506
507 /*
508 * If a list of column names was given, run through and insert these into
509 * the actual query tree. - thomas 2000-03-08
510 */
511 if (stmt->aliases != NIL)
512 {
513 ListCell *alist_item = list_head(stmt->aliases);
514 ListCell *targetList;
515
516 foreach(targetList, viewParse->targetList)
517 {
518 TargetEntry *te = lfirst_node(TargetEntry, targetList);
519
520 /* junk columns don't get aliases */
521 if (te->resjunk)
522 continue;
523 te->resname = pstrdup(strVal(lfirst(alist_item)));
524 alist_item = lnext(alist_item);
525 if (alist_item == NULL)
526 break; /* done assigning aliases */
527 }
528
529 if (alist_item != NULL)
530 ereport(ERROR,
531 (errcode(ERRCODE_SYNTAX_ERROR),
532 errmsg("CREATE VIEW specifies more column "
533 "names than columns")));
534 }
535
536 /* Unlogged views are not sensible. */
537 if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
538 ereport(ERROR,
539 (errcode(ERRCODE_SYNTAX_ERROR),
540 errmsg("views cannot be unlogged because they do not have storage")));
541
542 /*
543 * If the user didn't explicitly ask for a temporary view, check whether
544 * we need one implicitly. We allow TEMP to be inserted automatically as
545 * long as the CREATE command is consistent with that --- no explicit
546 * schema name.
547 */
548 view = copyObject(stmt->view); /* don't corrupt original command */
549 if (view->relpersistence == RELPERSISTENCE_PERMANENT
550 && isQueryUsingTempRelation(viewParse))
551 {
552 view->relpersistence = RELPERSISTENCE_TEMP;
553 ereport(NOTICE,
554 (errmsg("view \"%s\" will be a temporary view",
555 view->relname)));
556 }
557
558 /*
559 * Create the view relation
560 *
561 * NOTE: if it already exists and replace is false, the xact will be
562 * aborted.
563 */
564 address = DefineVirtualRelation(view, viewParse->targetList,
565 stmt->replace, stmt->options, viewParse);
566
567 return address;
568 }
569
570 /*
571 * Use the rules system to store the query for the view.
572 */
573 void
StoreViewQuery(Oid viewOid,Query * viewParse,bool replace)574 StoreViewQuery(Oid viewOid, Query *viewParse, bool replace)
575 {
576 /*
577 * The range table of 'viewParse' does not contain entries for the "OLD"
578 * and "NEW" relations. So... add them!
579 */
580 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
581
582 /*
583 * Now create the rules associated with the view.
584 */
585 DefineViewRules(viewOid, viewParse, replace);
586 }
587