PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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)
 
Nodeexpand_generated_columns_in_expr (Node *node, Relation rel, int rt_index)
 
Nodebuild_generation_expression (Relation rel, int attrno)
 

Function Documentation

◆ AcquireRewriteLocks()

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

Definition at line 148 of file rewriteHandler.c.

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

◆ build_column_default()

Node * build_column_default ( Relation  rel,
int  attrno 
)

Definition at line 1227 of file rewriteHandler.c.

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

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(), build_generation_expression(), ExecInitGenerated(), rewriteTargetListIU(), rewriteValuesRTE(), and slot_fill_defaults().

◆ build_generation_expression()

Node * build_generation_expression ( Relation  rel,
int  attrno 
)

Definition at line 4499 of file rewriteHandler.c.

4500{
4501 TupleDesc rd_att = RelationGetDescr(rel);
4502 Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1);
4503 Node *defexpr;
4504 Oid attcollid;
4505
4506 Assert(rd_att->constr && rd_att->constr->has_generated_virtual);
4507 Assert(att_tup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL);
4508
4509 defexpr = build_column_default(rel, attrno);
4510 if (defexpr == NULL)
4511 elog(ERROR, "no generation expression found for column number %d of table \"%s\"",
4512 attrno, RelationGetRelationName(rel));
4513
4514 /*
4515 * If the column definition has a collation and it is different from the
4516 * collation of the generation expression, put a COLLATE clause around the
4517 * expression.
4518 */
4519 attcollid = att_tup->attcollation;
4520 if (attcollid && attcollid != exprCollation(defexpr))
4521 {
4523
4524 ce->arg = (Expr *) defexpr;
4525 ce->collOid = attcollid;
4526 ce->location = -1;
4527
4528 defexpr = (Node *) ce;
4529 }
4530
4531 return defexpr;
4532}
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
#define RelationGetDescr(relation)
Definition: rel.h:542
Node * build_column_default(Relation rel, int attrno)
Expr * arg
Definition: primnodes.h:1296
ParseLoc location
Definition: primnodes.h:1298
bool has_generated_virtual
Definition: tupdesc.h:47
TupleConstr * constr
Definition: tupdesc.h:141

References CollateExpr::arg, Assert(), build_column_default(), CollateExpr::collOid, TupleDescData::constr, elog, ERROR, exprCollation(), TupleConstr::has_generated_virtual, CollateExpr::location, makeNode, RelationGetDescr, RelationGetRelationName, and TupleDescAttr().

Referenced by ExecRelGenVirtualNotNull(), expand_generated_columns_internal(), and expand_virtual_generated_columns().

◆ error_view_not_updatable()

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

Definition at line 3118 of file rewriteHandler.c.

3122{
3123 TriggerDesc *trigDesc = view->trigdesc;
3124
3125 switch (command)
3126 {
3127 case CMD_INSERT:
3128 ereport(ERROR,
3129 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3130 errmsg("cannot insert into view \"%s\"",
3132 detail ? errdetail_internal("%s", _(detail)) : 0,
3133 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule."));
3134 break;
3135 case CMD_UPDATE:
3136 ereport(ERROR,
3137 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3138 errmsg("cannot update view \"%s\"",
3140 detail ? errdetail_internal("%s", _(detail)) : 0,
3141 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule."));
3142 break;
3143 case CMD_DELETE:
3144 ereport(ERROR,
3145 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3146 errmsg("cannot delete from view \"%s\"",
3148 detail ? errdetail_internal("%s", _(detail)) : 0,
3149 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule."));
3150 break;
3151 case CMD_MERGE:
3152
3153 /*
3154 * Note that the error hints here differ from above, since MERGE
3155 * doesn't support rules.
3156 */
3157 foreach_node(MergeAction, action, mergeActionList)
3158 {
3159 switch (action->commandType)
3160 {
3161 case CMD_INSERT:
3162 if (!trigDesc || !trigDesc->trig_insert_instead_row)
3163 ereport(ERROR,
3164 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3165 errmsg("cannot insert into view \"%s\"",
3167 detail ? errdetail_internal("%s", _(detail)) : 0,
3168 errhint("To enable inserting into the view using MERGE, provide an INSTEAD OF INSERT trigger."));
3169 break;
3170 case CMD_UPDATE:
3171 if (!trigDesc || !trigDesc->trig_update_instead_row)
3172 ereport(ERROR,
3173 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3174 errmsg("cannot update view \"%s\"",
3176 detail ? errdetail_internal("%s", _(detail)) : 0,
3177 errhint("To enable updating the view using MERGE, provide an INSTEAD OF UPDATE trigger."));
3178 break;
3179 case CMD_DELETE:
3180 if (!trigDesc || !trigDesc->trig_delete_instead_row)
3181 ereport(ERROR,
3182 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3183 errmsg("cannot delete from view \"%s\"",
3185 detail ? errdetail_internal("%s", _(detail)) : 0,
3186 errhint("To enable deleting from the view using MERGE, provide an INSTEAD OF DELETE trigger."));
3187 break;
3188 case CMD_NOTHING:
3189 break;
3190 default:
3191 elog(ERROR, "unrecognized commandType: %d", action->commandType);
3192 break;
3193 }
3194 }
3195 break;
3196 default:
3197 elog(ERROR, "unrecognized CmdType: %d", (int) command);
3198 break;
3199 }
3200}
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1231
#define _(x)
Definition: elog.c:91
@ CMD_MERGE
Definition: nodes.h:275
@ CMD_INSERT
Definition: nodes.h:273
@ CMD_DELETE
Definition: nodes.h:274
@ CMD_UPDATE
Definition: nodes.h:272
@ CMD_NOTHING
Definition: nodes.h:278
#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().

◆ expand_generated_columns_in_expr()

Node * expand_generated_columns_in_expr ( Node node,
Relation  rel,
int  rt_index 
)

Definition at line 4473 of file rewriteHandler.c.

4474{
4475 TupleDesc tupdesc = RelationGetDescr(rel);
4476
4477 if (tupdesc->constr && tupdesc->constr->has_generated_virtual)
4478 {
4479 RangeTblEntry *rte;
4480
4481 rte = makeNode(RangeTblEntry);
4482 /* eref needs to be set, but the actual name doesn't matter */
4483 rte->eref = makeAlias(RelationGetRelationName(rel), NIL);
4484 rte->rtekind = RTE_RELATION;
4485 rte->relid = RelationGetRelid(rel);
4486
4487 node = expand_generated_columns_internal(node, rel, rt_index, rte, 0);
4488 }
4489
4490 return node;
4491}
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:438
#define RelationGetRelid(relation)
Definition: rel.h:516
static Node * expand_generated_columns_internal(Node *node, Relation rel, int rt_index, RangeTblEntry *rte, int result_relation)

References TupleDescData::constr, expand_generated_columns_internal(), TupleConstr::has_generated_virtual, makeAlias(), makeNode, NIL, RelationGetDescr, RelationGetRelationName, RelationGetRelid, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by ATRewriteTable(), ExecRelCheck(), pgoutput_row_filter_init(), QueueCheckConstraintValidation(), TransformPubWhereClauses(), and TriggerEnabled().

◆ get_view_query()

Query * get_view_query ( Relation  view)

Definition at line 2481 of file rewriteHandler.c.

2482{
2483 int i;
2484
2485 Assert(view->rd_rel->relkind == RELKIND_VIEW);
2486
2487 for (i = 0; i < view->rd_rules->numLocks; i++)
2488 {
2489 RewriteRule *rule = view->rd_rules->rules[i];
2490
2491 if (rule->event == CMD_SELECT)
2492 {
2493 /* A _RETURN rule should have only one action */
2494 if (list_length(rule->actions) != 1)
2495 elog(ERROR, "invalid _RETURN rule action specification");
2496
2497 return (Query *) linitial(rule->actions);
2498 }
2499 }
2500
2501 elog(ERROR, "failed to find _RETURN rule for view");
2502 return NULL; /* keep compiler quiet */
2503}
int i
Definition: isn.c:77
@ CMD_SELECT
Definition: nodes.h:271
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 4545 of file rewriteHandler.c.

4546{
4547 uint64 input_query_id = parsetree->queryId;
4548 List *querylist;
4549 List *results;
4550 ListCell *l;
4551 CmdType origCmdType;
4552 bool foundOriginalQuery;
4553 Query *lastInstead;
4554
4555 /*
4556 * This function is only applied to top-level original queries
4557 */
4558 Assert(parsetree->querySource == QSRC_ORIGINAL);
4559 Assert(parsetree->canSetTag);
4560
4561 /*
4562 * Step 1
4563 *
4564 * Apply all non-SELECT rules possibly getting 0 or many queries
4565 */
4566 querylist = RewriteQuery(parsetree, NIL, 0);
4567
4568 /*
4569 * Step 2
4570 *
4571 * Apply all the RIR rules on each query
4572 *
4573 * This is also a handy place to mark each query with the original queryId
4574 */
4575 results = NIL;
4576 foreach(l, querylist)
4577 {
4578 Query *query = (Query *) lfirst(l);
4579
4580 query = fireRIRrules(query, NIL);
4581
4582 query->queryId = input_query_id;
4583
4584 results = lappend(results, query);
4585 }
4586
4587 /*
4588 * Step 3
4589 *
4590 * Determine which, if any, of the resulting queries is supposed to set
4591 * the command-result tag; and update the canSetTag fields accordingly.
4592 *
4593 * If the original query is still in the list, it sets the command tag.
4594 * Otherwise, the last INSTEAD query of the same kind as the original is
4595 * allowed to set the tag. (Note these rules can leave us with no query
4596 * setting the tag. The tcop code has to cope with this by setting up a
4597 * default tag based on the original un-rewritten query.)
4598 *
4599 * The Asserts verify that at most one query in the result list is marked
4600 * canSetTag. If we aren't checking asserts, we can fall out of the loop
4601 * as soon as we find the original query.
4602 */
4603 origCmdType = parsetree->commandType;
4604 foundOriginalQuery = false;
4605 lastInstead = NULL;
4606
4607 foreach(l, results)
4608 {
4609 Query *query = (Query *) lfirst(l);
4610
4611 if (query->querySource == QSRC_ORIGINAL)
4612 {
4613 Assert(query->canSetTag);
4614 Assert(!foundOriginalQuery);
4615 foundOriginalQuery = true;
4616#ifndef USE_ASSERT_CHECKING
4617 break;
4618#endif
4619 }
4620 else
4621 {
4622 Assert(!query->canSetTag);
4623 if (query->commandType == origCmdType &&
4624 (query->querySource == QSRC_INSTEAD_RULE ||
4625 query->querySource == QSRC_QUAL_INSTEAD_RULE))
4626 lastInstead = query;
4627 }
4628 }
4629
4630 if (!foundOriginalQuery && lastInstead != NULL)
4631 lastInstead->canSetTag = true;
4632
4633 return results;
4634}
uint64_t uint64
Definition: c.h:503
CmdType
Definition: nodes.h:269
@ 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 2863 of file rewriteHandler.c.

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

◆ view_has_instead_trigger()

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

Definition at line 2520 of file rewriteHandler.c.

2521{
2522 TriggerDesc *trigDesc = view->trigdesc;
2523
2524 switch (event)
2525 {
2526 case CMD_INSERT:
2527 if (trigDesc && trigDesc->trig_insert_instead_row)
2528 return true;
2529 break;
2530 case CMD_UPDATE:
2531 if (trigDesc && trigDesc->trig_update_instead_row)
2532 return true;
2533 break;
2534 case CMD_DELETE:
2535 if (trigDesc && trigDesc->trig_delete_instead_row)
2536 return true;
2537 break;
2538 case CMD_MERGE:
2539 foreach_node(MergeAction, action, mergeActionList)
2540 {
2541 switch (action->commandType)
2542 {
2543 case CMD_INSERT:
2544 if (!trigDesc || !trigDesc->trig_insert_instead_row)
2545 return false;
2546 break;
2547 case CMD_UPDATE:
2548 if (!trigDesc || !trigDesc->trig_update_instead_row)
2549 return false;
2550 break;
2551 case CMD_DELETE:
2552 if (!trigDesc || !trigDesc->trig_delete_instead_row)
2553 return false;
2554 break;
2555 case CMD_NOTHING:
2556 /* No trigger required */
2557 break;
2558 default:
2559 elog(ERROR, "unrecognized commandType: %d", action->commandType);
2560 break;
2561 }
2562 }
2563 return true; /* no actions without an INSTEAD OF trigger */
2564 default:
2565 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2566 break;
2567 }
2568 return false;
2569}

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

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

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