PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 charview_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 
)
extern

Definition at line 149 of file rewriteHandler.c.

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

References AccessShareLock, acquireLocksOnSubLinks(), AcquireRewriteLocks(), Assert, Query::cteList, CommonTableExpr::ctequery, elog, ERROR, fb(), 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, relation_close(), relation_open(), RowShareLock, rt_fetch, Query::rtable, RTE_GRAPH_TABLE, RTE_JOIN, RTE_RELATION, RTE_SUBQUERY, and strip_implicit_coercions().

Referenced by acquireLocksOnSubLinks(), AcquireRewriteLocks(), ApplyRetrieveRule(), fmgr_sql_validator(), get_query_def(), inline_sql_function_in_from(), make_ruledef(), prepare_next_query(), print_function_sqlbody(), refresh_matview_datafill(), RevalidateCachedQuery(), rewriteGraphTable(), and rewriteRuleAction().

◆ build_column_default()

Node * build_column_default ( Relation  rel,
int  attrno 
)
extern

Definition at line 1246 of file rewriteHandler.c.

1247{
1248 TupleDesc rd_att = rel->rd_att;
1250 Oid atttype = att_tup->atttypid;
1251 int32 atttypmod = att_tup->atttypmod;
1252 Node *expr = NULL;
1253 Oid exprtype;
1254
1255 if (att_tup->attidentity)
1256 {
1258
1259 nve->seqid = getIdentitySequence(rel, attrno, false);
1260 nve->typeId = att_tup->atttypid;
1261
1262 return (Node *) nve;
1263 }
1264
1265 /*
1266 * If relation has a default for this column, fetch that expression.
1267 */
1268 if (att_tup->atthasdef)
1269 {
1270 expr = TupleDescGetDefault(rd_att, attrno);
1271 if (expr == NULL)
1272 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1274 }
1275
1276 /*
1277 * No per-column default, so look for a default for the type itself. But
1278 * not for generated columns.
1279 */
1280 if (expr == NULL && !att_tup->attgenerated)
1281 expr = get_typdefault(atttype);
1282
1283 if (expr == NULL)
1284 return NULL; /* No default anywhere */
1285
1286 /*
1287 * Make sure the value is coerced to the target column type; this will
1288 * generally be true already, but there seem to be some corner cases
1289 * involving domain defaults where it might not be true. This should match
1290 * the parser's processing of non-defaulted expressions --- see
1291 * transformAssignedExpr().
1292 */
1293 exprtype = exprType(expr);
1294
1295 expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1296 expr, exprtype,
1297 atttype, atttypmod,
1300 -1);
1301 if (expr == NULL)
1302 ereport(ERROR,
1304 errmsg("column \"%s\" is of type %s"
1305 " but default expression is of type %s",
1306 NameStr(att_tup->attname),
1307 format_type_be(atttype),
1308 format_type_be(exprtype)),
1309 errhint("You will need to rewrite or cast the expression.")));
1310
1311 return expr;
1312}
#define NameStr(name)
Definition c.h:837
int32_t int32
Definition c.h:614
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
#define ereport(elevel,...)
Definition elog.h:150
char * format_type_be(Oid type_oid)
Node * get_typdefault(Oid typid)
Definition lsyscache.c:2670
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
#define makeNode(_type_)
Definition nodes.h:161
static char * errmsg
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
FormData_pg_attribute * Form_pg_attribute
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition pg_depend.c:1018
unsigned int Oid
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:769
@ COERCION_ASSIGNMENT
Definition primnodes.h:748
#define RelationGetRelationName(relation)
Definition rel.h:548
TupleDesc rd_att
Definition rel.h:112
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition tupdesc.c:1149
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

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

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 
)
extern

Definition at line 4546 of file rewriteHandler.c.

4547{
4548 TupleDesc rd_att = RelationGetDescr(rel);
4550 Node *defexpr;
4551 Oid attcollid;
4552
4553 Assert(rd_att->constr && rd_att->constr->has_generated_virtual);
4554 Assert(att_tup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL);
4555
4556 defexpr = build_column_default(rel, attrno);
4557 if (defexpr == NULL)
4558 elog(ERROR, "no generation expression found for column number %d of table \"%s\"",
4560
4561 /*
4562 * If the column definition has a collation and it is different from the
4563 * collation of the generation expression, put a COLLATE clause around the
4564 * expression.
4565 */
4566 attcollid = att_tup->attcollation;
4567 if (attcollid && attcollid != exprCollation(defexpr))
4568 {
4570
4571 ce->arg = (Expr *) defexpr;
4572 ce->collOid = attcollid;
4573 ce->location = -1;
4574
4575 defexpr = (Node *) ce;
4576 }
4577
4578 return defexpr;
4579}
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
#define RelationGetDescr(relation)
Definition rel.h:540
Node * build_column_default(Relation rel, int attrno)
bool has_generated_virtual
Definition tupdesc.h:47
TupleConstr * constr
Definition tupdesc.h:159

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

Referenced by createTableConstraints(), 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 
)
extern

Definition at line 3147 of file rewriteHandler.c.

3151{
3152 TriggerDesc *trigDesc = view->trigdesc;
3153
3154 switch (command)
3155 {
3156 case CMD_INSERT:
3157 ereport(ERROR,
3159 errmsg("cannot insert into view \"%s\"",
3161 detail ? errdetail_internal("%s", _(detail)) : 0,
3162 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule."));
3163 break;
3164 case CMD_UPDATE:
3165 ereport(ERROR,
3167 errmsg("cannot update view \"%s\"",
3169 detail ? errdetail_internal("%s", _(detail)) : 0,
3170 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule."));
3171 break;
3172 case CMD_DELETE:
3173 ereport(ERROR,
3175 errmsg("cannot delete from view \"%s\"",
3177 detail ? errdetail_internal("%s", _(detail)) : 0,
3178 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule."));
3179 break;
3180 case CMD_MERGE:
3181
3182 /*
3183 * Note that the error hints here differ from above, since MERGE
3184 * doesn't support rules.
3185 */
3186 foreach_node(MergeAction, action, mergeActionList)
3187 {
3188 switch (action->commandType)
3189 {
3190 case CMD_INSERT:
3191 if (!trigDesc || !trigDesc->trig_insert_instead_row)
3192 ereport(ERROR,
3194 errmsg("cannot insert into view \"%s\"",
3196 detail ? errdetail_internal("%s", _(detail)) : 0,
3197 errhint("To enable inserting into the view using MERGE, provide an INSTEAD OF INSERT trigger."));
3198 break;
3199 case CMD_UPDATE:
3200 if (!trigDesc || !trigDesc->trig_update_instead_row)
3201 ereport(ERROR,
3203 errmsg("cannot update view \"%s\"",
3205 detail ? errdetail_internal("%s", _(detail)) : 0,
3206 errhint("To enable updating the view using MERGE, provide an INSTEAD OF UPDATE trigger."));
3207 break;
3208 case CMD_DELETE:
3209 if (!trigDesc || !trigDesc->trig_delete_instead_row)
3210 ereport(ERROR,
3212 errmsg("cannot delete from view \"%s\"",
3214 detail ? errdetail_internal("%s", _(detail)) : 0,
3215 errhint("To enable deleting from the view using MERGE, provide an INSTEAD OF DELETE trigger."));
3216 break;
3217 case CMD_NOTHING:
3218 break;
3219 default:
3220 elog(ERROR, "unrecognized commandType: %d", action->commandType);
3221 break;
3222 }
3223 }
3224 break;
3225 default:
3226 elog(ERROR, "unrecognized CmdType: %d", (int) command);
3227 break;
3228 }
3229}
#define _(x)
Definition elog.c:95
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
@ CMD_MERGE
Definition nodes.h:279
@ CMD_INSERT
Definition nodes.h:277
@ CMD_DELETE
Definition nodes.h:278
@ CMD_UPDATE
Definition nodes.h:276
@ CMD_NOTHING
Definition nodes.h:282
#define foreach_node(type, var, lst)
Definition pg_list.h:496
TriggerDesc * trigdesc
Definition rel.h:117

References _, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_NOTHING, CMD_UPDATE, elog, ereport, errcode(), errdetail_internal(), errhint(), errmsg, ERROR, fb(), foreach_node, RelationGetRelationName, 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 
)
extern

Definition at line 4520 of file rewriteHandler.c.

4521{
4522 TupleDesc tupdesc = RelationGetDescr(rel);
4523
4524 if (tupdesc->constr && tupdesc->constr->has_generated_virtual)
4525 {
4527
4529 /* eref needs to be set, but the actual name doesn't matter */
4531 rte->rtekind = RTE_RELATION;
4532 rte->relid = RelationGetRelid(rel);
4533
4534 node = expand_generated_columns_internal(node, rel, rt_index, rte, 0);
4535 }
4536
4537 return node;
4538}
Alias * makeAlias(const char *aliasname, List *colnames)
Definition makefuncs.c:438
#define RelationGetRelid(relation)
Definition rel.h:514
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(), fb(), TupleConstr::has_generated_virtual, makeAlias(), makeNode, NIL, RelationGetDescr, RelationGetRelationName, RelationGetRelid, and RTE_RELATION.

Referenced by ATExecAlterCheckConstrEnforceability(), ATPrepAlterColumnType(), ATRewriteTable(), createTableConstraints(), ExecRelCheck(), get_relation_constraints(), pgoutput_row_filter_init(), QueueCheckConstraintValidation(), TransformPubWhereClauses(), and TriggerEnabled().

◆ get_view_query()

Query * get_view_query ( Relation  view)
extern

Definition at line 2510 of file rewriteHandler.c.

2511{
2512 int i;
2513
2514 Assert(view->rd_rel->relkind == RELKIND_VIEW);
2515
2516 for (i = 0; i < view->rd_rules->numLocks; i++)
2517 {
2518 RewriteRule *rule = view->rd_rules->rules[i];
2519
2520 if (rule->event == CMD_SELECT)
2521 {
2522 /* A _RETURN rule should have only one action */
2523 if (list_length(rule->actions) != 1)
2524 elog(ERROR, "invalid _RETURN rule action specification");
2525
2526 return (Query *) linitial(rule->actions);
2527 }
2528 }
2529
2530 elog(ERROR, "failed to find _RETURN rule for view");
2531 return NULL; /* keep compiler quiet */
2532}
int i
Definition isn.c:77
@ CMD_SELECT
Definition nodes.h:275
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

References Assert, CMD_SELECT, elog, ERROR, fb(), 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)
extern

Definition at line 4592 of file rewriteHandler.c.

4593{
4594 int64 input_query_id = parsetree->queryId;
4595 List *querylist;
4596 List *results;
4597 ListCell *l;
4599 bool foundOriginalQuery;
4601
4602 /*
4603 * This function is only applied to top-level original queries
4604 */
4605 Assert(parsetree->querySource == QSRC_ORIGINAL);
4606 Assert(parsetree->canSetTag);
4607
4608 /*
4609 * Step 1
4610 *
4611 * Apply all non-SELECT rules possibly getting 0 or many queries
4612 */
4613 querylist = RewriteQuery(parsetree, NIL, 0, 0);
4614
4615 /*
4616 * Step 2
4617 *
4618 * Apply all the RIR rules on each query
4619 *
4620 * This is also a handy place to mark each query with the original queryId
4621 */
4622 results = NIL;
4623 foreach(l, querylist)
4624 {
4625 Query *query = (Query *) lfirst(l);
4626
4627 query = fireRIRrules(query, NIL);
4628
4629 query->queryId = input_query_id;
4630
4631 results = lappend(results, query);
4632 }
4633
4634 /*
4635 * Step 3
4636 *
4637 * Determine which, if any, of the resulting queries is supposed to set
4638 * the command-result tag; and update the canSetTag fields accordingly.
4639 *
4640 * If the original query is still in the list, it sets the command tag.
4641 * Otherwise, the last INSTEAD query of the same kind as the original is
4642 * allowed to set the tag. (Note these rules can leave us with no query
4643 * setting the tag. The tcop code has to cope with this by setting up a
4644 * default tag based on the original un-rewritten query.)
4645 *
4646 * The Asserts verify that at most one query in the result list is marked
4647 * canSetTag. If we aren't checking asserts, we can fall out of the loop
4648 * as soon as we find the original query.
4649 */
4650 origCmdType = parsetree->commandType;
4651 foundOriginalQuery = false;
4652 lastInstead = NULL;
4653
4654 foreach(l, results)
4655 {
4656 Query *query = (Query *) lfirst(l);
4657
4658 if (query->querySource == QSRC_ORIGINAL)
4659 {
4660 Assert(query->canSetTag);
4662 foundOriginalQuery = true;
4663#ifndef USE_ASSERT_CHECKING
4664 break;
4665#endif
4666 }
4667 else
4668 {
4669 Assert(!query->canSetTag);
4670 if (query->commandType == origCmdType &&
4671 (query->querySource == QSRC_INSTEAD_RULE ||
4672 query->querySource == QSRC_QUAL_INSTEAD_RULE))
4673 lastInstead = query;
4674 }
4675 }
4676
4678 lastInstead->canSetTag = true;
4679
4680 return results;
4681}
int64_t int64
Definition c.h:615
CmdType
Definition nodes.h:273
@ 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, int num_ctes_processed)
static Query * fireRIRrules(Query *parsetree, List *activeRIRs)
CmdType commandType
Definition parsenodes.h:121

References Assert, Query::commandType, fb(), 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 
)
extern

Definition at line 2892 of file rewriteHandler.c.

2896{
2897 int events = 0;
2898 Relation rel;
2900
2901#define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2902
2903 /* Since this function recurses, it could be driven to stack overflow */
2905
2906 rel = try_relation_open(reloid, AccessShareLock);
2907
2908 /*
2909 * If the relation doesn't exist, return zero rather than throwing an
2910 * error. This is helpful since scanning an information_schema view under
2911 * MVCC rules can result in referencing rels that have actually been
2912 * deleted already.
2913 */
2914 if (rel == NULL)
2915 return 0;
2916
2917 /* If we detect a recursive view, report that it is not updatable */
2919 {
2921 return 0;
2922 }
2923
2924 /* If the relation is a table, it is always updatable */
2925 if (rel->rd_rel->relkind == RELKIND_RELATION ||
2926 rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2927 {
2929 return ALL_EVENTS;
2930 }
2931
2932 /* Look for unconditional DO INSTEAD rules, and note supported events */
2933 rulelocks = rel->rd_rules;
2934 if (rulelocks != NULL)
2935 {
2936 int i;
2937
2938 for (i = 0; i < rulelocks->numLocks; i++)
2939 {
2940 if (rulelocks->rules[i]->isInstead &&
2941 rulelocks->rules[i]->qual == NULL)
2942 {
2943 events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2944 }
2945 }
2946
2947 /* If we have rules for all events, we're done */
2948 if (events == ALL_EVENTS)
2949 {
2951 return events;
2952 }
2953 }
2954
2955 /* Similarly look for INSTEAD OF triggers, if they are to be included */
2956 if (include_triggers)
2957 {
2959
2960 if (trigDesc)
2961 {
2962 if (trigDesc->trig_insert_instead_row)
2963 events |= (1 << CMD_INSERT);
2964 if (trigDesc->trig_update_instead_row)
2965 events |= (1 << CMD_UPDATE);
2966 if (trigDesc->trig_delete_instead_row)
2967 events |= (1 << CMD_DELETE);
2968
2969 /* If we have triggers for all events, we're done */
2970 if (events == ALL_EVENTS)
2971 {
2973 return events;
2974 }
2975 }
2976 }
2977
2978 /* If this is a foreign table, check which update events it supports */
2979 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2980 {
2981 FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2982
2983 if (fdwroutine->IsForeignRelUpdatable != NULL)
2984 events |= fdwroutine->IsForeignRelUpdatable(rel);
2985 else
2986 {
2987 /* Assume presence of executor functions is sufficient */
2988 if (fdwroutine->ExecForeignInsert != NULL)
2989 events |= (1 << CMD_INSERT);
2990 if (fdwroutine->ExecForeignUpdate != NULL)
2991 events |= (1 << CMD_UPDATE);
2992 if (fdwroutine->ExecForeignDelete != NULL)
2993 events |= (1 << CMD_DELETE);
2994 }
2995
2997 return events;
2998 }
2999
3000 /* Check if this is an automatically updatable view */
3001 if (rel->rd_rel->relkind == RELKIND_VIEW)
3002 {
3004
3006 {
3008 int auto_events;
3011 Oid baseoid;
3012
3013 /*
3014 * Determine which of the view's columns are updatable. If there
3015 * are none within the set of columns we are looking at, then the
3016 * view doesn't support INSERT/UPDATE, but it may still support
3017 * DELETE.
3018 */
3021
3022 if (include_cols != NULL)
3024
3026 auto_events = (1 << CMD_DELETE); /* May support DELETE */
3027 else
3028 auto_events = ALL_EVENTS; /* May support all events */
3029
3030 /*
3031 * The base relation must also support these update commands.
3032 * Tables are always updatable, but for any other kind of base
3033 * relation we must do a recursive check limited to the columns
3034 * referenced by the locally updatable columns in this view.
3035 */
3036 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
3037 base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
3038 Assert(base_rte->rtekind == RTE_RELATION);
3039
3040 if (base_rte->relkind != RELKIND_RELATION &&
3042 {
3043 baseoid = base_rte->relid;
3045 RelationGetRelid(rel));
3047 viewquery->targetList);
3051 include_cols);
3053 }
3054 events |= auto_events;
3055 }
3056 }
3057
3058 /* If we reach here, the relation may support some update commands */
3060 return events;
3061}
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:1093
#define bms_is_empty(a)
Definition bitmapset.h:118
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition foreign.c:531
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
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

References AccessShareLock, adjust_view_column_set(), ALL_EVENTS, Assert, bms_int_members(), bms_is_empty, check_stack_depth(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, FdwRoutine::ExecForeignDelete, FdwRoutine::ExecForeignInsert, FdwRoutine::ExecForeignUpdate, fb(), get_view_query(), GetFdwRoutineForRelation(), i, FdwRoutine::IsForeignRelUpdatable, lappend_oid(), linitial, list_delete_last(), list_member_oid(), RelationData::rd_rel, RelationData::rd_rules, relation_close(), relation_is_updatable(), RelationGetRelid, rt_fetch, RTE_RELATION, 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 
)
extern

Definition at line 2549 of file rewriteHandler.c.

2550{
2551 TriggerDesc *trigDesc = view->trigdesc;
2552
2553 switch (event)
2554 {
2555 case CMD_INSERT:
2556 if (trigDesc && trigDesc->trig_insert_instead_row)
2557 return true;
2558 break;
2559 case CMD_UPDATE:
2560 if (trigDesc && trigDesc->trig_update_instead_row)
2561 return true;
2562 break;
2563 case CMD_DELETE:
2564 if (trigDesc && trigDesc->trig_delete_instead_row)
2565 return true;
2566 break;
2567 case CMD_MERGE:
2568 foreach_node(MergeAction, action, mergeActionList)
2569 {
2570 switch (action->commandType)
2571 {
2572 case CMD_INSERT:
2573 if (!trigDesc || !trigDesc->trig_insert_instead_row)
2574 return false;
2575 break;
2576 case CMD_UPDATE:
2577 if (!trigDesc || !trigDesc->trig_update_instead_row)
2578 return false;
2579 break;
2580 case CMD_DELETE:
2581 if (!trigDesc || !trigDesc->trig_delete_instead_row)
2582 return false;
2583 break;
2584 case CMD_NOTHING:
2585 /* No trigger required */
2586 break;
2587 default:
2588 elog(ERROR, "unrecognized commandType: %d", action->commandType);
2589 break;
2590 }
2591 }
2592 return true; /* no actions without an INSTEAD OF trigger */
2593 default:
2594 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2595 break;
2596 }
2597 return false;
2598}

References CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_NOTHING, CMD_UPDATE, elog, ERROR, fb(), foreach_node, 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 
)
extern

Definition at line 2661 of file rewriteHandler.c.

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

References fb(), gettext_noop, IsA, lfirst, linitial, list_length(), NIL, rt_fetch, RTE_RELATION, and view_col_is_auto_updatable().

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