PostgreSQL Source Code  git master
rewriteHandler.h File Reference
#include "nodes/parsenodes.h"
#include "utils/relcache.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)
 
void fill_extraUpdatedCols (RangeTblEntry *target_rte, Relation target_relation)
 
Queryget_view_query (Relation view)
 
const char * view_query_is_auto_updatable (Query *viewquery, bool check_cols)
 
int relation_is_updatable (Oid reloid, List *outer_reloids, bool include_triggers, Bitmapset *include_cols)
 

Function Documentation

◆ AcquireRewriteLocks()

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

Definition at line 139 of file rewriteHandler.c.

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

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

Referenced by acquireLocksOnSubLinks(), ApplyRetrieveRule(), fmgr_sql_validator(), get_query_def(), init_sql_fcache(), inline_set_returning_function(), make_ruledef(), print_function_sqlbody(), refresh_matview_datafill(), and rewriteRuleAction().

◆ build_column_default()

Node* build_column_default ( Relation  rel,
int  attrno 
)

Definition at line 1196 of file rewriteHandler.c.

1197 {
1198  TupleDesc rd_att = rel->rd_att;
1199  Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1);
1200  Oid atttype = att_tup->atttypid;
1201  int32 atttypmod = att_tup->atttypmod;
1202  Node *expr = NULL;
1203  Oid exprtype;
1204 
1205  if (att_tup->attidentity)
1206  {
1208 
1209  nve->seqid = getIdentitySequence(RelationGetRelid(rel), attrno, false);
1210  nve->typeId = att_tup->atttypid;
1211 
1212  return (Node *) nve;
1213  }
1214 
1215  /*
1216  * If relation has a default for this column, fetch that expression.
1217  */
1218  if (att_tup->atthasdef)
1219  {
1220  if (rd_att->constr && rd_att->constr->num_defval > 0)
1221  {
1222  AttrDefault *defval = rd_att->constr->defval;
1223  int ndef = rd_att->constr->num_defval;
1224 
1225  while (--ndef >= 0)
1226  {
1227  if (attrno == defval[ndef].adnum)
1228  {
1229  /* Found it, convert string representation to node tree. */
1230  expr = stringToNode(defval[ndef].adbin);
1231  break;
1232  }
1233  }
1234  }
1235  if (expr == NULL)
1236  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1237  attrno, RelationGetRelationName(rel));
1238  }
1239 
1240  /*
1241  * No per-column default, so look for a default for the type itself. But
1242  * not for generated columns.
1243  */
1244  if (expr == NULL && !att_tup->attgenerated)
1245  expr = get_typdefault(atttype);
1246 
1247  if (expr == NULL)
1248  return NULL; /* No default anywhere */
1249 
1250  /*
1251  * Make sure the value is coerced to the target column type; this will
1252  * generally be true already, but there seem to be some corner cases
1253  * involving domain defaults where it might not be true. This should match
1254  * the parser's processing of non-defaulted expressions --- see
1255  * transformAssignedExpr().
1256  */
1257  exprtype = exprType(expr);
1258 
1259  expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1260  expr, exprtype,
1261  atttype, atttypmod,
1264  -1);
1265  if (expr == NULL)
1266  ereport(ERROR,
1267  (errcode(ERRCODE_DATATYPE_MISMATCH),
1268  errmsg("column \"%s\" is of type %s"
1269  " but default expression is of type %s",
1270  NameStr(att_tup->attname),
1271  format_type_be(atttype),
1272  format_type_be(exprtype)),
1273  errhint("You will need to rewrite or cast the expression.")));
1274 
1275  return expr;
1276 }
#define NameStr(name)
Definition: c.h:692
signed int int32
Definition: c.h:440
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 ereport(elevel,...)
Definition: elog.h:143
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Node * get_typdefault(Oid typid)
Definition: lsyscache.c:2405
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
#define makeNode(_type_)
Definition: nodes.h:622
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:78
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:887
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:575
@ COERCION_ASSIGNMENT
Definition: primnodes.h:554
void * stringToNode(const char *str)
Definition: read.c:89
#define RelationGetRelid(relation)
Definition: rel.h:488
#define RelationGetRelationName(relation)
Definition: rel.h:522
TupleDesc rd_att
Definition: rel.h:110
AttrDefault * defval
Definition: tupdesc.h:39
uint16 num_defval
Definition: tupdesc.h:42
TupleConstr * constr
Definition: tupdesc.h:85
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, TupleDescData::constr, TupleConstr::defval, elog(), ereport, errcode(), errhint(), errmsg(), ERROR, exprType(), format_type_be(), get_typdefault(), getIdentitySequence(), makeNode, NameStr, TupleConstr::num_defval, RelationData::rd_att, RelationGetRelationName, RelationGetRelid, NextValueExpr::seqid, stringToNode(), TupleDescAttr, and NextValueExpr::typeId.

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

◆ fill_extraUpdatedCols()

void fill_extraUpdatedCols ( RangeTblEntry target_rte,
Relation  target_relation 
)

Definition at line 1596 of file rewriteHandler.c.

1597 {
1598  TupleDesc tupdesc = RelationGetDescr(target_relation);
1599  TupleConstr *constr = tupdesc->constr;
1600 
1601  target_rte->extraUpdatedCols = NULL;
1602 
1603  if (constr && constr->has_generated_stored)
1604  {
1605  for (int i = 0; i < constr->num_defval; i++)
1606  {
1607  AttrDefault *defval = &constr->defval[i];
1608  Node *expr;
1609  Bitmapset *attrs_used = NULL;
1610 
1611  /* skip if not generated column */
1612  if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
1613  continue;
1614 
1615  /* identify columns this generated column depends on */
1616  expr = stringToNode(defval->adbin);
1617  pull_varattnos(expr, 1, &attrs_used);
1618 
1619  if (bms_overlap(target_rte->updatedCols, attrs_used))
1620  target_rte->extraUpdatedCols =
1621  bms_add_member(target_rte->extraUpdatedCols,
1623  }
1624  }
1625 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
int i
Definition: isn.c:73
#define RelationGetDescr(relation)
Definition: rel.h:514
AttrNumber adnum
Definition: tupdesc.h:24
char * adbin
Definition: tupdesc.h:25
Bitmapset * extraUpdatedCols
Definition: parsenodes.h:1171
Bitmapset * updatedCols
Definition: parsenodes.h:1170
bool has_generated_stored
Definition: tupdesc.h:45
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:288

References AttrDefault::adbin, AttrDefault::adnum, bms_add_member(), bms_overlap(), TupleDescData::constr, TupleConstr::defval, RangeTblEntry::extraUpdatedCols, FirstLowInvalidHeapAttributeNumber, TupleConstr::has_generated_stored, i, TupleConstr::num_defval, pull_varattnos(), RelationGetDescr, stringToNode(), TupleDescAttr, and RangeTblEntry::updatedCols.

Referenced by apply_handle_update(), and RewriteQuery().

◆ get_view_query()

Query* get_view_query ( Relation  view)

Definition at line 2431 of file rewriteHandler.c.

2432 {
2433  int i;
2434 
2435  Assert(view->rd_rel->relkind == RELKIND_VIEW);
2436 
2437  for (i = 0; i < view->rd_rules->numLocks; i++)
2438  {
2439  RewriteRule *rule = view->rd_rules->rules[i];
2440 
2441  if (rule->event == CMD_SELECT)
2442  {
2443  /* A _RETURN rule should have only one action */
2444  if (list_length(rule->actions) != 1)
2445  elog(ERROR, "invalid _RETURN rule action specification");
2446 
2447  return (Query *) linitial(rule->actions);
2448  }
2449  }
2450 
2451  elog(ERROR, "failed to find _RETURN rule for view");
2452  return NULL; /* keep compiler quiet */
2453 }
@ CMD_SELECT
Definition: nodes.h:722
static int list_length(const List *l)
Definition: pg_list.h:150
#define linitial(l)
Definition: pg_list.h:176
RuleLock * rd_rules
Definition: rel.h:113
RewriteRule ** rules
Definition: prs2lock.h:43
int numLocks
Definition: prs2lock.h:42
Definition: localtime.c:73

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

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

◆ QueryRewrite()

List* QueryRewrite ( Query parsetree)

Definition at line 4123 of file rewriteHandler.c.

4124 {
4125  uint64 input_query_id = parsetree->queryId;
4126  List *querylist;
4127  List *results;
4128  ListCell *l;
4129  CmdType origCmdType;
4130  bool foundOriginalQuery;
4131  Query *lastInstead;
4132 
4133  /*
4134  * This function is only applied to top-level original queries
4135  */
4136  Assert(parsetree->querySource == QSRC_ORIGINAL);
4137  Assert(parsetree->canSetTag);
4138 
4139  /*
4140  * Step 1
4141  *
4142  * Apply all non-SELECT rules possibly getting 0 or many queries
4143  */
4144  querylist = RewriteQuery(parsetree, NIL);
4145 
4146  /*
4147  * Step 2
4148  *
4149  * Apply all the RIR rules on each query
4150  *
4151  * This is also a handy place to mark each query with the original queryId
4152  */
4153  results = NIL;
4154  foreach(l, querylist)
4155  {
4156  Query *query = (Query *) lfirst(l);
4157 
4158  query = fireRIRrules(query, NIL);
4159 
4160  query->queryId = input_query_id;
4161 
4162  results = lappend(results, query);
4163  }
4164 
4165  /*
4166  * Step 3
4167  *
4168  * Determine which, if any, of the resulting queries is supposed to set
4169  * the command-result tag; and update the canSetTag fields accordingly.
4170  *
4171  * If the original query is still in the list, it sets the command tag.
4172  * Otherwise, the last INSTEAD query of the same kind as the original is
4173  * allowed to set the tag. (Note these rules can leave us with no query
4174  * setting the tag. The tcop code has to cope with this by setting up a
4175  * default tag based on the original un-rewritten query.)
4176  *
4177  * The Asserts verify that at most one query in the result list is marked
4178  * canSetTag. If we aren't checking asserts, we can fall out of the loop
4179  * as soon as we find the original query.
4180  */
4181  origCmdType = parsetree->commandType;
4182  foundOriginalQuery = false;
4183  lastInstead = NULL;
4184 
4185  foreach(l, results)
4186  {
4187  Query *query = (Query *) lfirst(l);
4188 
4189  if (query->querySource == QSRC_ORIGINAL)
4190  {
4191  Assert(query->canSetTag);
4192  Assert(!foundOriginalQuery);
4193  foundOriginalQuery = true;
4194 #ifndef USE_ASSERT_CHECKING
4195  break;
4196 #endif
4197  }
4198  else
4199  {
4200  Assert(!query->canSetTag);
4201  if (query->commandType == origCmdType &&
4202  (query->querySource == QSRC_INSTEAD_RULE ||
4204  lastInstead = query;
4205  }
4206  }
4207 
4208  if (!foundOriginalQuery && lastInstead != NULL)
4209  lastInstead->canSetTag = true;
4210 
4211  return results;
4212 }
CmdType
Definition: nodes.h:720
@ QSRC_QUAL_INSTEAD_RULE
Definition: parsenodes.h:45
@ QSRC_ORIGINAL
Definition: parsenodes.h:42
@ QSRC_INSTEAD_RULE
Definition: parsenodes.h:44
static List * RewriteQuery(Query *parsetree, List *rewrite_events)
static Query * fireRIRrules(Query *parsetree, List *activeRIRs)
uint64 queryId
Definition: parsenodes.h:126
bool canSetTag
Definition: parsenodes.h:128
QuerySource querySource
Definition: parsenodes.h:123
CmdType commandType
Definition: parsenodes.h:121

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

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

◆ relation_is_updatable()

int relation_is_updatable ( Oid  reloid,
List outer_reloids,
bool  include_triggers,
Bitmapset include_cols 
)

Definition at line 2781 of file rewriteHandler.c.

2785 {
2786  int events = 0;
2787  Relation rel;
2788  RuleLock *rulelocks;
2789 
2790 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2791 
2792  /* Since this function recurses, it could be driven to stack overflow */
2794 
2795  rel = try_relation_open(reloid, AccessShareLock);
2796 
2797  /*
2798  * If the relation doesn't exist, return zero rather than throwing an
2799  * error. This is helpful since scanning an information_schema view under
2800  * MVCC rules can result in referencing rels that have actually been
2801  * deleted already.
2802  */
2803  if (rel == NULL)
2804  return 0;
2805 
2806  /* If we detect a recursive view, report that it is not updatable */
2807  if (list_member_oid(outer_reloids, RelationGetRelid(rel)))
2808  {
2810  return 0;
2811  }
2812 
2813  /* If the relation is a table, it is always updatable */
2814  if (rel->rd_rel->relkind == RELKIND_RELATION ||
2815  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2816  {
2818  return ALL_EVENTS;
2819  }
2820 
2821  /* Look for unconditional DO INSTEAD rules, and note supported events */
2822  rulelocks = rel->rd_rules;
2823  if (rulelocks != NULL)
2824  {
2825  int i;
2826 
2827  for (i = 0; i < rulelocks->numLocks; i++)
2828  {
2829  if (rulelocks->rules[i]->isInstead &&
2830  rulelocks->rules[i]->qual == NULL)
2831  {
2832  events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2833  }
2834  }
2835 
2836  /* If we have rules for all events, we're done */
2837  if (events == ALL_EVENTS)
2838  {
2840  return events;
2841  }
2842  }
2843 
2844  /* Similarly look for INSTEAD OF triggers, if they are to be included */
2845  if (include_triggers)
2846  {
2847  TriggerDesc *trigDesc = rel->trigdesc;
2848 
2849  if (trigDesc)
2850  {
2851  if (trigDesc->trig_insert_instead_row)
2852  events |= (1 << CMD_INSERT);
2853  if (trigDesc->trig_update_instead_row)
2854  events |= (1 << CMD_UPDATE);
2855  if (trigDesc->trig_delete_instead_row)
2856  events |= (1 << CMD_DELETE);
2857 
2858  /* If we have triggers for all events, we're done */
2859  if (events == ALL_EVENTS)
2860  {
2862  return events;
2863  }
2864  }
2865  }
2866 
2867  /* If this is a foreign table, check which update events it supports */
2868  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2869  {
2870  FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2871 
2872  if (fdwroutine->IsForeignRelUpdatable != NULL)
2873  events |= fdwroutine->IsForeignRelUpdatable(rel);
2874  else
2875  {
2876  /* Assume presence of executor functions is sufficient */
2877  if (fdwroutine->ExecForeignInsert != NULL)
2878  events |= (1 << CMD_INSERT);
2879  if (fdwroutine->ExecForeignUpdate != NULL)
2880  events |= (1 << CMD_UPDATE);
2881  if (fdwroutine->ExecForeignDelete != NULL)
2882  events |= (1 << CMD_DELETE);
2883  }
2884 
2886  return events;
2887  }
2888 
2889  /* Check if this is an automatically updatable view */
2890  if (rel->rd_rel->relkind == RELKIND_VIEW)
2891  {
2892  Query *viewquery = get_view_query(rel);
2893 
2894  if (view_query_is_auto_updatable(viewquery, false) == NULL)
2895  {
2896  Bitmapset *updatable_cols;
2897  int auto_events;
2898  RangeTblRef *rtr;
2899  RangeTblEntry *base_rte;
2900  Oid baseoid;
2901 
2902  /*
2903  * Determine which of the view's columns are updatable. If there
2904  * are none within the set of columns we are looking at, then the
2905  * view doesn't support INSERT/UPDATE, but it may still support
2906  * DELETE.
2907  */
2908  view_cols_are_auto_updatable(viewquery, NULL,
2909  &updatable_cols, NULL);
2910 
2911  if (include_cols != NULL)
2912  updatable_cols = bms_int_members(updatable_cols, include_cols);
2913 
2914  if (bms_is_empty(updatable_cols))
2915  auto_events = (1 << CMD_DELETE); /* May support DELETE */
2916  else
2917  auto_events = ALL_EVENTS; /* May support all events */
2918 
2919  /*
2920  * The base relation must also support these update commands.
2921  * Tables are always updatable, but for any other kind of base
2922  * relation we must do a recursive check limited to the columns
2923  * referenced by the locally updatable columns in this view.
2924  */
2925  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2926  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2927  Assert(base_rte->rtekind == RTE_RELATION);
2928 
2929  if (base_rte->relkind != RELKIND_RELATION &&
2930  base_rte->relkind != RELKIND_PARTITIONED_TABLE)
2931  {
2932  baseoid = base_rte->relid;
2933  outer_reloids = lappend_oid(outer_reloids,
2934  RelationGetRelid(rel));
2935  include_cols = adjust_view_column_set(updatable_cols,
2936  viewquery->targetList);
2937  auto_events &= relation_is_updatable(baseoid,
2938  outer_reloids,
2939  include_triggers,
2940  include_cols);
2941  outer_reloids = list_delete_last(outer_reloids);
2942  }
2943  events |= auto_events;
2944  }
2945  }
2946 
2947  /* If we reach here, the relation may support some update commands */
2949  return events;
2950 }
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:904
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:703
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:428
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:721
List * list_delete_last(List *list)
Definition: list.c:956
@ CMD_INSERT
Definition: nodes.h:724
@ CMD_DELETE
Definition: nodes.h:725
@ CMD_UPDATE
Definition: nodes.h:723
void check_stack_depth(void)
Definition: postgres.c:3500
const char * view_query_is_auto_updatable(Query *viewquery, bool check_cols)
int relation_is_updatable(Oid reloid, List *outer_reloids, bool include_triggers, Bitmapset *include_cols)
static Bitmapset * adjust_view_column_set(Bitmapset *cols, List *targetlist)
static const char * view_cols_are_auto_updatable(Query *viewquery, Bitmapset *required_cols, Bitmapset **updatable_cols, char **non_updatable_col)
Query * get_view_query(Relation view)
#define ALL_EVENTS
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:89
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:232
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:235
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:236
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:240
List * fromlist
Definition: primnodes.h:1937
FromExpr * jointree
Definition: parsenodes.h:150
List * targetList
Definition: parsenodes.h:156
TriggerDesc * trigdesc
Definition: rel.h:115
CmdType event
Definition: prs2lock.h:27
bool isInstead
Definition: prs2lock.h:31
Node * qual
Definition: prs2lock.h:28
bool trig_update_instead_row
Definition: reltrigger.h:63
bool trig_delete_instead_row
Definition: reltrigger.h:68
bool trig_insert_instead_row
Definition: reltrigger.h:58

References AccessShareLock, adjust_view_column_set(), ALL_EVENTS, Assert(), bms_int_members(), bms_is_empty(), check_stack_depth(), 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, lappend_oid(), linitial, list_delete_last(), list_member_oid(), RuleLock::numLocks, RewriteRule::qual, RelationData::rd_rel, RelationData::rd_rules, relation_close(), RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::relkind, 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(), and pg_relation_is_updatable().

◆ view_query_is_auto_updatable()

const char* view_query_is_auto_updatable ( Query viewquery,
bool  check_cols 
)

Definition at line 2550 of file rewriteHandler.c.

2551 {
2552  RangeTblRef *rtr;
2553  RangeTblEntry *base_rte;
2554 
2555  /*----------
2556  * Check if the view is simply updatable. According to SQL-92 this means:
2557  * - No DISTINCT clause.
2558  * - Each TLE is a column reference, and each column appears at most once.
2559  * - FROM contains exactly one base relation.
2560  * - No GROUP BY or HAVING clauses.
2561  * - No set operations (UNION, INTERSECT or EXCEPT).
2562  * - No sub-queries in the WHERE clause that reference the target table.
2563  *
2564  * We ignore that last restriction since it would be complex to enforce
2565  * and there isn't any actual benefit to disallowing sub-queries. (The
2566  * semantic issues that the standard is presumably concerned about don't
2567  * arise in Postgres, since any such sub-query will not see any updates
2568  * executed by the outer query anyway, thanks to MVCC snapshotting.)
2569  *
2570  * We also relax the second restriction by supporting part of SQL:1999
2571  * feature T111, which allows for a mix of updatable and non-updatable
2572  * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2573  * a non-updatable column.
2574  *
2575  * In addition we impose these constraints, involving features that are
2576  * not part of SQL-92:
2577  * - No CTEs (WITH clauses).
2578  * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2579  * - No system columns (including whole-row references) in the tlist.
2580  * - No window functions in the tlist.
2581  * - No set-returning functions in the tlist.
2582  *
2583  * Note that we do these checks without recursively expanding the view.
2584  * If the base relation is a view, we'll recursively deal with it later.
2585  *----------
2586  */
2587  if (viewquery->distinctClause != NIL)
2588  return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2589 
2590  if (viewquery->groupClause != NIL || viewquery->groupingSets)
2591  return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2592 
2593  if (viewquery->havingQual != NULL)
2594  return gettext_noop("Views containing HAVING are not automatically updatable.");
2595 
2596  if (viewquery->setOperations != NULL)
2597  return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2598 
2599  if (viewquery->cteList != NIL)
2600  return gettext_noop("Views containing WITH are not automatically updatable.");
2601 
2602  if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2603  return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2604 
2605  /*
2606  * We must not allow window functions or set returning functions in the
2607  * targetlist. Otherwise we might end up inserting them into the quals of
2608  * the main query. We must also check for aggregates in the targetlist in
2609  * case they appear without a GROUP BY.
2610  *
2611  * These restrictions ensure that each row of the view corresponds to a
2612  * unique row in the underlying base relation.
2613  */
2614  if (viewquery->hasAggs)
2615  return gettext_noop("Views that return aggregate functions are not automatically updatable.");
2616 
2617  if (viewquery->hasWindowFuncs)
2618  return gettext_noop("Views that return window functions are not automatically updatable.");
2619 
2620  if (viewquery->hasTargetSRFs)
2621  return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2622 
2623  /*
2624  * The view query should select from a single base relation, which must be
2625  * a table or another view.
2626  */
2627  if (list_length(viewquery->jointree->fromlist) != 1)
2628  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2629 
2630  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2631  if (!IsA(rtr, RangeTblRef))
2632  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2633 
2634  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2635  if (base_rte->rtekind != RTE_RELATION ||
2636  (base_rte->relkind != RELKIND_RELATION &&
2637  base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2638  base_rte->relkind != RELKIND_VIEW &&
2639  base_rte->relkind != RELKIND_PARTITIONED_TABLE))
2640  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2641 
2642  if (base_rte->tablesample)
2643  return gettext_noop("Views containing TABLESAMPLE are not automatically updatable.");
2644 
2645  /*
2646  * Check that the view has at least one updatable column. This is required
2647  * for INSERT/UPDATE but not for DELETE.
2648  */
2649  if (check_cols)
2650  {
2651  ListCell *cell;
2652  bool found;
2653 
2654  found = false;
2655  foreach(cell, viewquery->targetList)
2656  {
2657  TargetEntry *tle = (TargetEntry *) lfirst(cell);
2658 
2659  if (view_col_is_auto_updatable(rtr, tle) == NULL)
2660  {
2661  found = true;
2662  break;
2663  }
2664  }
2665 
2666  if (!found)
2667  return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2668  }
2669 
2670  return NULL; /* the view is updatable */
2671 }
#define gettext_noop(x)
Definition: c.h:1205
static const char * view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
bool hasWindowFuncs
Definition: parsenodes.h:136
Node * limitCount
Definition: parsenodes.h:178
Node * setOperations
Definition: parsenodes.h:183
bool hasTargetSRFs
Definition: parsenodes.h:137
List * groupClause
Definition: parsenodes.h:164
Node * havingQual
Definition: parsenodes.h:169
Node * limitOffset
Definition: parsenodes.h:177
bool hasAggs
Definition: parsenodes.h:135
List * groupingSets
Definition: parsenodes.h:167
List * distinctClause
Definition: parsenodes.h:173
struct TableSampleClause * tablesample
Definition: parsenodes.h:1046

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, RangeTblEntry::relkind, 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().