OSDN Git Service

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