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 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)
295 }
#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:224
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:156
#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:1030
@ RTE_SUBQUERY
Definition: parsenodes.h:1029
@ RTE_RELATION
Definition: parsenodes.h:1028
#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:166
List * rtable
Definition: parsenodes.h:168
Query * subquery
Definition: parsenodes.h:1114
RTEKind rtekind
Definition: parsenodes.h:1057
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 1223 of file rewriteHandler.c.

1224 {
1225  TupleDesc rd_att = rel->rd_att;
1226  Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1);
1227  Oid atttype = att_tup->atttypid;
1228  int32 atttypmod = att_tup->atttypmod;
1229  Node *expr = NULL;
1230  Oid exprtype;
1231 
1232  if (att_tup->attidentity)
1233  {
1235 
1236  nve->seqid = getIdentitySequence(rel, attrno, false);
1237  nve->typeId = att_tup->atttypid;
1238 
1239  return (Node *) nve;
1240  }
1241 
1242  /*
1243  * If relation has a default for this column, fetch that expression.
1244  */
1245  if (att_tup->atthasdef)
1246  {
1247  expr = TupleDescGetDefault(rd_att, attrno);
1248  if (expr == NULL)
1249  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1250  attrno, RelationGetRelationName(rel));
1251  }
1252 
1253  /*
1254  * No per-column default, so look for a default for the type itself. But
1255  * not for generated columns.
1256  */
1257  if (expr == NULL && !att_tup->attgenerated)
1258  expr = get_typdefault(atttype);
1259 
1260  if (expr == NULL)
1261  return NULL; /* No default anywhere */
1262 
1263  /*
1264  * Make sure the value is coerced to the target column type; this will
1265  * generally be true already, but there seem to be some corner cases
1266  * involving domain defaults where it might not be true. This should match
1267  * the parser's processing of non-defaulted expressions --- see
1268  * transformAssignedExpr().
1269  */
1270  exprtype = exprType(expr);
1271 
1272  expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1273  expr, exprtype,
1274  atttype, atttypmod,
1277  -1);
1278  if (expr == NULL)
1279  ereport(ERROR,
1280  (errcode(ERRCODE_DATATYPE_MISMATCH),
1281  errmsg("column \"%s\" is of type %s"
1282  " but default expression is of type %s",
1283  NameStr(att_tup->attname),
1284  format_type_be(atttype),
1285  format_type_be(exprtype)),
1286  errhint("You will need to rewrite or cast the expression.")));
1287 
1288  return expr;
1289 }
#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 3067 of file rewriteHandler.c.

3071 {
3072  TriggerDesc *trigDesc = view->trigdesc;
3073 
3074  switch (command)
3075  {
3076  case CMD_INSERT:
3077  ereport(ERROR,
3078  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3079  errmsg("cannot insert into view \"%s\"",
3080  RelationGetRelationName(view)),
3081  detail ? errdetail_internal("%s", _(detail)) : 0,
3082  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule."));
3083  break;
3084  case CMD_UPDATE:
3085  ereport(ERROR,
3086  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3087  errmsg("cannot update view \"%s\"",
3088  RelationGetRelationName(view)),
3089  detail ? errdetail_internal("%s", _(detail)) : 0,
3090  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule."));
3091  break;
3092  case CMD_DELETE:
3093  ereport(ERROR,
3094  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3095  errmsg("cannot delete from view \"%s\"",
3096  RelationGetRelationName(view)),
3097  detail ? errdetail_internal("%s", _(detail)) : 0,
3098  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule."));
3099  break;
3100  case CMD_MERGE:
3101 
3102  /*
3103  * Note that the error hints here differ from above, since MERGE
3104  * doesn't support rules.
3105  */
3106  foreach_node(MergeAction, action, mergeActionList)
3107  {
3108  switch (action->commandType)
3109  {
3110  case CMD_INSERT:
3111  if (!trigDesc || !trigDesc->trig_insert_instead_row)
3112  ereport(ERROR,
3113  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3114  errmsg("cannot insert into view \"%s\"",
3115  RelationGetRelationName(view)),
3116  detail ? errdetail_internal("%s", _(detail)) : 0,
3117  errhint("To enable inserting into the view using MERGE, provide an INSTEAD OF INSERT trigger."));
3118  break;
3119  case CMD_UPDATE:
3120  if (!trigDesc || !trigDesc->trig_update_instead_row)
3121  ereport(ERROR,
3122  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3123  errmsg("cannot update view \"%s\"",
3124  RelationGetRelationName(view)),
3125  detail ? errdetail_internal("%s", _(detail)) : 0,
3126  errhint("To enable updating the view using MERGE, provide an INSTEAD OF UPDATE trigger."));
3127  break;
3128  case CMD_DELETE:
3129  if (!trigDesc || !trigDesc->trig_delete_instead_row)
3130  ereport(ERROR,
3131  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3132  errmsg("cannot delete from view \"%s\"",
3133  RelationGetRelationName(view)),
3134  detail ? errdetail_internal("%s", _(detail)) : 0,
3135  errhint("To enable deleting from the view using MERGE, provide an INSTEAD OF DELETE trigger."));
3136  break;
3137  case CMD_NOTHING:
3138  break;
3139  default:
3140  elog(ERROR, "unrecognized commandType: %d", action->commandType);
3141  break;
3142  }
3143  }
3144  break;
3145  default:
3146  elog(ERROR, "unrecognized CmdType: %d", (int) command);
3147  break;
3148  }
3149 }
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 2430 of file rewriteHandler.c.

2431 {
2432  int i;
2433 
2434  Assert(view->rd_rel->relkind == RELKIND_VIEW);
2435 
2436  for (i = 0; i < view->rd_rules->numLocks; i++)
2437  {
2438  RewriteRule *rule = view->rd_rules->rules[i];
2439 
2440  if (rule->event == CMD_SELECT)
2441  {
2442  /* A _RETURN rule should have only one action */
2443  if (list_length(rule->actions) != 1)
2444  elog(ERROR, "invalid _RETURN rule action specification");
2445 
2446  return (Query *) linitial(rule->actions);
2447  }
2448  }
2449 
2450  elog(ERROR, "failed to find _RETURN rule for view");
2451  return NULL; /* keep compiler quiet */
2452 }
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 4361 of file rewriteHandler.c.

4362 {
4363  uint64 input_query_id = parsetree->queryId;
4364  List *querylist;
4365  List *results;
4366  ListCell *l;
4367  CmdType origCmdType;
4368  bool foundOriginalQuery;
4369  Query *lastInstead;
4370 
4371  /*
4372  * This function is only applied to top-level original queries
4373  */
4374  Assert(parsetree->querySource == QSRC_ORIGINAL);
4375  Assert(parsetree->canSetTag);
4376 
4377  /*
4378  * Step 1
4379  *
4380  * Apply all non-SELECT rules possibly getting 0 or many queries
4381  */
4382  querylist = RewriteQuery(parsetree, NIL, 0);
4383 
4384  /*
4385  * Step 2
4386  *
4387  * Apply all the RIR rules on each query
4388  *
4389  * This is also a handy place to mark each query with the original queryId
4390  */
4391  results = NIL;
4392  foreach(l, querylist)
4393  {
4394  Query *query = (Query *) lfirst(l);
4395 
4396  query = fireRIRrules(query, NIL);
4397 
4398  query->queryId = input_query_id;
4399 
4400  results = lappend(results, query);
4401  }
4402 
4403  /*
4404  * Step 3
4405  *
4406  * Determine which, if any, of the resulting queries is supposed to set
4407  * the command-result tag; and update the canSetTag fields accordingly.
4408  *
4409  * If the original query is still in the list, it sets the command tag.
4410  * Otherwise, the last INSTEAD query of the same kind as the original is
4411  * allowed to set the tag. (Note these rules can leave us with no query
4412  * setting the tag. The tcop code has to cope with this by setting up a
4413  * default tag based on the original un-rewritten query.)
4414  *
4415  * The Asserts verify that at most one query in the result list is marked
4416  * canSetTag. If we aren't checking asserts, we can fall out of the loop
4417  * as soon as we find the original query.
4418  */
4419  origCmdType = parsetree->commandType;
4420  foundOriginalQuery = false;
4421  lastInstead = NULL;
4422 
4423  foreach(l, results)
4424  {
4425  Query *query = (Query *) lfirst(l);
4426 
4427  if (query->querySource == QSRC_ORIGINAL)
4428  {
4429  Assert(query->canSetTag);
4430  Assert(!foundOriginalQuery);
4431  foundOriginalQuery = true;
4432 #ifndef USE_ASSERT_CHECKING
4433  break;
4434 #endif
4435  }
4436  else
4437  {
4438  Assert(!query->canSetTag);
4439  if (query->commandType == origCmdType &&
4440  (query->querySource == QSRC_INSTEAD_RULE ||
4441  query->querySource == QSRC_QUAL_INSTEAD_RULE))
4442  lastInstead = query;
4443  }
4444  }
4445 
4446  if (!foundOriginalQuery && lastInstead != NULL)
4447  lastInstead->canSetTag = true;
4448 
4449  return results;
4450 }
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 2812 of file rewriteHandler.c.

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

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

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 2581 of file rewriteHandler.c.

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

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