1 /*-------------------------------------------------------------------------
2 *
3 * view.c
4 * use rewrite rules to construct views
5 *
6 * Portions Copyright (c) 1996-2016, 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(char * value)46 validateWithCheckOption(char *value)
47 {
48 if (value == NULL ||
49 (pg_strcasecmp(value, "local") != 0 &&
50 pg_strcasecmp(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 Assert(address.objectId != InvalidOid);
254
255 /* Make the new view relation visible */
256 CommandCounterIncrement();
257
258 /* Store the query for the view */
259 StoreViewQuery(address.objectId, viewParse, replace);
260
261 return address;
262 }
263 }
264
265 /*
266 * Verify that tupledesc associated with proposed new view definition
267 * matches tupledesc of old view. This is basically a cut-down version
268 * of equalTupleDescs(), with code added to generate specific complaints.
269 * Also, we allow the new tupledesc to have more columns than the old.
270 */
271 static void
checkViewTupleDesc(TupleDesc newdesc,TupleDesc olddesc)272 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
273 {
274 int i;
275
276 if (newdesc->natts < olddesc->natts)
277 ereport(ERROR,
278 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
279 errmsg("cannot drop columns from view")));
280 /* we can ignore tdhasoid */
281
282 for (i = 0; i < olddesc->natts; i++)
283 {
284 Form_pg_attribute newattr = newdesc->attrs[i];
285 Form_pg_attribute oldattr = olddesc->attrs[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
320 static void
DefineViewRules(Oid viewOid,Query * viewParse,bool replace)321 DefineViewRules(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 permission checking.
355 *---------------------------------------------------------------
356 */
357 static Query *
UpdateRangeTableOfViewParse(Oid viewOid,Query * viewParse)358 UpdateRangeTableOfViewParse(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 = (Query *) 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 makeAlias("old", NIL),
388 false, false);
389 rt_entry2 = addRangeTableEntryForRelation(pstate, viewRel,
390 makeAlias("new", NIL),
391 false, false);
392 /* Must override addRangeTableEntry's default access-check flags */
393 rt_entry1->requiredPerms = 0;
394 rt_entry2->requiredPerms = 0;
395
396 new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
397
398 viewParse->rtable = new_rt;
399
400 /*
401 * Now offset all var nodes by 2, and jointree RT indexes too.
402 */
403 OffsetVarNodes((Node *) viewParse, 2, 0);
404
405 relation_close(viewRel, AccessShareLock);
406
407 return viewParse;
408 }
409
410 /*
411 * DefineView
412 * Execute a CREATE VIEW command.
413 */
414 ObjectAddress
DefineView(ViewStmt * stmt,const char * queryString)415 DefineView(ViewStmt *stmt, const char *queryString)
416 {
417 Query *viewParse;
418 RangeVar *view;
419 ListCell *cell;
420 bool check_option;
421 ObjectAddress address;
422
423 /*
424 * Run parse analysis to convert the raw parse tree to a Query. Note this
425 * also acquires sufficient locks on the source table(s).
426 *
427 * Since parse analysis scribbles on its input, copy the raw parse tree;
428 * this ensures we don't corrupt a prepared statement, for example.
429 */
430 viewParse = parse_analyze((Node *) copyObject(stmt->query),
431 queryString, NULL, 0);
432
433 /*
434 * The grammar should ensure that the result is a single SELECT Query.
435 * However, it doesn't forbid SELECT INTO, so we have to check for that.
436 */
437 if (!IsA(viewParse, Query))
438 elog(ERROR, "unexpected parse analysis result");
439 if (viewParse->utilityStmt != NULL &&
440 IsA(viewParse->utilityStmt, CreateTableAsStmt))
441 ereport(ERROR,
442 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
443 errmsg("views must not contain SELECT INTO")));
444 if (viewParse->commandType != CMD_SELECT ||
445 viewParse->utilityStmt != NULL)
446 elog(ERROR, "unexpected parse analysis result");
447
448 /*
449 * Check for unsupported cases. These tests are redundant with ones in
450 * DefineQueryRewrite(), but that function will complain about a bogus ON
451 * SELECT rule, and we'd rather the message complain about a view.
452 */
453 if (viewParse->hasModifyingCTE)
454 ereport(ERROR,
455 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
456 errmsg("views must not contain data-modifying statements in WITH")));
457
458 /*
459 * If the user specified the WITH CHECK OPTION, add it to the list of
460 * reloptions.
461 */
462 if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
463 stmt->options = lappend(stmt->options,
464 makeDefElem("check_option",
465 (Node *) makeString("local")));
466 else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
467 stmt->options = lappend(stmt->options,
468 makeDefElem("check_option",
469 (Node *) makeString("cascaded")));
470
471 /*
472 * Check that the view is auto-updatable if WITH CHECK OPTION was
473 * specified.
474 */
475 check_option = false;
476
477 foreach(cell, stmt->options)
478 {
479 DefElem *defel = (DefElem *) lfirst(cell);
480
481 if (pg_strcasecmp(defel->defname, "check_option") == 0)
482 check_option = true;
483 }
484
485 /*
486 * If the check option is specified, look to see if the view is actually
487 * auto-updatable or not.
488 */
489 if (check_option)
490 {
491 const char *view_updatable_error =
492 view_query_is_auto_updatable(viewParse, true);
493
494 if (view_updatable_error)
495 ereport(ERROR,
496 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
497 errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
498 errhint("%s", _(view_updatable_error))));
499 }
500
501 /*
502 * If a list of column names was given, run through and insert these into
503 * the actual query tree. - thomas 2000-03-08
504 */
505 if (stmt->aliases != NIL)
506 {
507 ListCell *alist_item = list_head(stmt->aliases);
508 ListCell *targetList;
509
510 foreach(targetList, viewParse->targetList)
511 {
512 TargetEntry *te = (TargetEntry *) lfirst(targetList);
513
514 Assert(IsA(te, TargetEntry));
515 /* junk columns don't get aliases */
516 if (te->resjunk)
517 continue;
518 te->resname = pstrdup(strVal(lfirst(alist_item)));
519 alist_item = lnext(alist_item);
520 if (alist_item == NULL)
521 break; /* done assigning aliases */
522 }
523
524 if (alist_item != NULL)
525 ereport(ERROR,
526 (errcode(ERRCODE_SYNTAX_ERROR),
527 errmsg("CREATE VIEW specifies more column "
528 "names than columns")));
529 }
530
531 /* Unlogged views are not sensible. */
532 if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
533 ereport(ERROR,
534 (errcode(ERRCODE_SYNTAX_ERROR),
535 errmsg("views cannot be unlogged because they do not have storage")));
536
537 /*
538 * If the user didn't explicitly ask for a temporary view, check whether
539 * we need one implicitly. We allow TEMP to be inserted automatically as
540 * long as the CREATE command is consistent with that --- no explicit
541 * schema name.
542 */
543 view = copyObject(stmt->view); /* don't corrupt original command */
544 if (view->relpersistence == RELPERSISTENCE_PERMANENT
545 && isQueryUsingTempRelation(viewParse))
546 {
547 view->relpersistence = RELPERSISTENCE_TEMP;
548 ereport(NOTICE,
549 (errmsg("view \"%s\" will be a temporary view",
550 view->relname)));
551 }
552
553 /*
554 * Create the view relation
555 *
556 * NOTE: if it already exists and replace is false, the xact will be
557 * aborted.
558 */
559 address = DefineVirtualRelation(view, viewParse->targetList,
560 stmt->replace, stmt->options, viewParse);
561
562 return address;
563 }
564
565 /*
566 * Use the rules system to store the query for the view.
567 */
568 void
StoreViewQuery(Oid viewOid,Query * viewParse,bool replace)569 StoreViewQuery(Oid viewOid, Query *viewParse, bool replace)
570 {
571 /*
572 * The range table of 'viewParse' does not contain entries for the "OLD"
573 * and "NEW" relations. So... add them!
574 */
575 viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
576
577 /*
578 * Now create the rules associated with the view.
579 */
580 DefineViewRules(viewOid, viewParse, replace);
581 }
582