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 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 {
165 Relation rel;
166 LOCKMODE lockmode;
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 */
221 curinputvarno = 0;
223 foreach(ll, rte->joinaliasvars)
224 {
225 Var *aliasitem = (Var *) lfirst(ll);
227
228 /* Look through any implicit coercion */
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);
257 parsetree->rtable);
258 }
260 aliasvar->varattno))
261 {
262 /* Replace the join alias item with a NULL */
263 aliasitem = NULL;
264 }
265 }
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 */
277 AcquireRewriteLocks(rte->subquery,
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
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}
#define Assert(condition)
Definition c.h:885
unsigned int Index
Definition c.h:640
#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: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
@ RTE_SUBQUERY
@ 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)
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
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, 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, RowShareLock, rt_fetch, Query::rtable, RTE_JOIN, RTE_RELATION, RTE_SUBQUERY, strip_implicit_coercions(), table_close(), and table_open().

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

◆ build_column_default()

Node * build_column_default ( Relation  rel,
int  attrno 
)
extern

Definition at line 1244 of file rewriteHandler.c.

1245{
1246 TupleDesc rd_att = rel->rd_att;
1248 Oid atttype = att_tup->atttypid;
1249 int32 atttypmod = att_tup->atttypmod;
1250 Node *expr = NULL;
1251 Oid exprtype;
1252
1253 if (att_tup->attidentity)
1254 {
1256
1257 nve->seqid = getIdentitySequence(rel, attrno, false);
1258 nve->typeId = att_tup->atttypid;
1259
1260 return (Node *) nve;
1261 }
1262
1263 /*
1264 * If relation has a default for this column, fetch that expression.
1265 */
1266 if (att_tup->atthasdef)
1267 {
1268 expr = TupleDescGetDefault(rd_att, attrno);
1269 if (expr == NULL)
1270 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1272 }
1273
1274 /*
1275 * No per-column default, so look for a default for the type itself. But
1276 * not for generated columns.
1277 */
1278 if (expr == NULL && !att_tup->attgenerated)
1279 expr = get_typdefault(atttype);
1280
1281 if (expr == NULL)
1282 return NULL; /* No default anywhere */
1283
1284 /*
1285 * Make sure the value is coerced to the target column type; this will
1286 * generally be true already, but there seem to be some corner cases
1287 * involving domain defaults where it might not be true. This should match
1288 * the parser's processing of non-defaulted expressions --- see
1289 * transformAssignedExpr().
1290 */
1291 exprtype = exprType(expr);
1292
1293 expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1294 expr, exprtype,
1295 atttype, atttypmod,
1298 -1);
1299 if (expr == NULL)
1300 ereport(ERROR,
1302 errmsg("column \"%s\" is of type %s"
1303 " but default expression is of type %s",
1304 NameStr(att_tup->attname),
1305 format_type_be(atttype),
1306 format_type_be(exprtype)),
1307 errhint("You will need to rewrite or cast the expression.")));
1308
1309 return expr;
1310}
#define NameStr(name)
Definition c.h:777
int32_t int32
Definition c.h:554
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
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:2600
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)
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:1075
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(), 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 4534 of file rewriteHandler.c.

4535{
4536 TupleDesc rd_att = RelationGetDescr(rel);
4538 Node *defexpr;
4539 Oid attcollid;
4540
4541 Assert(rd_att->constr && rd_att->constr->has_generated_virtual);
4542 Assert(att_tup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL);
4543
4544 defexpr = build_column_default(rel, attrno);
4545 if (defexpr == NULL)
4546 elog(ERROR, "no generation expression found for column number %d of table \"%s\"",
4548
4549 /*
4550 * If the column definition has a collation and it is different from the
4551 * collation of the generation expression, put a COLLATE clause around the
4552 * expression.
4553 */
4554 attcollid = att_tup->attcollation;
4555 if (attcollid && attcollid != exprCollation(defexpr))
4556 {
4558
4559 ce->arg = (Expr *) defexpr;
4560 ce->collOid = attcollid;
4561 ce->location = -1;
4562
4563 defexpr = (Node *) ce;
4564 }
4565
4566 return defexpr;
4567}
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:821
#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:141

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

3139{
3140 TriggerDesc *trigDesc = view->trigdesc;
3141
3142 switch (command)
3143 {
3144 case CMD_INSERT:
3145 ereport(ERROR,
3147 errmsg("cannot insert into view \"%s\"",
3149 detail ? errdetail_internal("%s", _(detail)) : 0,
3150 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule."));
3151 break;
3152 case CMD_UPDATE:
3153 ereport(ERROR,
3155 errmsg("cannot update view \"%s\"",
3157 detail ? errdetail_internal("%s", _(detail)) : 0,
3158 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule."));
3159 break;
3160 case CMD_DELETE:
3161 ereport(ERROR,
3163 errmsg("cannot delete from view \"%s\"",
3165 detail ? errdetail_internal("%s", _(detail)) : 0,
3166 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule."));
3167 break;
3168 case CMD_MERGE:
3169
3170 /*
3171 * Note that the error hints here differ from above, since MERGE
3172 * doesn't support rules.
3173 */
3174 foreach_node(MergeAction, action, mergeActionList)
3175 {
3176 switch (action->commandType)
3177 {
3178 case CMD_INSERT:
3179 if (!trigDesc || !trigDesc->trig_insert_instead_row)
3180 ereport(ERROR,
3182 errmsg("cannot insert into view \"%s\"",
3184 detail ? errdetail_internal("%s", _(detail)) : 0,
3185 errhint("To enable inserting into the view using MERGE, provide an INSTEAD OF INSERT trigger."));
3186 break;
3187 case CMD_UPDATE:
3188 if (!trigDesc || !trigDesc->trig_update_instead_row)
3189 ereport(ERROR,
3191 errmsg("cannot update view \"%s\"",
3193 detail ? errdetail_internal("%s", _(detail)) : 0,
3194 errhint("To enable updating the view using MERGE, provide an INSTEAD OF UPDATE trigger."));
3195 break;
3196 case CMD_DELETE:
3197 if (!trigDesc || !trigDesc->trig_delete_instead_row)
3198 ereport(ERROR,
3200 errmsg("cannot delete from view \"%s\"",
3202 detail ? errdetail_internal("%s", _(detail)) : 0,
3203 errhint("To enable deleting from the view using MERGE, provide an INSTEAD OF DELETE trigger."));
3204 break;
3205 case CMD_NOTHING:
3206 break;
3207 default:
3208 elog(ERROR, "unrecognized commandType: %d", action->commandType);
3209 break;
3210 }
3211 }
3212 break;
3213 default:
3214 elog(ERROR, "unrecognized CmdType: %d", (int) command);
3215 break;
3216 }
3217}
#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 4508 of file rewriteHandler.c.

4509{
4510 TupleDesc tupdesc = RelationGetDescr(rel);
4511
4512 if (tupdesc->constr && tupdesc->constr->has_generated_virtual)
4513 {
4515
4517 /* eref needs to be set, but the actual name doesn't matter */
4519 rte->rtekind = RTE_RELATION;
4520 rte->relid = RelationGetRelid(rel);
4521
4522 node = expand_generated_columns_internal(node, rel, rt_index, rte, 0);
4523 }
4524
4525 return node;
4526}
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 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 2498 of file rewriteHandler.c.

2499{
2500 int i;
2501
2502 Assert(view->rd_rel->relkind == RELKIND_VIEW);
2503
2504 for (i = 0; i < view->rd_rules->numLocks; i++)
2505 {
2506 RewriteRule *rule = view->rd_rules->rules[i];
2507
2508 if (rule->event == CMD_SELECT)
2509 {
2510 /* A _RETURN rule should have only one action */
2511 if (list_length(rule->actions) != 1)
2512 elog(ERROR, "invalid _RETURN rule action specification");
2513
2514 return (Query *) linitial(rule->actions);
2515 }
2516 }
2517
2518 elog(ERROR, "failed to find _RETURN rule for view");
2519 return NULL; /* keep compiler quiet */
2520}
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 4580 of file rewriteHandler.c.

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

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

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

2538{
2539 TriggerDesc *trigDesc = view->trigdesc;
2540
2541 switch (event)
2542 {
2543 case CMD_INSERT:
2544 if (trigDesc && trigDesc->trig_insert_instead_row)
2545 return true;
2546 break;
2547 case CMD_UPDATE:
2548 if (trigDesc && trigDesc->trig_update_instead_row)
2549 return true;
2550 break;
2551 case CMD_DELETE:
2552 if (trigDesc && trigDesc->trig_delete_instead_row)
2553 return true;
2554 break;
2555 case CMD_MERGE:
2556 foreach_node(MergeAction, action, mergeActionList)
2557 {
2558 switch (action->commandType)
2559 {
2560 case CMD_INSERT:
2561 if (!trigDesc || !trigDesc->trig_insert_instead_row)
2562 return false;
2563 break;
2564 case CMD_UPDATE:
2565 if (!trigDesc || !trigDesc->trig_update_instead_row)
2566 return false;
2567 break;
2568 case CMD_DELETE:
2569 if (!trigDesc || !trigDesc->trig_delete_instead_row)
2570 return false;
2571 break;
2572 case CMD_NOTHING:
2573 /* No trigger required */
2574 break;
2575 default:
2576 elog(ERROR, "unrecognized commandType: %d", action->commandType);
2577 break;
2578 }
2579 }
2580 return true; /* no actions without an INSTEAD OF trigger */
2581 default:
2582 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2583 break;
2584 }
2585 return false;
2586}

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

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