OSDN Git Service

Update copyright for the year 2010.
[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-2010, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/commands/view.c,v 1.120 2010/01/02 16:57:40 momjian Exp $
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                                 bool            istemp = rel->rd_istemp;
72
73                                 heap_close(rel, AccessShareLock);
74                                 if (istemp)
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->storage = 0;
128                         def->raw_default = NULL;
129                         def->cooked_default = NULL;
130                         def->constraints = NIL;
131
132                         attrList = lappend(attrList, def);
133                 }
134         }
135
136         if (attrList == NIL)
137                 ereport(ERROR,
138                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
139                                  errmsg("view must have at least one column")));
140
141         /*
142          * Check to see if we want to replace an existing view.
143          */
144         namespaceId = RangeVarGetCreationNamespace(relation);
145         viewOid = get_relname_relid(relation->relname, namespaceId);
146
147         if (OidIsValid(viewOid) && replace)
148         {
149                 Relation        rel;
150                 TupleDesc       descriptor;
151
152                 /*
153                  * Yes.  Get exclusive lock on the existing view ...
154                  */
155                 rel = relation_open(viewOid, AccessExclusiveLock);
156
157                 /*
158                  * Make sure it *is* a view, and do permissions checks.
159                  */
160                 if (rel->rd_rel->relkind != RELKIND_VIEW)
161                         ereport(ERROR,
162                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
163                                          errmsg("\"%s\" is not a view",
164                                                         RelationGetRelationName(rel))));
165
166                 if (!pg_class_ownercheck(viewOid, GetUserId()))
167                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
168                                                    RelationGetRelationName(rel));
169
170                 /* Also check it's not in use already */
171                 CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
172
173                 /*
174                  * Due to the namespace visibility rules for temporary objects, we
175                  * should only end up replacing a temporary view with another
176                  * temporary view, and vice versa.
177                  */
178                 Assert(relation->istemp == rel->rd_istemp);
179
180                 /*
181                  * Create a tuple descriptor to compare against the existing view, and
182                  * verify that the old column list is an initial prefix of the new
183                  * column list.
184                  */
185                 descriptor = BuildDescForRelation(attrList);
186                 checkViewTupleDesc(descriptor, rel->rd_att);
187
188                 /*
189                  * If new attributes have been added, we must add pg_attribute entries
190                  * for them.  It is convenient (although overkill) to use the ALTER
191                  * TABLE ADD COLUMN infrastructure for this.
192                  */
193                 if (list_length(attrList) > rel->rd_att->natts)
194                 {
195                         List       *atcmds = NIL;
196                         ListCell   *c;
197                         int                     skip = rel->rd_att->natts;
198
199                         foreach(c, attrList)
200                         {
201                                 AlterTableCmd *atcmd;
202
203                                 if (skip > 0)
204                                 {
205                                         skip--;
206                                         continue;
207                                 }
208                                 atcmd = makeNode(AlterTableCmd);
209                                 atcmd->subtype = AT_AddColumnToView;
210                                 atcmd->def = (Node *) lfirst(c);
211                                 atcmds = lappend(atcmds, atcmd);
212                         }
213                         AlterTableInternal(viewOid, atcmds, true);
214                 }
215
216                 /*
217                  * Seems okay, so return the OID of the pre-existing view.
218                  */
219                 relation_close(rel, NoLock);    /* keep the lock! */
220
221                 return viewOid;
222         }
223         else
224         {
225                 /*
226                  * now set the parameters for keys/inheritance etc. All of these are
227                  * uninteresting for views...
228                  */
229                 createStmt->relation = (RangeVar *) relation;
230                 createStmt->tableElts = attrList;
231                 createStmt->inhRelations = NIL;
232                 createStmt->constraints = NIL;
233                 createStmt->options = list_make1(defWithOids(false));
234                 createStmt->oncommit = ONCOMMIT_NOOP;
235                 createStmt->tablespacename = NULL;
236
237                 /*
238                  * finally create the relation (this will error out if there's an
239                  * existing view, so we don't need more code to complain if "replace"
240                  * is false).
241                  */
242                 return DefineRelation(createStmt, RELKIND_VIEW);
243         }
244 }
245
246 /*
247  * Verify that tupledesc associated with proposed new view definition
248  * matches tupledesc of old view.  This is basically a cut-down version
249  * of equalTupleDescs(), with code added to generate specific complaints.
250  * Also, we allow the new tupledesc to have more columns than the old.
251  */
252 static void
253 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
254 {
255         int                     i;
256
257         if (newdesc->natts < olddesc->natts)
258                 ereport(ERROR,
259                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
260                                  errmsg("cannot drop columns from view")));
261         /* we can ignore tdhasoid */
262
263         for (i = 0; i < olddesc->natts; i++)
264         {
265                 Form_pg_attribute newattr = newdesc->attrs[i];
266                 Form_pg_attribute oldattr = olddesc->attrs[i];
267
268                 /* XXX msg not right, but we don't support DROP COL on view anyway */
269                 if (newattr->attisdropped != oldattr->attisdropped)
270                         ereport(ERROR,
271                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
272                                          errmsg("cannot drop columns from view")));
273
274                 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
275                         ereport(ERROR,
276                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
277                                  errmsg("cannot change name of view column \"%s\" to \"%s\"",
278                                                 NameStr(oldattr->attname),
279                                                 NameStr(newattr->attname))));
280                 /* XXX would it be safe to allow atttypmod to change?  Not sure */
281                 if (newattr->atttypid != oldattr->atttypid ||
282                         newattr->atttypmod != oldattr->atttypmod)
283                         ereport(ERROR,
284                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
285                                          errmsg("cannot change data type of view column \"%s\" from %s to %s",
286                                                         NameStr(oldattr->attname),
287                                                         format_type_with_typemod(oldattr->atttypid,
288                                                                                                          oldattr->atttypmod),
289                                                         format_type_with_typemod(newattr->atttypid,
290                                                                                                          newattr->atttypmod))));
291                 /* We can ignore the remaining attributes of an attribute... */
292         }
293
294         /*
295          * We ignore the constraint fields.  The new view desc can't have any
296          * constraints, and the only ones that could be on the old view are
297          * defaults, which we are happy to leave in place.
298          */
299 }
300
301 static void
302 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
303 {
304         /*
305          * Set up the ON SELECT rule.  Since the query has already been through
306          * parse analysis, we use DefineQueryRewrite() directly.
307          */
308         DefineQueryRewrite(pstrdup(ViewSelectRuleName),
309                                            viewOid,
310                                            NULL,
311                                            CMD_SELECT,
312                                            true,
313                                            replace,
314                                            list_make1(viewParse));
315
316         /*
317          * Someday: automatic ON INSERT, etc
318          */
319 }
320
321 /*---------------------------------------------------------------
322  * UpdateRangeTableOfViewParse
323  *
324  * Update the range table of the given parsetree.
325  * This update consists of adding two new entries IN THE BEGINNING
326  * of the range table (otherwise the rule system will die a slow,
327  * horrible and painful death, and we do not want that now, do we?)
328  * one for the OLD relation and one for the NEW one (both of
329  * them refer in fact to the "view" relation).
330  *
331  * Of course we must also increase the 'varnos' of all the Var nodes
332  * by 2...
333  *
334  * These extra RT entries are not actually used in the query,
335  * except for run-time permission checking.
336  *---------------------------------------------------------------
337  */
338 static Query *
339 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
340 {
341         Relation        viewRel;
342         List       *new_rt;
343         RangeTblEntry *rt_entry1,
344                            *rt_entry2;
345
346         /*
347          * Make a copy of the given parsetree.  It's not so much that we don't
348          * want to scribble on our input, it's that the parser has a bad habit of
349          * outputting multiple links to the same subtree for constructs like
350          * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
351          * Var node twice.      copyObject will expand any multiply-referenced subtree
352          * into multiple copies.
353          */
354         viewParse = (Query *) copyObject(viewParse);
355
356         /* need to open the rel for addRangeTableEntryForRelation */
357         viewRel = relation_open(viewOid, AccessShareLock);
358
359         /*
360          * Create the 2 new range table entries and form the new range table...
361          * OLD first, then NEW....
362          */
363         rt_entry1 = addRangeTableEntryForRelation(NULL, viewRel,
364                                                                                           makeAlias("old", NIL),
365                                                                                           false, false);
366         rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
367                                                                                           makeAlias("new", NIL),
368                                                                                           false, false);
369         /* Must override addRangeTableEntry's default access-check flags */
370         rt_entry1->requiredPerms = 0;
371         rt_entry2->requiredPerms = 0;
372
373         new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
374
375         viewParse->rtable = new_rt;
376
377         /*
378          * Now offset all var nodes by 2, and jointree RT indexes too.
379          */
380         OffsetVarNodes((Node *) viewParse, 2, 0);
381
382         relation_close(viewRel, AccessShareLock);
383
384         return viewParse;
385 }
386
387 /*
388  * DefineView
389  *              Execute a CREATE VIEW command.
390  */
391 void
392 DefineView(ViewStmt *stmt, const char *queryString)
393 {
394         Query      *viewParse;
395         Oid                     viewOid;
396         RangeVar   *view;
397
398         /*
399          * Run parse analysis to convert the raw parse tree to a Query.  Note this
400          * also acquires sufficient locks on the source table(s).
401          *
402          * Since parse analysis scribbles on its input, copy the raw parse tree;
403          * this ensures we don't corrupt a prepared statement, for example.
404          */
405         viewParse = parse_analyze((Node *) copyObject(stmt->query),
406                                                           queryString, NULL, 0);
407
408         /*
409          * The grammar should ensure that the result is a single SELECT Query.
410          */
411         if (!IsA(viewParse, Query) ||
412                 viewParse->commandType != CMD_SELECT)
413                 elog(ERROR, "unexpected parse analysis result");
414
415         /*
416          * If a list of column names was given, run through and insert these into
417          * the actual query tree. - thomas 2000-03-08
418          */
419         if (stmt->aliases != NIL)
420         {
421                 ListCell   *alist_item = list_head(stmt->aliases);
422                 ListCell   *targetList;
423
424                 foreach(targetList, viewParse->targetList)
425                 {
426                         TargetEntry *te = (TargetEntry *) lfirst(targetList);
427
428                         Assert(IsA(te, TargetEntry));
429                         /* junk columns don't get aliases */
430                         if (te->resjunk)
431                                 continue;
432                         te->resname = pstrdup(strVal(lfirst(alist_item)));
433                         alist_item = lnext(alist_item);
434                         if (alist_item == NULL)
435                                 break;                  /* done assigning aliases */
436                 }
437
438                 if (alist_item != NULL)
439                         ereport(ERROR,
440                                         (errcode(ERRCODE_SYNTAX_ERROR),
441                                          errmsg("CREATE VIEW specifies more column "
442                                                         "names than columns")));
443         }
444
445         /*
446          * If the user didn't explicitly ask for a temporary view, check whether
447          * we need one implicitly.      We allow TEMP to be inserted automatically as
448          * long as the CREATE command is consistent with that --- no explicit
449          * schema name.
450          */
451         view = stmt->view;
452         if (!view->istemp && isViewOnTempTable(viewParse))
453         {
454                 view = copyObject(view);        /* don't corrupt original command */
455                 view->istemp = true;
456                 ereport(NOTICE,
457                                 (errmsg("view \"%s\" will be a temporary view",
458                                                 view->relname)));
459         }
460
461         /*
462          * Create the view relation
463          *
464          * NOTE: if it already exists and replace is false, the xact will be
465          * aborted.
466          */
467         viewOid = DefineVirtualRelation(view, viewParse->targetList,
468                                                                         stmt->replace);
469
470         /*
471          * The relation we have just created is not visible to any other commands
472          * running with the same transaction & command id. So, increment the
473          * command id counter (but do NOT pfree any memory!!!!)
474          */
475         CommandCounterIncrement();
476
477         /*
478          * The range table of 'viewParse' does not contain entries for the "OLD"
479          * and "NEW" relations. So... add them!
480          */
481         viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
482
483         /*
484          * Now create the rules associated with the view.
485          */
486         DefineViewRules(viewOid, viewParse, stmt->replace);
487 }