PostgreSQL Source Code  git master
view.c File Reference
#include "postgres.h"
#include "access/relation.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "commands/defrem.h"
#include "commands/tablecmds.h"
#include "commands/view.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/analyze.h"
#include "parser/parse_relation.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteManip.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteSupport.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for view.c:

Go to the source code of this file.

Functions

static void checkViewTupleDesc (TupleDesc newdesc, TupleDesc olddesc)
 
static ObjectAddress DefineVirtualRelation (RangeVar *relation, List *tlist, bool replace, List *options, Query *viewParse)
 
static void DefineViewRules (Oid viewOid, Query *viewParse, bool replace)
 
static QueryUpdateRangeTableOfViewParse (Oid viewOid, Query *viewParse)
 
ObjectAddress DefineView (ViewStmt *stmt, const char *queryString, int stmt_location, int stmt_len)
 
void StoreViewQuery (Oid viewOid, Query *viewParse, bool replace)
 

Function Documentation

◆ checkViewTupleDesc()

static void checkViewTupleDesc ( TupleDesc  newdesc,
TupleDesc  olddesc 
)
static

Definition at line 255 of file view.c.

References ereport, errcode(), errmsg(), ERROR, format_type_with_typemod(), i, NameStr, TupleDescData::natts, and TupleDescAttr.

Referenced by DefineVirtualRelation().

256 {
257  int i;
258 
259  if (newdesc->natts < olddesc->natts)
260  ereport(ERROR,
261  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
262  errmsg("cannot drop columns from view")));
263 
264  for (i = 0; i < olddesc->natts; i++)
265  {
266  Form_pg_attribute newattr = TupleDescAttr(newdesc, i);
267  Form_pg_attribute oldattr = TupleDescAttr(olddesc, i);
268 
269  /* XXX msg not right, but we don't support DROP COL on view anyway */
270  if (newattr->attisdropped != oldattr->attisdropped)
271  ereport(ERROR,
272  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
273  errmsg("cannot drop columns from view")));
274 
275  if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
276  ereport(ERROR,
277  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
278  errmsg("cannot change name of view column \"%s\" to \"%s\"",
279  NameStr(oldattr->attname),
280  NameStr(newattr->attname))));
281  /* XXX would it be safe to allow atttypmod to change? Not sure */
282  if (newattr->atttypid != oldattr->atttypid ||
283  newattr->atttypmod != oldattr->atttypmod)
284  ereport(ERROR,
285  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
286  errmsg("cannot change data type of view column \"%s\" from %s to %s",
287  NameStr(oldattr->attname),
288  format_type_with_typemod(oldattr->atttypid,
289  oldattr->atttypmod),
290  format_type_with_typemod(newattr->atttypid,
291  newattr->atttypmod))));
292  /* We can ignore the remaining attributes of an attribute... */
293  }
294 
295  /*
296  * We ignore the constraint fields. The new view desc can't have any
297  * constraints, and the only ones that could be on the old view are
298  * defaults, which we are happy to leave in place.
299  */
300 }
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:345
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
#define NameStr(name)
Definition: c.h:609

◆ DefineView()

ObjectAddress DefineView ( ViewStmt stmt,
const char *  queryString,
int  stmt_location,
int  stmt_len 
)

Definition at line 399 of file view.c.

References _, ViewStmt::aliases, CASCADED_CHECK_OPTION, CMD_SELECT, Query::commandType, copyObject, DefineVirtualRelation(), DefElem::defname, elog, ereport, errcode(), errhint(), errmsg(), ERROR, Query::hasModifyingCTE, IsA, isQueryUsingTempRelation(), lappend(), lfirst, lfirst_node, list_head(), lnext(), LOCAL_CHECK_OPTION, makeDefElem(), makeNode, makeString(), NIL, NOTICE, ViewStmt::options, parse_analyze(), pstrdup(), ViewStmt::query, RangeVar::relname, RangeVar::relpersistence, ViewStmt::replace, TargetEntry::resjunk, TargetEntry::resname, RawStmt::stmt, RawStmt::stmt_len, RawStmt::stmt_location, strVal, Query::targetList, Query::utilityStmt, ViewStmt::view, view_query_is_auto_updatable(), and ViewStmt::withCheckOption.

Referenced by ProcessUtilitySlow().

401 {
402  RawStmt *rawstmt;
403  Query *viewParse;
404  RangeVar *view;
405  ListCell *cell;
406  bool check_option;
407  ObjectAddress address;
408 
409  /*
410  * Run parse analysis to convert the raw parse tree to a Query. Note this
411  * also acquires sufficient locks on the source table(s).
412  *
413  * Since parse analysis scribbles on its input, copy the raw parse tree;
414  * this ensures we don't corrupt a prepared statement, for example.
415  */
416  rawstmt = makeNode(RawStmt);
417  rawstmt->stmt = (Node *) copyObject(stmt->query);
418  rawstmt->stmt_location = stmt_location;
419  rawstmt->stmt_len = stmt_len;
420 
421  viewParse = parse_analyze(rawstmt, queryString, NULL, 0, NULL);
422 
423  /*
424  * The grammar should ensure that the result is a single SELECT Query.
425  * However, it doesn't forbid SELECT INTO, so we have to check for that.
426  */
427  if (!IsA(viewParse, Query))
428  elog(ERROR, "unexpected parse analysis result");
429  if (viewParse->utilityStmt != NULL &&
430  IsA(viewParse->utilityStmt, CreateTableAsStmt))
431  ereport(ERROR,
432  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
433  errmsg("views must not contain SELECT INTO")));
434  if (viewParse->commandType != CMD_SELECT)
435  elog(ERROR, "unexpected parse analysis result");
436 
437  /*
438  * Check for unsupported cases. These tests are redundant with ones in
439  * DefineQueryRewrite(), but that function will complain about a bogus ON
440  * SELECT rule, and we'd rather the message complain about a view.
441  */
442  if (viewParse->hasModifyingCTE)
443  ereport(ERROR,
444  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
445  errmsg("views must not contain data-modifying statements in WITH")));
446 
447  /*
448  * If the user specified the WITH CHECK OPTION, add it to the list of
449  * reloptions.
450  */
451  if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
452  stmt->options = lappend(stmt->options,
453  makeDefElem("check_option",
454  (Node *) makeString("local"), -1));
455  else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
456  stmt->options = lappend(stmt->options,
457  makeDefElem("check_option",
458  (Node *) makeString("cascaded"), -1));
459 
460  /*
461  * Check that the view is auto-updatable if WITH CHECK OPTION was
462  * specified.
463  */
464  check_option = false;
465 
466  foreach(cell, stmt->options)
467  {
468  DefElem *defel = (DefElem *) lfirst(cell);
469 
470  if (strcmp(defel->defname, "check_option") == 0)
471  check_option = true;
472  }
473 
474  /*
475  * If the check option is specified, look to see if the view is actually
476  * auto-updatable or not.
477  */
478  if (check_option)
479  {
480  const char *view_updatable_error =
481  view_query_is_auto_updatable(viewParse, true);
482 
483  if (view_updatable_error)
484  ereport(ERROR,
485  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
486  errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
487  errhint("%s", _(view_updatable_error))));
488  }
489 
490  /*
491  * If a list of column names was given, run through and insert these into
492  * the actual query tree. - thomas 2000-03-08
493  */
494  if (stmt->aliases != NIL)
495  {
496  ListCell *alist_item = list_head(stmt->aliases);
497  ListCell *targetList;
498 
499  foreach(targetList, viewParse->targetList)
500  {
501  TargetEntry *te = lfirst_node(TargetEntry, targetList);
502 
503  /* junk columns don't get aliases */
504  if (te->resjunk)
505  continue;
506  te->resname = pstrdup(strVal(lfirst(alist_item)));
507  alist_item = lnext(stmt->aliases, alist_item);
508  if (alist_item == NULL)
509  break; /* done assigning aliases */
510  }
511 
512  if (alist_item != NULL)
513  ereport(ERROR,
514  (errcode(ERRCODE_SYNTAX_ERROR),
515  errmsg("CREATE VIEW specifies more column "
516  "names than columns")));
517  }
518 
519  /* Unlogged views are not sensible. */
520  if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
521  ereport(ERROR,
522  (errcode(ERRCODE_SYNTAX_ERROR),
523  errmsg("views cannot be unlogged because they do not have storage")));
524 
525  /*
526  * If the user didn't explicitly ask for a temporary view, check whether
527  * we need one implicitly. We allow TEMP to be inserted automatically as
528  * long as the CREATE command is consistent with that --- no explicit
529  * schema name.
530  */
531  view = copyObject(stmt->view); /* don't corrupt original command */
532  if (view->relpersistence == RELPERSISTENCE_PERMANENT
533  && isQueryUsingTempRelation(viewParse))
534  {
535  view->relpersistence = RELPERSISTENCE_TEMP;
536  ereport(NOTICE,
537  (errmsg("view \"%s\" will be a temporary view",
538  view->relname)));
539  }
540 
541  /*
542  * Create the view relation
543  *
544  * NOTE: if it already exists and replace is false, the xact will be
545  * aborted.
546  */
547  address = DefineVirtualRelation(view, viewParse->targetList,
548  stmt->replace, stmt->options, viewParse);
549 
550  return address;
551 }
Value * makeString(char *str)
Definition: value.c:53
bool replace
Definition: parsenodes.h:3095
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int errhint(const char *fmt,...)
Definition: elog.c:974
bool isQueryUsingTempRelation(Query *query)
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
char * pstrdup(const char *in)
Definition: mcxt.c:1186
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:570
char * resname
Definition: primnodes.h:1395
Node * utilityStmt
Definition: parsenodes.h:120
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:544
RangeVar * view
Definition: parsenodes.h:3092
List * targetList
Definition: parsenodes.h:140
char * relname
Definition: primnodes.h:68
bool resjunk
Definition: primnodes.h:1400
#define ERROR
Definition: elog.h:43
List * aliases
Definition: parsenodes.h:3093
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Node * stmt
Definition: parsenodes.h:1485
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
int stmt_len
Definition: parsenodes.h:1487
int stmt_location
Definition: parsenodes.h:1486
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:100
#define NOTICE
Definition: elog.h:37
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:573
List * options
Definition: parsenodes.h:3096
#define lfirst(lc)
Definition: pg_list.h:190
static ObjectAddress DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace, List *options, Query *viewParse)
Definition: view.c:51
char relpersistence
Definition: primnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
bool hasModifyingCTE
Definition: parsenodes.h:131
char * defname
Definition: parsenodes.h:730
ViewCheckOption withCheckOption
Definition: parsenodes.h:3097
Node * query
Definition: parsenodes.h:3094
#define copyObject(obj)
Definition: nodes.h:641
const char * view_query_is_auto_updatable(Query *viewquery, bool check_cols)
#define _(x)
Definition: elog.c:84

◆ DefineViewRules()

static void DefineViewRules ( Oid  viewOid,
Query viewParse,
bool  replace 
)
static

Definition at line 303 of file view.c.

References CMD_SELECT, DefineQueryRewrite(), list_make1, pstrdup(), and ViewSelectRuleName.

Referenced by StoreViewQuery().

304 {
305  /*
306  * Set up the ON SELECT rule. Since the query has already been through
307  * parse analysis, we use DefineQueryRewrite() directly.
308  */
310  viewOid,
311  NULL,
312  CMD_SELECT,
313  true,
314  replace,
315  list_make1(viewParse));
316 
317  /*
318  * Someday: automatic ON INSERT, etc
319  */
320 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define ViewSelectRuleName
#define list_make1(x1)
Definition: pg_list.h:227
ObjectAddress DefineQueryRewrite(const char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)

◆ DefineVirtualRelation()

static ObjectAddress DefineVirtualRelation ( RangeVar relation,
List tlist,
bool  replace,
List options,
Query viewParse 
)
static

Definition at line 51 of file view.c.

References AccessExclusiveLock, AlterTableInternal(), Assert, AT_AddColumnToView, AT_ReplaceRelOptions, BuildDescForRelation(), CheckTableNotInUse(), checkViewTupleDesc(), ColumnDef::collOid, ColumnDef::colname, CommandCounterIncrement(), CreateStmt::constraints, AlterTableCmd::def, DefineRelation(), ereport, errcode(), errhint(), errmsg(), ERROR, TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), CreateStmt::if_not_exists, CreateStmt::inhRelations, InvalidOid, lappend(), lfirst, list_length(), list_make1, makeColumnDef(), makeNode, TupleDescData::natts, NIL, NoLock, ObjectAddressSet, ObjectAddress::objectId, OidIsValid, CreateStmt::oncommit, ONCOMMIT_NOOP, options, CreateStmt::options, RangeVarGetAndCheckCreationNamespace(), RelationData::rd_att, RelationData::rd_rel, CreateStmt::relation, relation_close(), relation_open(), RelationGetRelationName, RangeVar::relpersistence, TargetEntry::resjunk, TargetEntry::resname, skip, StoreViewQuery(), AlterTableCmd::subtype, CreateStmt::tableElts, CreateStmt::tablespacename, and type_is_collatable().

Referenced by DefineView().

53 {
54  Oid viewOid;
55  LOCKMODE lockmode;
56  CreateStmt *createStmt = makeNode(CreateStmt);
57  List *attrList;
58  ListCell *t;
59 
60  /*
61  * create a list of ColumnDef nodes based on the names and types of the
62  * (non-junk) targetlist items from the view's SELECT list.
63  */
64  attrList = NIL;
65  foreach(t, tlist)
66  {
67  TargetEntry *tle = (TargetEntry *) lfirst(t);
68 
69  if (!tle->resjunk)
70  {
71  ColumnDef *def = makeColumnDef(tle->resname,
72  exprType((Node *) tle->expr),
73  exprTypmod((Node *) tle->expr),
74  exprCollation((Node *) tle->expr));
75 
76  /*
77  * It's possible that the column is of a collatable type but the
78  * collation could not be resolved, so double-check.
79  */
80  if (type_is_collatable(exprType((Node *) tle->expr)))
81  {
82  if (!OidIsValid(def->collOid))
83  ereport(ERROR,
84  (errcode(ERRCODE_INDETERMINATE_COLLATION),
85  errmsg("could not determine which collation to use for view column \"%s\"",
86  def->colname),
87  errhint("Use the COLLATE clause to set the collation explicitly.")));
88  }
89  else
90  Assert(!OidIsValid(def->collOid));
91 
92  attrList = lappend(attrList, def);
93  }
94  }
95 
96  /*
97  * Look up, check permissions on, and lock the creation namespace; also
98  * check for a preexisting view with the same name. This will also set
99  * relation->relpersistence to RELPERSISTENCE_TEMP if the selected
100  * namespace is temporary.
101  */
102  lockmode = replace ? AccessExclusiveLock : NoLock;
103  (void) RangeVarGetAndCheckCreationNamespace(relation, lockmode, &viewOid);
104 
105  if (OidIsValid(viewOid) && replace)
106  {
107  Relation rel;
109  List *atcmds = NIL;
110  AlterTableCmd *atcmd;
111  ObjectAddress address;
112 
113  /* Relation is already locked, but we must build a relcache entry. */
114  rel = relation_open(viewOid, NoLock);
115 
116  /* Make sure it *is* a view. */
117  if (rel->rd_rel->relkind != RELKIND_VIEW)
118  ereport(ERROR,
119  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
120  errmsg("\"%s\" is not a view",
121  RelationGetRelationName(rel))));
122 
123  /* Also check it's not in use already */
124  CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");
125 
126  /*
127  * Due to the namespace visibility rules for temporary objects, we
128  * should only end up replacing a temporary view with another
129  * temporary view, and similarly for permanent views.
130  */
131  Assert(relation->relpersistence == rel->rd_rel->relpersistence);
132 
133  /*
134  * Create a tuple descriptor to compare against the existing view, and
135  * verify that the old column list is an initial prefix of the new
136  * column list.
137  */
138  descriptor = BuildDescForRelation(attrList);
139  checkViewTupleDesc(descriptor, rel->rd_att);
140 
141  /*
142  * If new attributes have been added, we must add pg_attribute entries
143  * for them. It is convenient (although overkill) to use the ALTER
144  * TABLE ADD COLUMN infrastructure for this.
145  *
146  * Note that we must do this before updating the query for the view,
147  * since the rules system requires that the correct view columns be in
148  * place when defining the new rules.
149  */
150  if (list_length(attrList) > rel->rd_att->natts)
151  {
152  ListCell *c;
153  int skip = rel->rd_att->natts;
154 
155  foreach(c, attrList)
156  {
157  if (skip > 0)
158  {
159  skip--;
160  continue;
161  }
162  atcmd = makeNode(AlterTableCmd);
163  atcmd->subtype = AT_AddColumnToView;
164  atcmd->def = (Node *) lfirst(c);
165  atcmds = lappend(atcmds, atcmd);
166  }
167 
168  /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
169  AlterTableInternal(viewOid, atcmds, true);
170 
171  /* Make the new view columns visible */
173  }
174 
175  /*
176  * Update the query for the view.
177  *
178  * Note that we must do this before updating the view options, because
179  * the new options may not be compatible with the old view query (for
180  * example if we attempt to add the WITH CHECK OPTION, we require that
181  * the new view be automatically updatable, but the old view may not
182  * have been).
183  */
184  StoreViewQuery(viewOid, viewParse, replace);
185 
186  /* Make the new view query visible */
188 
189  /*
190  * Finally update the view options.
191  *
192  * The new options list replaces the existing options list, even if
193  * it's empty.
194  */
195  atcmd = makeNode(AlterTableCmd);
196  atcmd->subtype = AT_ReplaceRelOptions;
197  atcmd->def = (Node *) options;
198  atcmds = list_make1(atcmd);
199 
200  /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
201  AlterTableInternal(viewOid, atcmds, true);
202 
203  ObjectAddressSet(address, RelationRelationId, viewOid);
204 
205  /*
206  * Seems okay, so return the OID of the pre-existing view.
207  */
208  relation_close(rel, NoLock); /* keep the lock! */
209 
210  return address;
211  }
212  else
213  {
214  ObjectAddress address;
215 
216  /*
217  * Set the parameters for keys/inheritance etc. All of these are
218  * uninteresting for views...
219  */
220  createStmt->relation = relation;
221  createStmt->tableElts = attrList;
222  createStmt->inhRelations = NIL;
223  createStmt->constraints = NIL;
224  createStmt->options = options;
225  createStmt->oncommit = ONCOMMIT_NOOP;
226  createStmt->tablespacename = NULL;
227  createStmt->if_not_exists = false;
228 
229  /*
230  * Create the relation (this will error out if there's an existing
231  * view, so we don't need more code to complain if "replace" is
232  * false).
233  */
234  address = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid, NULL,
235  NULL);
236  Assert(address.objectId != InvalidOid);
237 
238  /* Make the new view relation visible */
240 
241  /* Store the query for the view */
242  StoreViewQuery(address.objectId, viewParse, replace);
243 
244  return address;
245  }
246 }
RangeVar * relation
Definition: parsenodes.h:2049
#define NIL
Definition: pg_list.h:65
OnCommitAction oncommit
Definition: parsenodes.h:2058
List * inhRelations
Definition: parsenodes.h:2051
int errhint(const char *fmt,...)
Definition: elog.c:974
int LOCKMODE
Definition: lockdefs.h:26
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:570
AlterTableType subtype
Definition: parsenodes.h:1840
static void checkViewTupleDesc(TupleDesc newdesc, TupleDesc olddesc)
Definition: view.c:255
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1395
#define OidIsValid(objectId)
Definition: c.h:638
static const char *const skip[]
Definition: pg_checksums.c:99
List * constraints
Definition: parsenodes.h:2056
#define list_make1(x1)
Definition: pg_list.h:227
bool if_not_exists
Definition: parsenodes.h:2061
bool resjunk
Definition: primnodes.h:1400
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
char * c
#define NoLock
Definition: lockdefs.h:34
Oid collOid
Definition: parsenodes.h:660
#define RelationGetRelationName(relation)
Definition: rel.h:453
List * options
Definition: parsenodes.h:2057
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3416
ObjectAddress DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
Definition: tablecmds.c:556
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
char * tablespacename
Definition: parsenodes.h:2059
static char ** options
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:526
void CommandCounterIncrement(void)
Definition: xact.c:1003
void StoreViewQuery(Oid viewOid, Query *viewParse, bool replace)
Definition: view.c:557
TupleDesc rd_att
Definition: rel.h:84
#define InvalidOid
Definition: postgres_ext.h:36
List * tableElts
Definition: parsenodes.h:2050
#define makeNode(_type_)
Definition: nodes.h:573
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:169
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
char relpersistence
Definition: primnodes.h:71
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3519
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * colname
Definition: parsenodes.h:646
TupleDesc BuildDescForRelation(List *schema)
Definition: tupdesc.c:794
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2848
Definition: pg_list.h:50
ColumnDef * makeColumnDef(const char *colname, Oid typeOid, int32 typmod, Oid collOid)
Definition: makefuncs.c:488

◆ StoreViewQuery()

void StoreViewQuery ( Oid  viewOid,
Query viewParse,
bool  replace 
)

Definition at line 557 of file view.c.

References DefineViewRules(), and UpdateRangeTableOfViewParse().

Referenced by create_ctas_internal(), and DefineVirtualRelation().

558 {
559  /*
560  * The range table of 'viewParse' does not contain entries for the "OLD"
561  * and "NEW" relations. So... add them!
562  */
563  viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
564 
565  /*
566  * Now create the rules associated with the view.
567  */
568  DefineViewRules(viewOid, viewParse, replace);
569 }
static Query * UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
Definition: view.c:340
static void DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
Definition: view.c:303

◆ UpdateRangeTableOfViewParse()

static Query* UpdateRangeTableOfViewParse ( Oid  viewOid,
Query viewParse 
)
static

Definition at line 340 of file view.c.

References AccessShareLock, addRangeTableEntryForRelation(), copyObject, lcons(), make_parsestate(), makeAlias(), NIL, OffsetVarNodes(), relation_close(), relation_open(), RangeTblEntry::requiredPerms, and Query::rtable.

Referenced by StoreViewQuery().

341 {
342  Relation viewRel;
343  List *new_rt;
344  RangeTblEntry *rt_entry1,
345  *rt_entry2;
346  ParseState *pstate;
347 
348  /*
349  * Make a copy of the given parsetree. It's not so much that we don't
350  * want to scribble on our input, it's that the parser has a bad habit of
351  * outputting multiple links to the same subtree for constructs like
352  * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
353  * Var node twice. copyObject will expand any multiply-referenced subtree
354  * into multiple copies.
355  */
356  viewParse = copyObject(viewParse);
357 
358  /* Create a dummy ParseState for addRangeTableEntryForRelation */
359  pstate = make_parsestate(NULL);
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(pstate, viewRel,
370  makeAlias("old", NIL),
371  false, false);
372  rt_entry2 = addRangeTableEntryForRelation(pstate, viewRel,
374  makeAlias("new", NIL),
375  false, false);
376  /* Must override addRangeTableEntry's default access-check flags */
377  rt_entry1->requiredPerms = 0;
378  rt_entry2->requiredPerms = 0;
379 
380  new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
381 
382  viewParse->rtable = new_rt;
383 
384  /*
385  * Now offset all var nodes by 2, and jointree RT indexes too.
386  */
387  OffsetVarNodes((Node *) viewParse, 2, 0);
388 
390 
391  return viewParse;
392 }
#define NIL
Definition: pg_list.h:65
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
Definition: rewriteManip.c:424
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:525
AclMode requiredPerms
Definition: parsenodes.h:1096
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:385
List * rtable
Definition: parsenodes.h:137
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
List * lcons(void *datum, List *list)
Definition: list.c:454
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50