OSDN Git Service

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