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/rewriteHandler.h"
#include "rewrite/rewriteManip.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 258 of file view.c.

259 {
260  int i;
261 
262  if (newdesc->natts < olddesc->natts)
263  ereport(ERROR,
264  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
265  errmsg("cannot drop columns from view")));
266 
267  for (i = 0; i < olddesc->natts; i++)
268  {
269  Form_pg_attribute newattr = TupleDescAttr(newdesc, i);
270  Form_pg_attribute oldattr = TupleDescAttr(olddesc, i);
271 
272  /* XXX msg not right, but we don't support DROP COL on view anyway */
273  if (newattr->attisdropped != oldattr->attisdropped)
274  ereport(ERROR,
275  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
276  errmsg("cannot drop columns from view")));
277 
278  if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
279  ereport(ERROR,
280  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
281  errmsg("cannot change name of view column \"%s\" to \"%s\"",
282  NameStr(oldattr->attname),
283  NameStr(newattr->attname)),
284  errhint("Use ALTER VIEW ... RENAME COLUMN ... to change name of view column instead.")));
285 
286  /*
287  * We cannot allow type, typmod, or collation to change, since these
288  * properties may be embedded in Vars of other views/rules referencing
289  * this one. Other column attributes can be ignored.
290  */
291  if (newattr->atttypid != oldattr->atttypid ||
292  newattr->atttypmod != oldattr->atttypmod)
293  ereport(ERROR,
294  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
295  errmsg("cannot change data type of view column \"%s\" from %s to %s",
296  NameStr(oldattr->attname),
297  format_type_with_typemod(oldattr->atttypid,
298  oldattr->atttypmod),
299  format_type_with_typemod(newattr->atttypid,
300  newattr->atttypmod))));
301 
302  /*
303  * At this point, attcollations should be both valid or both invalid,
304  * so applying get_collation_name unconditionally should be fine.
305  */
306  if (newattr->attcollation != oldattr->attcollation)
307  ereport(ERROR,
308  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
309  errmsg("cannot change collation of view column \"%s\" from \"%s\" to \"%s\"",
310  NameStr(oldattr->attname),
311  get_collation_name(oldattr->attcollation),
312  get_collation_name(newattr->attcollation))));
313  }
314 
315  /*
316  * We ignore the constraint fields. The new view desc can't have any
317  * constraints, and the only ones that could be on the old view are
318  * defaults, which we are happy to leave in place.
319  */
320 }
#define NameStr(name)
Definition: c.h:681
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:362
int i
Definition: isn.c:73
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:1060
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

Referenced by DefineVirtualRelation().

◆ DefineView()

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

Definition at line 423 of file view.c.

425 {
426  RawStmt *rawstmt;
427  Query *viewParse;
428  RangeVar *view;
429  ListCell *cell;
430  bool check_option;
431  ObjectAddress address;
432 
433  /*
434  * Run parse analysis to convert the raw parse tree to a Query. Note this
435  * also acquires sufficient locks on the source table(s).
436  */
437  rawstmt = makeNode(RawStmt);
438  rawstmt->stmt = stmt->query;
439  rawstmt->stmt_location = stmt_location;
440  rawstmt->stmt_len = stmt_len;
441 
442  viewParse = parse_analyze_fixedparams(rawstmt, queryString, NULL, 0, NULL);
443 
444  /*
445  * The grammar should ensure that the result is a single SELECT Query.
446  * However, it doesn't forbid SELECT INTO, so we have to check for that.
447  */
448  if (!IsA(viewParse, Query))
449  elog(ERROR, "unexpected parse analysis result");
450  if (viewParse->utilityStmt != NULL &&
451  IsA(viewParse->utilityStmt, CreateTableAsStmt))
452  ereport(ERROR,
453  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
454  errmsg("views must not contain SELECT INTO")));
455  if (viewParse->commandType != CMD_SELECT)
456  elog(ERROR, "unexpected parse analysis result");
457 
458  /*
459  * Check for unsupported cases. These tests are redundant with ones in
460  * DefineQueryRewrite(), but that function will complain about a bogus ON
461  * SELECT rule, and we'd rather the message complain about a view.
462  */
463  if (viewParse->hasModifyingCTE)
464  ereport(ERROR,
465  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
466  errmsg("views must not contain data-modifying statements in WITH")));
467 
468  /*
469  * If the user specified the WITH CHECK OPTION, add it to the list of
470  * reloptions.
471  */
472  if (stmt->withCheckOption == LOCAL_CHECK_OPTION)
473  stmt->options = lappend(stmt->options,
474  makeDefElem("check_option",
475  (Node *) makeString("local"), -1));
476  else if (stmt->withCheckOption == CASCADED_CHECK_OPTION)
477  stmt->options = lappend(stmt->options,
478  makeDefElem("check_option",
479  (Node *) makeString("cascaded"), -1));
480 
481  /*
482  * Check that the view is auto-updatable if WITH CHECK OPTION was
483  * specified.
484  */
485  check_option = false;
486 
487  foreach(cell, stmt->options)
488  {
489  DefElem *defel = (DefElem *) lfirst(cell);
490 
491  if (strcmp(defel->defname, "check_option") == 0)
492  check_option = true;
493  }
494 
495  /*
496  * If the check option is specified, look to see if the view is actually
497  * auto-updatable or not.
498  */
499  if (check_option)
500  {
501  const char *view_updatable_error =
502  view_query_is_auto_updatable(viewParse, true);
503 
504  if (view_updatable_error)
505  ereport(ERROR,
506  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
507  errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
508  errhint("%s", _(view_updatable_error))));
509  }
510 
511  /*
512  * If a list of column names was given, run through and insert these into
513  * the actual query tree. - thomas 2000-03-08
514  */
515  if (stmt->aliases != NIL)
516  {
517  ListCell *alist_item = list_head(stmt->aliases);
518  ListCell *targetList;
519 
520  foreach(targetList, viewParse->targetList)
521  {
522  TargetEntry *te = lfirst_node(TargetEntry, targetList);
523 
524  /* junk columns don't get aliases */
525  if (te->resjunk)
526  continue;
527  te->resname = pstrdup(strVal(lfirst(alist_item)));
528  alist_item = lnext(stmt->aliases, alist_item);
529  if (alist_item == NULL)
530  break; /* done assigning aliases */
531  }
532 
533  if (alist_item != NULL)
534  ereport(ERROR,
535  (errcode(ERRCODE_SYNTAX_ERROR),
536  errmsg("CREATE VIEW specifies more column "
537  "names than columns")));
538  }
539 
540  /* Unlogged views are not sensible. */
541  if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
542  ereport(ERROR,
543  (errcode(ERRCODE_SYNTAX_ERROR),
544  errmsg("views cannot be unlogged because they do not have storage")));
545 
546  /*
547  * If the user didn't explicitly ask for a temporary view, check whether
548  * we need one implicitly. We allow TEMP to be inserted automatically as
549  * long as the CREATE command is consistent with that --- no explicit
550  * schema name.
551  */
552  view = copyObject(stmt->view); /* don't corrupt original command */
553  if (view->relpersistence == RELPERSISTENCE_PERMANENT
554  && isQueryUsingTempRelation(viewParse))
555  {
556  view->relpersistence = RELPERSISTENCE_TEMP;
557  ereport(NOTICE,
558  (errmsg("view \"%s\" will be a temporary view",
559  view->relname)));
560  }
561 
562  /*
563  * Create the view relation
564  *
565  * NOTE: if it already exists and replace is false, the xact will be
566  * aborted.
567  */
568  address = DefineVirtualRelation(view, viewParse->targetList,
569  stmt->replace, stmt->options, viewParse);
570 
571  return address;
572 }
#define _(x)
Definition: elog.c:89
#define elog(elevel,...)
Definition: elog.h:218
#define NOTICE
Definition: elog.h:29
List * lappend(List *list, void *datum)
Definition: list.c:336
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:547
char * pstrdup(const char *in)
Definition: mcxt.c:1305
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
#define copyObject(obj)
Definition: nodes.h:689
@ CMD_SELECT
Definition: nodes.h:721
#define makeNode(_type_)
Definition: nodes.h:621
bool isQueryUsingTempRelation(Query *query)
@ CASCADED_CHECK_OPTION
Definition: parsenodes.h:3610
@ LOCAL_CHECK_OPTION
Definition: parsenodes.h:3609
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:106
#define lfirst(lc)
Definition: pg_list.h:169
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:65
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
const char * view_query_is_auto_updatable(Query *viewquery, bool check_cols)
char * defname
Definition: parsenodes.h:765
Definition: nodes.h:574
CmdType commandType
Definition: parsenodes.h:121
bool hasModifyingCTE
Definition: parsenodes.h:140
Node * utilityStmt
Definition: parsenodes.h:129
List * targetList
Definition: parsenodes.h:155
char * relname
Definition: primnodes.h:68
char relpersistence
Definition: primnodes.h:71
int stmt_len
Definition: parsenodes.h:1905
Node * stmt
Definition: parsenodes.h:1903
int stmt_location
Definition: parsenodes.h:1904
char * resname
Definition: primnodes.h:1718
bool resjunk
Definition: primnodes.h:1723
bool replace
Definition: parsenodes.h:3619
List * options
Definition: parsenodes.h:3620
Node * query
Definition: parsenodes.h:3618
List * aliases
Definition: parsenodes.h:3617
RangeVar * view
Definition: parsenodes.h:3616
ViewCheckOption withCheckOption
Definition: parsenodes.h:3621
String * makeString(char *str)
Definition: value.c:63
#define strVal(v)
Definition: value.h:72
static ObjectAddress DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace, List *options, Query *viewParse)
Definition: view.c:50

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_fixedparams(), 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().

◆ DefineViewRules()

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

Definition at line 323 of file view.c.

324 {
325  /*
326  * Set up the ON SELECT rule. Since the query has already been through
327  * parse analysis, we use DefineQueryRewrite() directly.
328  */
330  viewOid,
331  NULL,
332  CMD_SELECT,
333  true,
334  replace,
335  list_make1(viewParse));
336 
337  /*
338  * Someday: automatic ON INSERT, etc
339  */
340 }
#define list_make1(x1)
Definition: pg_list.h:206
ObjectAddress DefineQueryRewrite(const char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)
#define ViewSelectRuleName

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

Referenced by StoreViewQuery().

◆ DefineVirtualRelation()

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

Definition at line 50 of file view.c.

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

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().

◆ StoreViewQuery()

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

Definition at line 578 of file view.c.

579 {
580  /*
581  * The range table of 'viewParse' does not contain entries for the "OLD"
582  * and "NEW" relations. So... add them!
583  */
584  viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);
585 
586  /*
587  * Now create the rules associated with the view.
588  */
589  DefineViewRules(viewOid, viewParse, replace);
590 }
static void DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
Definition: view.c:323
static Query * UpdateRangeTableOfViewParse(Oid viewOid, Query *viewParse)
Definition: view.c:360

References DefineViewRules(), and UpdateRangeTableOfViewParse().

Referenced by create_ctas_internal(), and DefineVirtualRelation().

◆ UpdateRangeTableOfViewParse()

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

Definition at line 360 of file view.c.

361 {
362  Relation viewRel;
363  List *new_rt;
364  ParseNamespaceItem *nsitem;
365  RangeTblEntry *rt_entry1,
366  *rt_entry2;
367  ParseState *pstate;
368 
369  /*
370  * Make a copy of the given parsetree. It's not so much that we don't
371  * want to scribble on our input, it's that the parser has a bad habit of
372  * outputting multiple links to the same subtree for constructs like
373  * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
374  * Var node twice. copyObject will expand any multiply-referenced subtree
375  * into multiple copies.
376  */
377  viewParse = copyObject(viewParse);
378 
379  /* Create a dummy ParseState for addRangeTableEntryForRelation */
380  pstate = make_parsestate(NULL);
381 
382  /* need to open the rel for addRangeTableEntryForRelation */
383  viewRel = relation_open(viewOid, AccessShareLock);
384 
385  /*
386  * Create the 2 new range table entries and form the new range table...
387  * OLD first, then NEW....
388  */
389  nsitem = addRangeTableEntryForRelation(pstate, viewRel,
391  makeAlias("old", NIL),
392  false, false);
393  rt_entry1 = nsitem->p_rte;
394  nsitem = addRangeTableEntryForRelation(pstate, viewRel,
396  makeAlias("new", NIL),
397  false, false);
398  rt_entry2 = nsitem->p_rte;
399 
400  /* Must override addRangeTableEntry's default access-check flags */
401  rt_entry1->requiredPerms = 0;
402  rt_entry2->requiredPerms = 0;
403 
404  new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));
405 
406  viewParse->rtable = new_rt;
407 
408  /*
409  * Now offset all var nodes by 2, and jointree RT indexes too.
410  */
411  OffsetVarNodes((Node *) viewParse, 2, 0);
412 
414 
415  return viewParse;
416 }
List * lcons(void *datum, List *list)
Definition: list.c:474
#define AccessShareLock
Definition: lockdefs.h:36
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:388
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
Definition: rewriteManip.c:425
RangeTblEntry * p_rte
Definition: parse_node.h:269
List * rtable
Definition: parsenodes.h:148
AclMode requiredPerms
Definition: parsenodes.h:1165

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

Referenced by StoreViewQuery().