OSDN Git Service

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