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 rewriteTargetListUD (Query *parsetree, RangeTblEntry *target_rte, Relation target_relation)
 
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.

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, 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(), AcquireRewriteLocks(), ApplyRetrieveRule(), get_query_def(), make_ruledef(), refresh_matview_datafill(), and rewriteRuleAction().

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 }
#define NIL
Definition: pg_list.h:65
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2322
#define IsA(nodeptr, _type_)
Definition: nodes.h:578
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
List * joinaliasvars
Definition: parsenodes.h:1057
Index varlevelsup
Definition: primnodes.h:191
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
static bool acquireLocksOnSubLinks(Node *node, acquireLocksOnSubLinks_context *context)
int LOCKMODE
Definition: lockdefs.h:26
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:527
AttrNumber varattno
Definition: primnodes.h:186
Form_pg_class rd_rel
Definition: rel.h:110
Definition: primnodes.h:181
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:22
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
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:321
Index varno
Definition: primnodes.h:184
#define RowShareLock
Definition: lockdefs.h:37
bool get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
unsigned int Index
Definition: c.h:537
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
RTEKind rtekind
Definition: parsenodes.h:982
List * cteList
Definition: parsenodes.h:135
Query * subquery
Definition: parsenodes.h:1017
bool hasSubLinks
Definition: parsenodes.h:128
#define elog(elevel,...)
Definition: elog.h:228
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:660

◆ build_column_default()

Node* build_column_default ( Relation  rel,
int  attrno 
)

Definition at line 1217 of file rewriteHandler.c.

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

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

1218 {
1219  TupleDesc rd_att = rel->rd_att;
1220  Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1);
1221  Oid atttype = att_tup->atttypid;
1222  int32 atttypmod = att_tup->atttypmod;
1223  Node *expr = NULL;
1224  Oid exprtype;
1225 
1226  if (att_tup->attidentity)
1227  {
1229 
1230  nve->seqid = getIdentitySequence(RelationGetRelid(rel), attrno, false);
1231  nve->typeId = att_tup->atttypid;
1232 
1233  return (Node *) nve;
1234  }
1235 
1236  /*
1237  * Scan to see if relation has a default for this column.
1238  */
1239  if (att_tup->atthasdef && rd_att->constr &&
1240  rd_att->constr->num_defval > 0)
1241  {
1242  AttrDefault *defval = rd_att->constr->defval;
1243  int ndef = rd_att->constr->num_defval;
1244 
1245  while (--ndef >= 0)
1246  {
1247  if (attrno == defval[ndef].adnum)
1248  {
1249  /*
1250  * Found it, convert string representation to node tree.
1251  */
1252  expr = stringToNode(defval[ndef].adbin);
1253  break;
1254  }
1255  }
1256  }
1257 
1258  /*
1259  * No per-column default, so look for a default for the type itself. But
1260  * not for generated columns.
1261  */
1262  if (expr == NULL && !att_tup->attgenerated)
1263  expr = get_typdefault(atttype);
1264 
1265  if (expr == NULL)
1266  return NULL; /* No default anywhere */
1267 
1268  /*
1269  * Make sure the value is coerced to the target column type; this will
1270  * generally be true already, but there seem to be some corner cases
1271  * involving domain defaults where it might not be true. This should match
1272  * the parser's processing of non-defaulted expressions --- see
1273  * transformAssignedExpr().
1274  */
1275  exprtype = exprType(expr);
1276 
1277  expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1278  expr, exprtype,
1279  atttype, atttypmod,
1282  -1);
1283  if (expr == NULL)
1284  ereport(ERROR,
1285  (errcode(ERRCODE_DATATYPE_MISMATCH),
1286  errmsg("column \"%s\" is of type %s"
1287  " but default expression is of type %s",
1288  NameStr(att_tup->attname),
1289  format_type_be(atttype),
1290  format_type_be(exprtype)),
1291  errhint("You will need to rewrite or cast the expression.")));
1292 
1293  return expr;
1294 }
int errhint(const char *fmt,...)
Definition: elog.c:1149
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:527
int errcode(int sqlerrcode)
Definition: elog.c:691
void * stringToNode(const char *str)
Definition: read.c:89
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:954
signed int int32
Definition: c.h:417
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
TupleConstr * constr
Definition: tupdesc.h:85
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
TupleDesc rd_att
Definition: rel.h:111
#define ereport(elevel,...)
Definition: elog.h:155
#define makeNode(_type_)
Definition: nodes.h:575
Node * get_typdefault(Oid typid)
Definition: lsyscache.c:2341
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
uint16 num_defval
Definition: tupdesc.h:42
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define NameStr(name)
Definition: c.h:677
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ fill_extraUpdatedCols()

void fill_extraUpdatedCols ( RangeTblEntry target_rte,
Relation  target_relation 
)

Definition at line 1698 of file rewriteHandler.c.

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

1699 {
1700  TupleDesc tupdesc = RelationGetDescr(target_relation);
1701  TupleConstr *constr = tupdesc->constr;
1702 
1703  target_rte->extraUpdatedCols = NULL;
1704 
1705  if (constr && constr->has_generated_stored)
1706  {
1707  for (int i = 0; i < constr->num_defval; i++)
1708  {
1709  AttrDefault *defval = &constr->defval[i];
1710  Node *expr;
1711  Bitmapset *attrs_used = NULL;
1712 
1713  /* skip if not generated column */
1714  if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
1715  continue;
1716 
1717  /* identify columns this generated column depends on */
1718  expr = stringToNode(defval->adbin);
1719  pull_varattnos(expr, 1, &attrs_used);
1720 
1721  if (bms_overlap(target_rte->updatedCols, attrs_used))
1722  target_rte->extraUpdatedCols =
1723  bms_add_member(target_rte->extraUpdatedCols,
1725  }
1726  }
1727 }
#define RelationGetDescr(relation)
Definition: rel.h:483
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:527
void * stringToNode(const char *str)
Definition: read.c:89
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
AttrDefault * defval
Definition: tupdesc.h:39
bool has_generated_stored
Definition: tupdesc.h:45
Bitmapset * extraUpdatedCols
Definition: parsenodes.h:1130
TupleConstr * constr
Definition: tupdesc.h:85
Bitmapset * updatedCols
Definition: parsenodes.h:1129
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
uint16 num_defval
Definition: tupdesc.h:42
int i
AttrNumber adnum
Definition: tupdesc.h:24
char * adbin
Definition: tupdesc.h:25

◆ get_view_query()

Query* get_view_query ( Relation  view)

Definition at line 2512 of file rewriteHandler.c.

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

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

2513 {
2514  int i;
2515 
2516  Assert(view->rd_rel->relkind == RELKIND_VIEW);
2517 
2518  for (i = 0; i < view->rd_rules->numLocks; i++)
2519  {
2520  RewriteRule *rule = view->rd_rules->rules[i];
2521 
2522  if (rule->event == CMD_SELECT)
2523  {
2524  /* A _RETURN rule should have only one action */
2525  if (list_length(rule->actions) != 1)
2526  elog(ERROR, "invalid _RETURN rule action specification");
2527 
2528  return (Query *) linitial(rule->actions);
2529  }
2530  }
2531 
2532  elog(ERROR, "failed to find _RETURN rule for view");
2533  return NULL; /* keep compiler quiet */
2534 }
int numLocks
Definition: prs2lock.h:42
Form_pg_class rd_rel
Definition: rel.h:110
Definition: localtime.c:72
#define linitial(l)
Definition: pg_list.h:174
#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 Assert(condition)
Definition: c.h:800
RuleLock * rd_rules
Definition: rel.h:114
static int list_length(const List *l)
Definition: pg_list.h:149
#define elog(elevel,...)
Definition: elog.h:228
int i

◆ QueryRewrite()

List* QueryRewrite ( Query parsetree)

Definition at line 4155 of file rewriteHandler.c.

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(), PrepareQuery(), and refresh_matview_datafill().

4156 {
4157  uint64 input_query_id = parsetree->queryId;
4158  List *querylist;
4159  List *results;
4160  ListCell *l;
4161  CmdType origCmdType;
4162  bool foundOriginalQuery;
4163  Query *lastInstead;
4164 
4165  /*
4166  * This function is only applied to top-level original queries
4167  */
4168  Assert(parsetree->querySource == QSRC_ORIGINAL);
4169  Assert(parsetree->canSetTag);
4170 
4171  /*
4172  * Step 1
4173  *
4174  * Apply all non-SELECT rules possibly getting 0 or many queries
4175  */
4176  querylist = RewriteQuery(parsetree, NIL);
4177 
4178  /*
4179  * Step 2
4180  *
4181  * Apply all the RIR rules on each query
4182  *
4183  * This is also a handy place to mark each query with the original queryId
4184  */
4185  results = NIL;
4186  foreach(l, querylist)
4187  {
4188  Query *query = (Query *) lfirst(l);
4189 
4190  query = fireRIRrules(query, NIL);
4191 
4192  query->queryId = input_query_id;
4193 
4194  results = lappend(results, query);
4195  }
4196 
4197  /*
4198  * Step 3
4199  *
4200  * Determine which, if any, of the resulting queries is supposed to set
4201  * the command-result tag; and update the canSetTag fields accordingly.
4202  *
4203  * If the original query is still in the list, it sets the command tag.
4204  * Otherwise, the last INSTEAD query of the same kind as the original is
4205  * allowed to set the tag. (Note these rules can leave us with no query
4206  * setting the tag. The tcop code has to cope with this by setting up a
4207  * default tag based on the original un-rewritten query.)
4208  *
4209  * The Asserts verify that at most one query in the result list is marked
4210  * canSetTag. If we aren't checking asserts, we can fall out of the loop
4211  * as soon as we find the original query.
4212  */
4213  origCmdType = parsetree->commandType;
4214  foundOriginalQuery = false;
4215  lastInstead = NULL;
4216 
4217  foreach(l, results)
4218  {
4219  Query *query = (Query *) lfirst(l);
4220 
4221  if (query->querySource == QSRC_ORIGINAL)
4222  {
4223  Assert(query->canSetTag);
4224  Assert(!foundOriginalQuery);
4225  foundOriginalQuery = true;
4226 #ifndef USE_ASSERT_CHECKING
4227  break;
4228 #endif
4229  }
4230  else
4231  {
4232  Assert(!query->canSetTag);
4233  if (query->commandType == origCmdType &&
4234  (query->querySource == QSRC_INSTEAD_RULE ||
4236  lastInstead = query;
4237  }
4238  }
4239 
4240  if (!foundOriginalQuery && lastInstead != NULL)
4241  lastInstead->canSetTag = true;
4242 
4243  return results;
4244 }
#define NIL
Definition: pg_list.h:65
static List * RewriteQuery(Query *parsetree, List *rewrite_events)
List * lappend(List *list, void *datum)
Definition: list.c:321
uint64 queryId
Definition: parsenodes.h:116
CmdType commandType
Definition: parsenodes.h:112
QuerySource querySource
Definition: parsenodes.h:114
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
bool canSetTag
Definition: parsenodes.h:118
static Query * fireRIRrules(Query *parsetree, List *activeRIRs)
Definition: pg_list.h:50
CmdType
Definition: nodes.h:670

◆ relation_is_updatable()

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

Definition at line 2862 of file rewriteHandler.c.

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(), relation_is_updatable(), 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(), pg_relation_is_updatable(), and relation_is_updatable().

2866 {
2867  int events = 0;
2868  Relation rel;
2869  RuleLock *rulelocks;
2870 
2871 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2872 
2873  /* Since this function recurses, it could be driven to stack overflow */
2875 
2876  rel = try_relation_open(reloid, AccessShareLock);
2877 
2878  /*
2879  * If the relation doesn't exist, return zero rather than throwing an
2880  * error. This is helpful since scanning an information_schema view under
2881  * MVCC rules can result in referencing rels that have actually been
2882  * deleted already.
2883  */
2884  if (rel == NULL)
2885  return 0;
2886 
2887  /* If we detect a recursive view, report that it is not updatable */
2888  if (list_member_oid(outer_reloids, RelationGetRelid(rel)))
2889  {
2891  return 0;
2892  }
2893 
2894  /* If the relation is a table, it is always updatable */
2895  if (rel->rd_rel->relkind == RELKIND_RELATION ||
2896  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2897  {
2899  return ALL_EVENTS;
2900  }
2901 
2902  /* Look for unconditional DO INSTEAD rules, and note supported events */
2903  rulelocks = rel->rd_rules;
2904  if (rulelocks != NULL)
2905  {
2906  int i;
2907 
2908  for (i = 0; i < rulelocks->numLocks; i++)
2909  {
2910  if (rulelocks->rules[i]->isInstead &&
2911  rulelocks->rules[i]->qual == NULL)
2912  {
2913  events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2914  }
2915  }
2916 
2917  /* If we have rules for all events, we're done */
2918  if (events == ALL_EVENTS)
2919  {
2921  return events;
2922  }
2923  }
2924 
2925  /* Similarly look for INSTEAD OF triggers, if they are to be included */
2926  if (include_triggers)
2927  {
2928  TriggerDesc *trigDesc = rel->trigdesc;
2929 
2930  if (trigDesc)
2931  {
2932  if (trigDesc->trig_insert_instead_row)
2933  events |= (1 << CMD_INSERT);
2934  if (trigDesc->trig_update_instead_row)
2935  events |= (1 << CMD_UPDATE);
2936  if (trigDesc->trig_delete_instead_row)
2937  events |= (1 << CMD_DELETE);
2938 
2939  /* If we have triggers for all events, we're done */
2940  if (events == ALL_EVENTS)
2941  {
2943  return events;
2944  }
2945  }
2946  }
2947 
2948  /* If this is a foreign table, check which update events it supports */
2949  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2950  {
2951  FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2952 
2953  if (fdwroutine->IsForeignRelUpdatable != NULL)
2954  events |= fdwroutine->IsForeignRelUpdatable(rel);
2955  else
2956  {
2957  /* Assume presence of executor functions is sufficient */
2958  if (fdwroutine->ExecForeignInsert != NULL)
2959  events |= (1 << CMD_INSERT);
2960  if (fdwroutine->ExecForeignUpdate != NULL)
2961  events |= (1 << CMD_UPDATE);
2962  if (fdwroutine->ExecForeignDelete != NULL)
2963  events |= (1 << CMD_DELETE);
2964  }
2965 
2967  return events;
2968  }
2969 
2970  /* Check if this is an automatically updatable view */
2971  if (rel->rd_rel->relkind == RELKIND_VIEW)
2972  {
2973  Query *viewquery = get_view_query(rel);
2974 
2975  if (view_query_is_auto_updatable(viewquery, false) == NULL)
2976  {
2977  Bitmapset *updatable_cols;
2978  int auto_events;
2979  RangeTblRef *rtr;
2980  RangeTblEntry *base_rte;
2981  Oid baseoid;
2982 
2983  /*
2984  * Determine which of the view's columns are updatable. If there
2985  * are none within the set of columns we are looking at, then the
2986  * view doesn't support INSERT/UPDATE, but it may still support
2987  * DELETE.
2988  */
2989  view_cols_are_auto_updatable(viewquery, NULL,
2990  &updatable_cols, NULL);
2991 
2992  if (include_cols != NULL)
2993  updatable_cols = bms_int_members(updatable_cols, include_cols);
2994 
2995  if (bms_is_empty(updatable_cols))
2996  auto_events = (1 << CMD_DELETE); /* May support DELETE */
2997  else
2998  auto_events = ALL_EVENTS; /* May support all events */
2999 
3000  /*
3001  * The base relation must also support these update commands.
3002  * Tables are always updatable, but for any other kind of base
3003  * relation we must do a recursive check limited to the columns
3004  * referenced by the locally updatable columns in this view.
3005  */
3006  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
3007  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
3008  Assert(base_rte->rtekind == RTE_RELATION);
3009 
3010  if (base_rte->relkind != RELKIND_RELATION &&
3011  base_rte->relkind != RELKIND_PARTITIONED_TABLE)
3012  {
3013  baseoid = base_rte->relid;
3014  outer_reloids = lappend_oid(outer_reloids,
3015  RelationGetRelid(rel));
3016  include_cols = adjust_view_column_set(updatable_cols,
3017  viewquery->targetList);
3018  auto_events &= relation_is_updatable(baseoid,
3019  outer_reloids,
3020  include_triggers,
3021  include_cols);
3022  outer_reloids = list_delete_last(outer_reloids);
3023  }
3024  events |= auto_events;
3025  }
3026  }
3027 
3028  /* If we reach here, the relation may support some update commands */
3030  return events;
3031 }
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:213
Node * qual
Definition: prs2lock.h:28
int numLocks
Definition: prs2lock.h:42
FromExpr * jointree
Definition: parsenodes.h:138
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:211
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
List * fromlist
Definition: primnodes.h:1525
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
bool isInstead
Definition: prs2lock.h:31
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:89
List * targetList
Definition: parsenodes.h:140
bool trig_insert_instead_row
Definition: reltrigger.h:58
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:137
#define ALL_EVENTS
TriggerDesc * trigdesc
Definition: rel.h:116
void check_stack_depth(void)
Definition: postgres.c:3317
CmdType event
Definition: prs2lock.h:27
List * list_delete_last(List *list)
Definition: list.c:877
RewriteRule ** rules
Definition: prs2lock.h:43
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
int relation_is_updatable(Oid reloid, List *outer_reloids, bool include_triggers, Bitmapset *include_cols)
bool trig_update_instead_row
Definition: reltrigger.h:63
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
bool trig_delete_instead_row
Definition: reltrigger.h:68
static Bitmapset * adjust_view_column_set(Bitmapset *cols, List *targetlist)
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:212
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:800
RuleLock * rd_rules
Definition: rel.h:114
RTEKind rtekind
Definition: parsenodes.h:982
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
Query * get_view_query(Relation view)
int i
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:217
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:902
const char * view_query_is_auto_updatable(Query *viewquery, bool check_cols)
#define RelationGetRelid(relation)
Definition: rel.h:457

◆ rewriteTargetListUD()

void rewriteTargetListUD ( Query parsetree,
RangeTblEntry target_rte,
Relation  target_relation 
)

Definition at line 1624 of file rewriteHandler.c.

References FdwRoutine::AddForeignUpdateTargets, CMD_DELETE, CMD_UPDATE, Query::commandType, GetFdwRoutineForRelation(), InvalidOid, lappend(), list_length(), makeTargetEntry(), makeVar(), makeWholeRowVar(), pstrdup(), RelationData::rd_rel, Query::resultRelation, SelfItemPointerAttributeNumber, Query::targetList, TriggerDesc::trig_delete_after_row, TriggerDesc::trig_delete_before_row, TriggerDesc::trig_update_after_row, TriggerDesc::trig_update_before_row, and RelationData::trigdesc.

Referenced by preprocess_targetlist().

1626 {
1627  Var *var = NULL;
1628  const char *attrname;
1629  TargetEntry *tle;
1630 
1631  if (target_relation->rd_rel->relkind == RELKIND_RELATION ||
1632  target_relation->rd_rel->relkind == RELKIND_MATVIEW ||
1633  target_relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1634  {
1635  /*
1636  * Emit CTID so that executor can find the row to update or delete.
1637  */
1638  var = makeVar(parsetree->resultRelation,
1640  TIDOID,
1641  -1,
1642  InvalidOid,
1643  0);
1644 
1645  attrname = "ctid";
1646  }
1647  else if (target_relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1648  {
1649  /*
1650  * Let the foreign table's FDW add whatever junk TLEs it wants.
1651  */
1652  FdwRoutine *fdwroutine;
1653 
1654  fdwroutine = GetFdwRoutineForRelation(target_relation, false);
1655 
1656  if (fdwroutine->AddForeignUpdateTargets != NULL)
1657  fdwroutine->AddForeignUpdateTargets(parsetree, target_rte,
1658  target_relation);
1659 
1660  /*
1661  * If we have a row-level trigger corresponding to the operation, emit
1662  * a whole-row Var so that executor will have the "old" row to pass to
1663  * the trigger. Alas, this misses system columns.
1664  */
1665  if (target_relation->trigdesc &&
1666  ((parsetree->commandType == CMD_UPDATE &&
1667  (target_relation->trigdesc->trig_update_after_row ||
1668  target_relation->trigdesc->trig_update_before_row)) ||
1669  (parsetree->commandType == CMD_DELETE &&
1670  (target_relation->trigdesc->trig_delete_after_row ||
1671  target_relation->trigdesc->trig_delete_before_row))))
1672  {
1673  var = makeWholeRowVar(target_rte,
1674  parsetree->resultRelation,
1675  0,
1676  false);
1677 
1678  attrname = "wholerow";
1679  }
1680  }
1681 
1682  if (var != NULL)
1683  {
1684  tle = makeTargetEntry((Expr *) var,
1685  list_length(parsetree->targetList) + 1,
1686  pstrdup(attrname),
1687  true);
1688 
1689  parsetree->targetList = lappend(parsetree->targetList, tle);
1690  }
1691 }
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int resultRelation
Definition: parsenodes.h:122
Var * makeWholeRowVar(RangeTblEntry *rte, Index varno, Index varlevelsup, bool allowScalar)
Definition: makefuncs.c:133
Form_pg_class rd_rel
Definition: rel.h:110
Definition: primnodes.h:181
AddForeignUpdateTargets_function AddForeignUpdateTargets
Definition: fdwapi.h:208
List * targetList
Definition: parsenodes.h:140
TriggerDesc * trigdesc
Definition: rel.h:116
bool trig_delete_after_row
Definition: reltrigger.h:67
bool trig_update_before_row
Definition: reltrigger.h:61
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
bool trig_update_after_row
Definition: reltrigger.h:62
List * lappend(List *list, void *datum)
Definition: list.c:321
#define InvalidOid
Definition: postgres_ext.h:36
CmdType commandType
Definition: parsenodes.h:112
static int list_length(const List *l)
Definition: pg_list.h:149
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
bool trig_delete_before_row
Definition: reltrigger.h:66

◆ view_query_is_auto_updatable()

const char* view_query_is_auto_updatable ( Query viewquery,
bool  check_cols 
)

Definition at line 2631 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, 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().

2632 {
2633  RangeTblRef *rtr;
2634  RangeTblEntry *base_rte;
2635 
2636  /*----------
2637  * Check if the view is simply updatable. According to SQL-92 this means:
2638  * - No DISTINCT clause.
2639  * - Each TLE is a column reference, and each column appears at most once.
2640  * - FROM contains exactly one base relation.
2641  * - No GROUP BY or HAVING clauses.
2642  * - No set operations (UNION, INTERSECT or EXCEPT).
2643  * - No sub-queries in the WHERE clause that reference the target table.
2644  *
2645  * We ignore that last restriction since it would be complex to enforce
2646  * and there isn't any actual benefit to disallowing sub-queries. (The
2647  * semantic issues that the standard is presumably concerned about don't
2648  * arise in Postgres, since any such sub-query will not see any updates
2649  * executed by the outer query anyway, thanks to MVCC snapshotting.)
2650  *
2651  * We also relax the second restriction by supporting part of SQL:1999
2652  * feature T111, which allows for a mix of updatable and non-updatable
2653  * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2654  * a non-updatable column.
2655  *
2656  * In addition we impose these constraints, involving features that are
2657  * not part of SQL-92:
2658  * - No CTEs (WITH clauses).
2659  * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2660  * - No system columns (including whole-row references) in the tlist.
2661  * - No window functions in the tlist.
2662  * - No set-returning functions in the tlist.
2663  *
2664  * Note that we do these checks without recursively expanding the view.
2665  * If the base relation is a view, we'll recursively deal with it later.
2666  *----------
2667  */
2668  if (viewquery->distinctClause != NIL)
2669  return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2670 
2671  if (viewquery->groupClause != NIL || viewquery->groupingSets)
2672  return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2673 
2674  if (viewquery->havingQual != NULL)
2675  return gettext_noop("Views containing HAVING are not automatically updatable.");
2676 
2677  if (viewquery->setOperations != NULL)
2678  return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2679 
2680  if (viewquery->cteList != NIL)
2681  return gettext_noop("Views containing WITH are not automatically updatable.");
2682 
2683  if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2684  return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2685 
2686  /*
2687  * We must not allow window functions or set returning functions in the
2688  * targetlist. Otherwise we might end up inserting them into the quals of
2689  * the main query. We must also check for aggregates in the targetlist in
2690  * case they appear without a GROUP BY.
2691  *
2692  * These restrictions ensure that each row of the view corresponds to a
2693  * unique row in the underlying base relation.
2694  */
2695  if (viewquery->hasAggs)
2696  return gettext_noop("Views that return aggregate functions are not automatically updatable.");
2697 
2698  if (viewquery->hasWindowFuncs)
2699  return gettext_noop("Views that return window functions are not automatically updatable.");
2700 
2701  if (viewquery->hasTargetSRFs)
2702  return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2703 
2704  /*
2705  * The view query should select from a single base relation, which must be
2706  * a table or another view.
2707  */
2708  if (list_length(viewquery->jointree->fromlist) != 1)
2709  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2710 
2711  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2712  if (!IsA(rtr, RangeTblRef))
2713  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2714 
2715  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2716  if (base_rte->rtekind != RTE_RELATION ||
2717  (base_rte->relkind != RELKIND_RELATION &&
2718  base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2719  base_rte->relkind != RELKIND_VIEW &&
2720  base_rte->relkind != RELKIND_PARTITIONED_TABLE))
2721  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2722 
2723  if (base_rte->tablesample)
2724  return gettext_noop("Views containing TABLESAMPLE are not automatically updatable.");
2725 
2726  /*
2727  * Check that the view has at least one updatable column. This is required
2728  * for INSERT/UPDATE but not for DELETE.
2729  */
2730  if (check_cols)
2731  {
2732  ListCell *cell;
2733  bool found;
2734 
2735  found = false;
2736  foreach(cell, viewquery->targetList)
2737  {
2738  TargetEntry *tle = (TargetEntry *) lfirst(cell);
2739 
2740  if (view_col_is_auto_updatable(rtr, tle) == NULL)
2741  {
2742  found = true;
2743  break;
2744  }
2745  }
2746 
2747  if (!found)
2748  return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2749  }
2750 
2751  return NULL; /* the view is updatable */
2752 }
Node * limitOffset
Definition: parsenodes.h:160
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:578
FromExpr * jointree
Definition: parsenodes.h:138
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
#define gettext_noop(x)
Definition: c.h:1193
List * fromlist
Definition: primnodes.h:1525
List * targetList
Definition: parsenodes.h:140
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
Node * limitCount
Definition: parsenodes.h:161
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
bool hasTargetSRFs
Definition: parsenodes.h:127
#define lfirst(lc)
Definition: pg_list.h:169
bool hasWindowFuncs
Definition: parsenodes.h:126
static int list_length(const List *l)
Definition: pg_list.h:149
RTEKind rtekind
Definition: parsenodes.h:982
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:166
List * groupClause
Definition: parsenodes.h:148
static const char * view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
Node * havingQual
Definition: parsenodes.h:152
struct TableSampleClause * tablesample
Definition: parsenodes.h:1012