PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
rewriteHandler.h File Reference
#include "utils/relcache.h"
#include "nodes/parsenodes.h"
Include dependency graph for rewriteHandler.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ListQueryRewrite (Query *parsetree)
 
void AcquireRewriteLocks (Query *parsetree, bool forExecute, bool forUpdatePushedDown)
 
Nodebuild_column_default (Relation rel, int attrno)
 
Queryget_view_query (Relation view)
 
const char * view_query_is_auto_updatable (Query *viewquery, bool check_cols)
 
int relation_is_updatable (Oid reloid, bool include_triggers, Bitmapset *include_cols)
 

Function Documentation

void AcquireRewriteLocks ( Query parsetree,
bool  forExecute,
bool  forUpdatePushedDown 
)

Definition at line 132 of file rewriteHandler.c.

References AccessShareLock, acquireLocksOnSubLinks(), AcquireRewriteLocks(), Assert, Query::cteList, CommonTableExpr::ctequery, elog, ERROR, acquireLocksOnSubLinks_context::for_execute, get_parse_rowmark(), get_rte_attribute_is_dropped(), Query::hasSubLinks, heap_close, heap_open(), IsA, RangeTblEntry::joinaliasvars, lappend(), lfirst, NIL, NoLock, NULL, QTW_IGNORE_RC_SUBQUERIES, query_tree_walker(), RelationData::rd_rel, RangeTblEntry::relid, RangeTblEntry::relkind, Query::resultRelation, RowExclusiveLock, RowShareLock, rt_fetch, Query::rtable, RTE_JOIN, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, strip_implicit_coercions(), RangeTblEntry::subquery, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by acquireLocksOnSubLinks(), AcquireRewriteLocks(), ApplyRetrieveRule(), get_query_def(), make_ruledef(), refresh_matview_datafill(), and rewriteRuleAction().

135 {
136  ListCell *l;
137  int rt_index;
139 
140  context.for_execute = forExecute;
141 
142  /*
143  * First, process RTEs of the current query level.
144  */
145  rt_index = 0;
146  foreach(l, parsetree->rtable)
147  {
148  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
149  Relation rel;
150  LOCKMODE lockmode;
151  List *newaliasvars;
152  Index curinputvarno;
153  RangeTblEntry *curinputrte;
154  ListCell *ll;
155 
156  ++rt_index;
157  switch (rte->rtekind)
158  {
159  case RTE_RELATION:
160 
161  /*
162  * Grab the appropriate lock type for the relation, and do not
163  * release it until end of transaction. This protects the
164  * rewriter and planner against schema changes mid-query.
165  *
166  * Assuming forExecute is true, this logic must match what the
167  * executor will do, else we risk lock-upgrade deadlocks.
168  */
169  if (!forExecute)
170  lockmode = AccessShareLock;
171  else if (rt_index == parsetree->resultRelation)
172  lockmode = RowExclusiveLock;
173  else if (forUpdatePushedDown ||
174  get_parse_rowmark(parsetree, rt_index) != NULL)
175  lockmode = RowShareLock;
176  else
177  lockmode = AccessShareLock;
178 
179  rel = heap_open(rte->relid, lockmode);
180 
181  /*
182  * While we have the relation open, update the RTE's relkind,
183  * just in case it changed since this rule was made.
184  */
185  rte->relkind = rel->rd_rel->relkind;
186 
187  heap_close(rel, NoLock);
188  break;
189 
190  case RTE_JOIN:
191 
192  /*
193  * Scan the join's alias var list to see if any columns have
194  * been dropped, and if so replace those Vars with null
195  * pointers.
196  *
197  * Since a join has only two inputs, we can expect to see
198  * multiple references to the same input RTE; optimize away
199  * multiple fetches.
200  */
201  newaliasvars = NIL;
202  curinputvarno = 0;
203  curinputrte = NULL;
204  foreach(ll, rte->joinaliasvars)
205  {
206  Var *aliasitem = (Var *) lfirst(ll);
207  Var *aliasvar = aliasitem;
208 
209  /* Look through any implicit coercion */
210  aliasvar = (Var *) strip_implicit_coercions((Node *) aliasvar);
211 
212  /*
213  * If the list item isn't a simple Var, then it must
214  * represent a merged column, ie a USING column, and so it
215  * couldn't possibly be dropped, since it's referenced in
216  * the join clause. (Conceivably it could also be a null
217  * pointer already? But that's OK too.)
218  */
219  if (aliasvar && IsA(aliasvar, Var))
220  {
221  /*
222  * The elements of an alias list have to refer to
223  * earlier RTEs of the same rtable, because that's the
224  * order the planner builds things in. So we already
225  * processed the referenced RTE, and so it's safe to
226  * use get_rte_attribute_is_dropped on it. (This might
227  * not hold after rewriting or planning, but it's OK
228  * to assume here.)
229  */
230  Assert(aliasvar->varlevelsup == 0);
231  if (aliasvar->varno != curinputvarno)
232  {
233  curinputvarno = aliasvar->varno;
234  if (curinputvarno >= rt_index)
235  elog(ERROR, "unexpected varno %d in JOIN RTE %d",
236  curinputvarno, rt_index);
237  curinputrte = rt_fetch(curinputvarno,
238  parsetree->rtable);
239  }
240  if (get_rte_attribute_is_dropped(curinputrte,
241  aliasvar->varattno))
242  {
243  /* Replace the join alias item with a NULL */
244  aliasitem = NULL;
245  }
246  }
247  newaliasvars = lappend(newaliasvars, aliasitem);
248  }
249  rte->joinaliasvars = newaliasvars;
250  break;
251 
252  case RTE_SUBQUERY:
253 
254  /*
255  * The subquery RTE itself is all right, but we have to
256  * recurse to process the represented subquery.
257  */
259  forExecute,
260  (forUpdatePushedDown ||
261  get_parse_rowmark(parsetree, rt_index) != NULL));
262  break;
263 
264  default:
265  /* ignore other types of RTEs */
266  break;
267  }
268  }
269 
270  /* Recurse into subqueries in WITH */
271  foreach(l, parsetree->cteList)
272  {
273  CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
274 
275  AcquireRewriteLocks((Query *) cte->ctequery, forExecute, false);
276  }
277 
278  /*
279  * Recurse into sublink subqueries, too. But we already did the ones in
280  * the rtable and cteList.
281  */
282  if (parsetree->hasSubLinks)
283  query_tree_walker(parsetree, acquireLocksOnSubLinks, &context,
285 }
#define NIL
Definition: pg_list.h:69
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2238
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
List * joinaliasvars
Definition: parsenodes.h:921
Index varlevelsup
Definition: primnodes.h:151
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
static bool acquireLocksOnSubLinks(Node *node, acquireLocksOnSubLinks_context *context)
int LOCKMODE
Definition: lockdefs.h:26
int resultRelation
Definition: parsenodes.h:113
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:508
AttrNumber varattno
Definition: primnodes.h:146
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:113
Definition: primnodes.h:141
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:22
List * rtable
Definition: parsenodes.h:128
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend(List *list, void *datum)
Definition: list.c:128
Index varno
Definition: primnodes.h:144
#define RowShareLock
Definition: lockdefs.h:37
bool get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
unsigned int Index
Definition: c.h:362
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:882
List * cteList
Definition: parsenodes.h:126
Query * subquery
Definition: parsenodes.h:900
bool hasSubLinks
Definition: parsenodes.h:119
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:609
Node* build_column_default ( Relation  rel,
int  attrno 
)

Definition at line 1034 of file rewriteHandler.c.

References tupleDesc::attrs, COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, tupleDesc::constr, tupleConstr::defval, ereport, errcode(), errhint(), errmsg(), ERROR, exprType(), format_type_be(), get_typdefault(), NameStr, NULL, tupleConstr::num_defval, RelationData::rd_att, and stringToNode().

Referenced by ATExecAddColumn(), ATExecAlterColumnType(), BeginCopyFrom(), rewriteTargetListIU(), rewriteValuesRTE(), and slot_fill_defaults().

1035 {
1036  TupleDesc rd_att = rel->rd_att;
1037  Form_pg_attribute att_tup = rd_att->attrs[attrno - 1];
1038  Oid atttype = att_tup->atttypid;
1039  int32 atttypmod = att_tup->atttypmod;
1040  Node *expr = NULL;
1041  Oid exprtype;
1042 
1043  /*
1044  * Scan to see if relation has a default for this column.
1045  */
1046  if (rd_att->constr && rd_att->constr->num_defval > 0)
1047  {
1048  AttrDefault *defval = rd_att->constr->defval;
1049  int ndef = rd_att->constr->num_defval;
1050 
1051  while (--ndef >= 0)
1052  {
1053  if (attrno == defval[ndef].adnum)
1054  {
1055  /*
1056  * Found it, convert string representation to node tree.
1057  */
1058  expr = stringToNode(defval[ndef].adbin);
1059  break;
1060  }
1061  }
1062  }
1063 
1064  if (expr == NULL)
1065  {
1066  /*
1067  * No per-column default, so look for a default for the type itself.
1068  */
1069  expr = get_typdefault(atttype);
1070  }
1071 
1072  if (expr == NULL)
1073  return NULL; /* No default anywhere */
1074 
1075  /*
1076  * Make sure the value is coerced to the target column type; this will
1077  * generally be true already, but there seem to be some corner cases
1078  * involving domain defaults where it might not be true. This should match
1079  * the parser's processing of non-defaulted expressions --- see
1080  * transformAssignedExpr().
1081  */
1082  exprtype = exprType(expr);
1083 
1084  expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1085  expr, exprtype,
1086  atttype, atttypmod,
1089  -1);
1090  if (expr == NULL)
1091  ereport(ERROR,
1092  (errcode(ERRCODE_DATATYPE_MISMATCH),
1093  errmsg("column \"%s\" is of type %s"
1094  " but default expression is of type %s",
1095  NameStr(att_tup->attname),
1096  format_type_be(atttype),
1097  format_type_be(exprtype)),
1098  errhint("You will need to rewrite or cast the expression.")));
1099 
1100  return expr;
1101 }
void * stringToNode(char *str)
Definition: read.c:38
int errhint(const char *fmt,...)
Definition: elog.c:987
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:253
AttrDefault * defval
Definition: tupdesc.h:39
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define ereport(elevel, rest)
Definition: elog.h:122
TupleDesc rd_att
Definition: rel.h:114
uint16 num_defval
Definition: tupdesc.h:41
#define NULL
Definition: c.h:226
Node * get_typdefault(Oid typid)
Definition: lsyscache.c:2166
TupleConstr * constr
Definition: tupdesc.h:76
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:495
Query* get_view_query ( Relation  view)

Definition at line 2051 of file rewriteHandler.c.

References RewriteRule::actions, Assert, CMD_SELECT, elog, ERROR, RewriteRule::event, i, linitial, list_length(), NULL, RuleLock::numLocks, RelationData::rd_rel, RelationData::rd_rules, RELKIND_VIEW, and RuleLock::rules.

Referenced by ATExecSetRelOptions(), relation_is_updatable(), and rewriteTargetView().

2052 {
2053  int i;
2054 
2055  Assert(view->rd_rel->relkind == RELKIND_VIEW);
2056 
2057  for (i = 0; i < view->rd_rules->numLocks; i++)
2058  {
2059  RewriteRule *rule = view->rd_rules->rules[i];
2060 
2061  if (rule->event == CMD_SELECT)
2062  {
2063  /* A _RETURN rule should have only one action */
2064  if (list_length(rule->actions) != 1)
2065  elog(ERROR, "invalid _RETURN rule action specification");
2066 
2067  return (Query *) linitial(rule->actions);
2068  }
2069  }
2070 
2071  elog(ERROR, "failed to find _RETURN rule for view");
2072  return NULL; /* keep compiler quiet */
2073 }
int numLocks
Definition: prs2lock.h:42
Form_pg_class rd_rel
Definition: rel.h:113
Definition: localtime.c:74
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
CmdType event
Definition: prs2lock.h:27
RewriteRule ** rules
Definition: prs2lock.h:43
List * actions
Definition: prs2lock.h:29
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
RuleLock * rd_rules
Definition: rel.h:117
static int list_length(const List *l)
Definition: pg_list.h:89
#define RELKIND_VIEW
Definition: pg_class.h:164
int i
#define elog
Definition: elog.h:219
List* QueryRewrite ( Query parsetree)

Definition at line 3490 of file rewriteHandler.c.

References Assert, Query::canSetTag, Query::commandType, fireRIRrules(), lappend(), lfirst, NIL, NULL, QSRC_INSTEAD_RULE, QSRC_ORIGINAL, QSRC_QUAL_INSTEAD_RULE, Query::queryId, Query::querySource, and RewriteQuery().

Referenced by ExecCreateTableAs(), ExplainOneUtility(), ExplainQuery(), PerformCursorOpen(), pg_rewrite_query(), PrepareQuery(), and refresh_matview_datafill().

3491 {
3492  uint32 input_query_id = parsetree->queryId;
3493  List *querylist;
3494  List *results;
3495  ListCell *l;
3496  CmdType origCmdType;
3497  bool foundOriginalQuery;
3498  Query *lastInstead;
3499 
3500  /*
3501  * This function is only applied to top-level original queries
3502  */
3503  Assert(parsetree->querySource == QSRC_ORIGINAL);
3504  Assert(parsetree->canSetTag);
3505 
3506  /*
3507  * Step 1
3508  *
3509  * Apply all non-SELECT rules possibly getting 0 or many queries
3510  */
3511  querylist = RewriteQuery(parsetree, NIL);
3512 
3513  /*
3514  * Step 2
3515  *
3516  * Apply all the RIR rules on each query
3517  *
3518  * This is also a handy place to mark each query with the original queryId
3519  */
3520  results = NIL;
3521  foreach(l, querylist)
3522  {
3523  Query *query = (Query *) lfirst(l);
3524 
3525  query = fireRIRrules(query, NIL, false);
3526 
3527  query->queryId = input_query_id;
3528 
3529  results = lappend(results, query);
3530  }
3531 
3532  /*
3533  * Step 3
3534  *
3535  * Determine which, if any, of the resulting queries is supposed to set
3536  * the command-result tag; and update the canSetTag fields accordingly.
3537  *
3538  * If the original query is still in the list, it sets the command tag.
3539  * Otherwise, the last INSTEAD query of the same kind as the original is
3540  * allowed to set the tag. (Note these rules can leave us with no query
3541  * setting the tag. The tcop code has to cope with this by setting up a
3542  * default tag based on the original un-rewritten query.)
3543  *
3544  * The Asserts verify that at most one query in the result list is marked
3545  * canSetTag. If we aren't checking asserts, we can fall out of the loop
3546  * as soon as we find the original query.
3547  */
3548  origCmdType = parsetree->commandType;
3549  foundOriginalQuery = false;
3550  lastInstead = NULL;
3551 
3552  foreach(l, results)
3553  {
3554  Query *query = (Query *) lfirst(l);
3555 
3556  if (query->querySource == QSRC_ORIGINAL)
3557  {
3558  Assert(query->canSetTag);
3559  Assert(!foundOriginalQuery);
3560  foundOriginalQuery = true;
3561 #ifndef USE_ASSERT_CHECKING
3562  break;
3563 #endif
3564  }
3565  else
3566  {
3567  Assert(!query->canSetTag);
3568  if (query->commandType == origCmdType &&
3569  (query->querySource == QSRC_INSTEAD_RULE ||
3571  lastInstead = query;
3572  }
3573  }
3574 
3575  if (!foundOriginalQuery && lastInstead != NULL)
3576  lastInstead->canSetTag = true;
3577 
3578  return results;
3579 }
#define NIL
Definition: pg_list.h:69
uint32 queryId
Definition: parsenodes.h:107
static List * RewriteQuery(Query *parsetree, List *rewrite_events)
unsigned int uint32
Definition: c.h:265
List * lappend(List *list, void *datum)
Definition: list.c:128
CmdType commandType
Definition: parsenodes.h:103
#define NULL
Definition: c.h:226
QuerySource querySource
Definition: parsenodes.h:105
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
static Query * fireRIRrules(Query *parsetree, List *activeRIRs, bool forUpdatePushedDown)
bool canSetTag
Definition: parsenodes.h:109
Definition: pg_list.h:45
CmdType
Definition: nodes.h:641
int relation_is_updatable ( Oid  reloid,
bool  include_triggers,
Bitmapset include_cols 
)

Definition at line 2387 of file rewriteHandler.c.

References AccessShareLock, adjust_view_column_set(), ALL_EVENTS, Assert, bms_int_members(), bms_is_empty(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, RewriteRule::event, FdwRoutine::ExecForeignDelete, FdwRoutine::ExecForeignInsert, FdwRoutine::ExecForeignUpdate, FromExpr::fromlist, get_view_query(), GetFdwRoutineForRelation(), i, FdwRoutine::IsForeignRelUpdatable, RewriteRule::isInstead, Query::jointree, linitial, NULL, RuleLock::numLocks, RewriteRule::qual, RelationData::rd_rel, RelationData::rd_rules, relation_close(), relation_is_updatable(), RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_FOREIGN_TABLE, RELKIND_RELATION, RELKIND_VIEW, rt_fetch, Query::rtable, RTE_RELATION, RangeTblEntry::rtekind, RangeTblRef::rtindex, RuleLock::rules, Query::targetList, TriggerDesc::trig_delete_instead_row, TriggerDesc::trig_insert_instead_row, TriggerDesc::trig_update_instead_row, RelationData::trigdesc, try_relation_open(), view_cols_are_auto_updatable(), and view_query_is_auto_updatable().

Referenced by pg_column_is_updatable(), pg_relation_is_updatable(), and relation_is_updatable().

2390 {
2391  int events = 0;
2392  Relation rel;
2393  RuleLock *rulelocks;
2394 
2395 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2396 
2397  rel = try_relation_open(reloid, AccessShareLock);
2398 
2399  /*
2400  * If the relation doesn't exist, return zero rather than throwing an
2401  * error. This is helpful since scanning an information_schema view under
2402  * MVCC rules can result in referencing rels that have actually been
2403  * deleted already.
2404  */
2405  if (rel == NULL)
2406  return 0;
2407 
2408  /* If the relation is a table, it is always updatable */
2409  if (rel->rd_rel->relkind == RELKIND_RELATION)
2410  {
2412  return ALL_EVENTS;
2413  }
2414 
2415  /* Look for unconditional DO INSTEAD rules, and note supported events */
2416  rulelocks = rel->rd_rules;
2417  if (rulelocks != NULL)
2418  {
2419  int i;
2420 
2421  for (i = 0; i < rulelocks->numLocks; i++)
2422  {
2423  if (rulelocks->rules[i]->isInstead &&
2424  rulelocks->rules[i]->qual == NULL)
2425  {
2426  events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2427  }
2428  }
2429 
2430  /* If we have rules for all events, we're done */
2431  if (events == ALL_EVENTS)
2432  {
2434  return events;
2435  }
2436  }
2437 
2438  /* Similarly look for INSTEAD OF triggers, if they are to be included */
2439  if (include_triggers)
2440  {
2441  TriggerDesc *trigDesc = rel->trigdesc;
2442 
2443  if (trigDesc)
2444  {
2445  if (trigDesc->trig_insert_instead_row)
2446  events |= (1 << CMD_INSERT);
2447  if (trigDesc->trig_update_instead_row)
2448  events |= (1 << CMD_UPDATE);
2449  if (trigDesc->trig_delete_instead_row)
2450  events |= (1 << CMD_DELETE);
2451 
2452  /* If we have triggers for all events, we're done */
2453  if (events == ALL_EVENTS)
2454  {
2456  return events;
2457  }
2458  }
2459  }
2460 
2461  /* If this is a foreign table, check which update events it supports */
2462  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2463  {
2464  FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2465 
2466  if (fdwroutine->IsForeignRelUpdatable != NULL)
2467  events |= fdwroutine->IsForeignRelUpdatable(rel);
2468  else
2469  {
2470  /* Assume presence of executor functions is sufficient */
2471  if (fdwroutine->ExecForeignInsert != NULL)
2472  events |= (1 << CMD_INSERT);
2473  if (fdwroutine->ExecForeignUpdate != NULL)
2474  events |= (1 << CMD_UPDATE);
2475  if (fdwroutine->ExecForeignDelete != NULL)
2476  events |= (1 << CMD_DELETE);
2477  }
2478 
2480  return events;
2481  }
2482 
2483  /* Check if this is an automatically updatable view */
2484  if (rel->rd_rel->relkind == RELKIND_VIEW)
2485  {
2486  Query *viewquery = get_view_query(rel);
2487 
2488  if (view_query_is_auto_updatable(viewquery, false) == NULL)
2489  {
2490  Bitmapset *updatable_cols;
2491  int auto_events;
2492  RangeTblRef *rtr;
2493  RangeTblEntry *base_rte;
2494  Oid baseoid;
2495 
2496  /*
2497  * Determine which of the view's columns are updatable. If there
2498  * are none within the set of columns we are looking at, then the
2499  * view doesn't support INSERT/UPDATE, but it may still support
2500  * DELETE.
2501  */
2503  &updatable_cols, NULL);
2504 
2505  if (include_cols != NULL)
2506  updatable_cols = bms_int_members(updatable_cols, include_cols);
2507 
2508  if (bms_is_empty(updatable_cols))
2509  auto_events = (1 << CMD_DELETE); /* May support DELETE */
2510  else
2511  auto_events = ALL_EVENTS; /* May support all events */
2512 
2513  /*
2514  * The base relation must also support these update commands.
2515  * Tables are always updatable, but for any other kind of base
2516  * relation we must do a recursive check limited to the columns
2517  * referenced by the locally updatable columns in this view.
2518  */
2519  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2520  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2521  Assert(base_rte->rtekind == RTE_RELATION);
2522 
2523  if (base_rte->relkind != RELKIND_RELATION)
2524  {
2525  baseoid = base_rte->relid;
2526  include_cols = adjust_view_column_set(updatable_cols,
2527  viewquery->targetList);
2528  auto_events &= relation_is_updatable(baseoid,
2529  include_triggers,
2530  include_cols);
2531  }
2532  events |= auto_events;
2533  }
2534  }
2535 
2536  /* If we reach here, the relation may support some update commands */
2538  return events;
2539 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:198
Node * qual
Definition: prs2lock.h:28
int numLocks
Definition: prs2lock.h:42
FromExpr * jointree
Definition: parsenodes.h:129
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1150
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:196
static const char * view_cols_are_auto_updatable(Query *viewquery, Bitmapset *required_cols, Bitmapset **updatable_cols, char **non_updatable_col)
#define AccessShareLock
Definition: lockdefs.h:36
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
List * fromlist
Definition: primnodes.h:1433
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
bool isInstead
Definition: prs2lock.h:31
List * targetList
Definition: parsenodes.h:131
bool trig_insert_instead_row
Definition: reltrigger.h:57
#define linitial(l)
Definition: pg_list.h:110
List * rtable
Definition: parsenodes.h:128
#define ALL_EVENTS
TriggerDesc * trigdesc
Definition: rel.h:119
int relation_is_updatable(Oid reloid, bool include_triggers, Bitmapset *include_cols)
CmdType event
Definition: prs2lock.h:27
RewriteRule ** rules
Definition: prs2lock.h:43
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
bool trig_update_instead_row
Definition: reltrigger.h:62
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:633
bool trig_delete_instead_row
Definition: reltrigger.h:67
static Bitmapset * adjust_view_column_set(Bitmapset *cols, List *targetlist)
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:197
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
RuleLock * rd_rules
Definition: rel.h:117
RTEKind rtekind
Definition: parsenodes.h:882
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
#define RELKIND_VIEW
Definition: pg_class.h:164
Query * get_view_query(Relation view)
int i
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:200
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:761
const char * view_query_is_auto_updatable(Query *viewquery, bool check_cols)
#define RELKIND_RELATION
Definition: pg_class.h:160
const char* view_query_is_auto_updatable ( Query viewquery,
bool  check_cols 
)

Definition at line 2164 of file rewriteHandler.c.

References Query::cteList, Query::distinctClause, FromExpr::fromlist, gettext_noop, Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, IsA, Query::jointree, lfirst, Query::limitCount, Query::limitOffset, linitial, list_length(), NIL, NULL, RangeTblEntry::relkind, RELKIND_FOREIGN_TABLE, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_VIEW, rt_fetch, Query::rtable, RTE_RELATION, RangeTblEntry::rtekind, RangeTblRef::rtindex, Query::setOperations, RangeTblEntry::tablesample, Query::targetList, and view_col_is_auto_updatable().

Referenced by ATExecSetRelOptions(), DefineView(), relation_is_updatable(), and rewriteTargetView().

2165 {
2166  RangeTblRef *rtr;
2167  RangeTblEntry *base_rte;
2168 
2169  /*----------
2170  * Check if the view is simply updatable. According to SQL-92 this means:
2171  * - No DISTINCT clause.
2172  * - Each TLE is a column reference, and each column appears at most once.
2173  * - FROM contains exactly one base relation.
2174  * - No GROUP BY or HAVING clauses.
2175  * - No set operations (UNION, INTERSECT or EXCEPT).
2176  * - No sub-queries in the WHERE clause that reference the target table.
2177  *
2178  * We ignore that last restriction since it would be complex to enforce
2179  * and there isn't any actual benefit to disallowing sub-queries. (The
2180  * semantic issues that the standard is presumably concerned about don't
2181  * arise in Postgres, since any such sub-query will not see any updates
2182  * executed by the outer query anyway, thanks to MVCC snapshotting.)
2183  *
2184  * We also relax the second restriction by supporting part of SQL:1999
2185  * feature T111, which allows for a mix of updatable and non-updatable
2186  * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2187  * a non-updatable column.
2188  *
2189  * In addition we impose these constraints, involving features that are
2190  * not part of SQL-92:
2191  * - No CTEs (WITH clauses).
2192  * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2193  * - No system columns (including whole-row references) in the tlist.
2194  * - No window functions in the tlist.
2195  * - No set-returning functions in the tlist.
2196  *
2197  * Note that we do these checks without recursively expanding the view.
2198  * If the base relation is a view, we'll recursively deal with it later.
2199  *----------
2200  */
2201  if (viewquery->distinctClause != NIL)
2202  return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2203 
2204  if (viewquery->groupClause != NIL || viewquery->groupingSets)
2205  return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2206 
2207  if (viewquery->havingQual != NULL)
2208  return gettext_noop("Views containing HAVING are not automatically updatable.");
2209 
2210  if (viewquery->setOperations != NULL)
2211  return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2212 
2213  if (viewquery->cteList != NIL)
2214  return gettext_noop("Views containing WITH are not automatically updatable.");
2215 
2216  if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2217  return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2218 
2219  /*
2220  * We must not allow window functions or set returning functions in the
2221  * targetlist. Otherwise we might end up inserting them into the quals of
2222  * the main query. We must also check for aggregates in the targetlist in
2223  * case they appear without a GROUP BY.
2224  *
2225  * These restrictions ensure that each row of the view corresponds to a
2226  * unique row in the underlying base relation.
2227  */
2228  if (viewquery->hasAggs)
2229  return gettext_noop("Views that return aggregate functions are not automatically updatable.");
2230 
2231  if (viewquery->hasWindowFuncs)
2232  return gettext_noop("Views that return window functions are not automatically updatable.");
2233 
2234  if (viewquery->hasTargetSRFs)
2235  return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2236 
2237  /*
2238  * The view query should select from a single base relation, which must be
2239  * a table or another view.
2240  */
2241  if (list_length(viewquery->jointree->fromlist) != 1)
2242  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2243 
2244  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2245  if (!IsA(rtr, RangeTblRef))
2246  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2247 
2248  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2249  if (base_rte->rtekind != RTE_RELATION ||
2250  (base_rte->relkind != RELKIND_RELATION &&
2251  base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2252  base_rte->relkind != RELKIND_VIEW &&
2253  base_rte->relkind != RELKIND_PARTITIONED_TABLE))
2254  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2255 
2256  if (base_rte->tablesample)
2257  return gettext_noop("Views containing TABLESAMPLE are not automatically updatable.");
2258 
2259  /*
2260  * Check that the view has at least one updatable column. This is required
2261  * for INSERT/UPDATE but not for DELETE.
2262  */
2263  if (check_cols)
2264  {
2265  ListCell *cell;
2266  bool found;
2267 
2268  found = false;
2269  foreach(cell, viewquery->targetList)
2270  {
2271  TargetEntry *tle = (TargetEntry *) lfirst(cell);
2272 
2273  if (view_col_is_auto_updatable(rtr, tle) == NULL)
2274  {
2275  found = true;
2276  break;
2277  }
2278  }
2279 
2280  if (!found)
2281  return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2282  }
2283 
2284  return NULL; /* the view is updatable */
2285 }
Node * limitOffset
Definition: parsenodes.h:149
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
FromExpr * jointree
Definition: parsenodes.h:129
bool hasAggs
Definition: parsenodes.h:116
List * groupingSets
Definition: parsenodes.h:139
#define gettext_noop(x)
Definition: c.h:139
List * fromlist
Definition: primnodes.h:1433
List * targetList
Definition: parsenodes.h:131
#define linitial(l)
Definition: pg_list.h:110
List * rtable
Definition: parsenodes.h:128
List * distinctClause
Definition: parsenodes.h:145
Node * limitCount
Definition: parsenodes.h:150
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
bool hasTargetSRFs
Definition: parsenodes.h:118
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:117
static int list_length(const List *l)
Definition: pg_list.h:89
RTEKind rtekind
Definition: parsenodes.h:882
List * cteList
Definition: parsenodes.h:126
Node * setOperations
Definition: parsenodes.h:154
List * groupClause
Definition: parsenodes.h:137
#define RELKIND_VIEW
Definition: pg_class.h:164
static const char * view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
Node * havingQual
Definition: parsenodes.h:141
#define RELKIND_RELATION
Definition: pg_class.h:160
struct TableSampleClause * tablesample
Definition: parsenodes.h:895