Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * rewriteDefine.c
4 : : * routines for defining a rewrite rule
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/rewrite/rewriteDefine.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/htup_details.h"
18 : : #include "access/relation.h"
19 : : #include "access/table.h"
20 : : #include "catalog/catalog.h"
21 : : #include "catalog/dependency.h"
22 : : #include "catalog/indexing.h"
23 : : #include "catalog/namespace.h"
24 : : #include "catalog/objectaccess.h"
25 : : #include "catalog/pg_rewrite.h"
26 : : #include "miscadmin.h"
27 : : #include "nodes/nodeFuncs.h"
28 : : #include "parser/parse_utilcmd.h"
29 : : #include "rewrite/rewriteDefine.h"
30 : : #include "rewrite/rewriteManip.h"
31 : : #include "rewrite/rewriteSupport.h"
32 : : #include "utils/acl.h"
33 : : #include "utils/builtins.h"
34 : : #include "utils/inval.h"
35 : : #include "utils/lsyscache.h"
36 : : #include "utils/rel.h"
37 : : #include "utils/syscache.h"
38 : :
39 : :
40 : : static void checkRuleResultList(List *targetList, TupleDesc resultDesc,
41 : : bool isSelect, bool requireColumnNameMatch);
42 : : static bool setRuleCheckAsUser_walker(Node *node, Oid *context);
43 : : static void setRuleCheckAsUser_Query(Query *qry, Oid userid);
44 : :
45 : :
46 : : /*
47 : : * InsertRule -
48 : : * takes the arguments and inserts them as a row into the system
49 : : * relation "pg_rewrite"
50 : : */
51 : : static Oid
3315 peter_e@gmx.net 52 :CBC 11994 : InsertRule(const char *rulname,
53 : : int evtype,
54 : : Oid eventrel_oid,
55 : : bool evinstead,
56 : : Node *event_qual,
57 : : List *action,
58 : : bool replace)
59 : : {
8901 tgl@sss.pgh.pa.us 60 : 11994 : char *evqual = nodeToString(event_qual);
61 : 11994 : char *actiontree = nodeToString((Node *) action);
62 : : Datum values[Natts_pg_rewrite];
1596 peter@eisentraut.org 63 : 11994 : bool nulls[Natts_pg_rewrite] = {0};
64 : : NameData rname;
65 : : Relation pg_rewrite_desc;
66 : : HeapTuple tup,
67 : : oldtup;
68 : : Oid rewriteObjectId;
69 : : ObjectAddress myself,
70 : : referenced;
8853 tgl@sss.pgh.pa.us 71 : 11994 : bool is_update = false;
72 : :
73 : : /*
74 : : * Set up *nulls and *values arrays
75 : : */
9649 76 : 11994 : namestrcpy(&rname, rulname);
5644 77 : 11994 : values[Anum_pg_rewrite_rulename - 1] = NameGetDatum(&rname);
78 : 11994 : values[Anum_pg_rewrite_ev_class - 1] = ObjectIdGetDatum(eventrel_oid);
79 : 11994 : values[Anum_pg_rewrite_ev_type - 1] = CharGetDatum(evtype + '0');
80 : 11994 : values[Anum_pg_rewrite_ev_enabled - 1] = CharGetDatum(RULE_FIRES_ON_ORIGIN);
81 : 11994 : values[Anum_pg_rewrite_is_instead - 1] = BoolGetDatum(evinstead);
82 : 11994 : values[Anum_pg_rewrite_ev_qual - 1] = CStringGetTextDatum(evqual);
83 : 11994 : values[Anum_pg_rewrite_ev_action - 1] = CStringGetTextDatum(actiontree);
84 : :
85 : : /*
86 : : * Ready to store new pg_rewrite tuple
87 : : */
2868 andres@anarazel.de 88 : 11994 : pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
89 : :
90 : : /*
91 : : * Check to see if we are replacing an existing tuple
92 : : */
6131 rhaas@postgresql.org 93 : 11994 : oldtup = SearchSysCache2(RULERELNAME,
94 : : ObjectIdGetDatum(eventrel_oid),
95 : : PointerGetDatum(rulname));
96 : :
8853 tgl@sss.pgh.pa.us 97 [ + + ]: 11994 : if (HeapTupleIsValid(oldtup))
98 : : {
1596 peter@eisentraut.org 99 : 201 : bool replaces[Natts_pg_rewrite] = {0};
100 : :
6514 peter_e@gmx.net 101 [ - + ]: 201 : if (!replace)
8527 tgl@sss.pgh.pa.us 102 [ # # ]:UBC 0 : ereport(ERROR,
103 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
104 : : errmsg("rule \"%s\" for relation \"%s\" already exists",
105 : : rulname, get_rel_name(eventrel_oid))));
106 : :
107 : : /*
108 : : * When replacing, we don't need to replace every attribute
109 : : */
6600 tgl@sss.pgh.pa.us 110 :CBC 201 : replaces[Anum_pg_rewrite_ev_type - 1] = true;
111 : 201 : replaces[Anum_pg_rewrite_is_instead - 1] = true;
112 : 201 : replaces[Anum_pg_rewrite_ev_qual - 1] = true;
113 : 201 : replaces[Anum_pg_rewrite_ev_action - 1] = true;
114 : :
115 : 201 : tup = heap_modify_tuple(oldtup, RelationGetDescr(pg_rewrite_desc),
116 : : values, nulls, replaces);
117 : :
3588 alvherre@alvh.no-ip. 118 : 201 : CatalogTupleUpdate(pg_rewrite_desc, &tup->t_self, tup);
119 : :
8853 tgl@sss.pgh.pa.us 120 : 201 : ReleaseSysCache(oldtup);
121 : :
2930 andres@anarazel.de 122 : 201 : rewriteObjectId = ((Form_pg_rewrite) GETSTRUCT(tup))->oid;
8853 tgl@sss.pgh.pa.us 123 : 201 : is_update = true;
124 : : }
125 : : else
126 : : {
2930 andres@anarazel.de 127 : 11793 : rewriteObjectId = GetNewOidWithIndex(pg_rewrite_desc,
128 : : RewriteOidIndexId,
129 : : Anum_pg_rewrite_oid);
130 : 11793 : values[Anum_pg_rewrite_oid - 1] = ObjectIdGetDatum(rewriteObjectId);
131 : :
6600 tgl@sss.pgh.pa.us 132 : 11793 : tup = heap_form_tuple(pg_rewrite_desc->rd_att, values, nulls);
133 : :
2930 andres@anarazel.de 134 : 11793 : CatalogTupleInsert(pg_rewrite_desc, tup);
135 : : }
136 : :
137 : :
9649 tgl@sss.pgh.pa.us 138 : 11994 : heap_freetuple(tup);
139 : :
140 : : /* If replacing, get rid of old dependencies and make new ones */
8853 141 [ + + ]: 11994 : if (is_update)
5772 142 : 201 : deleteDependencyRecordsFor(RewriteRelationId, rewriteObjectId, false);
143 : :
144 : : /*
145 : : * Install dependency on rule's relation to ensure it will go away on
146 : : * relation deletion. If the rule is ON SELECT, make the dependency
147 : : * implicit --- this prevents deleting a view's SELECT rule. Other kinds
148 : : * of rules can be AUTO.
149 : : */
7898 150 : 11994 : myself.classId = RewriteRelationId;
8905 151 : 11994 : myself.objectId = rewriteObjectId;
152 : 11994 : myself.objectSubId = 0;
153 : :
7898 154 : 11994 : referenced.classId = RelationRelationId;
8905 155 : 11994 : referenced.objectId = eventrel_oid;
156 : 11994 : referenced.objectSubId = 0;
157 : :
158 [ + + ]: 11994 : recordDependencyOn(&myself, &referenced,
159 : : (evtype == CMD_SELECT) ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO);
160 : :
161 : : /*
162 : : * Also install dependencies on objects referenced in action and qual.
163 : : */
110 nathan@postgresql.or 164 : 11994 : CheckUsageOnTypesInExpr((Node *) action, NIL, GetUserId());
8901 tgl@sss.pgh.pa.us 165 : 11990 : recordDependencyOnExpr(&myself, (Node *) action, NIL,
166 : : DEPENDENCY_NORMAL);
167 : :
168 [ + + ]: 11990 : if (event_qual != NULL)
169 : : {
170 : : /* Find query containing OLD/NEW rtable entries */
3519 171 : 178 : Query *qry = linitial_node(Query, action);
172 : :
8901 173 : 178 : qry = getInsertSelectQuery(qry, NULL);
110 nathan@postgresql.or 174 : 178 : CheckUsageOnTypesInExpr(event_qual, qry->rtable, GetUserId());
8901 tgl@sss.pgh.pa.us 175 : 178 : recordDependencyOnExpr(&myself, event_qual, qry->rtable,
176 : : DEPENDENCY_NORMAL);
177 : : }
178 : :
179 : : /* Post creation hook for new rule */
5015 rhaas@postgresql.org 180 [ + + ]: 11990 : InvokeObjectPostCreateHook(RewriteRelationId, rewriteObjectId, 0);
181 : :
2868 andres@anarazel.de 182 : 11990 : table_close(pg_rewrite_desc, RowExclusiveLock);
183 : :
9649 tgl@sss.pgh.pa.us 184 : 11990 : return rewriteObjectId;
185 : : }
186 : :
187 : : /*
188 : : * DefineRule
189 : : * Execute a CREATE RULE command.
190 : : */
191 : : ObjectAddress
7200 192 : 741 : DefineRule(RuleStmt *stmt, const char *queryString)
193 : : {
194 : : List *actions;
195 : : Node *whereClause;
196 : : Oid relId;
197 : :
198 : : /* Parse analysis. */
7098 199 : 741 : transformRuleStmt(stmt, queryString, &actions, &whereClause);
200 : :
201 : : /*
202 : : * Find and lock the relation. Lock level should match
203 : : * DefineQueryRewrite.
204 : : */
5477 rhaas@postgresql.org 205 : 729 : relId = RangeVarGetRelid(stmt->relation, AccessExclusiveLock, false);
206 : :
207 : : /* ... and execute */
5082 208 : 1437 : return DefineQueryRewrite(stmt->rulename,
209 : : relId,
210 : : whereClause,
211 : : stmt->event,
212 : 729 : stmt->instead,
213 : 729 : stmt->replace,
214 : : actions);
215 : : }
216 : :
217 : :
218 : : /*
219 : : * DefineQueryRewrite
220 : : * Create a rule
221 : : *
222 : : * This is essentially the same as DefineRule() except that the rule's
223 : : * action and qual have already been passed through parse analysis.
224 : : */
225 : : ObjectAddress
3315 peter_e@gmx.net 226 : 12015 : DefineQueryRewrite(const char *rulename,
227 : : Oid event_relid,
228 : : Node *event_qual,
229 : : CmdType event_type,
230 : : bool is_instead,
231 : : bool replace,
232 : : List *action)
233 : : {
234 : : Relation event_relation;
235 : : ListCell *l;
236 : : Query *query;
4931 bruce@momjian.us 237 : 12015 : Oid ruleId = InvalidOid;
238 : : ObjectAddress address;
239 : :
240 : : /*
241 : : * If we are installing an ON SELECT rule, we had better grab
242 : : * AccessExclusiveLock to ensure no SELECTs are currently running on the
243 : : * event relation. For other types of rules, it would be sufficient to
244 : : * grab ShareRowExclusiveLock to lock out insert/update/delete actions and
245 : : * to ensure that we lock out current CREATE RULE statements; but because
246 : : * of race conditions in access to catalog entries, we can't do that yet.
247 : : *
248 : : * Note that this lock level should match the one used in DefineRule.
249 : : */
2868 andres@anarazel.de 250 : 12015 : event_relation = table_open(event_relid, AccessExclusiveLock);
251 : :
252 : : /*
253 : : * Verify relation is of a type that rules can sensibly be applied to.
254 : : * Internal callers can target materialized views, but transformRuleStmt()
255 : : * blocks them for users. Don't mention them in the error message.
256 : : */
6408 tgl@sss.pgh.pa.us 257 [ + + ]: 12015 : if (event_relation->rd_rel->relkind != RELKIND_RELATION &&
5018 kgrittn@postgresql.o 258 [ + + ]: 11584 : event_relation->rd_rel->relkind != RELKIND_MATVIEW &&
3643 rhaas@postgresql.org 259 [ + + ]: 11297 : event_relation->rd_rel->relkind != RELKIND_VIEW &&
260 [ - + ]: 8 : event_relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
6408 tgl@sss.pgh.pa.us 261 [ # # ]:UBC 0 : ereport(ERROR,
262 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
263 : : errmsg("relation \"%s\" cannot have rules",
264 : : RelationGetRelationName(event_relation)),
265 : : errdetail_relkind_not_supported(event_relation->rd_rel->relkind)));
266 : :
149 akapila@postgresql.o 267 [ + + ]:GNC 12015 : if (IsConflictLogTableClass(event_relation->rd_rel))
268 [ + - ]: 4 : ereport(ERROR,
269 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
270 : : errmsg("conflict log table \"%s\" cannot have rules",
271 : : RelationGetRelationName(event_relation)),
272 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
273 : :
6408 tgl@sss.pgh.pa.us 274 [ + + + + ]:CBC 12011 : if (!allowSystemTableMods && IsSystemRelation(event_relation))
275 [ + - ]: 1 : ereport(ERROR,
276 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
277 : : errmsg("permission denied: \"%s\" is a system catalog",
278 : : RelationGetRelationName(event_relation))));
279 : :
280 : : /*
281 : : * Check user has permission to apply rules to this relation.
282 : : */
1476 peter@eisentraut.org 283 [ - + ]: 12010 : if (!object_ownercheck(RelationRelationId, event_relid, GetUserId()))
3283 peter_e@gmx.net 284 :UBC 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(event_relation->rd_rel->relkind),
8520 tgl@sss.pgh.pa.us 285 : 0 : RelationGetRelationName(event_relation));
286 : :
287 : : /*
288 : : * No rule actions that modify OLD or NEW
289 : : */
9647 tgl@sss.pgh.pa.us 290 [ + - + + :CBC 24050 : foreach(l, action)
+ + ]
291 : : {
3519 292 : 12040 : query = lfirst_node(Query, l);
9489 293 [ + + ]: 12040 : if (query->resultRelation == 0)
294 : 11509 : continue;
295 : : /* Don't be fooled by INSERT/SELECT */
296 [ + + ]: 531 : if (query != getInsertSelectQuery(query, NULL))
297 : 39 : continue;
9573 298 [ - + ]: 492 : if (query->resultRelation == PRS2_OLD_VARNO)
8527 tgl@sss.pgh.pa.us 299 [ # # ]:UBC 0 : ereport(ERROR,
300 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
301 : : errmsg("rule actions on OLD are not implemented"),
302 : : errhint("Use views or triggers instead.")));
9573 tgl@sss.pgh.pa.us 303 [ - + ]:CBC 492 : if (query->resultRelation == PRS2_NEW_VARNO)
8527 tgl@sss.pgh.pa.us 304 [ # # ]:UBC 0 : ereport(ERROR,
305 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
306 : : errmsg("rule actions on NEW are not implemented"),
307 : : errhint("Use triggers instead.")));
308 : : }
309 : :
10315 bruce@momjian.us 310 [ + + ]:CBC 12010 : if (event_type == CMD_SELECT)
311 : : {
312 : : /*
313 : : * Rules ON SELECT are restricted to view definitions
314 : : *
315 : : * So this had better be a view, ...
316 : : */
1457 tgl@sss.pgh.pa.us 317 [ + + ]: 11298 : if (event_relation->rd_rel->relkind != RELKIND_VIEW &&
318 [ + + ]: 299 : event_relation->rd_rel->relkind != RELKIND_MATVIEW)
319 [ + - ]: 12 : ereport(ERROR,
320 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
321 : : errmsg("relation \"%s\" cannot have ON SELECT rules",
322 : : RelationGetRelationName(event_relation)),
323 : : errdetail_relkind_not_supported(event_relation->rd_rel->relkind)));
324 : :
325 : : /*
326 : : * ... there cannot be INSTEAD NOTHING, ...
327 : : */
1564 328 [ - + ]: 11286 : if (action == NIL)
8527 tgl@sss.pgh.pa.us 329 [ # # ]:UBC 0 : ereport(ERROR,
330 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
331 : : errmsg("INSTEAD NOTHING rules on SELECT are not implemented"),
332 : : errhint("Use views instead.")));
333 : :
334 : : /*
335 : : * ... there cannot be multiple actions, ...
336 : : */
8217 neilc@samurai.com 337 [ - + ]:CBC 11286 : if (list_length(action) > 1)
8527 tgl@sss.pgh.pa.us 338 [ # # ]:UBC 0 : ereport(ERROR,
339 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
340 : : errmsg("multiple actions for rules on SELECT are not implemented")));
341 : :
342 : : /*
343 : : * ... the one action must be a SELECT, ...
344 : : */
3519 tgl@sss.pgh.pa.us 345 :CBC 11286 : query = linitial_node(Query, action);
7413 346 [ + - ]: 11286 : if (!is_instead ||
3605 347 [ - + ]: 11286 : query->commandType != CMD_SELECT)
8527 tgl@sss.pgh.pa.us 348 [ # # ]:UBC 0 : ereport(ERROR,
349 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
350 : : errmsg("rules on SELECT must have action INSTEAD SELECT")));
351 : :
352 : : /*
353 : : * ... it cannot contain data-modifying WITH ...
354 : : */
5755 tgl@sss.pgh.pa.us 355 [ - + ]:CBC 11286 : if (query->hasModifyingCTE)
5755 tgl@sss.pgh.pa.us 356 [ # # ]:UBC 0 : ereport(ERROR,
357 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
358 : : errmsg("rules on SELECT must not contain data-modifying statements in WITH")));
359 : :
360 : : /*
361 : : * ... there can be no rule qual, ...
362 : : */
10284 bruce@momjian.us 363 [ - + ]:CBC 11286 : if (event_qual != NULL)
8527 tgl@sss.pgh.pa.us 364 [ # # ]:UBC 0 : ereport(ERROR,
365 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
366 : : errmsg("event qualifications are not implemented for rules on SELECT")));
367 : :
368 : : /*
369 : : * ... the targetlist of the SELECT action must exactly match the
370 : : * event relation, ...
371 : : */
7392 tgl@sss.pgh.pa.us 372 :CBC 11286 : checkRuleResultList(query->targetList,
373 : : RelationGetDescr(event_relation),
374 : : true,
4772 kgrittn@postgresql.o 375 : 11286 : event_relation->rd_rel->relkind !=
376 : : RELKIND_MATVIEW);
377 : :
378 : : /*
379 : : * ... there must not be another ON SELECT rule already ...
380 : : */
8853 tgl@sss.pgh.pa.us 381 [ + + - + ]: 11286 : if (!replace && event_relation->rd_rules != NULL)
382 : : {
383 : : int i;
384 : :
10049 bruce@momjian.us 385 [ # # ]:UBC 0 : for (i = 0; i < event_relation->rd_rules->numLocks; i++)
386 : : {
387 : : RewriteRule *rule;
388 : :
10284 389 : 0 : rule = event_relation->rd_rules->rules[i];
390 [ # # ]: 0 : if (rule->event == CMD_SELECT)
8527 tgl@sss.pgh.pa.us 391 [ # # ]: 0 : ereport(ERROR,
392 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
393 : : errmsg("\"%s\" is already a view",
394 : : RelationGetRelationName(event_relation))));
395 : : }
396 : : }
397 : :
398 : : /*
399 : : * ... and finally the rule must be named _RETURN.
400 : : */
7200 tgl@sss.pgh.pa.us 401 [ - + ]:CBC 11286 : if (strcmp(rulename, ViewSelectRuleName) != 0)
147 tgl@sss.pgh.pa.us 402 [ # # ]:UBC 0 : ereport(ERROR,
403 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
404 : : errmsg("view rule for \"%s\" must be named \"%s\"",
405 : : RelationGetRelationName(event_relation),
406 : : ViewSelectRuleName)));
407 : : }
408 : : else
409 : : {
410 : : /*
411 : : * For non-SELECT rules, a RETURNING list can appear in at most one of
412 : : * the actions ... and there can't be any RETURNING list at all in a
413 : : * conditional or non-INSTEAD rule. (Actually, there can be at most
414 : : * one RETURNING list across all rules on the same event, but it seems
415 : : * best to enforce that at rule expansion time.) If there is a
416 : : * RETURNING list, it must match the event relation.
417 : : */
7360 bruce@momjian.us 418 :CBC 712 : bool haveReturning = false;
419 : :
7392 tgl@sss.pgh.pa.us 420 [ + - + + : 1450 : foreach(l, action)
+ + ]
421 : : {
3519 422 : 742 : query = lfirst_node(Query, l);
423 : :
7392 424 [ + + ]: 742 : if (!query->returningList)
425 : 652 : continue;
426 [ - + ]: 90 : if (haveReturning)
7392 tgl@sss.pgh.pa.us 427 [ # # ]:UBC 0 : ereport(ERROR,
428 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
429 : : errmsg("cannot have multiple RETURNING lists in a rule")));
7392 tgl@sss.pgh.pa.us 430 :CBC 90 : haveReturning = true;
431 [ - + ]: 90 : if (event_qual != NULL)
7392 tgl@sss.pgh.pa.us 432 [ # # ]:UBC 0 : ereport(ERROR,
433 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
434 : : errmsg("RETURNING lists are not supported in conditional rules")));
7392 tgl@sss.pgh.pa.us 435 [ - + ]:CBC 90 : if (!is_instead)
7392 tgl@sss.pgh.pa.us 436 [ # # ]:UBC 0 : ereport(ERROR,
437 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
438 : : errmsg("RETURNING lists are not supported in non-INSTEAD rules")));
7392 tgl@sss.pgh.pa.us 439 :CBC 90 : checkRuleResultList(query->returningList,
440 : : RelationGetDescr(event_relation),
441 : : false, false);
442 : : }
443 : :
444 : : /*
445 : : * And finally, if it's not an ON SELECT rule then it must *not* be
446 : : * named _RETURN. This prevents accidentally or maliciously replacing
447 : : * a view's ON SELECT rule with some other kind of rule.
448 : : */
1503 449 [ - + ]: 708 : if (strcmp(rulename, ViewSelectRuleName) == 0)
1503 tgl@sss.pgh.pa.us 450 [ # # ]:UBC 0 : ereport(ERROR,
451 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
452 : : errmsg("non-view rule for \"%s\" must not be named \"%s\"",
453 : : RelationGetRelationName(event_relation),
454 : : ViewSelectRuleName)));
455 : : }
456 : :
457 : : /*
458 : : * This rule is allowed - prepare to install it.
459 : : */
460 : :
461 : : /* discard rule if it's null action and not INSTEAD; it's a no-op */
9573 tgl@sss.pgh.pa.us 462 [ - + - - ]:CBC 11994 : if (action != NIL || is_instead)
463 : : {
5082 rhaas@postgresql.org 464 : 11994 : ruleId = InsertRule(rulename,
465 : : event_type,
466 : : event_relid,
467 : : is_instead,
468 : : event_qual,
469 : : action,
470 : : replace);
471 : :
472 : : /*
473 : : * Set pg_class 'relhasrules' field true for event relation.
474 : : *
475 : : * Important side effect: an SI notice is broadcast to force all
476 : : * backends (including me!) to update relcache entries with the new
477 : : * rule.
478 : : */
5018 tgl@sss.pgh.pa.us 479 : 11990 : SetRelationRuleStatus(event_relid, true);
480 : : }
481 : :
4288 alvherre@alvh.no-ip. 482 : 11990 : ObjectAddressSet(address, RewriteRelationId, ruleId);
483 : :
484 : : /* Close rel, but keep lock till commit... */
2868 andres@anarazel.de 485 : 11990 : table_close(event_relation, NoLock);
486 : :
4288 alvherre@alvh.no-ip. 487 : 11990 : return address;
488 : : }
489 : :
490 : : /*
491 : : * checkRuleResultList
492 : : * Verify that targetList produces output compatible with a tupledesc
493 : : *
494 : : * The targetList might be either a SELECT targetlist, or a RETURNING list;
495 : : * isSelect tells which. This is used for choosing error messages.
496 : : *
497 : : * A SELECT targetlist may optionally require that column names match.
498 : : */
499 : : static void
4772 kgrittn@postgresql.o 500 : 11376 : checkRuleResultList(List *targetList, TupleDesc resultDesc, bool isSelect,
501 : : bool requireColumnNameMatch)
502 : : {
503 : : ListCell *tllist;
504 : : int i;
505 : :
506 : : /* Only a SELECT may require a column name match. */
507 [ + + - + ]: 11376 : Assert(isSelect || !requireColumnNameMatch);
508 : :
7392 tgl@sss.pgh.pa.us 509 : 11376 : i = 0;
510 [ + + + + : 113448 : foreach(tllist, targetList)
+ + ]
511 : : {
512 : 102076 : TargetEntry *tle = (TargetEntry *) lfirst(tllist);
513 : : Oid tletypid;
514 : : int32 tletypmod;
515 : : Form_pg_attribute attr;
516 : : char *attname;
517 : :
518 : : /* resjunk entries may be ignored */
519 [ + + ]: 102076 : if (tle->resjunk)
520 : 400 : continue;
521 : 101676 : i++;
522 [ + + ]: 101676 : if (i > resultDesc->natts)
523 [ + - - + ]: 4 : ereport(ERROR,
524 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
525 : : isSelect ?
526 : : errmsg("SELECT rule's target list has too many entries") :
527 : : errmsg("RETURNING list has too many entries")));
528 : :
3387 andres@anarazel.de 529 : 101672 : attr = TupleDescAttr(resultDesc, i - 1);
7392 tgl@sss.pgh.pa.us 530 : 101672 : attname = NameStr(attr->attname);
531 : :
532 : : /*
533 : : * Disallow dropped columns in the relation. This is not really
534 : : * expected to happen when creating an ON SELECT rule. It'd be
535 : : * possible if someone tried to convert a relation with dropped
536 : : * columns to a view, but the only case we care about supporting
537 : : * table-to-view conversion for is pg_dump, and pg_dump won't do that.
538 : : *
539 : : * Unfortunately, the situation is also possible when adding a rule
540 : : * with RETURNING to a regular table, and rejecting that case is
541 : : * altogether more annoying. In principle we could support it by
542 : : * modifying the targetlist to include dummy NULL columns
543 : : * corresponding to the dropped columns in the tupdesc. However,
544 : : * places like ruleutils.c would have to be fixed to not process such
545 : : * entries, and that would take an uncertain and possibly rather large
546 : : * amount of work. (Note we could not dodge that by marking the dummy
547 : : * columns resjunk, since it's precisely the non-resjunk tlist columns
548 : : * that are expected to correspond to table columns.)
549 : : */
550 [ - + ]: 101672 : if (attr->attisdropped)
7392 tgl@sss.pgh.pa.us 551 [ # # # # ]:UBC 0 : ereport(ERROR,
552 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
553 : : isSelect ?
554 : : errmsg("cannot convert relation containing dropped columns to view") :
555 : : errmsg("cannot create a RETURNING list for a relation containing dropped columns")));
556 : :
557 : : /* Check name match if required; no need for two error texts here */
4772 kgrittn@postgresql.o 558 [ + + - + ]:CBC 101672 : if (requireColumnNameMatch && strcmp(tle->resname, attname) != 0)
7392 tgl@sss.pgh.pa.us 559 [ # # ]:UBC 0 : ereport(ERROR,
560 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
561 : : errmsg("SELECT rule's target entry %d has different column name from column \"%s\"",
562 : : i, attname),
563 : : errdetail("SELECT target entry is named \"%s\".",
564 : : tle->resname)));
565 : :
566 : : /* Check type match. */
4532 tgl@sss.pgh.pa.us 567 :CBC 101672 : tletypid = exprType((Node *) tle->expr);
568 [ - + ]: 101672 : if (attr->atttypid != tletypid)
7392 tgl@sss.pgh.pa.us 569 [ # # # # :UBC 0 : ereport(ERROR,
# # ]
570 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
571 : : isSelect ?
572 : : errmsg("SELECT rule's target entry %d has different type from column \"%s\"",
573 : : i, attname) :
574 : : errmsg("RETURNING list's entry %d has different type from column \"%s\"",
575 : : i, attname),
576 : : isSelect ?
577 : : errdetail("SELECT target entry has type %s, but column has type %s.",
578 : : format_type_be(tletypid),
579 : : format_type_be(attr->atttypid)) :
580 : : errdetail("RETURNING list entry has type %s, but column has type %s.",
581 : : format_type_be(tletypid),
582 : : format_type_be(attr->atttypid))));
583 : :
584 : : /*
585 : : * Allow typmods to be different only if one of them is -1, ie,
586 : : * "unspecified". This is necessary for cases like "numeric", where
587 : : * the table will have a filled-in default length but the select
588 : : * rule's expression will probably have typmod = -1.
589 : : */
7392 tgl@sss.pgh.pa.us 590 :CBC 101672 : tletypmod = exprTypmod((Node *) tle->expr);
591 [ - + ]: 101672 : if (attr->atttypmod != tletypmod &&
7392 tgl@sss.pgh.pa.us 592 [ # # # # ]:UBC 0 : attr->atttypmod != -1 && tletypmod != -1)
593 [ # # # # : 0 : ereport(ERROR,
# # ]
594 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
595 : : isSelect ?
596 : : errmsg("SELECT rule's target entry %d has different size from column \"%s\"",
597 : : i, attname) :
598 : : errmsg("RETURNING list's entry %d has different size from column \"%s\"",
599 : : i, attname),
600 : : isSelect ?
601 : : errdetail("SELECT target entry has type %s, but column has type %s.",
602 : : format_type_with_typemod(tletypid, tletypmod),
603 : : format_type_with_typemod(attr->atttypid,
604 : : attr->atttypmod)) :
605 : : errdetail("RETURNING list entry has type %s, but column has type %s.",
606 : : format_type_with_typemod(tletypid, tletypmod),
607 : : format_type_with_typemod(attr->atttypid,
608 : : attr->atttypmod))));
609 : : }
610 : :
7392 tgl@sss.pgh.pa.us 611 [ - + ]:CBC 11372 : if (i != resultDesc->natts)
7392 tgl@sss.pgh.pa.us 612 [ # # # # ]:UBC 0 : ereport(ERROR,
613 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
614 : : isSelect ?
615 : : errmsg("SELECT rule's target list has too few entries") :
616 : : errmsg("RETURNING list has too few entries")));
7392 tgl@sss.pgh.pa.us 617 :CBC 11372 : }
618 : :
619 : : /*
620 : : * setRuleCheckAsUser
621 : : * Recursively scan a query or expression tree and set the checkAsUser
622 : : * field to the given userid in all RTEPermissionInfos of the query.
623 : : */
624 : : void
7389 625 : 55500 : setRuleCheckAsUser(Node *node, Oid userid)
626 : : {
627 : 55500 : (void) setRuleCheckAsUser_walker(node, &userid);
628 : 55500 : }
629 : :
630 : : static bool
631 : 273056 : setRuleCheckAsUser_walker(Node *node, Oid *context)
632 : : {
633 [ + + ]: 273056 : if (node == NULL)
634 : 57169 : return false;
635 [ + + ]: 215887 : if (IsA(node, Query))
636 : : {
637 : 28844 : setRuleCheckAsUser_Query((Query *) node, *context);
638 : 28844 : return false;
639 : : }
640 : 187043 : return expression_tree_walker(node, setRuleCheckAsUser_walker,
641 : : context);
642 : : }
643 : :
644 : : static void
7823 645 : 41416 : setRuleCheckAsUser_Query(Query *qry, Oid userid)
646 : : {
647 : : ListCell *l;
648 : :
649 : : /* Set in all RTEPermissionInfos for this query. */
1453 alvherre@alvh.no-ip. 650 [ + + + + : 102672 : foreach(l, qry->rteperminfos)
+ + ]
651 : : {
652 : 61256 : RTEPermissionInfo *perminfo = lfirst_node(RTEPermissionInfo, l);
653 : :
654 : 61256 : perminfo->checkAsUser = userid;
655 : : }
656 : :
657 : : /* Now recurse to any subquery RTEs */
9556 tgl@sss.pgh.pa.us 658 [ + + + + : 145984 : foreach(l, qry->rtable)
+ + ]
659 : : {
660 : 104568 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
661 : :
8966 662 [ + + ]: 104568 : if (rte->rtekind == RTE_SUBQUERY)
8229 663 : 12413 : setRuleCheckAsUser_Query(rte->subquery, userid);
664 : : }
665 : :
666 : : /* Recurse into subquery-in-WITH */
6629 667 [ + + + + : 41575 : foreach(l, qry->cteList)
+ + ]
668 : : {
669 : 159 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
670 : :
3593 671 : 159 : setRuleCheckAsUser_Query(castNode(Query, cte->ctequery), userid);
672 : : }
673 : :
674 : : /* If there are sublinks, search for them and process their RTEs */
9556 675 [ + + ]: 41416 : if (qry->hasSubLinks)
730 peter@eisentraut.org 676 : 1828 : query_tree_walker(qry, setRuleCheckAsUser_walker, &userid,
677 : : QTW_IGNORE_RC_SUBQUERIES);
9556 tgl@sss.pgh.pa.us 678 : 41416 : }
679 : :
680 : :
681 : : /*
682 : : * Change the firing semantics of an existing rule.
683 : : */
684 : : void
7194 JanWieck@Yahoo.com 685 : 29 : EnableDisableRule(Relation rel, const char *rulename,
686 : : char fires_when)
687 : : {
688 : : Relation pg_rewrite_desc;
689 : 29 : Oid owningRel = RelationGetRelid(rel);
690 : : Oid eventRelationOid;
691 : : HeapTuple ruletup;
692 : : Form_pg_rewrite ruleform;
693 : 29 : bool changed = false;
694 : :
695 : : /*
696 : : * Find the rule tuple to change.
697 : : */
2868 andres@anarazel.de 698 : 29 : pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
6131 rhaas@postgresql.org 699 : 29 : ruletup = SearchSysCacheCopy2(RULERELNAME,
700 : : ObjectIdGetDatum(owningRel),
701 : : PointerGetDatum(rulename));
7194 JanWieck@Yahoo.com 702 [ - + ]: 29 : if (!HeapTupleIsValid(ruletup))
7194 JanWieck@Yahoo.com 703 [ # # ]:UBC 0 : ereport(ERROR,
704 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
705 : : errmsg("rule \"%s\" for relation \"%s\" does not exist",
706 : : rulename, get_rel_name(owningRel))));
707 : :
2930 andres@anarazel.de 708 :CBC 29 : ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
709 : :
710 : : /*
711 : : * Verify that the user has appropriate permissions.
712 : : */
713 : 29 : eventRelationOid = ruleform->ev_class;
7194 JanWieck@Yahoo.com 714 [ - + ]: 29 : Assert(eventRelationOid == owningRel);
1476 peter@eisentraut.org 715 [ - + ]: 29 : if (!object_ownercheck(RelationRelationId, eventRelationOid, GetUserId()))
3283 peter_e@gmx.net 716 :UBC 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(eventRelationOid)),
6953 bruce@momjian.us 717 : 0 : get_rel_name(eventRelationOid));
718 : :
719 : : /*
720 : : * Change ev_enabled if it is different from the desired new state.
721 : : */
477 peter@eisentraut.org 722 [ + - ]:CBC 29 : if (ruleform->ev_enabled != fires_when)
723 : : {
724 : 29 : ruleform->ev_enabled = fires_when;
3588 alvherre@alvh.no-ip. 725 : 29 : CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
726 : :
7194 JanWieck@Yahoo.com 727 : 29 : changed = true;
728 : : }
729 : :
2930 andres@anarazel.de 730 [ + + ]: 29 : InvokeObjectPostAlterHook(RewriteRelationId, ruleform->oid, 0);
731 : :
7194 JanWieck@Yahoo.com 732 : 29 : heap_freetuple(ruletup);
2868 andres@anarazel.de 733 : 29 : table_close(pg_rewrite_desc, RowExclusiveLock);
734 : :
735 : : /*
736 : : * If we changed anything, broadcast a SI inval message to force each
737 : : * backend (including our own!) to rebuild relation's relcache entry.
738 : : * Otherwise they will fail to apply the change promptly.
739 : : */
7194 JanWieck@Yahoo.com 740 [ + - ]: 29 : if (changed)
741 : 29 : CacheInvalidateRelcache(rel);
742 : 29 : }
743 : :
744 : :
745 : : /*
746 : : * Perform permissions and integrity checks before acquiring a relation lock.
747 : : */
748 : : static void
5041 tgl@sss.pgh.pa.us 749 : 30 : RangeVarCallbackForRenameRule(const RangeVar *rv, Oid relid, Oid oldrelid,
750 : : void *arg)
751 : : {
752 : : HeapTuple tuple;
753 : : Form_pg_class form;
754 : :
755 : 30 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
756 [ - + ]: 30 : if (!HeapTupleIsValid(tuple))
5041 tgl@sss.pgh.pa.us 757 :UBC 0 : return; /* concurrently dropped */
5041 tgl@sss.pgh.pa.us 758 :CBC 30 : form = (Form_pg_class) GETSTRUCT(tuple);
759 : :
760 : : /* only tables and views can have rules */
3518 rhaas@postgresql.org 761 [ + + ]: 30 : if (form->relkind != RELKIND_RELATION &&
762 [ + + ]: 20 : form->relkind != RELKIND_VIEW &&
763 [ - + ]: 4 : form->relkind != RELKIND_PARTITIONED_TABLE)
5041 tgl@sss.pgh.pa.us 764 [ # # ]:UBC 0 : ereport(ERROR,
765 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
766 : : errmsg("relation \"%s\" cannot have rules", rv->relname),
767 : : errdetail_relkind_not_supported(form->relkind)));
768 : :
149 akapila@postgresql.o 769 [ + + ]:GNC 30 : if (IsConflictLogTableClass(form))
770 [ + - ]: 4 : ereport(ERROR,
771 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
772 : : errmsg("conflict log table \"%s\" cannot have rules",
773 : : rv->relname),
774 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
775 : :
4748 rhaas@postgresql.org 776 [ + + + + ]:CBC 26 : if (!allowSystemTableMods && IsSystemClass(relid, form))
5041 tgl@sss.pgh.pa.us 777 [ + - ]: 1 : ereport(ERROR,
778 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
779 : : errmsg("permission denied: \"%s\" is a system catalog",
780 : : rv->relname)));
781 : :
782 : : /* you must own the table to rename one of its rules */
1476 peter@eisentraut.org 783 [ - + ]: 25 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
3283 peter_e@gmx.net 784 :UBC 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
785 : :
5041 tgl@sss.pgh.pa.us 786 :CBC 25 : ReleaseSysCache(tuple);
787 : : }
788 : :
789 : : /*
790 : : * Rename an existing rewrite rule.
791 : : */
792 : : ObjectAddress
793 : 30 : RenameRewriteRule(RangeVar *relation, const char *oldName,
794 : : const char *newName)
795 : : {
796 : : Oid relid;
797 : : Relation targetrel;
798 : : Relation pg_rewrite_desc;
799 : : HeapTuple ruletup;
800 : : Form_pg_rewrite ruleform;
801 : : Oid ruleOid;
802 : : ObjectAddress address;
803 : :
804 : : /*
805 : : * Look up name, check permissions, and acquire lock (which we will NOT
806 : : * release until end of transaction).
807 : : */
808 : 30 : relid = RangeVarGetRelidExtended(relation, AccessExclusiveLock,
809 : : 0,
810 : : RangeVarCallbackForRenameRule,
811 : : NULL);
812 : :
813 : : /* Have lock already, so just need to build relcache entry. */
814 : 25 : targetrel = relation_open(relid, NoLock);
815 : :
816 : : /* Prepare to modify pg_rewrite */
2868 andres@anarazel.de 817 : 25 : pg_rewrite_desc = table_open(RewriteRelationId, RowExclusiveLock);
818 : :
819 : : /* Fetch the rule's entry (it had better exist) */
6131 rhaas@postgresql.org 820 : 25 : ruletup = SearchSysCacheCopy2(RULERELNAME,
821 : : ObjectIdGetDatum(relid),
822 : : PointerGetDatum(oldName));
9239 tgl@sss.pgh.pa.us 823 [ + + ]: 25 : if (!HeapTupleIsValid(ruletup))
8527 824 [ + - ]: 4 : ereport(ERROR,
825 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
826 : : errmsg("rule \"%s\" for relation \"%s\" does not exist",
827 : : oldName, RelationGetRelationName(targetrel))));
5041 828 : 21 : ruleform = (Form_pg_rewrite) GETSTRUCT(ruletup);
2930 andres@anarazel.de 829 : 21 : ruleOid = ruleform->oid;
830 : :
831 : : /* rule with the new name should not already exist */
5041 tgl@sss.pgh.pa.us 832 [ + + ]: 21 : if (IsDefinedRewriteRule(relid, newName))
8527 833 [ + - ]: 4 : ereport(ERROR,
834 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
835 : : errmsg("rule \"%s\" for relation \"%s\" already exists",
836 : : newName, RelationGetRelationName(targetrel))));
837 : :
838 : : /*
839 : : * We disallow renaming ON SELECT rules, because they should always be
840 : : * named "_RETURN".
841 : : */
5041 842 [ + + ]: 17 : if (ruleform->ev_type == CMD_SELECT + '0')
843 [ + - ]: 4 : ereport(ERROR,
844 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
845 : : errmsg("renaming an ON SELECT rule is not allowed")));
846 : :
847 : : /*
848 : : * Conversely, if it's not an ON SELECT rule then it must *not* be named
849 : : * _RETURN.
850 : : */
147 851 [ + + ]: 13 : if (strcmp(newName, ViewSelectRuleName) == 0)
852 [ + - ]: 4 : ereport(ERROR,
853 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
854 : : errmsg("non-view rule for \"%s\" must not be named \"%s\"",
855 : : RelationGetRelationName(targetrel),
856 : : ViewSelectRuleName)));
857 : :
858 : : /* OK, do the update */
5041 859 : 9 : namestrcpy(&(ruleform->rulename), newName);
860 : :
3588 alvherre@alvh.no-ip. 861 : 9 : CatalogTupleUpdate(pg_rewrite_desc, &ruletup->t_self, ruletup);
862 : :
2380 michael@paquier.xyz 863 [ - + ]: 9 : InvokeObjectPostAlterHook(RewriteRelationId, ruleOid, 0);
864 : :
9239 tgl@sss.pgh.pa.us 865 : 9 : heap_freetuple(ruletup);
2868 andres@anarazel.de 866 : 9 : table_close(pg_rewrite_desc, RowExclusiveLock);
867 : :
868 : : /*
869 : : * Invalidate relation's relcache entry so that other backends (and this
870 : : * one too!) are sent SI message to make them rebuild relcache entries.
871 : : * (Ideally this should happen automatically...)
872 : : */
5041 tgl@sss.pgh.pa.us 873 : 9 : CacheInvalidateRelcache(targetrel);
874 : :
4288 alvherre@alvh.no-ip. 875 : 9 : ObjectAddressSet(address, RewriteRelationId, ruleOid);
876 : :
877 : : /*
878 : : * Close rel, but keep exclusive lock!
879 : : */
5041 tgl@sss.pgh.pa.us 880 : 9 : relation_close(targetrel, NoLock);
881 : :
4288 alvherre@alvh.no-ip. 882 : 9 : return address;
883 : : }
|