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)
 
Queryget_view_query (Relation view)
 
bool view_has_instead_trigger (Relation view, CmdType event, List *mergeActionList)
 
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)
 
void error_view_not_updatable (Relation view, CmdType command, List *mergeActionList, const char *detail)
 

Function Documentation

◆ AcquireRewriteLocks()

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

Definition at line 140 of file rewriteHandler.c.

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

References AccessShareLock, acquireLocksOnSubLinks(), Assert, context, Query::cteList, CommonTableExpr::ctequery, elog, ERROR, get_parse_rowmark(), get_rte_attribute_is_dropped(), IsA, lappend(), lfirst, NIL, NoLock, QTW_IGNORE_RC_SUBQUERIES, query_tree_walker, RelationData::rd_rel, RangeTblEntry::relid, 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 1224 of file rewriteHandler.c.

1225 {
1226  TupleDesc rd_att = rel->rd_att;
1227  Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1);
1228  Oid atttype = att_tup->atttypid;
1229  int32 atttypmod = att_tup->atttypmod;
1230  Node *expr = NULL;
1231  Oid exprtype;
1232 
1233  if (att_tup->attidentity)
1234  {
1236 
1237  nve->seqid = getIdentitySequence(rel, attrno, false);
1238  nve->typeId = att_tup->atttypid;
1239 
1240  return (Node *) nve;
1241  }
1242 
1243  /*
1244  * If relation has a default for this column, fetch that expression.
1245  */
1246  if (att_tup->atthasdef)
1247  {
1248  expr = TupleDescGetDefault(rd_att, attrno);
1249  if (expr == NULL)
1250  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1251  attrno, RelationGetRelationName(rel));
1252  }
1253 
1254  /*
1255  * No per-column default, so look for a default for the type itself. But
1256  * not for generated columns.
1257  */
1258  if (expr == NULL && !att_tup->attgenerated)
1259  expr = get_typdefault(atttype);
1260 
1261  if (expr == NULL)
1262  return NULL; /* No default anywhere */
1263 
1264  /*
1265  * Make sure the value is coerced to the target column type; this will
1266  * generally be true already, but there seem to be some corner cases
1267  * involving domain defaults where it might not be true. This should match
1268  * the parser's processing of non-defaulted expressions --- see
1269  * transformAssignedExpr().
1270  */
1271  exprtype = exprType(expr);
1272 
1273  expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1274  expr, exprtype,
1275  atttype, atttypmod,
1278  -1);
1279  if (expr == NULL)
1280  ereport(ERROR,
1281  (errcode(ERRCODE_DATATYPE_MISMATCH),
1282  errmsg("column \"%s\" is of type %s"
1283  " but default expression is of type %s",
1284  NameStr(att_tup->attname),
1285  format_type_be(atttype),
1286  format_type_be(exprtype)),
1287  errhint("You will need to rewrite or cast the expression.")));
1288 
1289  return expr;
1290 }
#define NameStr(name)
Definition: c.h:746
signed int int32
Definition: c.h:494
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Node * get_typdefault(Oid typid)
Definition: lsyscache.c:2448
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define makeNode(_type_)
Definition: nodes.h:155
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:209
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:946
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:736
@ COERCION_ASSIGNMENT
Definition: primnodes.h:715
#define RelationGetRelationName(relation)
Definition: rel.h:539
TupleDesc rd_att
Definition: rel.h:112
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition: tupdesc.c:899
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, elog, ereport, errcode(), errhint(), errmsg(), ERROR, exprType(), format_type_be(), get_typdefault(), getIdentitySequence(), makeNode, NameStr, RelationData::rd_att, RelationGetRelationName, NextValueExpr::seqid, TupleDescAttr, TupleDescGetDefault(), and NextValueExpr::typeId.

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

◆ error_view_not_updatable()

void error_view_not_updatable ( Relation  view,
CmdType  command,
List mergeActionList,
const char *  detail 
)

Definition at line 3076 of file rewriteHandler.c.

3080 {
3081  TriggerDesc *trigDesc = view->trigdesc;
3082 
3083  switch (command)
3084  {
3085  case CMD_INSERT:
3086  ereport(ERROR,
3087  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3088  errmsg("cannot insert into view \"%s\"",
3089  RelationGetRelationName(view)),
3090  detail ? errdetail_internal("%s", _(detail)) : 0,
3091  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule."));
3092  break;
3093  case CMD_UPDATE:
3094  ereport(ERROR,
3095  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3096  errmsg("cannot update view \"%s\"",
3097  RelationGetRelationName(view)),
3098  detail ? errdetail_internal("%s", _(detail)) : 0,
3099  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule."));
3100  break;
3101  case CMD_DELETE:
3102  ereport(ERROR,
3103  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3104  errmsg("cannot delete from view \"%s\"",
3105  RelationGetRelationName(view)),
3106  detail ? errdetail_internal("%s", _(detail)) : 0,
3107  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule."));
3108  break;
3109  case CMD_MERGE:
3110 
3111  /*
3112  * Note that the error hints here differ from above, since MERGE
3113  * doesn't support rules.
3114  */
3115  foreach_node(MergeAction, action, mergeActionList)
3116  {
3117  switch (action->commandType)
3118  {
3119  case CMD_INSERT:
3120  if (!trigDesc || !trigDesc->trig_insert_instead_row)
3121  ereport(ERROR,
3122  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3123  errmsg("cannot insert into view \"%s\"",
3124  RelationGetRelationName(view)),
3125  detail ? errdetail_internal("%s", _(detail)) : 0,
3126  errhint("To enable inserting into the view using MERGE, provide an INSTEAD OF INSERT trigger."));
3127  break;
3128  case CMD_UPDATE:
3129  if (!trigDesc || !trigDesc->trig_update_instead_row)
3130  ereport(ERROR,
3131  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3132  errmsg("cannot update view \"%s\"",
3133  RelationGetRelationName(view)),
3134  detail ? errdetail_internal("%s", _(detail)) : 0,
3135  errhint("To enable updating the view using MERGE, provide an INSTEAD OF UPDATE trigger."));
3136  break;
3137  case CMD_DELETE:
3138  if (!trigDesc || !trigDesc->trig_delete_instead_row)
3139  ereport(ERROR,
3140  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3141  errmsg("cannot delete from view \"%s\"",
3142  RelationGetRelationName(view)),
3143  detail ? errdetail_internal("%s", _(detail)) : 0,
3144  errhint("To enable deleting from the view using MERGE, provide an INSTEAD OF DELETE trigger."));
3145  break;
3146  case CMD_NOTHING:
3147  break;
3148  default:
3149  elog(ERROR, "unrecognized commandType: %d", action->commandType);
3150  break;
3151  }
3152  }
3153  break;
3154  default:
3155  elog(ERROR, "unrecognized CmdType: %d", (int) command);
3156  break;
3157  }
3158 }
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
#define _(x)
Definition: elog.c:90
@ CMD_MERGE
Definition: nodes.h:269
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_NOTHING
Definition: nodes.h:272
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
TriggerDesc * trigdesc
Definition: rel.h:117
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 _, generate_unaccent_rules::action, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_NOTHING, CMD_UPDATE, elog, ereport, errcode(), errdetail_internal(), errhint(), errmsg(), ERROR, foreach_node, RelationGetRelationName, TriggerDesc::trig_delete_instead_row, TriggerDesc::trig_insert_instead_row, TriggerDesc::trig_update_instead_row, and RelationData::trigdesc.

Referenced by CheckValidResultRel(), RewriteQuery(), and rewriteTargetView().

◆ get_view_query()

Query* get_view_query ( Relation  view)

Definition at line 2439 of file rewriteHandler.c.

2440 {
2441  int i;
2442 
2443  Assert(view->rd_rel->relkind == RELKIND_VIEW);
2444 
2445  for (i = 0; i < view->rd_rules->numLocks; i++)
2446  {
2447  RewriteRule *rule = view->rd_rules->rules[i];
2448 
2449  if (rule->event == CMD_SELECT)
2450  {
2451  /* A _RETURN rule should have only one action */
2452  if (list_length(rule->actions) != 1)
2453  elog(ERROR, "invalid _RETURN rule action specification");
2454 
2455  return (Query *) linitial(rule->actions);
2456  }
2457  }
2458 
2459  elog(ERROR, "failed to find _RETURN rule for view");
2460  return NULL; /* keep compiler quiet */
2461 }
int i
Definition: isn.c:73
@ CMD_SELECT
Definition: nodes.h:265
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial(l)
Definition: pg_list.h:178
RuleLock * rd_rules
Definition: rel.h:115
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 4378 of file rewriteHandler.c.

4379 {
4380  uint64 input_query_id = parsetree->queryId;
4381  List *querylist;
4382  List *results;
4383  ListCell *l;
4384  CmdType origCmdType;
4385  bool foundOriginalQuery;
4386  Query *lastInstead;
4387 
4388  /*
4389  * This function is only applied to top-level original queries
4390  */
4391  Assert(parsetree->querySource == QSRC_ORIGINAL);
4392  Assert(parsetree->canSetTag);
4393 
4394  /*
4395  * Step 1
4396  *
4397  * Apply all non-SELECT rules possibly getting 0 or many queries
4398  */
4399  querylist = RewriteQuery(parsetree, NIL, 0);
4400 
4401  /*
4402  * Step 2
4403  *
4404  * Apply all the RIR rules on each query
4405  *
4406  * This is also a handy place to mark each query with the original queryId
4407  */
4408  results = NIL;
4409  foreach(l, querylist)
4410  {
4411  Query *query = (Query *) lfirst(l);
4412 
4413  query = fireRIRrules(query, NIL);
4414 
4415  query->queryId = input_query_id;
4416 
4417  results = lappend(results, query);
4418  }
4419 
4420  /*
4421  * Step 3
4422  *
4423  * Determine which, if any, of the resulting queries is supposed to set
4424  * the command-result tag; and update the canSetTag fields accordingly.
4425  *
4426  * If the original query is still in the list, it sets the command tag.
4427  * Otherwise, the last INSTEAD query of the same kind as the original is
4428  * allowed to set the tag. (Note these rules can leave us with no query
4429  * setting the tag. The tcop code has to cope with this by setting up a
4430  * default tag based on the original un-rewritten query.)
4431  *
4432  * The Asserts verify that at most one query in the result list is marked
4433  * canSetTag. If we aren't checking asserts, we can fall out of the loop
4434  * as soon as we find the original query.
4435  */
4436  origCmdType = parsetree->commandType;
4437  foundOriginalQuery = false;
4438  lastInstead = NULL;
4439 
4440  foreach(l, results)
4441  {
4442  Query *query = (Query *) lfirst(l);
4443 
4444  if (query->querySource == QSRC_ORIGINAL)
4445  {
4446  Assert(query->canSetTag);
4447  Assert(!foundOriginalQuery);
4448  foundOriginalQuery = true;
4449 #ifndef USE_ASSERT_CHECKING
4450  break;
4451 #endif
4452  }
4453  else
4454  {
4455  Assert(!query->canSetTag);
4456  if (query->commandType == origCmdType &&
4457  (query->querySource == QSRC_INSTEAD_RULE ||
4458  query->querySource == QSRC_QUAL_INSTEAD_RULE))
4459  lastInstead = query;
4460  }
4461  }
4462 
4463  if (!foundOriginalQuery && lastInstead != NULL)
4464  lastInstead->canSetTag = true;
4465 
4466  return results;
4467 }
CmdType
Definition: nodes.h:263
@ QSRC_QUAL_INSTEAD_RULE
Definition: parsenodes.h:39
@ QSRC_ORIGINAL
Definition: parsenodes.h:36
@ QSRC_INSTEAD_RULE
Definition: parsenodes.h:38
static List * RewriteQuery(Query *parsetree, List *rewrite_events, int orig_rt_length)
static Query * fireRIRrules(Query *parsetree, List *activeRIRs)
CmdType commandType
Definition: parsenodes.h:121

References Assert, Query::commandType, fireRIRrules(), lappend(), lfirst, NIL, QSRC_INSTEAD_RULE, QSRC_ORIGINAL, QSRC_QUAL_INSTEAD_RULE, 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 2821 of file rewriteHandler.c.

2825 {
2826  int events = 0;
2827  Relation rel;
2828  RuleLock *rulelocks;
2829 
2830 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2831 
2832  /* Since this function recurses, it could be driven to stack overflow */
2834 
2835  rel = try_relation_open(reloid, AccessShareLock);
2836 
2837  /*
2838  * If the relation doesn't exist, return zero rather than throwing an
2839  * error. This is helpful since scanning an information_schema view under
2840  * MVCC rules can result in referencing rels that have actually been
2841  * deleted already.
2842  */
2843  if (rel == NULL)
2844  return 0;
2845 
2846  /* If we detect a recursive view, report that it is not updatable */
2847  if (list_member_oid(outer_reloids, RelationGetRelid(rel)))
2848  {
2850  return 0;
2851  }
2852 
2853  /* If the relation is a table, it is always updatable */
2854  if (rel->rd_rel->relkind == RELKIND_RELATION ||
2855  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2856  {
2858  return ALL_EVENTS;
2859  }
2860 
2861  /* Look for unconditional DO INSTEAD rules, and note supported events */
2862  rulelocks = rel->rd_rules;
2863  if (rulelocks != NULL)
2864  {
2865  int i;
2866 
2867  for (i = 0; i < rulelocks->numLocks; i++)
2868  {
2869  if (rulelocks->rules[i]->isInstead &&
2870  rulelocks->rules[i]->qual == NULL)
2871  {
2872  events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2873  }
2874  }
2875 
2876  /* If we have rules for all events, we're done */
2877  if (events == ALL_EVENTS)
2878  {
2880  return events;
2881  }
2882  }
2883 
2884  /* Similarly look for INSTEAD OF triggers, if they are to be included */
2885  if (include_triggers)
2886  {
2887  TriggerDesc *trigDesc = rel->trigdesc;
2888 
2889  if (trigDesc)
2890  {
2891  if (trigDesc->trig_insert_instead_row)
2892  events |= (1 << CMD_INSERT);
2893  if (trigDesc->trig_update_instead_row)
2894  events |= (1 << CMD_UPDATE);
2895  if (trigDesc->trig_delete_instead_row)
2896  events |= (1 << CMD_DELETE);
2897 
2898  /* If we have triggers for all events, we're done */
2899  if (events == ALL_EVENTS)
2900  {
2902  return events;
2903  }
2904  }
2905  }
2906 
2907  /* If this is a foreign table, check which update events it supports */
2908  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2909  {
2910  FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2911 
2912  if (fdwroutine->IsForeignRelUpdatable != NULL)
2913  events |= fdwroutine->IsForeignRelUpdatable(rel);
2914  else
2915  {
2916  /* Assume presence of executor functions is sufficient */
2917  if (fdwroutine->ExecForeignInsert != NULL)
2918  events |= (1 << CMD_INSERT);
2919  if (fdwroutine->ExecForeignUpdate != NULL)
2920  events |= (1 << CMD_UPDATE);
2921  if (fdwroutine->ExecForeignDelete != NULL)
2922  events |= (1 << CMD_DELETE);
2923  }
2924 
2926  return events;
2927  }
2928 
2929  /* Check if this is an automatically updatable view */
2930  if (rel->rd_rel->relkind == RELKIND_VIEW)
2931  {
2932  Query *viewquery = get_view_query(rel);
2933 
2934  if (view_query_is_auto_updatable(viewquery, false) == NULL)
2935  {
2936  Bitmapset *updatable_cols;
2937  int auto_events;
2938  RangeTblRef *rtr;
2939  RangeTblEntry *base_rte;
2940  Oid baseoid;
2941 
2942  /*
2943  * Determine which of the view's columns are updatable. If there
2944  * are none within the set of columns we are looking at, then the
2945  * view doesn't support INSERT/UPDATE, but it may still support
2946  * DELETE.
2947  */
2948  view_cols_are_auto_updatable(viewquery, NULL,
2949  &updatable_cols, NULL);
2950 
2951  if (include_cols != NULL)
2952  updatable_cols = bms_int_members(updatable_cols, include_cols);
2953 
2954  if (bms_is_empty(updatable_cols))
2955  auto_events = (1 << CMD_DELETE); /* May support DELETE */
2956  else
2957  auto_events = ALL_EVENTS; /* May support all events */
2958 
2959  /*
2960  * The base relation must also support these update commands.
2961  * Tables are always updatable, but for any other kind of base
2962  * relation we must do a recursive check limited to the columns
2963  * referenced by the locally updatable columns in this view.
2964  */
2965  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2966  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2967  Assert(base_rte->rtekind == RTE_RELATION);
2968 
2969  if (base_rte->relkind != RELKIND_RELATION &&
2970  base_rte->relkind != RELKIND_PARTITIONED_TABLE)
2971  {
2972  baseoid = base_rte->relid;
2973  outer_reloids = lappend_oid(outer_reloids,
2974  RelationGetRelid(rel));
2975  include_cols = adjust_view_column_set(updatable_cols,
2976  viewquery->targetList);
2977  auto_events &= relation_is_updatable(baseoid,
2978  outer_reloids,
2979  include_triggers,
2980  include_cols);
2981  outer_reloids = list_delete_last(outer_reloids);
2982  }
2983  events |= auto_events;
2984  }
2985  }
2986 
2987  /* If we reach here, the relation may support some update commands */
2989  return events;
2990 }
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1109
#define bms_is_empty(a)
Definition: bitmapset.h:118
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:442
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
List * list_delete_last(List *list)
Definition: list.c:957
void check_stack_depth(void)
Definition: postgres.c:3564
#define RelationGetRelid(relation)
Definition: rel.h:505
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:205
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:88
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:2304
FromExpr * jointree
Definition: parsenodes.h:177
List * targetList
Definition: parsenodes.h:193
CmdType event
Definition: prs2lock.h:27
bool isInstead
Definition: prs2lock.h:31
Node * qual
Definition: prs2lock.h:28

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, 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_has_instead_trigger()

bool view_has_instead_trigger ( Relation  view,
CmdType  event,
List mergeActionList 
)

Definition at line 2478 of file rewriteHandler.c.

2479 {
2480  TriggerDesc *trigDesc = view->trigdesc;
2481 
2482  switch (event)
2483  {
2484  case CMD_INSERT:
2485  if (trigDesc && trigDesc->trig_insert_instead_row)
2486  return true;
2487  break;
2488  case CMD_UPDATE:
2489  if (trigDesc && trigDesc->trig_update_instead_row)
2490  return true;
2491  break;
2492  case CMD_DELETE:
2493  if (trigDesc && trigDesc->trig_delete_instead_row)
2494  return true;
2495  break;
2496  case CMD_MERGE:
2497  foreach_node(MergeAction, action, mergeActionList)
2498  {
2499  switch (action->commandType)
2500  {
2501  case CMD_INSERT:
2502  if (!trigDesc || !trigDesc->trig_insert_instead_row)
2503  return false;
2504  break;
2505  case CMD_UPDATE:
2506  if (!trigDesc || !trigDesc->trig_update_instead_row)
2507  return false;
2508  break;
2509  case CMD_DELETE:
2510  if (!trigDesc || !trigDesc->trig_delete_instead_row)
2511  return false;
2512  break;
2513  case CMD_NOTHING:
2514  /* No trigger required */
2515  break;
2516  default:
2517  elog(ERROR, "unrecognized commandType: %d", action->commandType);
2518  break;
2519  }
2520  }
2521  return true; /* no actions without an INSTEAD OF trigger */
2522  default:
2523  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2524  break;
2525  }
2526  return false;
2527 }

References generate_unaccent_rules::action, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_NOTHING, CMD_UPDATE, elog, ERROR, foreach_node, TriggerDesc::trig_delete_instead_row, TriggerDesc::trig_insert_instead_row, TriggerDesc::trig_update_instead_row, and RelationData::trigdesc.

Referenced by CheckValidResultRel(), RewriteQuery(), rewriteTargetView(), and rewriteValuesRTE().

◆ view_query_is_auto_updatable()

const char* view_query_is_auto_updatable ( Query viewquery,
bool  check_cols 
)

Definition at line 2590 of file rewriteHandler.c.

2591 {
2592  RangeTblRef *rtr;
2593  RangeTblEntry *base_rte;
2594 
2595  /*----------
2596  * Check if the view is simply updatable. According to SQL-92 this means:
2597  * - No DISTINCT clause.
2598  * - Each TLE is a column reference, and each column appears at most once.
2599  * - FROM contains exactly one base relation.
2600  * - No GROUP BY or HAVING clauses.
2601  * - No set operations (UNION, INTERSECT or EXCEPT).
2602  * - No sub-queries in the WHERE clause that reference the target table.
2603  *
2604  * We ignore that last restriction since it would be complex to enforce
2605  * and there isn't any actual benefit to disallowing sub-queries. (The
2606  * semantic issues that the standard is presumably concerned about don't
2607  * arise in Postgres, since any such sub-query will not see any updates
2608  * executed by the outer query anyway, thanks to MVCC snapshotting.)
2609  *
2610  * We also relax the second restriction by supporting part of SQL:1999
2611  * feature T111, which allows for a mix of updatable and non-updatable
2612  * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2613  * a non-updatable column.
2614  *
2615  * In addition we impose these constraints, involving features that are
2616  * not part of SQL-92:
2617  * - No CTEs (WITH clauses).
2618  * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2619  * - No system columns (including whole-row references) in the tlist.
2620  * - No window functions in the tlist.
2621  * - No set-returning functions in the tlist.
2622  *
2623  * Note that we do these checks without recursively expanding the view.
2624  * If the base relation is a view, we'll recursively deal with it later.
2625  *----------
2626  */
2627  if (viewquery->distinctClause != NIL)
2628  return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2629 
2630  if (viewquery->groupClause != NIL || viewquery->groupingSets)
2631  return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2632 
2633  if (viewquery->havingQual != NULL)
2634  return gettext_noop("Views containing HAVING are not automatically updatable.");
2635 
2636  if (viewquery->setOperations != NULL)
2637  return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2638 
2639  if (viewquery->cteList != NIL)
2640  return gettext_noop("Views containing WITH are not automatically updatable.");
2641 
2642  if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2643  return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2644 
2645  /*
2646  * We must not allow window functions or set returning functions in the
2647  * targetlist. Otherwise we might end up inserting them into the quals of
2648  * the main query. We must also check for aggregates in the targetlist in
2649  * case they appear without a GROUP BY.
2650  *
2651  * These restrictions ensure that each row of the view corresponds to a
2652  * unique row in the underlying base relation.
2653  */
2654  if (viewquery->hasAggs)
2655  return gettext_noop("Views that return aggregate functions are not automatically updatable.");
2656 
2657  if (viewquery->hasWindowFuncs)
2658  return gettext_noop("Views that return window functions are not automatically updatable.");
2659 
2660  if (viewquery->hasTargetSRFs)
2661  return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2662 
2663  /*
2664  * The view query should select from a single base relation, which must be
2665  * a table or another view.
2666  */
2667  if (list_length(viewquery->jointree->fromlist) != 1)
2668  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2669 
2670  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2671  if (!IsA(rtr, RangeTblRef))
2672  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2673 
2674  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2675  if (base_rte->rtekind != RTE_RELATION ||
2676  (base_rte->relkind != RELKIND_RELATION &&
2677  base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2678  base_rte->relkind != RELKIND_VIEW &&
2679  base_rte->relkind != RELKIND_PARTITIONED_TABLE))
2680  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2681 
2682  if (base_rte->tablesample)
2683  return gettext_noop("Views containing TABLESAMPLE are not automatically updatable.");
2684 
2685  /*
2686  * Check that the view has at least one updatable column. This is required
2687  * for INSERT/UPDATE but not for DELETE.
2688  */
2689  if (check_cols)
2690  {
2691  ListCell *cell;
2692  bool found;
2693 
2694  found = false;
2695  foreach(cell, viewquery->targetList)
2696  {
2697  TargetEntry *tle = (TargetEntry *) lfirst(cell);
2698 
2699  if (view_col_is_auto_updatable(rtr, tle) == NULL)
2700  {
2701  found = true;
2702  break;
2703  }
2704  }
2705 
2706  if (!found)
2707  return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2708  }
2709 
2710  return NULL; /* the view is updatable */
2711 }
#define gettext_noop(x)
Definition: c.h:1196
static const char * view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
Node * limitCount
Definition: parsenodes.h:216
Node * setOperations
Definition: parsenodes.h:221
List * groupClause
Definition: parsenodes.h:202
Node * havingQual
Definition: parsenodes.h:207
Node * limitOffset
Definition: parsenodes.h:215
List * groupingSets
Definition: parsenodes.h:205
List * distinctClause
Definition: parsenodes.h:211
struct TableSampleClause * tablesample
Definition: parsenodes.h:1098

References Query::cteList, Query::distinctClause, FromExpr::fromlist, gettext_noop, Query::groupClause, Query::groupingSets, Query::havingQual, IsA, Query::jointree, lfirst, Query::limitCount, Query::limitOffset, linitial, list_length(), NIL, 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().