OSDN Git Service

Replace pg_attribute.attisinherited with attislocal and attinhcount
[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-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/commands/view.c,v 1.72 2002/09/22 19:42:50 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "access/heapam.h"
18 #include "catalog/dependency.h"
19 #include "catalog/namespace.h"
20 #include "commands/tablecmds.h"
21 #include "commands/view.h"
22 #include "miscadmin.h"
23 #include "nodes/makefuncs.h"
24 #include "parser/parse_relation.h"
25 #include "rewrite/rewriteDefine.h"
26 #include "rewrite/rewriteManip.h"
27 #include "rewrite/rewriteSupport.h"
28 #include "utils/acl.h"
29 #include "utils/lsyscache.h"
30
31
32 static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc);
33
34
35 /*---------------------------------------------------------------------
36  * DefineVirtualRelation
37  *
38  * Create the "view" relation. `DefineRelation' does all the work,
39  * we just provide the correct arguments ... at least when we're
40  * creating a view.  If we're updating an existing view, we have to
41  * work harder.
42  *---------------------------------------------------------------------
43  */
44 static Oid
45 DefineVirtualRelation(const RangeVar *relation, List *tlist, bool replace)
46 {
47         Oid                     viewOid,
48                                 namespaceId;
49         CreateStmt *createStmt = makeNode(CreateStmt);
50         List       *attrList,
51                            *t;
52
53         /*
54          * create a list of ColumnDef nodes based on the names and types of
55          * the (non-junk) targetlist items from the view's SELECT list.
56          */
57         attrList = NIL;
58         foreach(t, tlist)
59         {
60                 TargetEntry *entry = lfirst(t);
61                 Resdom     *res = entry->resdom;
62
63                 if (!res->resjunk)
64                 {
65                         ColumnDef  *def = makeNode(ColumnDef);
66                         TypeName   *typename = makeNode(TypeName);
67
68                         def->colname = pstrdup(res->resname);
69
70                         typename->typeid = res->restype;
71                         typename->typmod = res->restypmod;
72                         def->typename = typename;
73
74                         def->inhcount = 0;
75                         def->is_local = true;
76                         def->is_not_null = false;
77                         def->raw_default = NULL;
78                         def->cooked_default = NULL;
79                         def->constraints = NIL;
80                         def->support = NULL;
81
82                         attrList = lappend(attrList, def);
83                 }
84         }
85
86         if (attrList == NIL)
87                 elog(ERROR, "attempted to define virtual relation with no attrs");
88
89         /*
90          * Check to see if we want to replace an existing view.
91          */
92         namespaceId = RangeVarGetCreationNamespace(relation);
93         viewOid = get_relname_relid(relation->relname, namespaceId);
94
95         if (OidIsValid(viewOid) && replace)
96         {
97                 Relation        rel;
98                 TupleDesc       descriptor;
99
100                 /*
101                  * Yes.  Get exclusive lock on the existing view ...
102                  */
103                 rel = relation_open(viewOid, AccessExclusiveLock);
104
105                 /*
106                  * Make sure it *is* a view, and do permissions checks.
107                  */
108                 if (rel->rd_rel->relkind != RELKIND_VIEW)
109                         elog(ERROR, "%s is not a view",
110                                  RelationGetRelationName(rel));
111
112                 if (!pg_class_ownercheck(viewOid, GetUserId()))
113                         aclcheck_error(ACLCHECK_NOT_OWNER, RelationGetRelationName(rel));
114
115                 /*
116                  * Create a tuple descriptor to compare against the existing view,
117                  * and verify it matches.
118                  */
119                 descriptor = BuildDescForRelation(attrList);
120                 checkViewTupleDesc(descriptor, rel->rd_att);
121
122                 /*
123                  * Seems okay, so return the OID of the pre-existing view.
124                  */
125                 relation_close(rel, NoLock);    /* keep the lock! */
126
127                 return viewOid;
128         }
129         else
130         {
131                 /*
132                  * now create the parameters for keys/inheritance etc. All of them
133                  * are nil...
134                  */
135                 createStmt->relation = (RangeVar *) relation;
136                 createStmt->tableElts = attrList;
137                 createStmt->inhRelations = NIL;
138                 createStmt->constraints = NIL;
139                 createStmt->hasoids = false;
140
141                 /*
142                  * finally create the relation (this will error out if there's an
143                  * existing view, so we don't need more code to complain if
144                  * "replace" is false).
145                  */
146                 return DefineRelation(createStmt, RELKIND_VIEW);
147         }
148 }
149
150 /*
151  * Verify that tupledesc associated with proposed new view definition
152  * matches tupledesc of old view.  This is basically a cut-down version
153  * of equalTupleDescs(), with code added to generate specific complaints.
154  */
155 static void
156 checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
157 {
158         int                     i;
159
160         if (newdesc->natts != olddesc->natts)
161                 elog(ERROR, "Cannot change number of columns in view");
162         /* we can ignore tdhasoid */
163
164         for (i = 0; i < newdesc->natts; i++)
165         {
166                 Form_pg_attribute newattr = newdesc->attrs[i];
167                 Form_pg_attribute oldattr = olddesc->attrs[i];
168
169                 /* XXX not right, but we don't support DROP COL on view anyway */
170                 if (newattr->attisdropped != oldattr->attisdropped)
171                         elog(ERROR, "Cannot change number of columns in view");
172
173                 if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
174                         elog(ERROR, "Cannot change name of view column \"%s\"",
175                                  NameStr(oldattr->attname));
176                 /* XXX would it be safe to allow atttypmod to change?  Not sure */
177                 if (newattr->atttypid != oldattr->atttypid ||
178                         newattr->atttypmod != oldattr->atttypmod)
179                         elog(ERROR, "Cannot change datatype of view column \"%s\"",
180                                  NameStr(oldattr->attname));
181                 /* We can ignore the remaining attributes of an attribute... */
182         }
183
184         /*
185          * We ignore the constraint fields.  The new view desc can't have any
186          * constraints, and the only ones that could be on the old view are
187          * defaults, which we are happy to leave in place.
188          */
189 }
190
191 static RuleStmt *
192 FormViewRetrieveRule(const RangeVar *view, Query *viewParse, bool replace)
193 {
194         RuleStmt   *rule;
195
196         /*
197          * Create a RuleStmt that corresponds to the suitable rewrite rule
198          * args for DefineQueryRewrite();
199          */
200         rule = makeNode(RuleStmt);
201         rule->relation = copyObject((RangeVar *) view);
202         rule->rulename = pstrdup(ViewSelectRuleName);
203         rule->whereClause = NULL;
204         rule->event = CMD_SELECT;
205         rule->instead = true;
206         rule->actions = makeList1(viewParse);
207         rule->replace = replace;
208
209         return rule;
210 }
211
212 static void
213 DefineViewRules(const RangeVar *view, Query *viewParse, bool replace)
214 {
215         RuleStmt   *retrieve_rule;
216
217 #ifdef NOTYET
218         RuleStmt   *replace_rule;
219         RuleStmt   *append_rule;
220         RuleStmt   *delete_rule;
221 #endif
222
223         retrieve_rule = FormViewRetrieveRule(view, viewParse, replace);
224
225 #ifdef NOTYET
226         replace_rule = FormViewReplaceRule(view, viewParse);
227         append_rule = FormViewAppendRule(view, viewParse);
228         delete_rule = FormViewDeleteRule(view, viewParse);
229 #endif
230
231         DefineQueryRewrite(retrieve_rule);
232
233 #ifdef NOTYET
234         DefineQueryRewrite(replace_rule);
235         DefineQueryRewrite(append_rule);
236         DefineQueryRewrite(delete_rule);
237 #endif
238
239 }
240
241 /*---------------------------------------------------------------
242  * UpdateRangeTableOfViewParse
243  *
244  * Update the range table of the given parsetree.
245  * This update consists of adding two new entries IN THE BEGINNING
246  * of the range table (otherwise the rule system will die a slow,
247  * horrible and painful death, and we do not want that now, do we?)
248  * one for the OLD relation and one for the NEW one (both of
249  * them refer in fact to the "view" relation).
250  *
251  * Of course we must also increase the 'varnos' of all the Var nodes
252  * by 2...
253  *
254  * These extra RT entries are not actually used in the query,
255  * except for run-time permission checking.
256  *---------------------------------------------------------------
257  */
258 static Query *
259 UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
260 {
261         List       *new_rt;
262         RangeTblEntry *rt_entry1,
263                            *rt_entry2;
264
265         /*
266          * Make a copy of the given parsetree.  It's not so much that we don't
267          * want to scribble on our input, it's that the parser has a bad habit
268          * of outputting multiple links to the same subtree for constructs
269          * like BETWEEN, and we mustn't have OffsetVarNodes increment the
270          * varno of a Var node twice.  copyObject will expand any
271          * multiply-referenced subtree into multiple copies.
272          */
273         viewParse = (Query *) copyObject(viewParse);
274
275         /*
276          * Create the 2 new range table entries and form the new range
277          * table... OLD first, then NEW....
278          */
279         rt_entry1 = addRangeTableEntryForRelation(NULL, viewOid,
280                                                                                           makeAlias("*OLD*", NIL),
281                                                                                           false, false);
282         rt_entry2 = addRangeTableEntryForRelation(NULL, viewOid,
283                                                                                           makeAlias("*NEW*", NIL),
284                                                                                           false, false);
285         /* Must override addRangeTableEntry's default access-check flags */
286         rt_entry1->checkForRead = false;
287         rt_entry2->checkForRead = false;
288
289         new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
290
291         viewParse->rtable = new_rt;
292
293         /*
294          * Now offset all var nodes by 2, and jointree RT indexes too.
295          */
296         OffsetVarNodes((Node *) viewParse, 2, 0);
297
298         return viewParse;
299 }
300
301 /*-------------------------------------------------------------------
302  * DefineView
303  *
304  *              - takes a "viewname", "parsetree" pair and then
305  *              1)              construct the "virtual" relation
306  *              2)              commit the command but NOT the transaction,
307  *                              so that the relation exists
308  *                              before the rules are defined.
309  *              2)              define the "n" rules specified in the PRS2 paper
310  *                              over the "virtual" relation
311  *-------------------------------------------------------------------
312  */
313 void
314 DefineView(const RangeVar *view, Query *viewParse, bool replace)
315 {
316         Oid                     viewOid;
317
318         /*
319          * Create the view relation
320          *
321          * NOTE: if it already exists and replace is false, the xact will be
322          * aborted.
323          */
324
325         viewOid = DefineVirtualRelation(view, viewParse->targetList, replace);
326
327         /*
328          * The relation we have just created is not visible to any other
329          * commands running with the same transaction & command id. So,
330          * increment the command id counter (but do NOT pfree any memory!!!!)
331          */
332         CommandCounterIncrement();
333
334         /*
335          * The range table of 'viewParse' does not contain entries for the
336          * "OLD" and "NEW" relations. So... add them!
337          */
338         viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
339
340         /*
341          * Now create the rules associated with the view.
342          */
343         DefineViewRules(view, viewParse, replace);
344 }
345
346 /*
347  * RemoveView
348  *
349  * Remove a view given its name
350  *
351  * We just have to drop the relation; the associated rules will be
352  * cleaned up automatically.
353  */
354 void
355 RemoveView(const RangeVar *view, DropBehavior behavior)
356 {
357         Oid                     viewOid;
358         ObjectAddress object;
359
360         viewOid = RangeVarGetRelid(view, false);
361
362         object.classId = RelOid_pg_class;
363         object.objectId = viewOid;
364         object.objectSubId = 0;
365
366         performDeletion(&object, behavior);
367 }