OSDN Git Service

Stamp copyrights for year 2011.
[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->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 similarly for permanent views.
177                  */
178                 Assert(relation->relpersistence == rel->rd_rel->relpersistence);
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                 Oid             relid;
226
227                 /*
228                  * now set the parameters for keys/inheritance etc. All of these are
229                  * uninteresting for views...
230                  */
231                 createStmt->relation = (RangeVar *) relation;
232                 createStmt->tableElts = attrList;
233                 createStmt->inhRelations = NIL;
234                 createStmt->constraints = NIL;
235                 createStmt->options = list_make1(defWithOids(false));
236                 createStmt->oncommit = ONCOMMIT_NOOP;
237                 createStmt->tablespacename = NULL;
238                 createStmt->if_not_exists = false;
239
240                 /*
241                  * finally create the relation (this will error out if there's an
242                  * existing view, so we don't need more code to complain if "replace"
243                  * is false).
244                  */
245                 relid = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid);
246                 Assert(relid != InvalidOid);
247                 return relid;
248         }
249 }
250
251 /*
252  * Verify that tupledesc associated with proposed new view definition
253  * matches tupledesc of old view.  This is basically a cut-down version
254  * of equalTupleDescs(), with code added to generate specific complaints.
255  * Also, we allow the new tupledesc to have more columns than the old.
256  */
257 static void
258 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
259 {
260         int                     i;
261
262         if (newdesc->natts < olddesc->natts)
263                 ereport(ERROR,
264                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
265                                  errmsg("cannot drop columns from view")));
266         /* we can ignore tdhasoid */
267
268         for (i = 0; i < olddesc->natts; i++)
269         {
270                 Form_pg_attribute newattr = newdesc->attrs[i];
271                 Form_pg_attribute oldattr = olddesc->attrs[i];
272
273                 /* XXX msg not right, but we don't support DROP COL on view anyway */
274                 if (newattr->attisdropped != oldattr->attisdropped)
275                         ereport(ERROR,
276                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
277                                          errmsg("cannot drop columns from view")));
278
279                 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
280                         ereport(ERROR,
281                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
282                                  errmsg("cannot change name of view column \"%s\" to \"%s\"",
283                                                 NameStr(oldattr->attname),
284                                                 NameStr(newattr->attname))));
285                 /* XXX would it be safe to allow atttypmod to change?  Not sure */
286                 if (newattr->atttypid != oldattr->atttypid ||
287                         newattr->atttypmod != oldattr->atttypmod)
288                         ereport(ERROR,
289                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
290                                          errmsg("cannot change data type of view column \"%s\" from %s to %s",
291                                                         NameStr(oldattr->attname),
292                                                         format_type_with_typemod(oldattr->atttypid,
293                                                                                                          oldattr->atttypmod),
294                                                         format_type_with_typemod(newattr->atttypid,
295                                                                                                          newattr->atttypmod))));
296                 /* We can ignore the remaining attributes of an attribute... */
297         }
298
299         /*
300          * We ignore the constraint fields.  The new view desc can't have any
301          * constraints, and the only ones that could be on the old view are
302          * defaults, which we are happy to leave in place.
303          */
304 }
305
306 static void
307 DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
308 {
309         /*
310          * Set up the ON SELECT rule.  Since the query has already been through
311          * parse analysis, we use DefineQueryRewrite() directly.
312          */
313         DefineQueryRewrite(pstrdup(ViewSelectRuleName),
314                                            viewOid,
315                                            NULL,
316                                            CMD_SELECT,
317                                            true,
318                                            replace,
319                                            list_make1(viewParse));
320
321         /*
322          * Someday: automatic ON INSERT, etc
323          */
324 }
325
326 /*---------------------------------------------------------------
327  * UpdateRangeTableOfViewParse
328  *
329  * Update the range table of the given parsetree.
330  * This update consists of adding two new entries IN THE BEGINNING
331  * of the range table (otherwise the rule system will die a slow,
332  * horrible and painful death, and we do not want that now, do we?)
333  * one for the OLD relation and one for the NEW one (both of
334  * them refer in fact to the "view" relation).
335  *
336  * Of course we must also increase the 'varnos' of all the Var nodes
337  * by 2...
338  *
339  * These extra RT entries are not actually used in the query,
340  * except for run-time permission checking.
341  *---------------------------------------------------------------
342  */
343 static Query *
344 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
345 {
346         Relation        viewRel;
347         List       *new_rt;
348         RangeTblEntry *rt_entry1,
349                            *rt_entry2;
350
351         /*
352          * Make a copy of the given parsetree.  It's not so much that we don't
353          * want to scribble on our input, it's that the parser has a bad habit of
354          * outputting multiple links to the same subtree for constructs like
355          * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
356          * Var node twice.      copyObject will expand any multiply-referenced subtree
357          * into multiple copies.
358          */
359         viewParse = (Query *) copyObject(viewParse);
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(NULL, viewRel,
369                                                                                           makeAlias("old", NIL),
370                                                                                           false, false);
371         rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
372                                                                                           makeAlias("new", NIL),
373                                                                                           false, false);
374         /* Must override addRangeTableEntry's default access-check flags */
375         rt_entry1->requiredPerms = 0;
376         rt_entry2->requiredPerms = 0;
377
378         new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
379
380         viewParse->rtable = new_rt;
381
382         /*
383          * Now offset all var nodes by 2, and jointree RT indexes too.
384          */
385         OffsetVarNodes((Node *) viewParse, 2, 0);
386
387         relation_close(viewRel, AccessShareLock);
388
389         return viewParse;
390 }
391
392 /*
393  * DefineView
394  *              Execute a CREATE VIEW command.
395  */
396 void
397 DefineView(ViewStmt *stmt, const char *queryString)
398 {
399         Query      *viewParse;
400         Oid                     viewOid;
401         RangeVar   *view;
402
403         /*
404          * Run parse analysis to convert the raw parse tree to a Query.  Note this
405          * also acquires sufficient locks on the source table(s).
406          *
407          * Since parse analysis scribbles on its input, copy the raw parse tree;
408          * this ensures we don't corrupt a prepared statement, for example.
409          */
410         viewParse = parse_analyze((Node *) copyObject(stmt->query),
411                                                           queryString, NULL, 0);
412
413         /*
414          * The grammar should ensure that the result is a single SELECT Query.
415          */
416         if (!IsA(viewParse, Query) ||
417                 viewParse->commandType != CMD_SELECT)
418                 elog(ERROR, "unexpected parse analysis result");
419
420         /*
421          * If a list of column names was given, run through and insert these into
422          * the actual query tree. - thomas 2000-03-08
423          */
424         if (stmt->aliases != NIL)
425         {
426                 ListCell   *alist_item = list_head(stmt->aliases);
427                 ListCell   *targetList;
428
429                 foreach(targetList, viewParse->targetList)
430                 {
431                         TargetEntry *te = (TargetEntry *) lfirst(targetList);
432
433                         Assert(IsA(te, TargetEntry));
434                         /* junk columns don't get aliases */
435                         if (te->resjunk)
436                                 continue;
437                         te->resname = pstrdup(strVal(lfirst(alist_item)));
438                         alist_item = lnext(alist_item);
439                         if (alist_item == NULL)
440                                 break;                  /* done assigning aliases */
441                 }
442
443                 if (alist_item != NULL)
444                         ereport(ERROR,
445                                         (errcode(ERRCODE_SYNTAX_ERROR),
446                                          errmsg("CREATE VIEW specifies more column "
447                                                         "names than columns")));
448         }
449
450         /*
451          * If the user didn't explicitly ask for a temporary view, check whether
452          * we need one implicitly.      We allow TEMP to be inserted automatically as
453          * long as the CREATE command is consistent with that --- no explicit
454          * schema name.
455          */
456         view = stmt->view;
457         if (view->relpersistence == RELPERSISTENCE_PERMANENT
458                 && isViewOnTempTable(viewParse))
459         {
460                 view = copyObject(view);        /* don't corrupt original command */
461                 view->relpersistence = RELPERSISTENCE_TEMP;
462                 ereport(NOTICE,
463                                 (errmsg("view \"%s\" will be a temporary view",
464                                                 view->relname)));
465         }
466
467         /*
468          * Create the view relation
469          *
470          * NOTE: if it already exists and replace is false, the xact will be
471          * aborted.
472          */
473         viewOid = DefineVirtualRelation(view, viewParse->targetList,
474                                                                         stmt->replace);
475
476         /*
477          * The relation we have just created is not visible to any other commands
478          * running with the same transaction & command id. So, increment the
479          * command id counter (but do NOT pfree any memory!!!!)
480          */
481         CommandCounterIncrement();
482
483         /*
484          * The range table of 'viewParse' does not contain entries for the "OLD"
485          * and "NEW" relations. So... add them!
486          */
487         viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
488
489         /*
490          * Now create the rules associated with the view.
491          */
492         DefineViewRules(viewOid, viewParse, stmt->replace);
493 }