OSDN Git Service

pgindent run before PG 9.1 beta 1.
[pg-rex/syncrep.git] / src / backend / commands / view.c
1 /*-------------------------------------------------------------------------
2  *
3  * view.c
4  *        use rewrite rules to construct views
5  *
6  * Portions Copyright (c) 1996-2011, 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/rewriteSupport.h"
31 #include "utils/acl.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/rel.h"
35
36
37 static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
38 static bool isViewOnTempTable_walker(Node *node, void *context);
39
40 /*---------------------------------------------------------------------
41  * isViewOnTempTable
42  *
43  * Returns true iff any of the relations underlying this view are
44  * temporary tables.
45  *---------------------------------------------------------------------
46  */
47 static bool
48 isViewOnTempTable(Query *viewParse)
49 {
50         return isViewOnTempTable_walker((Node *) viewParse, NULL);
51 }
52
53 static bool
54 isViewOnTempTable_walker(Node *node, void *context)
55 {
56         if (node == NULL)
57                 return false;
58
59         if (IsA(node, Query))
60         {
61                 Query      *query = (Query *) node;
62                 ListCell   *rtable;
63
64                 foreach(rtable, query->rtable)
65                 {
66                         RangeTblEntry *rte = lfirst(rtable);
67
68                         if (rte->rtekind == RTE_RELATION)
69                         {
70                                 Relation        rel = heap_open(rte->relid, AccessShareLock);
71                                 char            relpersistence = rel->rd_rel->relpersistence;
72
73                                 heap_close(rel, AccessShareLock);
74                                 if (relpersistence == RELPERSISTENCE_TEMP)
75                                         return true;
76                         }
77                 }
78
79                 return query_tree_walker(query,
80                                                                  isViewOnTempTable_walker,
81                                                                  context,
82                                                                  QTW_IGNORE_JOINALIASES);
83         }
84
85         return expression_tree_walker(node,
86                                                                   isViewOnTempTable_walker,
87                                                                   context);
88 }
89
90 /*---------------------------------------------------------------------
91  * DefineVirtualRelation
92  *
93  * Create the "view" relation. `DefineRelation' does all the work,
94  * we just provide the correct arguments ... at least when we're
95  * creating a view.  If we're updating an existing view, we have to
96  * work harder.
97  *---------------------------------------------------------------------
98  */
99 static Oid
100 DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
101 {
102         Oid                     viewOid,
103                                 namespaceId;
104         CreateStmt *createStmt = makeNode(CreateStmt);
105         List       *attrList;
106         ListCell   *t;
107
108         /*
109          * create a list of ColumnDef nodes based on the names and types of the
110          * (non-junk) targetlist items from the view's SELECT list.
111          */
112         attrList = NIL;
113         foreach(t, tlist)
114         {
115                 TargetEntry *tle = lfirst(t);
116
117                 if (!tle->resjunk)
118                 {
119                         ColumnDef  *def = makeNode(ColumnDef);
120
121                         def->colname = pstrdup(tle->resname);
122                         def->typeName = makeTypeNameFromOid(exprType((Node *) tle->expr),
123                                                                                          exprTypmod((Node *) tle->expr));
124                         def->inhcount = 0;
125                         def->is_local = true;
126                         def->is_not_null = false;
127                         def->is_from_type = false;
128                         def->storage = 0;
129                         def->raw_default = NULL;
130                         def->cooked_default = NULL;
131                         def->collClause = NULL;
132                         def->collOid = exprCollation((Node *) tle->expr);
133
134                         /*
135                          * It's possible that the column is of a collatable type but the
136                          * collation could not be resolved, so double-check.
137                          */
138                         if (type_is_collatable(exprType((Node *) tle->expr)))
139                         {
140                                 if (!OidIsValid(def->collOid))
141                                         ereport(ERROR,
142                                                         (errcode(ERRCODE_INDETERMINATE_COLLATION),
143                                                          errmsg("could not determine which collation to use for view column \"%s\"",
144                                                                         def->colname),
145                                                          errhint("Use the COLLATE clause to set the collation explicitly.")));
146                         }
147                         else
148                                 Assert(!OidIsValid(def->collOid));
149                         def->constraints = NIL;
150
151                         attrList = lappend(attrList, def);
152                 }
153         }
154
155         if (attrList == NIL)
156                 ereport(ERROR,
157                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
158                                  errmsg("view must have at least one column")));
159
160         /*
161          * Check to see if we want to replace an existing view.
162          */
163         namespaceId = RangeVarGetCreationNamespace(relation);
164         viewOid = get_relname_relid(relation->relname, namespaceId);
165
166         if (OidIsValid(viewOid) && replace)
167         {
168                 Relation        rel;
169                 TupleDesc       descriptor;
170
171                 /*
172                  * Yes.  Get exclusive lock on the existing view ...
173                  */
174                 rel = relation_open(viewOid, AccessExclusiveLock);
175
176                 /*
177                  * Make sure it *is* a view, and do permissions checks.
178                  */
179                 if (rel->rd_rel->relkind != RELKIND_VIEW)
180                         ereport(ERROR,
181                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
182                                          errmsg("\"%s\" is not a view",
183                                                         RelationGetRelationName(rel))));
184
185                 if (!pg_class_ownercheck(viewOid, GetUserId()))
186                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
187                                                    RelationGetRelationName(rel));
188
189                 /* Also check it's not in use already */
190                 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
191
192                 /*
193                  * Due to the namespace visibility rules for temporary objects, we
194                  * should only end up replacing a temporary view with another
195                  * temporary view, and similarly for permanent views.
196                  */
197                 Assert(relation->relpersistence == rel->rd_rel->relpersistence);
198
199                 /*
200                  * Create a tuple descriptor to compare against the existing view, and
201                  * verify that the old column list is an initial prefix of the new
202                  * column list.
203                  */
204                 descriptor = BuildDescForRelation(attrList);
205                 checkViewTupleDesc(descriptor, rel->rd_att);
206
207                 /*
208                  * If new attributes have been added, we must add pg_attribute entries
209                  * for them.  It is convenient (although overkill) to use the ALTER
210                  * TABLE ADD COLUMN infrastructure for this.
211                  */
212                 if (list_length(attrList) > rel->rd_att->natts)
213                 {
214                         List       *atcmds = NIL;
215                         ListCell   *c;
216                         int                     skip = rel->rd_att->natts;
217
218                         foreach(c, attrList)
219                         {
220                                 AlterTableCmd *atcmd;
221
222                                 if (skip > 0)
223                                 {
224                                         skip--;
225                                         continue;
226                                 }
227                                 atcmd = makeNode(AlterTableCmd);
228                                 atcmd->subtype = AT_AddColumnToView;
229                                 atcmd->def = (Node *) lfirst(c);
230                                 atcmds = lappend(atcmds, atcmd);
231                         }
232                         AlterTableInternal(viewOid, atcmds, true);
233                 }
234
235                 /*
236                  * Seems okay, so return the OID of the pre-existing view.
237                  */
238                 relation_close(rel, NoLock);    /* keep the lock! */
239
240                 return viewOid;
241         }
242         else
243         {
244                 Oid                     relid;
245
246                 /*
247                  * now set the parameters for keys/inheritance etc. All of these are
248                  * uninteresting for views...
249                  */
250                 createStmt->relation = (RangeVar *) relation;
251                 createStmt->tableElts = attrList;
252                 createStmt->inhRelations = NIL;
253                 createStmt->constraints = NIL;
254                 createStmt->options = list_make1(defWithOids(false));
255                 createStmt->oncommit = ONCOMMIT_NOOP;
256                 createStmt->tablespacename = NULL;
257                 createStmt->if_not_exists = false;
258
259                 /*
260                  * finally create the relation (this will error out if there's an
261                  * existing view, so we don't need more code to complain if "replace"
262                  * is false).
263                  */
264                 relid = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid);
265                 Assert(relid != InvalidOid);
266                 return relid;
267         }
268 }
269
270 /*
271  * Verify that tupledesc associated with proposed new view definition
272  * matches tupledesc of old view.  This is basically a cut-down version
273  * of equalTupleDescs(), with code added to generate specific complaints.
274  * Also, we allow the new tupledesc to have more columns than the old.
275  */
276 static void
277 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
278 {
279         int                     i;
280
281         if (newdesc->natts < olddesc->natts)
282                 ereport(ERROR,
283                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
284                                  errmsg("cannot drop columns from view")));
285         /* we can ignore tdhasoid */
286
287         for (i = 0; i < olddesc->natts; i++)
288         {
289                 Form_pg_attribute newattr = newdesc->attrs[i];
290                 Form_pg_attribute oldattr = olddesc->attrs[i];
291
292                 /* XXX msg not right, but we don't support DROP COL on view anyway */
293                 if (newattr->attisdropped != oldattr->attisdropped)
294                         ereport(ERROR,
295                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
296                                          errmsg("cannot drop columns from view")));
297
298                 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
299                         ereport(ERROR,
300                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
301                                  errmsg("cannot change name of view column \"%s\" to \"%s\"",
302                                                 NameStr(oldattr->attname),
303                                                 NameStr(newattr->attname))));
304                 /* XXX would it be safe to allow atttypmod to change?  Not sure */
305                 if (newattr->atttypid != oldattr->atttypid ||
306                         newattr->atttypmod != oldattr->atttypmod)
307                         ereport(ERROR,
308                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
309                                          errmsg("cannot change data type of view column \"%s\" from %s to %s",
310                                                         NameStr(oldattr->attname),
311                                                         format_type_with_typemod(oldattr->atttypid,
312                                                                                                          oldattr->atttypmod),
313                                                         format_type_with_typemod(newattr->atttypid,
314                                                                                                          newattr->atttypmod))));
315                 /* We can ignore the remaining attributes of an attribute... */
316         }
317
318         /*
319          * We ignore the constraint fields.  The new view desc can't have any
320          * constraints, and the only ones that could be on the old view are
321          * defaults, which we are happy to leave in place.
322          */
323 }
324
325 static void
326 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
327 {
328         /*
329          * Set up the ON SELECT rule.  Since the query has already been through
330          * parse analysis, we use DefineQueryRewrite() directly.
331          */
332         DefineQueryRewrite(pstrdup(ViewSelectRuleName),
333                                            viewOid,
334                                            NULL,
335                                            CMD_SELECT,
336                                            true,
337                                            replace,
338                                            list_make1(viewParse));
339
340         /*
341          * Someday: automatic ON INSERT, etc
342          */
343 }
344
345 /*---------------------------------------------------------------
346  * UpdateRangeTableOfViewParse
347  *
348  * Update the range table of the given parsetree.
349  * This update consists of adding two new entries IN THE BEGINNING
350  * of the range table (otherwise the rule system will die a slow,
351  * horrible and painful death, and we do not want that now, do we?)
352  * one for the OLD relation and one for the NEW one (both of
353  * them refer in fact to the "view" relation).
354  *
355  * Of course we must also increase the 'varnos' of all the Var nodes
356  * by 2...
357  *
358  * These extra RT entries are not actually used in the query,
359  * except for run-time permission checking.
360  *---------------------------------------------------------------
361  */
362 static Query *
363 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
364 {
365         Relation        viewRel;
366         List       *new_rt;
367         RangeTblEntry *rt_entry1,
368                            *rt_entry2;
369
370         /*
371          * Make a copy of the given parsetree.  It's not so much that we don't
372          * want to scribble on our input, it's that the parser has a bad habit of
373          * outputting multiple links to the same subtree for constructs like
374          * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
375          * Var node twice.      copyObject will expand any multiply-referenced subtree
376          * into multiple copies.
377          */
378         viewParse = (Query *) copyObject(viewParse);
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(NULL, viewRel,
388                                                                                           makeAlias("old", NIL),
389                                                                                           false, false);
390         rt_entry2 = addRangeTableEntryForRelation(NULL, 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 void
416 DefineView(ViewStmt *stmt, const char *queryString)
417 {
418         Query      *viewParse;
419         Oid                     viewOid;
420         RangeVar   *view;
421
422         /*
423          * Run parse analysis to convert the raw parse tree to a Query.  Note this
424          * also acquires sufficient locks on the source table(s).
425          *
426          * Since parse analysis scribbles on its input, copy the raw parse tree;
427          * this ensures we don't corrupt a prepared statement, for example.
428          */
429         viewParse = parse_analyze((Node *) copyObject(stmt->query),
430                                                           queryString, NULL, 0);
431
432         /*
433          * The grammar should ensure that the result is a single SELECT Query.
434          */
435         if (!IsA(viewParse, Query) ||
436                 viewParse->commandType != CMD_SELECT)
437                 elog(ERROR, "unexpected parse analysis result");
438
439         /*
440          * Check for unsupported cases.  These tests are redundant with ones in
441          * DefineQueryRewrite(), but that function will complain about a bogus ON
442          * SELECT rule, and we'd rather the message complain about a view.
443          */
444         if (viewParse->intoClause != NULL)
445                 ereport(ERROR,
446                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
447                                  errmsg("views must not contain SELECT INTO")));
448         if (viewParse->hasModifyingCTE)
449                 ereport(ERROR,
450                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
451                 errmsg("views must not contain data-modifying statements in WITH")));
452
453         /*
454          * If a list of column names was given, run through and insert these into
455          * the actual query tree. - thomas 2000-03-08
456          */
457         if (stmt->aliases != NIL)
458         {
459                 ListCell   *alist_item = list_head(stmt->aliases);
460                 ListCell   *targetList;
461
462                 foreach(targetList, viewParse->targetList)
463                 {
464                         TargetEntry *te = (TargetEntry *) lfirst(targetList);
465
466                         Assert(IsA(te, TargetEntry));
467                         /* junk columns don't get aliases */
468                         if (te->resjunk)
469                                 continue;
470                         te->resname = pstrdup(strVal(lfirst(alist_item)));
471                         alist_item = lnext(alist_item);
472                         if (alist_item == NULL)
473                                 break;                  /* done assigning aliases */
474                 }
475
476                 if (alist_item != NULL)
477                         ereport(ERROR,
478                                         (errcode(ERRCODE_SYNTAX_ERROR),
479                                          errmsg("CREATE VIEW specifies more column "
480                                                         "names than columns")));
481         }
482
483         /*
484          * If the user didn't explicitly ask for a temporary view, check whether
485          * we need one implicitly.      We allow TEMP to be inserted automatically as
486          * long as the CREATE command is consistent with that --- no explicit
487          * schema name.
488          */
489         view = stmt->view;
490         if (view->relpersistence == RELPERSISTENCE_PERMANENT
491                 && isViewOnTempTable(viewParse))
492         {
493                 view = copyObject(view);        /* don't corrupt original command */
494                 view->relpersistence = RELPERSISTENCE_TEMP;
495                 ereport(NOTICE,
496                                 (errmsg("view \"%s\" will be a temporary view",
497                                                 view->relname)));
498         }
499
500         /* Unlogged views are not sensible. */
501         if (view->relpersistence == RELPERSISTENCE_UNLOGGED)
502                 ereport(ERROR,
503                                 (errcode(ERRCODE_SYNTAX_ERROR),
504                 errmsg("views cannot be unlogged because they do not have storage")));
505
506         /*
507          * Create the view relation
508          *
509          * NOTE: if it already exists and replace is false, the xact will be
510          * aborted.
511          */
512         viewOid = DefineVirtualRelation(view, viewParse->targetList,
513                                                                         stmt->replace);
514
515         /*
516          * The relation we have just created is not visible to any other commands
517          * running with the same transaction & command id. So, increment the
518          * command id counter (but do NOT pfree any memory!!!!)
519          */
520         CommandCounterIncrement();
521
522         /*
523          * The range table of 'viewParse' does not contain entries for the "OLD"
524          * and "NEW" relations. So... add them!
525          */
526         viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
527
528         /*
529          * Now create the rules associated with the view.
530          */
531         DefineViewRules(viewOid, viewParse, stmt->replace);
532 }