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