Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * tablecmds.c
4 : : * Commands for creating and altering table structures and settings
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/commands/tablecmds.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/attmap.h"
18 : : #include "access/genam.h"
19 : : #include "access/gist.h"
20 : : #include "access/heapam.h"
21 : : #include "access/heapam_xlog.h"
22 : : #include "access/multixact.h"
23 : : #include "access/reloptions.h"
24 : : #include "access/relscan.h"
25 : : #include "access/sysattr.h"
26 : : #include "access/tableam.h"
27 : : #include "access/toast_compression.h"
28 : : #include "access/tupconvert.h"
29 : : #include "access/xact.h"
30 : : #include "access/xlog.h"
31 : : #include "access/xloginsert.h"
32 : : #include "catalog/catalog.h"
33 : : #include "catalog/heap.h"
34 : : #include "catalog/index.h"
35 : : #include "catalog/namespace.h"
36 : : #include "catalog/objectaccess.h"
37 : : #include "catalog/partition.h"
38 : : #include "catalog/pg_am.h"
39 : : #include "catalog/pg_attrdef.h"
40 : : #include "catalog/pg_cast.h"
41 : : #include "catalog/pg_collation.h"
42 : : #include "catalog/pg_constraint.h"
43 : : #include "catalog/pg_depend.h"
44 : : #include "catalog/pg_foreign_table.h"
45 : : #include "catalog/pg_inherits.h"
46 : : #include "catalog/pg_largeobject.h"
47 : : #include "catalog/pg_largeobject_metadata.h"
48 : : #include "catalog/pg_namespace.h"
49 : : #include "catalog/pg_opclass.h"
50 : : #include "catalog/pg_operator.h"
51 : : #include "catalog/pg_partitioned_table.h"
52 : : #include "catalog/pg_policy.h"
53 : : #include "catalog/pg_proc.h"
54 : : #include "catalog/pg_publication_rel.h"
55 : : #include "catalog/pg_rewrite.h"
56 : : #include "catalog/pg_statistic_ext.h"
57 : : #include "catalog/pg_tablespace.h"
58 : : #include "catalog/pg_trigger.h"
59 : : #include "catalog/pg_type.h"
60 : : #include "catalog/storage.h"
61 : : #include "catalog/storage_xlog.h"
62 : : #include "catalog/toasting.h"
63 : : #include "commands/comment.h"
64 : : #include "commands/defrem.h"
65 : : #include "commands/event_trigger.h"
66 : : #include "commands/repack.h"
67 : : #include "commands/sequence.h"
68 : : #include "commands/tablecmds.h"
69 : : #include "commands/tablespace.h"
70 : : #include "commands/trigger.h"
71 : : #include "commands/typecmds.h"
72 : : #include "commands/user.h"
73 : : #include "commands/vacuum.h"
74 : : #include "common/int.h"
75 : : #include "executor/executor.h"
76 : : #include "foreign/fdwapi.h"
77 : : #include "foreign/foreign.h"
78 : : #include "miscadmin.h"
79 : : #include "nodes/makefuncs.h"
80 : : #include "nodes/nodeFuncs.h"
81 : : #include "nodes/parsenodes.h"
82 : : #include "optimizer/optimizer.h"
83 : : #include "parser/parse_coerce.h"
84 : : #include "parser/parse_collate.h"
85 : : #include "parser/parse_expr.h"
86 : : #include "parser/parse_relation.h"
87 : : #include "parser/parse_type.h"
88 : : #include "parser/parse_utilcmd.h"
89 : : #include "parser/parser.h"
90 : : #include "partitioning/partbounds.h"
91 : : #include "partitioning/partdesc.h"
92 : : #include "pgstat.h"
93 : : #include "rewrite/rewriteDefine.h"
94 : : #include "rewrite/rewriteHandler.h"
95 : : #include "rewrite/rewriteManip.h"
96 : : #include "storage/bufmgr.h"
97 : : #include "storage/lmgr.h"
98 : : #include "storage/lock.h"
99 : : #include "storage/predicate.h"
100 : : #include "storage/smgr.h"
101 : : #include "tcop/utility.h"
102 : : #include "utils/acl.h"
103 : : #include "utils/builtins.h"
104 : : #include "utils/fmgroids.h"
105 : : #include "utils/inval.h"
106 : : #include "utils/lsyscache.h"
107 : : #include "utils/memutils.h"
108 : : #include "utils/partcache.h"
109 : : #include "utils/relcache.h"
110 : : #include "utils/ruleutils.h"
111 : : #include "utils/snapmgr.h"
112 : : #include "utils/syscache.h"
113 : : #include "utils/timestamp.h"
114 : : #include "utils/typcache.h"
115 : : #include "utils/usercontext.h"
116 : :
117 : : /*
118 : : * ON COMMIT action list
119 : : */
120 : : typedef struct OnCommitItem
121 : : {
122 : : Oid relid; /* relid of relation */
123 : : OnCommitAction oncommit; /* what to do at end of xact */
124 : :
125 : : /*
126 : : * If this entry was created during the current transaction,
127 : : * creating_subid is the ID of the creating subxact; if created in a prior
128 : : * transaction, creating_subid is zero. If deleted during the current
129 : : * transaction, deleting_subid is the ID of the deleting subxact; if no
130 : : * deletion request is pending, deleting_subid is zero.
131 : : */
132 : : SubTransactionId creating_subid;
133 : : SubTransactionId deleting_subid;
134 : : } OnCommitItem;
135 : :
136 : : static List *on_commits = NIL;
137 : :
138 : :
139 : : /*
140 : : * State information for ALTER TABLE
141 : : *
142 : : * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
143 : : * structs, one for each table modified by the operation (the named table
144 : : * plus any child tables that are affected). We save lists of subcommands
145 : : * to apply to this table (possibly modified by parse transformation steps);
146 : : * these lists will be executed in Phase 2. If a Phase 3 step is needed,
147 : : * necessary information is stored in the constraints and newvals lists.
148 : : *
149 : : * Phase 2 is divided into multiple passes; subcommands are executed in
150 : : * a pass determined by subcommand type.
151 : : */
152 : :
153 : : typedef enum AlterTablePass
154 : : {
155 : : AT_PASS_UNSET = -1, /* UNSET will cause ERROR */
156 : : AT_PASS_DROP, /* DROP (all flavors) */
157 : : AT_PASS_ALTER_TYPE, /* ALTER COLUMN TYPE */
158 : : AT_PASS_ADD_COL, /* ADD COLUMN */
159 : : AT_PASS_SET_EXPRESSION, /* ALTER SET EXPRESSION */
160 : : AT_PASS_OLD_INDEX, /* re-add existing indexes */
161 : : AT_PASS_OLD_CONSTR, /* re-add existing constraints */
162 : : /* We could support a RENAME COLUMN pass here, but not currently used */
163 : : AT_PASS_ADD_CONSTR, /* ADD constraints (initial examination) */
164 : : AT_PASS_COL_ATTRS, /* set column attributes, eg NOT NULL */
165 : : AT_PASS_ADD_INDEXCONSTR, /* ADD index-based constraints */
166 : : AT_PASS_ADD_INDEX, /* ADD indexes */
167 : : AT_PASS_ADD_OTHERCONSTR, /* ADD other constraints, defaults */
168 : : AT_PASS_MISC, /* other stuff */
169 : : } AlterTablePass;
170 : :
171 : : #define AT_NUM_PASSES (AT_PASS_MISC + 1)
172 : :
173 : : typedef struct AlteredTableInfo
174 : : {
175 : : /* Information saved before any work commences: */
176 : : Oid relid; /* Relation to work on */
177 : : char relkind; /* Its relkind */
178 : : TupleDesc oldDesc; /* Pre-modification tuple descriptor */
179 : :
180 : : /*
181 : : * Transiently set during Phase 2, normally set to NULL.
182 : : *
183 : : * ATRewriteCatalogs sets this when it starts, and closes when ATExecCmd
184 : : * returns control. This can be exploited by ATExecCmd subroutines to
185 : : * close/reopen across transaction boundaries.
186 : : */
187 : : Relation rel;
188 : :
189 : : /* Information saved by Phase 1 for Phase 2: */
190 : : List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
191 : : /* Information saved by Phases 1/2 for Phase 3: */
192 : : List *constraints; /* List of NewConstraint */
193 : : List *newvals; /* List of NewColumnValue */
194 : : List *afterStmts; /* List of utility command parsetrees */
195 : : bool verify_new_notnull; /* T if we should recheck NOT NULL */
196 : : int rewrite; /* Reason for forced rewrite, if any */
197 : : bool chgAccessMethod; /* T if SET ACCESS METHOD is used */
198 : : Oid newAccessMethod; /* new access method; 0 means no change,
199 : : * if above is true */
200 : : Oid newTableSpace; /* new tablespace; 0 means no change */
201 : : bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
202 : : char newrelpersistence; /* if above is true */
203 : : Expr *partition_constraint; /* for attach partition validation */
204 : : /* true, if validating default due to some other attach/detach */
205 : : bool validate_default;
206 : : /* Objects to rebuild after ALTER TYPE or SET EXPRESSION operations */
207 : : List *changedConstraintOids; /* OIDs of constraints to rebuild */
208 : : List *changedConstraintDefs; /* string definitions of same */
209 : : List *changedIndexOids; /* OIDs of indexes to rebuild */
210 : : List *changedIndexDefs; /* string definitions of same */
211 : : char *replicaIdentityIndex; /* index to reset as REPLICA IDENTITY */
212 : : char *clusterOnIndex; /* index to use for CLUSTER */
213 : : List *changedStatisticsOids; /* OIDs of statistics to rebuild */
214 : : List *changedStatisticsDefs; /* string definitions of same */
215 : : List *changedStatisticsOwners; /* owners of same */
216 : : } AlteredTableInfo;
217 : :
218 : : /* Struct describing one new constraint to check in Phase 3 scan */
219 : : /* Note: new not-null constraints are handled elsewhere */
220 : : typedef struct NewConstraint
221 : : {
222 : : char *name; /* Constraint name, or NULL if none */
223 : : ConstrType contype; /* CHECK or FOREIGN */
224 : : Oid refrelid; /* PK rel, if FOREIGN */
225 : : Oid refindid; /* OID of PK's index, if FOREIGN */
226 : : bool conwithperiod; /* Whether the new FOREIGN KEY uses PERIOD */
227 : : Oid conid; /* OID of pg_constraint entry, if FOREIGN */
228 : : Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
229 : : ExprState *qualstate; /* Execution state for CHECK expr */
230 : : } NewConstraint;
231 : :
232 : : /*
233 : : * Struct describing one new column value that needs to be computed during
234 : : * Phase 3 copy (this could be either a new column with a non-null default, or
235 : : * a column that we're changing the type of). Columns without such an entry
236 : : * are just copied from the old table during ATRewriteTable. Note that the
237 : : * expr is an expression over *old* table values, except when is_generated
238 : : * is true; then it is an expression over columns of the *new* tuple.
239 : : */
240 : : typedef struct NewColumnValue
241 : : {
242 : : AttrNumber attnum; /* which column */
243 : : Expr *expr; /* expression to compute */
244 : : ExprState *exprstate; /* execution state */
245 : : bool is_generated; /* is it a GENERATED expression? */
246 : : } NewColumnValue;
247 : :
248 : : /*
249 : : * Error-reporting support for RemoveRelations
250 : : */
251 : : struct dropmsgstrings
252 : : {
253 : : char kind;
254 : : int nonexistent_code;
255 : : const char *nonexistent_msg;
256 : : const char *skipping_msg;
257 : : const char *nota_msg;
258 : : const char *drophint_msg;
259 : : };
260 : :
261 : : static const struct dropmsgstrings dropmsgstringarray[] = {
262 : : {RELKIND_RELATION,
263 : : ERRCODE_UNDEFINED_TABLE,
264 : : gettext_noop("table \"%s\" does not exist"),
265 : : gettext_noop("table \"%s\" does not exist, skipping"),
266 : : gettext_noop("\"%s\" is not a table"),
267 : : gettext_noop("Use DROP TABLE to remove a table.")},
268 : : {RELKIND_SEQUENCE,
269 : : ERRCODE_UNDEFINED_TABLE,
270 : : gettext_noop("sequence \"%s\" does not exist"),
271 : : gettext_noop("sequence \"%s\" does not exist, skipping"),
272 : : gettext_noop("\"%s\" is not a sequence"),
273 : : gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
274 : : {RELKIND_VIEW,
275 : : ERRCODE_UNDEFINED_TABLE,
276 : : gettext_noop("view \"%s\" does not exist"),
277 : : gettext_noop("view \"%s\" does not exist, skipping"),
278 : : gettext_noop("\"%s\" is not a view"),
279 : : gettext_noop("Use DROP VIEW to remove a view.")},
280 : : {RELKIND_MATVIEW,
281 : : ERRCODE_UNDEFINED_TABLE,
282 : : gettext_noop("materialized view \"%s\" does not exist"),
283 : : gettext_noop("materialized view \"%s\" does not exist, skipping"),
284 : : gettext_noop("\"%s\" is not a materialized view"),
285 : : gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
286 : : {RELKIND_INDEX,
287 : : ERRCODE_UNDEFINED_OBJECT,
288 : : gettext_noop("index \"%s\" does not exist"),
289 : : gettext_noop("index \"%s\" does not exist, skipping"),
290 : : gettext_noop("\"%s\" is not an index"),
291 : : gettext_noop("Use DROP INDEX to remove an index.")},
292 : : {RELKIND_COMPOSITE_TYPE,
293 : : ERRCODE_UNDEFINED_OBJECT,
294 : : gettext_noop("type \"%s\" does not exist"),
295 : : gettext_noop("type \"%s\" does not exist, skipping"),
296 : : gettext_noop("\"%s\" is not a type"),
297 : : gettext_noop("Use DROP TYPE to remove a type.")},
298 : : {RELKIND_FOREIGN_TABLE,
299 : : ERRCODE_UNDEFINED_OBJECT,
300 : : gettext_noop("foreign table \"%s\" does not exist"),
301 : : gettext_noop("foreign table \"%s\" does not exist, skipping"),
302 : : gettext_noop("\"%s\" is not a foreign table"),
303 : : gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
304 : : {RELKIND_PARTITIONED_TABLE,
305 : : ERRCODE_UNDEFINED_TABLE,
306 : : gettext_noop("table \"%s\" does not exist"),
307 : : gettext_noop("table \"%s\" does not exist, skipping"),
308 : : gettext_noop("\"%s\" is not a table"),
309 : : gettext_noop("Use DROP TABLE to remove a table.")},
310 : : {RELKIND_PARTITIONED_INDEX,
311 : : ERRCODE_UNDEFINED_OBJECT,
312 : : gettext_noop("index \"%s\" does not exist"),
313 : : gettext_noop("index \"%s\" does not exist, skipping"),
314 : : gettext_noop("\"%s\" is not an index"),
315 : : gettext_noop("Use DROP INDEX to remove an index.")},
316 : : {'\0', 0, NULL, NULL, NULL, NULL}
317 : : };
318 : :
319 : : /* communication between RemoveRelations and RangeVarCallbackForDropRelation */
320 : : struct DropRelationCallbackState
321 : : {
322 : : /* These fields are set by RemoveRelations: */
323 : : char expected_relkind;
324 : : LOCKMODE heap_lockmode;
325 : : /* These fields are state to track which subsidiary locks are held: */
326 : : Oid heapOid;
327 : : Oid partParentOid;
328 : : /* These fields are passed back by RangeVarCallbackForDropRelation: */
329 : : char actual_relkind;
330 : : char actual_relpersistence;
331 : : };
332 : :
333 : : /* Alter table target-type flags for ATSimplePermissions */
334 : : #define ATT_TABLE 0x0001
335 : : #define ATT_VIEW 0x0002
336 : : #define ATT_MATVIEW 0x0004
337 : : #define ATT_INDEX 0x0008
338 : : #define ATT_COMPOSITE_TYPE 0x0010
339 : : #define ATT_FOREIGN_TABLE 0x0020
340 : : #define ATT_PARTITIONED_INDEX 0x0040
341 : : #define ATT_SEQUENCE 0x0080
342 : : #define ATT_PARTITIONED_TABLE 0x0100
343 : :
344 : : /*
345 : : * ForeignTruncateInfo
346 : : *
347 : : * Information related to truncation of foreign tables. This is used for
348 : : * the elements in a hash table. It uses the server OID as lookup key,
349 : : * and includes a per-server list of all foreign tables involved in the
350 : : * truncation.
351 : : */
352 : : typedef struct ForeignTruncateInfo
353 : : {
354 : : Oid serverid;
355 : : List *rels;
356 : : } ForeignTruncateInfo;
357 : :
358 : : /* Partial or complete FK creation in addFkConstraint() */
359 : : typedef enum addFkConstraintSides
360 : : {
361 : : addFkReferencedSide,
362 : : addFkReferencingSide,
363 : : addFkBothSides,
364 : : } addFkConstraintSides;
365 : :
366 : : /*
367 : : * Partition tables are expected to be dropped when the parent partitioned
368 : : * table gets dropped. Hence for partitioning we use AUTO dependency.
369 : : * Otherwise, for regular inheritance use NORMAL dependency.
370 : : */
371 : : #define child_dependency_type(child_is_partition) \
372 : : ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
373 : :
374 : : static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
375 : : static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
376 : : static void truncate_check_activity(Relation rel);
377 : : static void RangeVarCallbackForTruncate(const RangeVar *relation,
378 : : Oid relId, Oid oldRelId, void *arg);
379 : : static List *MergeAttributes(List *columns, const List *supers, char relpersistence,
380 : : bool is_partition, List **supconstr,
381 : : List **supnotnulls);
382 : : static List *MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced);
383 : : static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef);
384 : : static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
385 : : static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
386 : : static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
387 : : static void StoreCatalogInheritance(Oid relationId, List *supers,
388 : : bool child_is_partition);
389 : : static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
390 : : int32 seqNumber, Relation inhRelation,
391 : : bool child_is_partition);
392 : : static int findAttrByName(const char *attributeName, const List *columns);
393 : : static void AlterIndexNamespaces(Relation classRel, Relation rel,
394 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
395 : : static void AlterSeqNamespaces(Relation classRel, Relation rel,
396 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
397 : : LOCKMODE lockmode);
398 : : static ObjectAddress ATExecAlterConstraint(List **wqueue, Relation rel,
399 : : ATAlterConstraint *cmdcon,
400 : : bool recurse, LOCKMODE lockmode);
401 : : static bool ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel,
402 : : Relation tgrel, Relation rel, HeapTuple contuple,
403 : : bool recurse, LOCKMODE lockmode);
404 : : static bool ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
405 : : Relation conrel, Relation tgrel,
406 : : Oid fkrelid, Oid pkrelid,
407 : : HeapTuple contuple, LOCKMODE lockmode,
408 : : Oid ReferencedParentDelTrigger,
409 : : Oid ReferencedParentUpdTrigger,
410 : : Oid ReferencingParentInsTrigger,
411 : : Oid ReferencingParentUpdTrigger);
412 : : static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
413 : : Relation conrel, HeapTuple contuple,
414 : : bool recurse, bool recursing,
415 : : List *changing_conids,
416 : : LOCKMODE lockmode);
417 : : static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
418 : : Relation conrel, Relation tgrel, Relation rel,
419 : : HeapTuple contuple, bool recurse,
420 : : List **otherrelids, LOCKMODE lockmode);
421 : : static bool ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
422 : : Relation conrel, Relation rel,
423 : : HeapTuple contuple, LOCKMODE lockmode);
424 : : static void AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
425 : : bool deferrable, bool initdeferred,
426 : : List **otherrelids);
427 : : static void AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
428 : : Relation conrel, Relation tgrel,
429 : : Oid fkrelid, Oid pkrelid,
430 : : HeapTuple contuple, LOCKMODE lockmode,
431 : : Oid ReferencedParentDelTrigger,
432 : : Oid ReferencedParentUpdTrigger,
433 : : Oid ReferencingParentInsTrigger,
434 : : Oid ReferencingParentUpdTrigger);
435 : : static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
436 : : Relation conrel, Oid conrelid,
437 : : bool recurse, bool recursing,
438 : : List *changing_conids,
439 : : LOCKMODE lockmode);
440 : : static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
441 : : Relation conrel, Relation tgrel, Relation rel,
442 : : HeapTuple contuple, bool recurse,
443 : : List **otherrelids, LOCKMODE lockmode);
444 : : static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
445 : : HeapTuple contuple);
446 : : static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel,
447 : : HeapTuple contuple,
448 : : List *changing_conids,
449 : : Oid *enforced_parentoid);
450 : : static ObjectAddress ATExecValidateConstraint(List **wqueue,
451 : : Relation rel, char *constrName,
452 : : bool recurse, bool recursing, LOCKMODE lockmode);
453 : : static void QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
454 : : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode);
455 : : static void QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
456 : : char *constrName, HeapTuple contuple,
457 : : bool recurse, bool recursing, LOCKMODE lockmode);
458 : : static void QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
459 : : HeapTuple contuple, bool recurse, bool recursing,
460 : : LOCKMODE lockmode);
461 : : static bool constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc);
462 : : static int transformColumnNameList(Oid relId, List *colList,
463 : : int16 *attnums, Oid *atttypids, Oid *attcollids);
464 : : static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
465 : : List **attnamelist,
466 : : int16 *attnums, Oid *atttypids, Oid *attcollids,
467 : : Oid *opclasses, bool *pk_has_without_overlaps);
468 : : static Oid transformFkeyCheckAttrs(Relation pkrel,
469 : : int numattrs, int16 *attnums,
470 : : bool with_period, Oid *opclasses,
471 : : bool *pk_has_without_overlaps);
472 : : static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
473 : : static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
474 : : Oid *funcid);
475 : : static void validateForeignKeyConstraint(char *conname,
476 : : Relation rel, Relation pkrel,
477 : : Oid pkindOid, Oid constraintOid, bool hasperiod);
478 : : static void CheckAlterTableIsSafe(Relation rel);
479 : : static void ATController(AlterTableStmt *parsetree,
480 : : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
481 : : AlterTableUtilityContext *context);
482 : : static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
483 : : bool recurse, bool recursing, LOCKMODE lockmode,
484 : : AlterTableUtilityContext *context);
485 : : static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
486 : : AlterTableUtilityContext *context);
487 : : static void ATExecCmd(List **wqueue, AlteredTableInfo *tab,
488 : : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
489 : : AlterTableUtilityContext *context);
490 : : static AlterTableCmd *ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab,
491 : : Relation rel, AlterTableCmd *cmd,
492 : : bool recurse, LOCKMODE lockmode,
493 : : AlterTablePass cur_pass,
494 : : AlterTableUtilityContext *context);
495 : : static void ATRewriteTables(AlterTableStmt *parsetree,
496 : : List **wqueue, LOCKMODE lockmode,
497 : : AlterTableUtilityContext *context);
498 : : static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
499 : : static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
500 : : static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets);
501 : : static void ATSimpleRecursion(List **wqueue, Relation rel,
502 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
503 : : AlterTableUtilityContext *context);
504 : : static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
505 : : static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
506 : : LOCKMODE lockmode,
507 : : AlterTableUtilityContext *context);
508 : : static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
509 : : DropBehavior behavior);
510 : : static void find_composite_type_dependencies_recurse(Oid typeOid, Relation origRelation,
511 : : const char *origTypeName, HTAB *visited);
512 : : static void check_composite_type_dependency(ObjectAddress *depobj, Oid typeOid,
513 : : Relation origRelation, const char *origTypeName,
514 : : HTAB *visited);
515 : : static void report_type_used_in_column(const char *relname, const char *attname,
516 : : Relation origRelation, const char *origTypeName);
517 : : static void report_type_used_in_expr(const ObjectAddress *obj, Relation origRelation,
518 : : const char *origTypeName);
519 : : static Node *get_node_tree_attr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attnum);
520 : : static void find_missing_composite_type_dependencies(HTAB *types, Relation origRelation, const char *origTypeName);
521 : : static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
522 : : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
523 : : AlterTableUtilityContext *context);
524 : : static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
525 : : Relation rel, AlterTableCmd **cmd,
526 : : bool recurse, bool recursing,
527 : : LOCKMODE lockmode, AlterTablePass cur_pass,
528 : : AlterTableUtilityContext *context);
529 : : static bool check_for_column_name_collision(Relation rel, const char *colname,
530 : : bool if_not_exists);
531 : : static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
532 : : static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
533 : : static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
534 : : LOCKMODE lockmode);
535 : : static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
536 : : bool queue_validation);
537 : : static ObjectAddress ATExecSetNotNull(List **wqueue, Relation rel,
538 : : char *conName, char *colName,
539 : : bool recurse, bool recursing,
540 : : LOCKMODE lockmode);
541 : : static bool NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr);
542 : : static bool ConstraintImpliedByRelConstraint(Relation scanrel,
543 : : List *testConstraint, List *provenConstraint);
544 : : static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
545 : : Node *newDefault, LOCKMODE lockmode);
546 : : static ObjectAddress ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
547 : : Node *newDefault);
548 : : static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
549 : : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
550 : : static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
551 : : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
552 : : static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
553 : : bool recurse, bool recursing);
554 : : static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
555 : : Node *newExpr, LOCKMODE lockmode);
556 : : static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
557 : : static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
558 : : static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
559 : : Node *newValue, LOCKMODE lockmode);
560 : : static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
561 : : Node *options, bool isReset, LOCKMODE lockmode);
562 : : static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
563 : : Node *newValue, LOCKMODE lockmode);
564 : : static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
565 : : AlterTableCmd *cmd, LOCKMODE lockmode,
566 : : AlterTableUtilityContext *context);
567 : : static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
568 : : DropBehavior behavior,
569 : : bool recurse, bool recursing,
570 : : bool missing_ok, LOCKMODE lockmode,
571 : : ObjectAddresses *addrs);
572 : : static void ATPrepAddPrimaryKey(AlteredTableInfo *tab, Relation rel,
573 : : AlterTableCmd *cmd, LOCKMODE lockmode);
574 : : static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
575 : : static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
576 : : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
577 : : static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
578 : : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
579 : : static ObjectAddress ATExecAddConstraint(List **wqueue,
580 : : AlteredTableInfo *tab, Relation rel,
581 : : Constraint *newConstraint, bool recurse, bool is_readd,
582 : : LOCKMODE lockmode);
583 : : static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
584 : : static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
585 : : IndexStmt *stmt, LOCKMODE lockmode);
586 : : static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
587 : : AlteredTableInfo *tab, Relation rel,
588 : : Constraint *constr,
589 : : bool recurse, bool recursing, bool is_readd,
590 : : LOCKMODE lockmode);
591 : : static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
592 : : Relation rel, Constraint *fkconstraint,
593 : : bool recurse, bool recursing,
594 : : LOCKMODE lockmode);
595 : : static int validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
596 : : int numfksetcols, int16 *fksetcolsattnums,
597 : : List *fksetcols);
598 : : static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
599 : : char *constraintname,
600 : : Constraint *fkconstraint, Relation rel,
601 : : Relation pkrel, Oid indexOid,
602 : : Oid parentConstr,
603 : : int numfks, int16 *pkattnum, int16 *fkattnum,
604 : : Oid *pfeqoperators, Oid *ppeqoperators,
605 : : Oid *ffeqoperators, int numfkdelsetcols,
606 : : int16 *fkdelsetcols, bool is_internal,
607 : : bool with_period);
608 : : static void addFkRecurseReferenced(Constraint *fkconstraint,
609 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
610 : : int numfks, int16 *pkattnum, int16 *fkattnum,
611 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
612 : : int numfkdelsetcols, int16 *fkdelsetcols,
613 : : bool old_check_ok,
614 : : Oid parentDelTrigger, Oid parentUpdTrigger,
615 : : bool with_period);
616 : : static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
617 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
618 : : int numfks, int16 *pkattnum, int16 *fkattnum,
619 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
620 : : int numfkdelsetcols, int16 *fkdelsetcols,
621 : : bool old_check_ok, LOCKMODE lockmode,
622 : : Oid parentInsTrigger, Oid parentUpdTrigger,
623 : : bool with_period);
624 : : static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
625 : : Relation partitionRel);
626 : : static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
627 : : static void CloneFkReferencing(List **wqueue, Relation parentRel,
628 : : Relation partRel);
629 : : static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
630 : : Constraint *fkconstraint, Oid constraintOid,
631 : : Oid indexOid,
632 : : Oid parentInsTrigger, Oid parentUpdTrigger,
633 : : Oid *insertTrigOid, Oid *updateTrigOid);
634 : : static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
635 : : Constraint *fkconstraint, Oid constraintOid,
636 : : Oid indexOid,
637 : : Oid parentDelTrigger, Oid parentUpdTrigger,
638 : : Oid *deleteTrigOid, Oid *updateTrigOid);
639 : : static bool tryAttachPartitionForeignKey(List **wqueue,
640 : : ForeignKeyCacheInfo *fk,
641 : : Relation partition,
642 : : Oid parentConstrOid, int numfks,
643 : : AttrNumber *mapped_conkey, AttrNumber *confkey,
644 : : Oid *conpfeqop,
645 : : Oid parentInsTrigger,
646 : : Oid parentUpdTrigger,
647 : : Relation trigrel);
648 : : static void AttachPartitionForeignKey(List **wqueue, Relation partition,
649 : : Oid partConstrOid, Oid parentConstrOid,
650 : : Oid parentInsTrigger, Oid parentUpdTrigger,
651 : : Relation trigrel);
652 : : static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
653 : : Oid conoid, Oid conrelid);
654 : : static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
655 : : Oid confrelid, Oid conrelid);
656 : : static void GetForeignKeyActionTriggers(Relation trigrel,
657 : : Oid conoid, Oid confrelid, Oid conrelid,
658 : : Oid *deleteTriggerOid,
659 : : Oid *updateTriggerOid);
660 : : static void GetForeignKeyCheckTriggers(Relation trigrel,
661 : : Oid conoid, Oid confrelid, Oid conrelid,
662 : : Oid *insertTriggerOid,
663 : : Oid *updateTriggerOid);
664 : : static void ATExecDropConstraint(Relation rel, const char *constrName,
665 : : DropBehavior behavior, bool recurse,
666 : : bool missing_ok, LOCKMODE lockmode);
667 : : static ObjectAddress dropconstraint_internal(Relation rel,
668 : : HeapTuple constraintTup, DropBehavior behavior,
669 : : bool recurse, bool recursing,
670 : : bool missing_ok, LOCKMODE lockmode);
671 : : static void ATPrepAlterColumnType(List **wqueue,
672 : : AlteredTableInfo *tab, Relation rel,
673 : : bool recurse, bool recursing,
674 : : AlterTableCmd *cmd, LOCKMODE lockmode,
675 : : AlterTableUtilityContext *context);
676 : : static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
677 : : static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
678 : : AlterTableCmd *cmd, LOCKMODE lockmode);
679 : : static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
680 : : Relation rel, AttrNumber attnum, const char *colName);
681 : : static void RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, Relation rel);
682 : : static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
683 : : static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
684 : : static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
685 : : static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
686 : : LOCKMODE lockmode);
687 : : static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
688 : : const char *cmdstring, List **wqueue,
689 : : LOCKMODE lockmode, bool rewrite);
690 : : static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
691 : : Oid objid, Relation rel, List *domname,
692 : : const char *conname);
693 : : static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
694 : : static void TryReuseForeignKey(Oid oldId, Constraint *con);
695 : : static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
696 : : List *options, LOCKMODE lockmode);
697 : : static void change_owner_fix_column_acls(Oid relationOid,
698 : : Oid oldOwnerId, Oid newOwnerId);
699 : : static void change_owner_recurse_to_sequences(Oid relationOid,
700 : : Oid newOwnerId, LOCKMODE lockmode);
701 : : static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
702 : : LOCKMODE lockmode);
703 : : static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
704 : : static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
705 : : static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
706 : : static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
707 : : bool toLogged);
708 : : static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
709 : : const char *tablespacename, LOCKMODE lockmode);
710 : : static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
711 : : static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
712 : : static void ATExecSetRelOptions(Relation rel, List *defList,
713 : : AlterTableType operation,
714 : : LOCKMODE lockmode);
715 : : static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
716 : : char fires_when, bool skip_system, bool recurse,
717 : : LOCKMODE lockmode);
718 : : static void ATExecEnableDisableRule(Relation rel, const char *rulename,
719 : : char fires_when, LOCKMODE lockmode);
720 : : static void ATPrepChangeInherit(Relation child_rel);
721 : : static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
722 : : static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
723 : : static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
724 : : DependencyType deptype);
725 : : static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
726 : : static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
727 : : static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
728 : : static void ATExecGenericOptions(Relation rel, List *options);
729 : : static void ATExecSetRowSecurity(Relation rel, bool rls);
730 : : static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
731 : : static ObjectAddress ATExecSetCompression(Relation rel,
732 : : const char *column, Node *newValue, LOCKMODE lockmode);
733 : :
734 : : static void index_copy_data(Relation rel, RelFileLocator newrlocator);
735 : : static const char *storage_name(char c);
736 : :
737 : : static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
738 : : Oid oldRelOid, void *arg);
739 : : static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
740 : : Oid oldrelid, void *arg);
741 : : static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
742 : : static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
743 : : List **partexprs, Oid *partopclass, Oid *partcollation,
744 : : PartitionStrategy strategy);
745 : : static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
746 : : static void RemoveInheritance(Relation child_rel, Relation parent_rel,
747 : : bool expect_detached);
748 : : static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
749 : : PartitionCmd *cmd,
750 : : AlterTableUtilityContext *context);
751 : : static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
752 : : static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
753 : : List *partConstraint,
754 : : bool validate_default);
755 : : static void CloneRowTriggersToPartition(Relation parent, Relation partition);
756 : : static void DropClonedTriggersFromPartition(Oid partitionId);
757 : : static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
758 : : Relation rel, RangeVar *name,
759 : : bool concurrent);
760 : : static void DetachPartitionFinalize(Relation rel, Relation partRel,
761 : : bool concurrent, Oid defaultPartOid);
762 : : static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
763 : : static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
764 : : RangeVar *name);
765 : : static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
766 : : static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
767 : : Relation partitionTbl);
768 : : static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
769 : : static List *GetParentedForeignKeyRefs(Relation partition);
770 : : static void ATDetachCheckNoForeignKeyRefs(Relation partition);
771 : : static char GetAttributeCompression(Oid atttypid, const char *compression);
772 : : static char GetAttributeStorage(Oid atttypid, const char *storagemode);
773 : :
774 : :
775 : : /* ----------------------------------------------------------------
776 : : * DefineRelation
777 : : * Creates a new relation.
778 : : *
779 : : * stmt carries parsetree information from an ordinary CREATE TABLE statement.
780 : : * The other arguments are used to extend the behavior for other cases:
781 : : * relkind: relkind to assign to the new relation
782 : : * ownerId: if not InvalidOid, use this as the new relation's owner.
783 : : * typaddress: if not null, it's set to the pg_type entry's address.
784 : : * queryString: for error reporting
785 : : *
786 : : * Note that permissions checks are done against current user regardless of
787 : : * ownerId. A nonzero ownerId is used when someone is creating a relation
788 : : * "on behalf of" someone else, so we still want to see that the current user
789 : : * has permissions to do it.
790 : : *
791 : : * If successful, returns the address of the new relation.
792 : : * ----------------------------------------------------------------
793 : : */
794 : : ObjectAddress
795 : 42969 : DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
796 : : ObjectAddress *typaddress, const char *queryString)
797 : : {
798 : : char relname[NAMEDATALEN];
799 : : Oid namespaceId;
800 : : Oid relationId;
801 : : Oid tablespaceId;
802 : : Relation rel;
803 : : TupleDesc descriptor;
804 : : List *inheritOids;
805 : : List *old_constraints;
806 : : List *old_notnulls;
807 : : List *rawDefaults;
808 : : List *cookedDefaults;
809 : : List *nncols;
810 : 42969 : List *connames = NIL;
811 : : Datum reloptions;
812 : : ListCell *listptr;
813 : : AttrNumber attnum;
814 : : bool partitioned;
815 : 42969 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
816 : : Oid ofTypeId;
817 : : ObjectAddress address;
818 : : LOCKMODE parentLockmode;
819 : 42969 : Oid accessMethodId = InvalidOid;
820 : :
821 : : /*
822 : : * Truncate relname to appropriate length (probably a waste of time, as
823 : : * parser should have done this already).
824 : : */
825 : 42969 : strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
826 : :
827 : : /*
828 : : * Check consistency of arguments
829 : : */
830 [ + + ]: 42969 : if (stmt->oncommit != ONCOMMIT_NOOP
831 [ + + ]: 124 : && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
832 [ + - ]: 8 : ereport(ERROR,
833 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
834 : : errmsg("ON COMMIT can only be used on temporary tables")));
835 : :
836 [ + + ]: 42961 : if (stmt->partspec != NULL)
837 : : {
838 [ - + ]: 3574 : if (relkind != RELKIND_RELATION)
839 [ # # ]: 0 : elog(ERROR, "unexpected relkind: %d", (int) relkind);
840 : :
841 : 3574 : relkind = RELKIND_PARTITIONED_TABLE;
842 : 3574 : partitioned = true;
843 : : }
844 : : else
845 : 39387 : partitioned = false;
846 : :
847 [ + + ]: 42961 : if (relkind == RELKIND_PARTITIONED_TABLE &&
848 [ + + ]: 3574 : stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
849 [ + - ]: 4 : ereport(ERROR,
850 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
851 : : errmsg("partitioned tables cannot be unlogged")));
852 : :
853 : : /*
854 : : * Look up the namespace in which we are supposed to create the relation,
855 : : * check we have permission to create there, lock it against concurrent
856 : : * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
857 : : * namespace is selected.
858 : : */
859 : : namespaceId =
860 : 42957 : RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
861 : :
862 : : /*
863 : : * Security check: disallow creating temp tables from security-restricted
864 : : * code. This is needed because calling code might not expect untrusted
865 : : * tables to appear in pg_temp at the front of its search path.
866 : : */
867 [ + + ]: 42957 : if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
868 [ - + ]: 2386 : && InSecurityRestrictedOperation())
869 [ # # ]: 0 : ereport(ERROR,
870 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
871 : : errmsg("cannot create temporary table within security-restricted operation")));
872 : :
873 : : /*
874 : : * Determine the lockmode to use when scanning parents. A self-exclusive
875 : : * lock is needed here.
876 : : *
877 : : * For regular inheritance, if two backends attempt to add children to the
878 : : * same parent simultaneously, and that parent has no pre-existing
879 : : * children, then both will attempt to update the parent's relhassubclass
880 : : * field, leading to a "tuple concurrently updated" error. Also, this
881 : : * interlocks against a concurrent ANALYZE on the parent table, which
882 : : * might otherwise be attempting to clear the parent's relhassubclass
883 : : * field, if its previous children were recently dropped.
884 : : *
885 : : * If the child table is a partition, then we instead grab an exclusive
886 : : * lock on the parent because its partition descriptor will be changed by
887 : : * addition of the new partition.
888 : : */
889 [ + + ]: 42957 : parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
890 : : ShareUpdateExclusiveLock);
891 : :
892 : : /* Determine the list of OIDs of the parents. */
893 : 42957 : inheritOids = NIL;
894 [ + + + + : 50778 : foreach(listptr, stmt->inhRelations)
+ + ]
895 : : {
896 : 7821 : RangeVar *rv = (RangeVar *) lfirst(listptr);
897 : : Oid parentOid;
898 : :
899 : 7821 : parentOid = RangeVarGetRelid(rv, parentLockmode, false);
900 : :
901 : : /*
902 : : * Reject duplications in the list of parents.
903 : : */
904 [ - + ]: 7821 : if (list_member_oid(inheritOids, parentOid))
905 [ # # ]: 0 : ereport(ERROR,
906 : : (errcode(ERRCODE_DUPLICATE_TABLE),
907 : : errmsg("relation \"%s\" would be inherited from more than once",
908 : : get_rel_name(parentOid))));
909 : :
910 : 7821 : inheritOids = lappend_oid(inheritOids, parentOid);
911 : : }
912 : :
913 : : /*
914 : : * Select tablespace to use: an explicitly indicated one, or (in the case
915 : : * of a partitioned table) the parent's, if it has one.
916 : : */
917 [ + + ]: 42957 : if (stmt->tablespacename)
918 : : {
919 : 83 : tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
920 : :
921 [ + + + + ]: 79 : if (partitioned && tablespaceId == MyDatabaseTableSpace)
922 [ + - ]: 4 : ereport(ERROR,
923 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
924 : : errmsg("cannot specify default tablespace for partitioned relations")));
925 : : }
926 [ + + ]: 42874 : else if (stmt->partbound)
927 : : {
928 : : Assert(list_length(inheritOids) == 1);
929 : 6134 : tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
930 : : }
931 : : else
932 : 36740 : tablespaceId = InvalidOid;
933 : :
934 : : /* still nothing? use the default */
935 [ + + ]: 42949 : if (!OidIsValid(tablespaceId))
936 : 42860 : tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
937 : : partitioned);
938 : :
939 : : /* Check permissions except when using database's default */
940 [ + + + + ]: 42945 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
941 : : {
942 : : AclResult aclresult;
943 : :
944 : 105 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
945 : : ACL_CREATE);
946 [ + + ]: 105 : if (aclresult != ACLCHECK_OK)
947 : 3 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
948 : 3 : get_tablespace_name(tablespaceId));
949 : : }
950 : :
951 : : /* In all cases disallow placing user relations in pg_global */
952 [ + + ]: 42942 : if (tablespaceId == GLOBALTABLESPACE_OID)
953 [ + - ]: 12 : ereport(ERROR,
954 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
955 : : errmsg("only shared relations can be placed in pg_global tablespace")));
956 : :
957 : : /* Identify user ID that will own the table */
958 [ + + ]: 42930 : if (!OidIsValid(ownerId))
959 : 42760 : ownerId = GetUserId();
960 : :
961 : : /*
962 : : * Parse and validate reloptions, if any.
963 : : */
964 : 42930 : reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
965 : : true, false);
966 : :
967 [ + + + ]: 42918 : switch (relkind)
968 : : {
969 : 10991 : case RELKIND_VIEW:
970 : 10991 : (void) view_reloptions(reloptions, true);
971 : 10979 : break;
972 : 3558 : case RELKIND_PARTITIONED_TABLE:
973 : 3558 : (void) partitioned_table_reloptions(reloptions, true);
974 : 3550 : break;
975 : 28369 : default:
976 : 28369 : (void) heap_reloptions(relkind, reloptions, true);
977 : : }
978 : :
979 [ + + ]: 42830 : if (stmt->ofTypename)
980 : : {
981 : : AclResult aclresult;
982 : :
983 : 58 : ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
984 : :
985 : 58 : aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
986 [ + + ]: 58 : if (aclresult != ACLCHECK_OK)
987 : 4 : aclcheck_error_type(aclresult, ofTypeId);
988 : : }
989 : : else
990 : 42772 : ofTypeId = InvalidOid;
991 : :
992 : : /*
993 : : * Look up inheritance ancestors and generate relation schema, including
994 : : * inherited attributes. (Note that stmt->tableElts is destructively
995 : : * modified by MergeAttributes.)
996 : : */
997 : 42662 : stmt->tableElts =
998 : 42826 : MergeAttributes(stmt->tableElts, inheritOids,
999 : 42826 : stmt->relation->relpersistence,
1000 : 42826 : stmt->partbound != NULL,
1001 : : &old_constraints, &old_notnulls);
1002 : :
1003 : : /*
1004 : : * NB: The defaults and constraints we just inherited are already cooked,
1005 : : * so they don't get the USAGE checks that AddRelationNewConstraints()
1006 : : * applies to raw ones. That's intentional: the parent's own catalog
1007 : : * entries already depend on those types, so copying them pins nothing
1008 : : * new, and creating a child requires owning the parent, anyway.
1009 : : */
1010 : :
1011 : : /*
1012 : : * Create a tuple descriptor from the relation schema. Note that this
1013 : : * deals with column names, types, and in-descriptor NOT NULL flags, but
1014 : : * not default values, NOT NULL or CHECK constraints; we handle those
1015 : : * below.
1016 : : */
1017 : 42662 : descriptor = BuildDescForRelation(stmt->tableElts);
1018 : :
1019 : : /*
1020 : : * Find columns with default values and prepare for insertion of the
1021 : : * defaults. Pre-cooked (that is, inherited) defaults go into a list of
1022 : : * CookedConstraint structs that we'll pass to heap_create_with_catalog,
1023 : : * while raw defaults go into a list of RawColumnDefault structs that will
1024 : : * be processed by AddRelationNewConstraints. (We can't deal with raw
1025 : : * expressions until we can do transformExpr.)
1026 : : */
1027 : 42630 : rawDefaults = NIL;
1028 : 42630 : cookedDefaults = NIL;
1029 : 42630 : attnum = 0;
1030 : :
1031 [ + + + + : 212139 : foreach(listptr, stmt->tableElts)
+ + ]
1032 : : {
1033 : 169509 : ColumnDef *colDef = lfirst(listptr);
1034 : :
1035 : 169509 : attnum++;
1036 [ + + ]: 169509 : if (colDef->raw_default != NULL)
1037 : : {
1038 : : RawColumnDefault *rawEnt;
1039 : :
1040 : : Assert(colDef->cooked_default == NULL);
1041 : :
1042 : 2196 : rawEnt = palloc_object(RawColumnDefault);
1043 : 2196 : rawEnt->attnum = attnum;
1044 : 2196 : rawEnt->raw_default = colDef->raw_default;
1045 : 2196 : rawEnt->generated = colDef->generated;
1046 : 2196 : rawDefaults = lappend(rawDefaults, rawEnt);
1047 : : }
1048 [ + + ]: 167313 : else if (colDef->cooked_default != NULL)
1049 : : {
1050 : : CookedConstraint *cooked;
1051 : :
1052 : 274 : cooked = palloc_object(CookedConstraint);
1053 : 274 : cooked->contype = CONSTR_DEFAULT;
1054 : 274 : cooked->conoid = InvalidOid; /* until created */
1055 : 274 : cooked->name = NULL;
1056 : 274 : cooked->attnum = attnum;
1057 : 274 : cooked->expr = colDef->cooked_default;
1058 : 274 : cooked->is_enforced = true;
1059 : 274 : cooked->skip_validation = false;
1060 : 274 : cooked->is_local = true; /* not used for defaults */
1061 : 274 : cooked->inhcount = 0; /* ditto */
1062 : 274 : cooked->is_no_inherit = false;
1063 : 274 : cookedDefaults = lappend(cookedDefaults, cooked);
1064 : : }
1065 : : }
1066 : :
1067 : 42630 : TupleDescFinalize(descriptor);
1068 : :
1069 : : /*
1070 : : * For relations with table AM and partitioned tables, select access
1071 : : * method to use: an explicitly indicated one, or (in the case of a
1072 : : * partitioned table) the parent's, if it has one.
1073 : : */
1074 [ + + ]: 42630 : if (stmt->accessMethod != NULL)
1075 : : {
1076 : : Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
1077 : 79 : accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1078 : : }
1079 [ + + + - : 42551 : else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
+ + + + ]
1080 : : {
1081 [ + + ]: 27340 : if (stmt->partbound)
1082 : : {
1083 : : Assert(list_length(inheritOids) == 1);
1084 : 6003 : accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1085 : : }
1086 : :
1087 [ + + + - : 27340 : if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
+ + + + ]
1088 : 23781 : accessMethodId = get_table_am_oid(default_table_access_method, false);
1089 : : }
1090 : :
1091 : : /*
1092 : : * Create the relation. Inherited defaults and CHECK constraints are
1093 : : * passed in for immediate handling --- since they don't need parsing,
1094 : : * they can be stored immediately.
1095 : : */
1096 : 42618 : relationId = heap_create_with_catalog(relname,
1097 : : namespaceId,
1098 : : tablespaceId,
1099 : : InvalidOid,
1100 : : InvalidOid,
1101 : : ofTypeId,
1102 : : ownerId,
1103 : : accessMethodId,
1104 : : descriptor,
1105 : : list_concat(cookedDefaults,
1106 : : old_constraints),
1107 : : relkind,
1108 : 42618 : stmt->relation->relpersistence,
1109 : : false,
1110 : : false,
1111 : : stmt->oncommit,
1112 : : reloptions,
1113 : : true,
1114 : : allowSystemTableMods,
1115 : : false,
1116 : : InvalidOid,
1117 : : typaddress);
1118 : :
1119 : : /*
1120 : : * We must bump the command counter to make the newly-created relation
1121 : : * tuple visible for opening.
1122 : : */
1123 : 42585 : CommandCounterIncrement();
1124 : :
1125 : : /*
1126 : : * Open the new relation and acquire exclusive lock on it. This isn't
1127 : : * really necessary for locking out other backends (since they can't see
1128 : : * the new rel anyway until we commit), but it keeps the lock manager from
1129 : : * complaining about deadlock risks.
1130 : : */
1131 : 42585 : rel = relation_open(relationId, AccessExclusiveLock);
1132 : :
1133 : : /*
1134 : : * Now add any newly specified column default and generation expressions
1135 : : * to the new relation. These are passed to us in the form of raw
1136 : : * parsetrees; we need to transform them to executable expression trees
1137 : : * before they can be added. The most convenient way to do that is to
1138 : : * apply the parser's transformExpr routine, but transformExpr doesn't
1139 : : * work unless we have a pre-existing relation. So, the transformation has
1140 : : * to be postponed to this final step of CREATE TABLE.
1141 : : *
1142 : : * This needs to be before processing the partitioning clauses because
1143 : : * those could refer to generated columns.
1144 : : */
1145 [ + + ]: 42585 : if (rawDefaults)
1146 : 1890 : AddRelationNewConstraints(rel, rawDefaults, NIL,
1147 : : true, true, false, queryString);
1148 : :
1149 : : /*
1150 : : * Make column generation expressions visible for use by partitioning.
1151 : : */
1152 : 42453 : CommandCounterIncrement();
1153 : :
1154 : : /* Process and store partition bound, if any. */
1155 [ + + ]: 42453 : if (stmt->partbound)
1156 : : {
1157 : : PartitionBoundSpec *bound;
1158 : : ParseState *pstate;
1159 : 6082 : Oid parentId = linitial_oid(inheritOids),
1160 : : defaultPartOid;
1161 : : Relation parent,
1162 : 6082 : defaultRel = NULL;
1163 : : ParseNamespaceItem *nsitem;
1164 : :
1165 : : /* Already have strong enough lock on the parent */
1166 : 6082 : parent = table_open(parentId, NoLock);
1167 : :
1168 : : /*
1169 : : * We are going to try to validate the partition bound specification
1170 : : * against the partition key of parentRel, so it better have one.
1171 : : */
1172 [ + + ]: 6082 : if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1173 [ + - ]: 12 : ereport(ERROR,
1174 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1175 : : errmsg("\"%s\" is not partitioned",
1176 : : RelationGetRelationName(parent))));
1177 : :
1178 : : /*
1179 : : * The partition constraint of the default partition depends on the
1180 : : * partition bounds of every other partition. It is possible that
1181 : : * another backend might be about to execute a query on the default
1182 : : * partition table, and that the query relies on previously cached
1183 : : * default partition constraints. We must therefore take a table lock
1184 : : * strong enough to prevent all queries on the default partition from
1185 : : * proceeding until we commit and send out a shared-cache-inval notice
1186 : : * that will make them update their index lists.
1187 : : *
1188 : : * Order of locking: The relation being added won't be visible to
1189 : : * other backends until it is committed, hence here in
1190 : : * DefineRelation() the order of locking the default partition and the
1191 : : * relation being added does not matter. But at all other places we
1192 : : * need to lock the default relation before we lock the relation being
1193 : : * added or removed i.e. we should take the lock in same order at all
1194 : : * the places such that lock parent, lock default partition and then
1195 : : * lock the partition so as to avoid a deadlock.
1196 : : */
1197 : : defaultPartOid =
1198 : 6070 : get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
1199 : : true));
1200 [ + + ]: 6070 : if (OidIsValid(defaultPartOid))
1201 : 271 : defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1202 : :
1203 : : /* Transform the bound values */
1204 : 6070 : pstate = make_parsestate(NULL);
1205 : 6070 : pstate->p_sourcetext = queryString;
1206 : :
1207 : : /*
1208 : : * Add an nsitem containing this relation, so that transformExpr
1209 : : * called on partition bound expressions is able to report errors
1210 : : * using a proper context.
1211 : : */
1212 : 6070 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1213 : : NULL, false, false);
1214 : 6070 : addNSItemToQuery(pstate, nsitem, false, true, true);
1215 : :
1216 : 6070 : bound = transformPartitionBound(pstate, parent, stmt->partbound);
1217 : :
1218 : : /*
1219 : : * Check first that the new partition's bound is valid and does not
1220 : : * overlap with any of existing partitions of the parent.
1221 : : */
1222 : 5934 : check_new_partition_bound(relname, parent, bound, pstate);
1223 : :
1224 : : /*
1225 : : * If the default partition exists, its partition constraints will
1226 : : * change after the addition of this new partition such that it won't
1227 : : * allow any row that qualifies for this new partition. So, check that
1228 : : * the existing data in the default partition satisfies the constraint
1229 : : * as it will exist after adding this partition.
1230 : : */
1231 [ + + ]: 5858 : if (OidIsValid(defaultPartOid))
1232 : : {
1233 : 251 : check_default_partition_contents(parent, defaultRel, bound);
1234 : : /* Keep the lock until commit. */
1235 : 239 : table_close(defaultRel, NoLock);
1236 : : }
1237 : :
1238 : : /* Update the pg_class entry. */
1239 : 5846 : StorePartitionBound(rel, parent, bound);
1240 : :
1241 : 5846 : table_close(parent, NoLock);
1242 : : }
1243 : :
1244 : : /* Store inheritance information for new rel. */
1245 : 42217 : StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1246 : :
1247 : : /*
1248 : : * Process the partitioning specification (if any) and store the partition
1249 : : * key information into the catalog.
1250 : : */
1251 [ + + ]: 42217 : if (partitioned)
1252 : : {
1253 : : ParseState *pstate;
1254 : : int partnatts;
1255 : : AttrNumber partattrs[PARTITION_MAX_KEYS];
1256 : : Oid partopclass[PARTITION_MAX_KEYS];
1257 : : Oid partcollation[PARTITION_MAX_KEYS];
1258 : 3549 : List *partexprs = NIL;
1259 : :
1260 : 3549 : pstate = make_parsestate(NULL);
1261 : 3549 : pstate->p_sourcetext = queryString;
1262 : :
1263 : 3549 : partnatts = list_length(stmt->partspec->partParams);
1264 : :
1265 : : /* Protect fixed-size arrays here and in executor */
1266 [ - + ]: 3549 : if (partnatts > PARTITION_MAX_KEYS)
1267 [ # # ]: 0 : ereport(ERROR,
1268 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
1269 : : errmsg("cannot partition using more than %d columns",
1270 : : PARTITION_MAX_KEYS)));
1271 : :
1272 : : /*
1273 : : * We need to transform the raw parsetrees corresponding to partition
1274 : : * expressions into executable expression trees. Like column defaults
1275 : : * and CHECK constraints, we could not have done the transformation
1276 : : * earlier.
1277 : : */
1278 : 3549 : stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1279 : :
1280 : 3529 : ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1281 : : partattrs, &partexprs, partopclass,
1282 : 3529 : partcollation, stmt->partspec->strategy);
1283 : :
1284 : 3441 : StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1285 : : partexprs,
1286 : : partopclass, partcollation);
1287 : :
1288 : : /* make it all visible */
1289 : 3437 : CommandCounterIncrement();
1290 : : }
1291 : :
1292 : : /*
1293 : : * If we're creating a partition, create now all the indexes, triggers,
1294 : : * FKs defined in the parent.
1295 : : *
1296 : : * We can't do it earlier, because DefineIndex wants to know the partition
1297 : : * key which we just stored.
1298 : : */
1299 [ + + ]: 42105 : if (stmt->partbound)
1300 : : {
1301 : 5842 : Oid parentId = linitial_oid(inheritOids);
1302 : : Relation parent;
1303 : : List *idxlist;
1304 : : ListCell *cell;
1305 : :
1306 : : /* Already have strong enough lock on the parent */
1307 : 5842 : parent = table_open(parentId, NoLock);
1308 : 5842 : idxlist = RelationGetIndexList(parent);
1309 : :
1310 : : /*
1311 : : * For each index in the parent table, create one in the partition
1312 : : */
1313 [ + + + + : 6799 : foreach(cell, idxlist)
+ + ]
1314 : : {
1315 : 969 : Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1316 : : AttrMap *attmap;
1317 : : IndexStmt *idxstmt;
1318 : : Oid constraintOid;
1319 : :
1320 [ + + ]: 969 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1321 : : {
1322 [ + + ]: 36 : if (idxRel->rd_index->indisunique)
1323 [ + - ]: 8 : ereport(ERROR,
1324 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1325 : : errmsg("cannot create foreign partition of partitioned table \"%s\"",
1326 : : RelationGetRelationName(parent)),
1327 : : errdetail("Table \"%s\" contains indexes that are unique.",
1328 : : RelationGetRelationName(parent))));
1329 : : else
1330 : : {
1331 : 28 : index_close(idxRel, AccessShareLock);
1332 : 28 : continue;
1333 : : }
1334 : : }
1335 : :
1336 : 933 : attmap = build_attrmap_by_name(RelationGetDescr(rel),
1337 : : RelationGetDescr(parent),
1338 : : false);
1339 : : idxstmt =
1340 : 933 : generateClonedIndexStmt(NULL, idxRel,
1341 : : attmap, &constraintOid);
1342 : 933 : DefineIndex(NULL,
1343 : : RelationGetRelid(rel),
1344 : : idxstmt,
1345 : : InvalidOid,
1346 : : RelationGetRelid(idxRel),
1347 : : constraintOid,
1348 : : -1,
1349 : : false, false, false, false, false);
1350 : :
1351 : 929 : index_close(idxRel, AccessShareLock);
1352 : : }
1353 : :
1354 : 5830 : list_free(idxlist);
1355 : :
1356 : : /*
1357 : : * If there are any row-level triggers, clone them to the new
1358 : : * partition.
1359 : : */
1360 [ + + ]: 5830 : if (parent->trigdesc != NULL)
1361 : 232 : CloneRowTriggersToPartition(parent, rel);
1362 : :
1363 : : /*
1364 : : * And foreign keys too. Note that because we're freshly creating the
1365 : : * table, there is no need to verify these new constraints.
1366 : : */
1367 : 5830 : CloneForeignKeyConstraints(NULL, parent, rel);
1368 : :
1369 : 5830 : table_close(parent, NoLock);
1370 : : }
1371 : :
1372 : : /*
1373 : : * Now add any newly specified CHECK constraints to the new relation. Same
1374 : : * as for defaults above, but these need to come after partitioning is set
1375 : : * up. We save the constraint names that were used, to avoid dupes below.
1376 : : */
1377 [ + + ]: 42093 : if (stmt->constraints)
1378 : : {
1379 : : List *conlist;
1380 : :
1381 : 539 : conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1382 : : true, true, false, queryString);
1383 [ + + + + : 1620 : foreach_ptr(CookedConstraint, cons, conlist)
+ + ]
1384 : : {
1385 [ + - ]: 590 : if (cons->name != NULL)
1386 : 590 : connames = lappend(connames, cons->name);
1387 : : }
1388 : : }
1389 : :
1390 : : /*
1391 : : * Finally, merge the not-null constraints that are declared directly with
1392 : : * those that come from parent relations (making sure to count inheritance
1393 : : * appropriately for each), create them, and set the attnotnull flag on
1394 : : * columns that don't yet have it.
1395 : : */
1396 : 42069 : nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1397 : : old_notnulls, connames);
1398 [ + + + + : 93837 : foreach_int(attrnum, nncols)
+ + ]
1399 : 9811 : set_attnotnull(NULL, rel, attrnum, false);
1400 : :
1401 : 42013 : ObjectAddressSet(address, RelationRelationId, relationId);
1402 : :
1403 : : /*
1404 : : * Clean up. We keep lock on new relation (although it shouldn't be
1405 : : * visible to anyone else anyway, until commit).
1406 : : */
1407 : 42013 : relation_close(rel, NoLock);
1408 : :
1409 : 42013 : return address;
1410 : : }
1411 : :
1412 : : /*
1413 : : * BuildDescForRelation
1414 : : *
1415 : : * Given a list of ColumnDef nodes, build a TupleDesc.
1416 : : *
1417 : : * Note: This is only for the limited purpose of table and view creation. Not
1418 : : * everything is filled in. A real tuple descriptor should be obtained from
1419 : : * the relcache.
1420 : : */
1421 : : TupleDesc
1422 : 46959 : BuildDescForRelation(const List *columns)
1423 : : {
1424 : : int natts;
1425 : : AttrNumber attnum;
1426 : : ListCell *l;
1427 : : TupleDesc desc;
1428 : : char *attname;
1429 : : Oid atttypid;
1430 : : int32 atttypmod;
1431 : : Oid attcollation;
1432 : : int attdim;
1433 : :
1434 : : /*
1435 : : * allocate a new tuple descriptor
1436 : : */
1437 : 46959 : natts = list_length(columns);
1438 : 46959 : desc = CreateTemplateTupleDesc(natts);
1439 : :
1440 : 46959 : attnum = 0;
1441 : :
1442 [ + + + + : 221019 : foreach(l, columns)
+ + ]
1443 : : {
1444 : 174100 : ColumnDef *entry = lfirst(l);
1445 : : AclResult aclresult;
1446 : : Form_pg_attribute att;
1447 : :
1448 : : /*
1449 : : * for each entry in the list, get the name and type information from
1450 : : * the list and have TupleDescInitEntry fill in the attribute
1451 : : * information we need.
1452 : : */
1453 : 174100 : attnum++;
1454 : :
1455 : 174100 : attname = entry->colname;
1456 : 174100 : typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1457 : :
1458 : 174100 : aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1459 [ + + ]: 174100 : if (aclresult != ACLCHECK_OK)
1460 : 28 : aclcheck_error_type(aclresult, atttypid);
1461 : :
1462 : 174072 : attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1463 : 174072 : attdim = list_length(entry->typeName->arrayBounds);
1464 [ - + ]: 174072 : if (attdim > PG_INT16_MAX)
1465 [ # # ]: 0 : ereport(ERROR,
1466 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1467 : : errmsg("too many array dimensions"));
1468 : :
1469 [ - + ]: 174072 : if (entry->typeName->setof)
1470 [ # # ]: 0 : ereport(ERROR,
1471 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1472 : : errmsg("column \"%s\" cannot be declared SETOF",
1473 : : attname)));
1474 : :
1475 : 174072 : TupleDescInitEntry(desc, attnum, attname,
1476 : : atttypid, atttypmod, attdim);
1477 : 174072 : att = TupleDescAttr(desc, attnum - 1);
1478 : :
1479 : : /* Override TupleDescInitEntry's settings as requested */
1480 : 174072 : TupleDescInitEntryCollation(desc, attnum, attcollation);
1481 : :
1482 : : /* Fill in additional stuff not handled by TupleDescInitEntry */
1483 : 174072 : att->attnotnull = entry->is_not_null;
1484 : 174072 : att->attislocal = entry->is_local;
1485 : 174072 : att->attinhcount = entry->inhcount;
1486 : 174072 : att->attidentity = entry->identity;
1487 : 174072 : att->attgenerated = entry->generated;
1488 : 174072 : att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1489 [ + + ]: 174064 : if (entry->storage)
1490 : 14398 : att->attstorage = entry->storage;
1491 [ + + ]: 159666 : else if (entry->storage_name)
1492 : 26 : att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1493 : :
1494 : 174060 : populate_compact_attribute(desc, attnum - 1);
1495 : : }
1496 : :
1497 : 46919 : TupleDescFinalize(desc);
1498 : :
1499 : 46919 : return desc;
1500 : : }
1501 : :
1502 : : /*
1503 : : * Emit the right error or warning message for a "DROP" command issued on a
1504 : : * non-existent relation
1505 : : */
1506 : : static void
1507 : 679 : DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
1508 : : {
1509 : : const struct dropmsgstrings *rentry;
1510 : :
1511 [ + + + + ]: 763 : if (rel->schemaname != NULL &&
1512 : 84 : !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
1513 : : {
1514 [ - + ]: 28 : if (!missing_ok)
1515 : : {
1516 [ # # ]: 0 : ereport(ERROR,
1517 : : (errcode(ERRCODE_UNDEFINED_SCHEMA),
1518 : : errmsg("schema \"%s\" does not exist", rel->schemaname)));
1519 : : }
1520 : : else
1521 : : {
1522 [ + - ]: 28 : ereport(NOTICE,
1523 : : (errmsg("schema \"%s\" does not exist, skipping",
1524 : : rel->schemaname)));
1525 : : }
1526 : 28 : return;
1527 : : }
1528 : :
1529 [ + - ]: 880 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1530 : : {
1531 [ + + ]: 880 : if (rentry->kind == rightkind)
1532 : : {
1533 [ + + ]: 651 : if (!missing_ok)
1534 : : {
1535 [ + - ]: 86 : ereport(ERROR,
1536 : : (errcode(rentry->nonexistent_code),
1537 : : errmsg(rentry->nonexistent_msg, rel->relname)));
1538 : : }
1539 : : else
1540 : : {
1541 [ + + ]: 565 : ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
1542 : 565 : break;
1543 : : }
1544 : : }
1545 : : }
1546 : :
1547 : : Assert(rentry->kind != '\0'); /* Should be impossible */
1548 : : }
1549 : :
1550 : : /*
1551 : : * Emit the right error message for a "DROP" command issued on a
1552 : : * relation of the wrong type
1553 : : */
1554 : : static void
1555 : 0 : DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
1556 : : {
1557 : : const struct dropmsgstrings *rentry;
1558 : : const struct dropmsgstrings *wentry;
1559 : :
1560 [ # # ]: 0 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1561 [ # # ]: 0 : if (rentry->kind == rightkind)
1562 : 0 : break;
1563 : : Assert(rentry->kind != '\0');
1564 : :
1565 [ # # ]: 0 : for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
1566 [ # # ]: 0 : if (wentry->kind == wrongkind)
1567 : 0 : break;
1568 : : /* wrongkind could be something we don't have in our table... */
1569 : :
1570 [ # # # # ]: 0 : ereport(ERROR,
1571 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1572 : : errmsg(rentry->nota_msg, relname),
1573 : : (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
1574 : : }
1575 : :
1576 : : /*
1577 : : * RemoveRelations
1578 : : * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
1579 : : * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
1580 : : */
1581 : : void
1582 : 12300 : RemoveRelations(DropStmt *drop)
1583 : : {
1584 : : ObjectAddresses *objects;
1585 : : char relkind;
1586 : : ListCell *cell;
1587 : 12300 : int flags = 0;
1588 : 12300 : LOCKMODE lockmode = AccessExclusiveLock;
1589 : :
1590 : : /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1591 [ + + ]: 12300 : if (drop->concurrent)
1592 : : {
1593 : : /*
1594 : : * Note that for temporary relations this lock may get upgraded later
1595 : : * on, but as no other session can access a temporary relation, this
1596 : : * is actually fine.
1597 : : */
1598 : 98 : lockmode = ShareUpdateExclusiveLock;
1599 : : Assert(drop->removeType == OBJECT_INDEX);
1600 [ + + ]: 98 : if (list_length(drop->objects) != 1)
1601 [ + - ]: 4 : ereport(ERROR,
1602 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1603 : : errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1604 [ - + ]: 94 : if (drop->behavior == DROP_CASCADE)
1605 [ # # ]: 0 : ereport(ERROR,
1606 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1607 : : errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1608 : : }
1609 : :
1610 : : /*
1611 : : * First we identify all the relations, then we delete them in a single
1612 : : * performMultipleDeletions() call. This is to avoid unwanted DROP
1613 : : * RESTRICT errors if one of the relations depends on another.
1614 : : */
1615 : :
1616 : : /* Determine required relkind */
1617 [ + + + + : 12296 : switch (drop->removeType)
+ + - ]
1618 : : {
1619 : 10657 : case OBJECT_TABLE:
1620 : 10657 : relkind = RELKIND_RELATION;
1621 : 10657 : break;
1622 : :
1623 : 569 : case OBJECT_INDEX:
1624 : 569 : relkind = RELKIND_INDEX;
1625 : 569 : break;
1626 : :
1627 : 123 : case OBJECT_SEQUENCE:
1628 : 123 : relkind = RELKIND_SEQUENCE;
1629 : 123 : break;
1630 : :
1631 : 747 : case OBJECT_VIEW:
1632 : 747 : relkind = RELKIND_VIEW;
1633 : 747 : break;
1634 : :
1635 : 85 : case OBJECT_MATVIEW:
1636 : 85 : relkind = RELKIND_MATVIEW;
1637 : 85 : break;
1638 : :
1639 : 115 : case OBJECT_FOREIGN_TABLE:
1640 : 115 : relkind = RELKIND_FOREIGN_TABLE;
1641 : 115 : break;
1642 : :
1643 : 0 : default:
1644 [ # # ]: 0 : elog(ERROR, "unrecognized drop object type: %d",
1645 : : (int) drop->removeType);
1646 : : relkind = 0; /* keep compiler quiet */
1647 : : break;
1648 : : }
1649 : :
1650 : : /* Lock and validate each relation; build a list of object addresses */
1651 : 12296 : objects = new_object_addresses();
1652 : :
1653 [ + - + + : 27341 : foreach(cell, drop->objects)
+ + ]
1654 : : {
1655 : 15152 : RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1656 : : Oid relOid;
1657 : : ObjectAddress obj;
1658 : : struct DropRelationCallbackState state;
1659 : :
1660 : : /*
1661 : : * These next few steps are a great deal like relation_openrv, but we
1662 : : * don't bother building a relcache entry since we don't need it.
1663 : : *
1664 : : * Check for shared-cache-inval messages before trying to access the
1665 : : * relation. This is needed to cover the case where the name
1666 : : * identifies a rel that has been dropped and recreated since the
1667 : : * start of our transaction: if we don't flush the old syscache entry,
1668 : : * then we'll latch onto that entry and suffer an error later.
1669 : : */
1670 : 15152 : AcceptInvalidationMessages();
1671 : :
1672 : : /* Look up the appropriate relation using namespace search. */
1673 : 15152 : state.expected_relkind = relkind;
1674 : 30304 : state.heap_lockmode = drop->concurrent ?
1675 [ + + ]: 15152 : ShareUpdateExclusiveLock : AccessExclusiveLock;
1676 : : /* We must initialize these fields to show that no locks are held: */
1677 : 15152 : state.heapOid = InvalidOid;
1678 : 15152 : state.partParentOid = InvalidOid;
1679 : :
1680 : 15152 : relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1681 : : RangeVarCallbackForDropRelation,
1682 : : &state);
1683 : :
1684 : : /* Not there? */
1685 [ + + ]: 15135 : if (!OidIsValid(relOid))
1686 : : {
1687 : 679 : DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1688 : 593 : continue;
1689 : : }
1690 : :
1691 : : /*
1692 : : * Decide if concurrent mode needs to be used here or not. The
1693 : : * callback retrieved the rel's persistence for us.
1694 : : */
1695 [ + + ]: 14456 : if (drop->concurrent &&
1696 [ + + ]: 90 : state.actual_relpersistence != RELPERSISTENCE_TEMP)
1697 : : {
1698 : : Assert(list_length(drop->objects) == 1 &&
1699 : : drop->removeType == OBJECT_INDEX);
1700 : 78 : flags |= PERFORM_DELETION_CONCURRENTLY;
1701 : : }
1702 : :
1703 : : /*
1704 : : * Concurrent index drop cannot be used with partitioned indexes,
1705 : : * either.
1706 : : */
1707 [ + + ]: 14456 : if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1708 [ + + ]: 78 : state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1709 [ + - ]: 4 : ereport(ERROR,
1710 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1711 : : errmsg("cannot drop partitioned index \"%s\" concurrently",
1712 : : rel->relname)));
1713 : :
1714 : : /*
1715 : : * If we're told to drop a partitioned index, we must acquire lock on
1716 : : * all the children of its parent partitioned table before proceeding.
1717 : : * Otherwise we'd try to lock the child index partitions before their
1718 : : * tables, leading to potential deadlock against other sessions that
1719 : : * will lock those objects in the other order.
1720 : : */
1721 [ + + ]: 14452 : if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1722 : 50 : (void) find_all_inheritors(state.heapOid,
1723 : : state.heap_lockmode,
1724 : : NULL);
1725 : :
1726 : : /* OK, we're ready to delete this one */
1727 : 14452 : obj.classId = RelationRelationId;
1728 : 14452 : obj.objectId = relOid;
1729 : 14452 : obj.objectSubId = 0;
1730 : :
1731 : 14452 : add_exact_object_address(&obj, objects);
1732 : : }
1733 : :
1734 : 12189 : performMultipleDeletions(objects, drop->behavior, flags);
1735 : :
1736 : 12083 : free_object_addresses(objects);
1737 : 12083 : }
1738 : :
1739 : : /*
1740 : : * Before acquiring a table lock, check whether we have sufficient rights.
1741 : : * In the case of DROP INDEX, also try to lock the table before the index.
1742 : : * Also, if the table to be dropped is a partition, we try to lock the parent
1743 : : * first.
1744 : : */
1745 : : static void
1746 : 15436 : RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
1747 : : void *arg)
1748 : : {
1749 : : HeapTuple tuple;
1750 : : struct DropRelationCallbackState *state;
1751 : : char expected_relkind;
1752 : : bool is_partition;
1753 : : Form_pg_class classform;
1754 : : LOCKMODE heap_lockmode;
1755 : 15436 : bool invalid_system_index = false;
1756 : :
1757 : 15436 : state = (struct DropRelationCallbackState *) arg;
1758 : 15436 : heap_lockmode = state->heap_lockmode;
1759 : :
1760 : : /*
1761 : : * If we previously locked some other index's heap, and the name we're
1762 : : * looking up no longer refers to that relation, release the now-useless
1763 : : * lock.
1764 : : */
1765 [ + + - + ]: 15436 : if (relOid != oldRelOid && OidIsValid(state->heapOid))
1766 : : {
1767 : 0 : UnlockRelationOid(state->heapOid, heap_lockmode);
1768 : 0 : state->heapOid = InvalidOid;
1769 : : }
1770 : :
1771 : : /*
1772 : : * Similarly, if we previously locked some other partition's heap, and the
1773 : : * name we're looking up no longer refers to that relation, release the
1774 : : * now-useless lock.
1775 : : */
1776 [ + + - + ]: 15436 : if (relOid != oldRelOid && OidIsValid(state->partParentOid))
1777 : : {
1778 : 0 : UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
1779 : 0 : state->partParentOid = InvalidOid;
1780 : : }
1781 : :
1782 : : /* Didn't find a relation, so no need for locking or permission checks. */
1783 [ + + ]: 15436 : if (!OidIsValid(relOid))
1784 : 683 : return;
1785 : :
1786 : 14753 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1787 [ - + ]: 14753 : if (!HeapTupleIsValid(tuple))
1788 : 0 : return; /* concurrently dropped, so nothing to do */
1789 : 14753 : classform = (Form_pg_class) GETSTRUCT(tuple);
1790 : 14753 : is_partition = classform->relispartition;
1791 : :
1792 : : /* Pass back some data to save lookups in RemoveRelations */
1793 : 14753 : state->actual_relkind = classform->relkind;
1794 : 14753 : state->actual_relpersistence = classform->relpersistence;
1795 : :
1796 : : /*
1797 : : * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
1798 : : * but RemoveRelations() can only pass one relkind for a given relation.
1799 : : * It chooses RELKIND_RELATION for both regular and partitioned tables.
1800 : : * That means we must be careful before giving the wrong type error when
1801 : : * the relation is RELKIND_PARTITIONED_TABLE. An equivalent problem
1802 : : * exists with indexes.
1803 : : */
1804 [ + + ]: 14753 : if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1805 : 2140 : expected_relkind = RELKIND_RELATION;
1806 [ + + ]: 12613 : else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1807 : 55 : expected_relkind = RELKIND_INDEX;
1808 : : else
1809 : 12558 : expected_relkind = classform->relkind;
1810 : :
1811 [ - + ]: 14753 : if (state->expected_relkind != expected_relkind)
1812 : 0 : DropErrorMsgWrongType(rel->relname, classform->relkind,
1813 : 0 : state->expected_relkind);
1814 : :
1815 : : /* Allow DROP to either table owner or schema owner */
1816 [ + + ]: 14753 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
1817 [ + - ]: 12 : !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
1818 : 12 : aclcheck_error(ACLCHECK_NOT_OWNER,
1819 : 12 : get_relkind_objtype(classform->relkind),
1820 : 12 : rel->relname);
1821 : :
1822 : : /*
1823 : : * Check the case of a system index that might have been invalidated by a
1824 : : * failed concurrent process and allow its drop. For the time being, this
1825 : : * only concerns indexes of toast relations that became invalid during a
1826 : : * REINDEX CONCURRENTLY process.
1827 : : */
1828 [ + + - + ]: 14741 : if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
1829 : : {
1830 : : HeapTuple locTuple;
1831 : : Form_pg_index indexform;
1832 : : bool indisvalid;
1833 : :
1834 : 0 : locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
1835 [ # # ]: 0 : if (!HeapTupleIsValid(locTuple))
1836 : : {
1837 : 0 : ReleaseSysCache(tuple);
1838 : 0 : return;
1839 : : }
1840 : :
1841 : 0 : indexform = (Form_pg_index) GETSTRUCT(locTuple);
1842 : 0 : indisvalid = indexform->indisvalid;
1843 : 0 : ReleaseSysCache(locTuple);
1844 : :
1845 : : /* Mark object as being an invalid index of system catalogs */
1846 [ # # ]: 0 : if (!indisvalid)
1847 : 0 : invalid_system_index = true;
1848 : : }
1849 : :
1850 : : /* In the case of an invalid index, it is fine to bypass this check */
1851 [ + - + + : 14741 : if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
+ + ]
1852 [ + - ]: 5 : ereport(ERROR,
1853 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1854 : : errmsg("permission denied: \"%s\" is a system catalog",
1855 : : rel->relname)));
1856 : :
1857 : 14736 : ReleaseSysCache(tuple);
1858 : :
1859 : : /*
1860 : : * In DROP INDEX, attempt to acquire lock on the parent table before
1861 : : * locking the index. index_drop() will need this anyway, and since
1862 : : * regular queries lock tables before their indexes, we risk deadlock if
1863 : : * we do it the other way around. No error if we don't find a pg_index
1864 : : * entry, though --- the relation may have been dropped. Note that this
1865 : : * code will execute for either plain or partitioned indexes.
1866 : : */
1867 [ + + + + ]: 14736 : if (expected_relkind == RELKIND_INDEX &&
1868 : : relOid != oldRelOid)
1869 : : {
1870 : 557 : state->heapOid = IndexGetRelation(relOid, true);
1871 [ + - ]: 557 : if (OidIsValid(state->heapOid))
1872 : 557 : LockRelationOid(state->heapOid, heap_lockmode);
1873 : : }
1874 : :
1875 : : /*
1876 : : * Similarly, if the relation is a partition, we must acquire lock on its
1877 : : * parent before locking the partition. That's because queries lock the
1878 : : * parent before its partitions, so we risk deadlock if we do it the other
1879 : : * way around.
1880 : : */
1881 [ + + + + ]: 14736 : if (is_partition && relOid != oldRelOid)
1882 : : {
1883 : 450 : state->partParentOid = get_partition_parent(relOid, true);
1884 [ + - ]: 450 : if (OidIsValid(state->partParentOid))
1885 : 450 : LockRelationOid(state->partParentOid, AccessExclusiveLock);
1886 : : }
1887 : : }
1888 : :
1889 : : /*
1890 : : * ExecuteTruncate
1891 : : * Executes a TRUNCATE command.
1892 : : *
1893 : : * This is a multi-relation truncate. We first open and grab exclusive
1894 : : * lock on all relations involved, checking permissions and otherwise
1895 : : * verifying that the relation is OK for truncation. Note that if relations
1896 : : * are foreign tables, at this stage, we have not yet checked that their
1897 : : * foreign data in external data sources are OK for truncation. These are
1898 : : * checked when foreign data are actually truncated later. In CASCADE mode,
1899 : : * relations having FK references to the targeted relations are automatically
1900 : : * added to the group; in RESTRICT mode, we check that all FK references are
1901 : : * internal to the group that's being truncated. Finally all the relations
1902 : : * are truncated and reindexed.
1903 : : */
1904 : : void
1905 : 1192 : ExecuteTruncate(TruncateStmt *stmt)
1906 : : {
1907 : 1192 : List *rels = NIL;
1908 : 1192 : List *relids = NIL;
1909 : 1192 : List *relids_logged = NIL;
1910 : : ListCell *cell;
1911 : :
1912 : : /*
1913 : : * Open, exclusive-lock, and check all the explicitly-specified relations
1914 : : */
1915 [ + - + + : 2520 : foreach(cell, stmt->relations)
+ + ]
1916 : : {
1917 : 1364 : RangeVar *rv = lfirst(cell);
1918 : : Relation rel;
1919 : 1364 : bool recurse = rv->inh;
1920 : : Oid myrelid;
1921 : 1364 : LOCKMODE lockmode = AccessExclusiveLock;
1922 : :
1923 : 1364 : myrelid = RangeVarGetRelidExtended(rv, lockmode,
1924 : : 0, RangeVarCallbackForTruncate,
1925 : : NULL);
1926 : :
1927 : : /* don't throw error for "TRUNCATE foo, foo" */
1928 [ + + ]: 1341 : if (list_member_oid(relids, myrelid))
1929 : 1 : continue;
1930 : :
1931 : : /* open the relation, we already hold a lock on it */
1932 : 1340 : rel = table_open(myrelid, NoLock);
1933 : :
1934 : : /*
1935 : : * RangeVarGetRelidExtended() has done most checks with its callback,
1936 : : * but other checks with the now-opened Relation remain.
1937 : : */
1938 : 1340 : truncate_check_activity(rel);
1939 : :
1940 : 1335 : rels = lappend(rels, rel);
1941 : 1335 : relids = lappend_oid(relids, myrelid);
1942 : :
1943 : : /* Log this relation only if needed for logical decoding */
1944 [ + + - + : 1335 : if (RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ + + - ]
1945 : 39 : relids_logged = lappend_oid(relids_logged, myrelid);
1946 : :
1947 [ + + ]: 1335 : if (recurse)
1948 : : {
1949 : : ListCell *child;
1950 : : List *children;
1951 : :
1952 : 1292 : children = find_all_inheritors(myrelid, lockmode, NULL);
1953 : :
1954 [ + - + + : 3804 : foreach(child, children)
+ + ]
1955 : : {
1956 : 2512 : Oid childrelid = lfirst_oid(child);
1957 : :
1958 [ + + ]: 2512 : if (list_member_oid(relids, childrelid))
1959 : 1292 : continue;
1960 : :
1961 : : /* find_all_inheritors already got lock */
1962 : 1220 : rel = table_open(childrelid, NoLock);
1963 : :
1964 : : /*
1965 : : * It is possible that the parent table has children that are
1966 : : * temp tables of other backends. We cannot safely access
1967 : : * such tables (because of buffering issues), and the best
1968 : : * thing to do is to silently ignore them. Note that this
1969 : : * check is the same as one of the checks done in
1970 : : * truncate_check_activity() called below, still it is kept
1971 : : * here for simplicity.
1972 : : */
1973 [ + + + + ]: 1220 : if (RELATION_IS_OTHER_TEMP(rel))
1974 : : {
1975 : 4 : table_close(rel, lockmode);
1976 : 4 : continue;
1977 : : }
1978 : :
1979 : : /*
1980 : : * Inherited TRUNCATE commands perform access permission
1981 : : * checks on the parent table only. So we skip checking the
1982 : : * children's permissions and don't call
1983 : : * truncate_check_perms() here.
1984 : : */
1985 : 1216 : truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
1986 : 1216 : truncate_check_activity(rel);
1987 : :
1988 : 1216 : rels = lappend(rels, rel);
1989 : 1216 : relids = lappend_oid(relids, childrelid);
1990 : :
1991 : : /* Log this relation only if needed for logical decoding */
1992 [ + + - + : 1216 : if (RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ - + - ]
1993 : 11 : relids_logged = lappend_oid(relids_logged, childrelid);
1994 : : }
1995 : : }
1996 [ + + ]: 43 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1997 [ + - ]: 8 : ereport(ERROR,
1998 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1999 : : errmsg("cannot truncate only a partitioned table"),
2000 : : errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
2001 : : }
2002 : :
2003 : 1156 : ExecuteTruncateGuts(rels, relids, relids_logged,
2004 : 1156 : stmt->behavior, stmt->restart_seqs, false);
2005 : :
2006 : : /* And close the rels */
2007 [ + - + + : 3545 : foreach(cell, rels)
+ + ]
2008 : : {
2009 : 2442 : Relation rel = (Relation) lfirst(cell);
2010 : :
2011 : 2442 : table_close(rel, NoLock);
2012 : : }
2013 : 1103 : }
2014 : :
2015 : : /*
2016 : : * ExecuteTruncateGuts
2017 : : *
2018 : : * Internal implementation of TRUNCATE. This is called by the actual TRUNCATE
2019 : : * command (see above) as well as replication subscribers that execute a
2020 : : * replicated TRUNCATE action.
2021 : : *
2022 : : * explicit_rels is the list of Relations to truncate that the command
2023 : : * specified. relids is the list of Oids corresponding to explicit_rels.
2024 : : * relids_logged is the list of Oids (a subset of relids) that require
2025 : : * WAL-logging. This is all a bit redundant, but the existing callers have
2026 : : * this information handy in this form.
2027 : : */
2028 : : void
2029 : 1176 : ExecuteTruncateGuts(List *explicit_rels,
2030 : : List *relids,
2031 : : List *relids_logged,
2032 : : DropBehavior behavior, bool restart_seqs,
2033 : : bool run_as_table_owner)
2034 : : {
2035 : : List *rels;
2036 : 1176 : List *seq_relids = NIL;
2037 : 1176 : HTAB *ft_htab = NULL;
2038 : : EState *estate;
2039 : : ResultRelInfo *resultRelInfos;
2040 : : ResultRelInfo *resultRelInfo;
2041 : : SubTransactionId mySubid;
2042 : : ListCell *cell;
2043 : : Oid *logrelids;
2044 : :
2045 : : /*
2046 : : * Check the explicitly-specified relations.
2047 : : *
2048 : : * In CASCADE mode, suck in all referencing relations as well. This
2049 : : * requires multiple iterations to find indirectly-dependent relations. At
2050 : : * each phase, we need to exclusive-lock new rels before looking for their
2051 : : * dependencies, else we might miss something. Also, we check each rel as
2052 : : * soon as we open it, to avoid a faux pas such as holding lock for a long
2053 : : * time on a rel we have no permissions for.
2054 : : */
2055 : 1176 : rels = list_copy(explicit_rels);
2056 [ + + ]: 1176 : if (behavior == DROP_CASCADE)
2057 : : {
2058 : : for (;;)
2059 : 26 : {
2060 : : List *newrelids;
2061 : :
2062 : 51 : newrelids = heap_truncate_find_FKs(relids);
2063 [ + + ]: 51 : if (newrelids == NIL)
2064 : 25 : break; /* nothing else to add */
2065 : :
2066 [ + - + + : 88 : foreach(cell, newrelids)
+ + ]
2067 : : {
2068 : 62 : Oid relid = lfirst_oid(cell);
2069 : : Relation rel;
2070 : :
2071 : 62 : rel = table_open(relid, AccessExclusiveLock);
2072 [ + - ]: 62 : ereport(NOTICE,
2073 : : (errmsg("truncate cascades to table \"%s\"",
2074 : : RelationGetRelationName(rel))));
2075 : 62 : truncate_check_rel(relid, rel->rd_rel);
2076 : 62 : truncate_check_perms(relid, rel->rd_rel);
2077 : 62 : truncate_check_activity(rel);
2078 : 62 : rels = lappend(rels, rel);
2079 : 62 : relids = lappend_oid(relids, relid);
2080 : :
2081 : : /* Log this relation only if needed for logical decoding */
2082 [ + - - + : 62 : if (RelationIsLogicallyLogged(rel))
- - - - -
- - - - -
- - - - ]
2083 : 0 : relids_logged = lappend_oid(relids_logged, relid);
2084 : : }
2085 : : }
2086 : : }
2087 : :
2088 : : /*
2089 : : * Check foreign key references. In CASCADE mode, this should be
2090 : : * unnecessary since we just pulled in all the references; but as a
2091 : : * cross-check, do it anyway if in an Assert-enabled build.
2092 : : */
2093 : : #ifdef USE_ASSERT_CHECKING
2094 : : heap_truncate_check_FKs(rels, false);
2095 : : #else
2096 [ + + ]: 1176 : if (behavior == DROP_RESTRICT)
2097 : 1151 : heap_truncate_check_FKs(rels, false);
2098 : : #endif
2099 : :
2100 : : /*
2101 : : * If we are asked to restart sequences, find all the sequences, lock them
2102 : : * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2103 : : * We want to do this early since it's pointless to do all the truncation
2104 : : * work only to fail on sequence permissions.
2105 : : */
2106 [ + + ]: 1127 : if (restart_seqs)
2107 : : {
2108 [ + - + + : 30 : foreach(cell, rels)
+ + ]
2109 : : {
2110 : 15 : Relation rel = (Relation) lfirst(cell);
2111 : 15 : List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2112 : : ListCell *seqcell;
2113 : :
2114 [ + + + + : 37 : foreach(seqcell, seqlist)
+ + ]
2115 : : {
2116 : 22 : Oid seq_relid = lfirst_oid(seqcell);
2117 : : Relation seq_rel;
2118 : :
2119 : 22 : seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2120 : :
2121 : : /* This check must match AlterSequence! */
2122 [ - + ]: 22 : if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2123 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
2124 : 0 : RelationGetRelationName(seq_rel));
2125 : :
2126 : 22 : seq_relids = lappend_oid(seq_relids, seq_relid);
2127 : :
2128 : 22 : relation_close(seq_rel, NoLock);
2129 : : }
2130 : : }
2131 : : }
2132 : :
2133 : : /* Prepare to catch AFTER triggers. */
2134 : 1127 : AfterTriggerBeginQuery();
2135 : :
2136 : : /*
2137 : : * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2138 : : * each relation. We don't need to call ExecOpenIndices, though.
2139 : : *
2140 : : * We put the ResultRelInfos in the es_opened_result_relations list, even
2141 : : * though we don't have a range table and don't populate the
2142 : : * es_result_relations array. That's a bit bogus, but it's enough to make
2143 : : * ExecGetTriggerResultRel() find them.
2144 : : */
2145 : 1127 : estate = CreateExecutorState();
2146 : 1127 : resultRelInfos = palloc_array(ResultRelInfo, list_length(rels));
2147 : 1127 : resultRelInfo = resultRelInfos;
2148 [ + - + + : 3671 : foreach(cell, rels)
+ + ]
2149 : : {
2150 : 2544 : Relation rel = (Relation) lfirst(cell);
2151 : :
2152 : 2544 : InitResultRelInfo(resultRelInfo,
2153 : : rel,
2154 : : 0, /* dummy rangetable index */
2155 : : NULL,
2156 : : 0);
2157 : 2544 : estate->es_opened_result_relations =
2158 : 2544 : lappend(estate->es_opened_result_relations, resultRelInfo);
2159 : 2544 : resultRelInfo++;
2160 : : }
2161 : :
2162 : : /*
2163 : : * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2164 : : * truncating (this is because one of them might throw an error). Also, if
2165 : : * we were to allow them to prevent statement execution, that would need
2166 : : * to be handled here.
2167 : : */
2168 : 1127 : resultRelInfo = resultRelInfos;
2169 [ + - + + : 3671 : foreach(cell, rels)
+ + ]
2170 : : {
2171 : : UserContext ucxt;
2172 : :
2173 [ + + ]: 2544 : if (run_as_table_owner)
2174 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2175 : : &ucxt);
2176 : 2544 : ExecBSTruncateTriggers(estate, resultRelInfo);
2177 [ + + ]: 2544 : if (run_as_table_owner)
2178 : 36 : RestoreUserContext(&ucxt);
2179 : 2544 : resultRelInfo++;
2180 : : }
2181 : :
2182 : : /*
2183 : : * OK, truncate each table.
2184 : : */
2185 : 1127 : mySubid = GetCurrentSubTransactionId();
2186 : :
2187 [ + - + + : 3671 : foreach(cell, rels)
+ + ]
2188 : : {
2189 : 2544 : Relation rel = (Relation) lfirst(cell);
2190 : :
2191 : : /* Skip partitioned tables as there is nothing to do */
2192 [ + + ]: 2544 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2193 : 477 : continue;
2194 : :
2195 : : /*
2196 : : * Build the lists of foreign tables belonging to each foreign server
2197 : : * and pass each list to the foreign data wrapper's callback function,
2198 : : * so that each server can truncate its all foreign tables in bulk.
2199 : : * Each list is saved as a single entry in a hash table that uses the
2200 : : * server OID as lookup key.
2201 : : */
2202 [ + + ]: 2067 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2203 : 17 : {
2204 : 17 : Oid serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
2205 : : bool found;
2206 : : ForeignTruncateInfo *ft_info;
2207 : :
2208 : : /* First time through, initialize hashtable for foreign tables */
2209 [ + + ]: 17 : if (!ft_htab)
2210 : : {
2211 : : HASHCTL hctl;
2212 : :
2213 : 15 : memset(&hctl, 0, sizeof(HASHCTL));
2214 : 15 : hctl.keysize = sizeof(Oid);
2215 : 15 : hctl.entrysize = sizeof(ForeignTruncateInfo);
2216 : 15 : hctl.hcxt = CurrentMemoryContext;
2217 : :
2218 : 15 : ft_htab = hash_create("TRUNCATE for Foreign Tables",
2219 : : 32, /* start small and extend */
2220 : : &hctl,
2221 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2222 : : }
2223 : :
2224 : : /* Find or create cached entry for the foreign table */
2225 : 17 : ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2226 [ + + ]: 17 : if (!found)
2227 : 15 : ft_info->rels = NIL;
2228 : :
2229 : : /*
2230 : : * Save the foreign table in the entry of the server that the
2231 : : * foreign table belongs to.
2232 : : */
2233 : 17 : ft_info->rels = lappend(ft_info->rels, rel);
2234 : 17 : continue;
2235 : : }
2236 : :
2237 : : /*
2238 : : * Normally, we need a transaction-safe truncation here. However, if
2239 : : * the table was either created in the current (sub)transaction or has
2240 : : * a new relfilenumber in the current (sub)transaction, then we can
2241 : : * just truncate it in-place, because a rollback would cause the whole
2242 : : * table or the current physical file to be thrown away anyway.
2243 : : */
2244 [ + + ]: 2050 : if (rel->rd_createSubid == mySubid ||
2245 [ + + ]: 2034 : rel->rd_newRelfilelocatorSubid == mySubid)
2246 : : {
2247 : : /* Immediate, non-rollbackable truncation is OK */
2248 : 48 : heap_truncate_one_rel(rel);
2249 : : }
2250 : : else
2251 : : {
2252 : : Oid heap_relid;
2253 : : Oid toast_relid;
2254 : 2002 : ReindexParams reindex_params = {0};
2255 : :
2256 : : /*
2257 : : * This effectively deletes all rows in the table, and may be done
2258 : : * in a serializable transaction. In that case we must record a
2259 : : * rw-conflict in to this transaction from each transaction
2260 : : * holding a predicate lock on the table.
2261 : : */
2262 : 2002 : CheckTableForSerializableConflictIn(rel);
2263 : :
2264 : : /*
2265 : : * Need the full transaction-safe pushups.
2266 : : *
2267 : : * Create a new empty storage file for the relation, and assign it
2268 : : * as the relfilenumber value. The old storage file is scheduled
2269 : : * for deletion at commit.
2270 : : */
2271 : 2002 : RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2272 : :
2273 : 2002 : heap_relid = RelationGetRelid(rel);
2274 : :
2275 : : /*
2276 : : * The same for the toast table, if any.
2277 : : */
2278 : 2002 : toast_relid = rel->rd_rel->reltoastrelid;
2279 [ + + ]: 2002 : if (OidIsValid(toast_relid))
2280 : : {
2281 : 1207 : Relation toastrel = relation_open(toast_relid,
2282 : : AccessExclusiveLock);
2283 : :
2284 : 1207 : RelationSetNewRelfilenumber(toastrel,
2285 : 1207 : toastrel->rd_rel->relpersistence);
2286 : 1207 : table_close(toastrel, NoLock);
2287 : : }
2288 : :
2289 : : /*
2290 : : * Reconstruct the indexes to match, and we're done.
2291 : : */
2292 : 2002 : reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2293 : : &reindex_params);
2294 : : }
2295 : :
2296 : 2050 : pgstat_count_truncate(rel);
2297 : : }
2298 : :
2299 : : /* Now go through the hash table, and truncate foreign tables */
2300 [ + + ]: 1127 : if (ft_htab)
2301 : : {
2302 : : ForeignTruncateInfo *ft_info;
2303 : : HASH_SEQ_STATUS seq;
2304 : :
2305 : 15 : hash_seq_init(&seq, ft_htab);
2306 : :
2307 [ + + ]: 15 : PG_TRY();
2308 : : {
2309 [ + + ]: 26 : while ((ft_info = hash_seq_search(&seq)) != NULL)
2310 : : {
2311 : 15 : FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2312 : :
2313 : : /* truncate_check_rel() has checked that already */
2314 : : Assert(routine->ExecForeignTruncate != NULL);
2315 : :
2316 : 15 : routine->ExecForeignTruncate(ft_info->rels,
2317 : : behavior,
2318 : : restart_seqs);
2319 : : }
2320 : : }
2321 : 4 : PG_FINALLY();
2322 : : {
2323 : 15 : hash_destroy(ft_htab);
2324 : : }
2325 [ + + ]: 15 : PG_END_TRY();
2326 : : }
2327 : :
2328 : : /*
2329 : : * Restart owned sequences if we were asked to.
2330 : : */
2331 [ + + + + : 1145 : foreach(cell, seq_relids)
+ + ]
2332 : : {
2333 : 22 : Oid seq_relid = lfirst_oid(cell);
2334 : :
2335 : 22 : ResetSequence(seq_relid);
2336 : : }
2337 : :
2338 : : /*
2339 : : * Write a WAL record to allow this set of actions to be logically
2340 : : * decoded.
2341 : : *
2342 : : * Assemble an array of relids so we can write a single WAL record for the
2343 : : * whole action.
2344 : : */
2345 [ + + ]: 1123 : if (relids_logged != NIL)
2346 : : {
2347 : : xl_heap_truncate xlrec;
2348 : 33 : int i = 0;
2349 : :
2350 : : /* should only get here if effective_wal_level is 'logical' */
2351 : : Assert(XLogLogicalInfoActive());
2352 : :
2353 : 33 : logrelids = palloc_array(Oid, list_length(relids_logged));
2354 [ + - + + : 84 : foreach(cell, relids_logged)
+ + ]
2355 : 51 : logrelids[i++] = lfirst_oid(cell);
2356 : :
2357 : 33 : xlrec.dbId = MyDatabaseId;
2358 : 33 : xlrec.nrelids = list_length(relids_logged);
2359 : 33 : xlrec.flags = 0;
2360 [ + + ]: 33 : if (behavior == DROP_CASCADE)
2361 : 1 : xlrec.flags |= XLH_TRUNCATE_CASCADE;
2362 [ + + ]: 33 : if (restart_seqs)
2363 : 2 : xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
2364 : :
2365 : 33 : XLogBeginInsert();
2366 : 33 : XLogRegisterData(&xlrec, SizeOfHeapTruncate);
2367 : 33 : XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
2368 : :
2369 : 33 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2370 : :
2371 : 33 : (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2372 : : }
2373 : :
2374 : : /*
2375 : : * Process all AFTER STATEMENT TRUNCATE triggers.
2376 : : */
2377 : 1123 : resultRelInfo = resultRelInfos;
2378 [ + - + + : 3663 : foreach(cell, rels)
+ + ]
2379 : : {
2380 : : UserContext ucxt;
2381 : :
2382 [ + + ]: 2540 : if (run_as_table_owner)
2383 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2384 : : &ucxt);
2385 : 2540 : ExecASTruncateTriggers(estate, resultRelInfo);
2386 [ + + ]: 2540 : if (run_as_table_owner)
2387 : 36 : RestoreUserContext(&ucxt);
2388 : 2540 : resultRelInfo++;
2389 : : }
2390 : :
2391 : : /* Handle queued AFTER triggers */
2392 : 1123 : AfterTriggerEndQuery(estate);
2393 : :
2394 : : /* We can clean up the EState now */
2395 : 1123 : FreeExecutorState(estate);
2396 : :
2397 : : /*
2398 : : * Close any rels opened by CASCADE (can't do this while EState still
2399 : : * holds refs)
2400 : : */
2401 : 1123 : rels = list_difference_ptr(rels, explicit_rels);
2402 [ + + + + : 1185 : foreach(cell, rels)
+ + ]
2403 : : {
2404 : 62 : Relation rel = (Relation) lfirst(cell);
2405 : :
2406 : 62 : table_close(rel, NoLock);
2407 : : }
2408 : 1123 : }
2409 : :
2410 : : /*
2411 : : * Check that a given relation is safe to truncate. Subroutine for
2412 : : * ExecuteTruncate() and RangeVarCallbackForTruncate().
2413 : : */
2414 : : static void
2415 : 2740 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
2416 : : {
2417 : 2740 : char *relname = NameStr(reltuple->relname);
2418 : :
2419 : : /*
2420 : : * Only allow truncate on regular tables, foreign tables using foreign
2421 : : * data wrappers supporting TRUNCATE and partitioned tables (although, the
2422 : : * latter are only being included here for the following checks; no
2423 : : * physical truncation will occur in their case.).
2424 : : */
2425 [ + + ]: 2740 : if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
2426 : : {
2427 : 19 : Oid serverid = GetForeignServerIdByRelId(relid);
2428 : 19 : FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
2429 : :
2430 [ + + ]: 18 : if (!fdwroutine->ExecForeignTruncate)
2431 [ + - ]: 1 : ereport(ERROR,
2432 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2433 : : errmsg("cannot truncate foreign table \"%s\"",
2434 : : relname)));
2435 : : }
2436 [ + + ]: 2721 : else if (reltuple->relkind != RELKIND_RELATION &&
2437 [ - + ]: 492 : reltuple->relkind != RELKIND_PARTITIONED_TABLE)
2438 [ # # ]: 0 : ereport(ERROR,
2439 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2440 : : errmsg("\"%s\" is not a table", relname)));
2441 : :
2442 : : /*
2443 : : * Most system catalogs can't be truncated at all, or at least not unless
2444 : : * allow_system_table_mods=on. As an exception, however, we allow
2445 : : * pg_largeobject and pg_largeobject_metadata to be truncated as part of
2446 : : * pg_upgrade, because we need to change its relfilenode to match the old
2447 : : * cluster, and allowing a TRUNCATE command to be executed is the easiest
2448 : : * way of doing that. We also allow TRUNCATE on the conflict log tables,
2449 : : * to permit users to manually prune conflict data to manage disk space.
2450 : : */
2451 [ + + + + ]: 2738 : if (!allowSystemTableMods && IsSystemClass(relid, reltuple) &&
2452 [ + + ]: 77 : !IsConflictLogTableClass(reltuple)
2453 [ + + + + ]: 69 : && (!IsBinaryUpgrade ||
2454 [ - + ]: 34 : (relid != LargeObjectRelationId &&
2455 : : relid != LargeObjectMetadataRelationId)))
2456 [ + - ]: 1 : ereport(ERROR,
2457 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2458 : : errmsg("permission denied: \"%s\" is a system catalog",
2459 : : relname)));
2460 : :
2461 [ - + ]: 2737 : InvokeObjectTruncateHook(relid);
2462 : 2737 : }
2463 : :
2464 : : /*
2465 : : * Check that current user has the permission to truncate given relation.
2466 : : */
2467 : : static void
2468 : 1521 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
2469 : : {
2470 : 1521 : char *relname = NameStr(reltuple->relname);
2471 : : AclResult aclresult;
2472 : :
2473 : : /* Permissions checks */
2474 : 1521 : aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2475 [ + + ]: 1521 : if (aclresult != ACLCHECK_OK)
2476 : 20 : aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2477 : : relname);
2478 : 1501 : }
2479 : :
2480 : : /*
2481 : : * Set of extra sanity checks to check if a given relation is safe to
2482 : : * truncate. This is split with truncate_check_rel() as
2483 : : * RangeVarCallbackForTruncate() cannot open a Relation yet.
2484 : : */
2485 : : static void
2486 : 2618 : truncate_check_activity(Relation rel)
2487 : : {
2488 : : /*
2489 : : * Don't allow truncate on temp tables of other backends ... their local
2490 : : * buffer manager is not going to cope.
2491 : : */
2492 [ + + + + ]: 2618 : if (RELATION_IS_OTHER_TEMP(rel))
2493 [ + - ]: 1 : ereport(ERROR,
2494 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2495 : : errmsg("cannot truncate temporary tables of other sessions")));
2496 : :
2497 : : /*
2498 : : * Also check for active uses of the relation in the current transaction,
2499 : : * including open scans and pending AFTER trigger events.
2500 : : */
2501 : 2617 : CheckTableNotInUse(rel, "TRUNCATE");
2502 : 2613 : }
2503 : :
2504 : : /*
2505 : : * storage_name
2506 : : * returns the name corresponding to a typstorage/attstorage enum value
2507 : : */
2508 : : static const char *
2509 : 16 : storage_name(char c)
2510 : : {
2511 [ - - + + : 16 : switch (c)
- ]
2512 : : {
2513 : 0 : case TYPSTORAGE_PLAIN:
2514 : 0 : return "PLAIN";
2515 : 0 : case TYPSTORAGE_EXTERNAL:
2516 : 0 : return "EXTERNAL";
2517 : 8 : case TYPSTORAGE_EXTENDED:
2518 : 8 : return "EXTENDED";
2519 : 8 : case TYPSTORAGE_MAIN:
2520 : 8 : return "MAIN";
2521 : 0 : default:
2522 : 0 : return "???";
2523 : : }
2524 : : }
2525 : :
2526 : : /*----------
2527 : : * MergeAttributes
2528 : : * Returns new schema given initial schema and superclasses.
2529 : : *
2530 : : * Input arguments:
2531 : : * 'columns' is the column/attribute definition for the table. (It's a list
2532 : : * of ColumnDef's.) It is destructively changed.
2533 : : * 'supers' is a list of OIDs of parent relations, already locked by caller.
2534 : : * 'relpersistence' is the persistence type of the table.
2535 : : * 'is_partition' tells if the table is a partition.
2536 : : *
2537 : : * Output arguments:
2538 : : * 'supconstr' receives a list of CookedConstraint representing
2539 : : * CHECK constraints belonging to parent relations, updated as
2540 : : * necessary to be valid for the child.
2541 : : * 'supnotnulls' receives a list of CookedConstraint representing
2542 : : * not-null constraints based on those from parent relations.
2543 : : *
2544 : : * Return value:
2545 : : * Completed schema list.
2546 : : *
2547 : : * Notes:
2548 : : * The order in which the attributes are inherited is very important.
2549 : : * Intuitively, the inherited attributes should come first. If a table
2550 : : * inherits from multiple parents, the order of those attributes are
2551 : : * according to the order of the parents specified in CREATE TABLE.
2552 : : *
2553 : : * Here's an example:
2554 : : *
2555 : : * create table person (name text, age int4, location point);
2556 : : * create table emp (salary int4, manager text) inherits(person);
2557 : : * create table student (gpa float8) inherits (person);
2558 : : * create table stud_emp (percent int4) inherits (emp, student);
2559 : : *
2560 : : * The order of the attributes of stud_emp is:
2561 : : *
2562 : : * person {1:name, 2:age, 3:location}
2563 : : * / \
2564 : : * {6:gpa} student emp {4:salary, 5:manager}
2565 : : * \ /
2566 : : * stud_emp {7:percent}
2567 : : *
2568 : : * If the same attribute name appears multiple times, then it appears
2569 : : * in the result table in the proper location for its first appearance.
2570 : : *
2571 : : * Constraints (including not-null constraints) for the child table
2572 : : * are the union of all relevant constraints, from both the child schema
2573 : : * and parent tables. In addition, in legacy inheritance, each column that
2574 : : * appears in a primary key in any of the parents also gets a NOT NULL
2575 : : * constraint (partitioning doesn't need this, because the PK itself gets
2576 : : * inherited.)
2577 : : *
2578 : : * The default value for a child column is defined as:
2579 : : * (1) If the child schema specifies a default, that value is used.
2580 : : * (2) If neither the child nor any parent specifies a default, then
2581 : : * the column will not have a default.
2582 : : * (3) If conflicting defaults are inherited from different parents
2583 : : * (and not overridden by the child), an error is raised.
2584 : : * (4) Otherwise the inherited default is used.
2585 : : *
2586 : : * Note that the default-value infrastructure is used for generated
2587 : : * columns' expressions too, so most of the preceding paragraph applies
2588 : : * to generation expressions too. We insist that a child column be
2589 : : * generated if and only if its parent(s) are, but it need not have
2590 : : * the same generation expression.
2591 : : *----------
2592 : : */
2593 : : static List *
2594 : 42826 : MergeAttributes(List *columns, const List *supers, char relpersistence,
2595 : : bool is_partition, List **supconstr, List **supnotnulls)
2596 : : {
2597 : 42826 : List *inh_columns = NIL;
2598 : 42826 : List *constraints = NIL;
2599 : 42826 : List *nnconstraints = NIL;
2600 : 42826 : bool have_bogus_defaults = false;
2601 : : int child_attno;
2602 : : static Node bogus_marker = {0}; /* marks conflicting defaults */
2603 : 42826 : List *saved_columns = NIL;
2604 : : ListCell *lc;
2605 : :
2606 : : /*
2607 : : * Check for and reject tables with too many columns. We perform this
2608 : : * check relatively early for two reasons: (a) we don't run the risk of
2609 : : * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
2610 : : * okay if we're processing <= 1600 columns, but could take minutes to
2611 : : * execute if the user attempts to create a table with hundreds of
2612 : : * thousands of columns.
2613 : : *
2614 : : * Note that we also need to check that we do not exceed this figure after
2615 : : * including columns from inherited relations.
2616 : : */
2617 [ - + ]: 42826 : if (list_length(columns) > MaxHeapAttributeNumber)
2618 [ # # ]: 0 : ereport(ERROR,
2619 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2620 : : errmsg("tables can have at most %d columns",
2621 : : MaxHeapAttributeNumber)));
2622 : :
2623 : : /*
2624 : : * Check for duplicate names in the explicit list of attributes.
2625 : : *
2626 : : * Although we might consider merging such entries in the same way that we
2627 : : * handle name conflicts for inherited attributes, it seems to make more
2628 : : * sense to assume such conflicts are errors.
2629 : : *
2630 : : * We don't use foreach() here because we have two nested loops over the
2631 : : * columns list, with possible element deletions in the inner one. If we
2632 : : * used foreach_delete_current() it could only fix up the state of one of
2633 : : * the loops, so it seems cleaner to use looping over list indexes for
2634 : : * both loops. Note that any deletion will happen beyond where the outer
2635 : : * loop is, so its index never needs adjustment.
2636 : : */
2637 [ + + ]: 198553 : for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
2638 : : {
2639 : 155743 : ColumnDef *coldef = list_nth_node(ColumnDef, columns, coldefpos);
2640 : :
2641 [ + + + + ]: 155743 : if (!is_partition && coldef->typeName == NULL)
2642 : : {
2643 : : /*
2644 : : * Typed table column option that does not belong to a column from
2645 : : * the type. This works because the columns from the type come
2646 : : * first in the list. (We omit this check for partition column
2647 : : * lists; those are processed separately below.)
2648 : : */
2649 [ + - ]: 4 : ereport(ERROR,
2650 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
2651 : : errmsg("column \"%s\" does not exist",
2652 : : coldef->colname)));
2653 : : }
2654 : :
2655 : : /* restpos scans all entries beyond coldef; incr is in loop body */
2656 [ + + ]: 4146624 : for (int restpos = coldefpos + 1; restpos < list_length(columns);)
2657 : : {
2658 : 3990897 : ColumnDef *restdef = list_nth_node(ColumnDef, columns, restpos);
2659 : :
2660 [ + + ]: 3990897 : if (strcmp(coldef->colname, restdef->colname) == 0)
2661 : : {
2662 [ + + ]: 33 : if (coldef->is_from_type)
2663 : : {
2664 : : /*
2665 : : * merge the column options into the column from the type
2666 : : */
2667 : 21 : coldef->is_not_null = restdef->is_not_null;
2668 : 21 : coldef->raw_default = restdef->raw_default;
2669 : 21 : coldef->cooked_default = restdef->cooked_default;
2670 : 21 : coldef->constraints = restdef->constraints;
2671 : 21 : coldef->is_from_type = false;
2672 : 21 : columns = list_delete_nth_cell(columns, restpos);
2673 : : }
2674 : : else
2675 [ + - ]: 12 : ereport(ERROR,
2676 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
2677 : : errmsg("column \"%s\" specified more than once",
2678 : : coldef->colname)));
2679 : : }
2680 : : else
2681 : 3990864 : restpos++;
2682 : : }
2683 : : }
2684 : :
2685 : : /*
2686 : : * In case of a partition, there are no new column definitions, only dummy
2687 : : * ColumnDefs created for column constraints. Set them aside for now and
2688 : : * process them at the end.
2689 : : */
2690 [ + + ]: 42810 : if (is_partition)
2691 : : {
2692 : 6126 : saved_columns = columns;
2693 : 6126 : columns = NIL;
2694 : : }
2695 : :
2696 : : /*
2697 : : * Scan the parents left-to-right, and merge their attributes to form a
2698 : : * list of inherited columns (inh_columns).
2699 : : */
2700 : 42810 : child_attno = 0;
2701 [ + + + + : 50555 : foreach(lc, supers)
+ + ]
2702 : : {
2703 : 7805 : Oid parent = lfirst_oid(lc);
2704 : : Relation relation;
2705 : : TupleDesc tupleDesc;
2706 : : TupleConstr *constr;
2707 : : AttrMap *newattmap;
2708 : : List *inherited_defaults;
2709 : : List *cols_with_defaults;
2710 : : List *nnconstrs;
2711 : : ListCell *lc1;
2712 : : ListCell *lc2;
2713 : 7805 : Bitmapset *nncols = NULL;
2714 : :
2715 : : /* caller already got lock */
2716 : 7805 : relation = table_open(parent, NoLock);
2717 : :
2718 : : /*
2719 : : * Check for active uses of the parent partitioned table in the
2720 : : * current transaction, such as being used in some manner by an
2721 : : * enclosing command.
2722 : : */
2723 [ + + ]: 7805 : if (is_partition)
2724 : 6126 : CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
2725 : :
2726 : : /*
2727 : : * We do not allow partitioned tables and partitions to participate in
2728 : : * regular inheritance.
2729 : : */
2730 [ + + + + ]: 7801 : if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
2731 [ + - ]: 4 : ereport(ERROR,
2732 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2733 : : errmsg("cannot inherit from partitioned table \"%s\"",
2734 : : RelationGetRelationName(relation))));
2735 [ + + + + ]: 7797 : if (relation->rd_rel->relispartition && !is_partition)
2736 [ + - ]: 4 : ereport(ERROR,
2737 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2738 : : errmsg("cannot inherit from partition \"%s\"",
2739 : : RelationGetRelationName(relation))));
2740 : :
2741 : : /*
2742 : : * Conflict log tables are managed by the system for logical
2743 : : * replication and should not be used as parent tables, as inheritance
2744 : : * could interfere with the logging behavior.
2745 : : */
2746 [ + + ]: 7793 : if (IsConflictLogTableNamespace(relation->rd_rel->relnamespace))
2747 [ + - ]: 4 : ereport(ERROR,
2748 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2749 : : errmsg("cannot inherit from conflict log table \"%s\"",
2750 : : RelationGetRelationName(relation)),
2751 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
2752 : :
2753 [ + + ]: 7789 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2754 [ + + ]: 6122 : relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2755 [ - + ]: 6110 : relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2756 [ # # ]: 0 : ereport(ERROR,
2757 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2758 : : errmsg("inherited relation \"%s\" is not a table or foreign table",
2759 : : RelationGetRelationName(relation))));
2760 : :
2761 : : /*
2762 : : * If the parent is permanent, so must be all of its partitions. Note
2763 : : * that inheritance allows that case.
2764 : : */
2765 [ + + ]: 7789 : if (is_partition &&
2766 [ + + + + ]: 6122 : relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
2767 : : relpersistence == RELPERSISTENCE_TEMP)
2768 [ + - ]: 4 : ereport(ERROR,
2769 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2770 : : errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
2771 : : RelationGetRelationName(relation))));
2772 : :
2773 : : /* Permanent rels cannot inherit from temporary ones */
2774 [ + + ]: 7785 : if (relpersistence != RELPERSISTENCE_TEMP &&
2775 [ + + ]: 7543 : relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
2776 [ + - + + ]: 16 : ereport(ERROR,
2777 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2778 : : errmsg(!is_partition
2779 : : ? "cannot inherit from temporary relation \"%s\""
2780 : : : "cannot create a permanent relation as partition of temporary relation \"%s\"",
2781 : : RelationGetRelationName(relation))));
2782 : :
2783 : : /* If existing rel is temp, it must belong to this session */
2784 [ + + - + ]: 7769 : if (RELATION_IS_OTHER_TEMP(relation))
2785 [ # # # # ]: 0 : ereport(ERROR,
2786 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2787 : : errmsg(!is_partition
2788 : : ? "cannot inherit from temporary relation of another session"
2789 : : : "cannot create as partition of temporary relation of another session")));
2790 : :
2791 : : /*
2792 : : * We should have an UNDER permission flag for this, but for now,
2793 : : * demand that creator of a child table own the parent.
2794 : : */
2795 [ - + ]: 7769 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
2796 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
2797 : 0 : RelationGetRelationName(relation));
2798 : :
2799 : 7769 : tupleDesc = RelationGetDescr(relation);
2800 : 7769 : constr = tupleDesc->constr;
2801 : :
2802 : : /*
2803 : : * newattmap->attnums[] will contain the child-table attribute numbers
2804 : : * for the attributes of this parent table. (They are not the same
2805 : : * for parents after the first one, nor if we have dropped columns.)
2806 : : */
2807 : 7769 : newattmap = make_attrmap(tupleDesc->natts);
2808 : :
2809 : : /* We can't process inherited defaults until newattmap is complete. */
2810 : 7769 : inherited_defaults = cols_with_defaults = NIL;
2811 : :
2812 : : /*
2813 : : * Request attnotnull on columns that have a not-null constraint
2814 : : * that's not marked NO INHERIT (even if not valid).
2815 : : */
2816 : 7769 : nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
2817 : : true, false);
2818 [ + + + + : 17182 : foreach_ptr(CookedConstraint, cc, nnconstrs)
+ + ]
2819 : 1644 : nncols = bms_add_member(nncols, cc->attnum);
2820 : :
2821 [ + + ]: 22678 : for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
2822 : 14909 : parent_attno++)
2823 : : {
2824 : 14933 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2825 : : parent_attno - 1);
2826 : 14933 : char *attributeName = NameStr(attribute->attname);
2827 : : int exist_attno;
2828 : : ColumnDef *newdef;
2829 : : ColumnDef *mergeddef;
2830 : :
2831 : : /*
2832 : : * Ignore dropped columns in the parent.
2833 : : */
2834 [ + + ]: 14933 : if (attribute->attisdropped)
2835 : 132 : continue; /* leave newattmap->attnums entry as zero */
2836 : :
2837 : : /*
2838 : : * Create new column definition
2839 : : */
2840 : 14801 : newdef = makeColumnDef(attributeName, attribute->atttypid,
2841 : : attribute->atttypmod, attribute->attcollation);
2842 : 14801 : newdef->storage = attribute->attstorage;
2843 : 14801 : newdef->generated = attribute->attgenerated;
2844 [ + + ]: 14801 : if (CompressionMethodIsValid(attribute->attcompression))
2845 : 24 : newdef->compression =
2846 : 24 : pstrdup(GetCompressionMethodName(attribute->attcompression));
2847 : :
2848 : : /*
2849 : : * Regular inheritance children are independent enough not to
2850 : : * inherit identity columns. But partitions are integral part of
2851 : : * a partitioned table and inherit identity column.
2852 : : */
2853 [ + + ]: 14801 : if (is_partition)
2854 : 11832 : newdef->identity = attribute->attidentity;
2855 : :
2856 : : /*
2857 : : * Does it match some previously considered column from another
2858 : : * parent?
2859 : : */
2860 : 14801 : exist_attno = findAttrByName(attributeName, inh_columns);
2861 [ + + ]: 14801 : if (exist_attno > 0)
2862 : : {
2863 : : /*
2864 : : * Yes, try to merge the two column definitions.
2865 : : */
2866 : 253 : mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
2867 : :
2868 : 229 : newattmap->attnums[parent_attno - 1] = exist_attno;
2869 : :
2870 : : /*
2871 : : * Partitions have only one parent, so conflict should never
2872 : : * occur.
2873 : : */
2874 : : Assert(!is_partition);
2875 : : }
2876 : : else
2877 : : {
2878 : : /*
2879 : : * No, create a new inherited column
2880 : : */
2881 : 14548 : newdef->inhcount = 1;
2882 : 14548 : newdef->is_local = false;
2883 : 14548 : inh_columns = lappend(inh_columns, newdef);
2884 : :
2885 : 14548 : newattmap->attnums[parent_attno - 1] = ++child_attno;
2886 : 14548 : mergeddef = newdef;
2887 : : }
2888 : :
2889 : : /*
2890 : : * mark attnotnull if parent has it
2891 : : */
2892 [ + + ]: 14777 : if (bms_is_member(parent_attno, nncols))
2893 : 1644 : mergeddef->is_not_null = true;
2894 : :
2895 : : /*
2896 : : * Locate default/generation expression if any
2897 : : */
2898 [ + + ]: 14777 : if (attribute->atthasdef)
2899 : : {
2900 : : Node *this_default;
2901 : :
2902 : 470 : this_default = TupleDescGetDefault(tupleDesc, parent_attno);
2903 [ - + ]: 470 : if (this_default == NULL)
2904 [ # # ]: 0 : elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
2905 : : parent_attno, RelationGetRelationName(relation));
2906 : :
2907 : : /*
2908 : : * If it's a GENERATED default, it might contain Vars that
2909 : : * need to be mapped to the inherited column(s)' new numbers.
2910 : : * We can't do that till newattmap is ready, so just remember
2911 : : * all the inherited default expressions for the moment.
2912 : : */
2913 : 470 : inherited_defaults = lappend(inherited_defaults, this_default);
2914 : 470 : cols_with_defaults = lappend(cols_with_defaults, mergeddef);
2915 : : }
2916 : : }
2917 : :
2918 : : /*
2919 : : * Now process any inherited default expressions, adjusting attnos
2920 : : * using the completed newattmap map.
2921 : : */
2922 [ + + + + : 8215 : forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
+ + + + +
+ + - +
+ ]
2923 : : {
2924 : 470 : Node *this_default = (Node *) lfirst(lc1);
2925 : 470 : ColumnDef *def = (ColumnDef *) lfirst(lc2);
2926 : : bool found_whole_row;
2927 : :
2928 : : /* Adjust Vars to match new table's column numbering */
2929 : 470 : this_default = map_variable_attnos(this_default,
2930 : : 1, 0,
2931 : : newattmap,
2932 : : InvalidOid, &found_whole_row);
2933 : :
2934 : : /*
2935 : : * For the moment we have to reject whole-row variables. We could
2936 : : * convert them, if we knew the new table's rowtype OID, but that
2937 : : * hasn't been assigned yet. (A variable could only appear in a
2938 : : * generation expression, so the error message is correct.)
2939 : : */
2940 [ - + ]: 470 : if (found_whole_row)
2941 [ # # ]: 0 : ereport(ERROR,
2942 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2943 : : errmsg("cannot convert whole-row table reference"),
2944 : : errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
2945 : : def->colname,
2946 : : RelationGetRelationName(relation))));
2947 : :
2948 : : /*
2949 : : * If we already had a default from some prior parent, check to
2950 : : * see if they are the same. If so, no problem; if not, mark the
2951 : : * column as having a bogus default. Below, we will complain if
2952 : : * the bogus default isn't overridden by the child columns.
2953 : : */
2954 : : Assert(def->raw_default == NULL);
2955 [ + + ]: 470 : if (def->cooked_default == NULL)
2956 : 442 : def->cooked_default = this_default;
2957 [ + + ]: 28 : else if (!equal(def->cooked_default, this_default))
2958 : : {
2959 : 24 : def->cooked_default = &bogus_marker;
2960 : 24 : have_bogus_defaults = true;
2961 : : }
2962 : : }
2963 : :
2964 : : /*
2965 : : * Now copy the CHECK constraints of this parent, adjusting attnos
2966 : : * using the completed newattmap map. Identically named constraints
2967 : : * are merged if possible, else we throw error.
2968 : : */
2969 [ + + + + ]: 7745 : if (constr && constr->num_check > 0)
2970 : : {
2971 : 281 : ConstrCheck *check = constr->check;
2972 : :
2973 [ + + ]: 842 : for (int i = 0; i < constr->num_check; i++)
2974 : : {
2975 : 561 : char *name = check[i].ccname;
2976 : : Node *expr;
2977 : : bool found_whole_row;
2978 : :
2979 : : /* ignore if the constraint is non-inheritable */
2980 [ + + ]: 561 : if (check[i].ccnoinherit)
2981 : 32 : continue;
2982 : :
2983 : : /* Adjust Vars to match new table's column numbering */
2984 : 529 : expr = map_variable_attnos(stringToNode(check[i].ccbin),
2985 : : 1, 0,
2986 : : newattmap,
2987 : : InvalidOid, &found_whole_row);
2988 : :
2989 : : /*
2990 : : * For the moment we have to reject whole-row variables. We
2991 : : * could convert them, if we knew the new table's rowtype OID,
2992 : : * but that hasn't been assigned yet.
2993 : : */
2994 [ - + ]: 529 : if (found_whole_row)
2995 [ # # ]: 0 : ereport(ERROR,
2996 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2997 : : errmsg("cannot convert whole-row table reference"),
2998 : : errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
2999 : : name,
3000 : : RelationGetRelationName(relation))));
3001 : :
3002 : 529 : constraints = MergeCheckConstraint(constraints, name, expr,
3003 : 529 : check[i].ccenforced);
3004 : : }
3005 : : }
3006 : :
3007 : : /*
3008 : : * Also copy the not-null constraints from this parent. The
3009 : : * attnotnull markings were already installed above.
3010 : : */
3011 [ + + + + : 17134 : foreach_ptr(CookedConstraint, nn, nnconstrs)
+ + ]
3012 : : {
3013 : : Assert(nn->contype == CONSTR_NOTNULL);
3014 : :
3015 : 1644 : nn->attnum = newattmap->attnums[nn->attnum - 1];
3016 : :
3017 : 1644 : nnconstraints = lappend(nnconstraints, nn);
3018 : : }
3019 : :
3020 : 7745 : free_attrmap(newattmap);
3021 : :
3022 : : /*
3023 : : * Close the parent rel, but keep our lock on it until xact commit.
3024 : : * That will prevent someone else from deleting or ALTERing the parent
3025 : : * before the child is committed.
3026 : : */
3027 : 7745 : table_close(relation, NoLock);
3028 : : }
3029 : :
3030 : : /*
3031 : : * If we had no inherited attributes, the result columns are just the
3032 : : * explicitly declared columns. Otherwise, we need to merge the declared
3033 : : * columns into the inherited column list. Although, we never have any
3034 : : * explicitly declared columns if the table is a partition.
3035 : : */
3036 [ + + ]: 42750 : if (inh_columns != NIL)
3037 : : {
3038 : 7447 : int newcol_attno = 0;
3039 : :
3040 [ + + + + : 8100 : foreach(lc, columns)
+ + ]
3041 : : {
3042 : 705 : ColumnDef *newdef = lfirst_node(ColumnDef, lc);
3043 : 705 : char *attributeName = newdef->colname;
3044 : : int exist_attno;
3045 : :
3046 : : /*
3047 : : * Partitions have only one parent and have no column definitions
3048 : : * of their own, so conflict should never occur.
3049 : : */
3050 : : Assert(!is_partition);
3051 : :
3052 : 705 : newcol_attno++;
3053 : :
3054 : : /*
3055 : : * Does it match some inherited column?
3056 : : */
3057 : 705 : exist_attno = findAttrByName(attributeName, inh_columns);
3058 [ + + ]: 705 : if (exist_attno > 0)
3059 : : {
3060 : : /*
3061 : : * Yes, try to merge the two column definitions.
3062 : : */
3063 : 251 : MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
3064 : : }
3065 : : else
3066 : : {
3067 : : /*
3068 : : * No, attach new column unchanged to result columns.
3069 : : */
3070 : 454 : inh_columns = lappend(inh_columns, newdef);
3071 : : }
3072 : : }
3073 : :
3074 : 7395 : columns = inh_columns;
3075 : :
3076 : : /*
3077 : : * Check that we haven't exceeded the legal # of columns after merging
3078 : : * in inherited columns.
3079 : : */
3080 [ - + ]: 7395 : if (list_length(columns) > MaxHeapAttributeNumber)
3081 [ # # ]: 0 : ereport(ERROR,
3082 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
3083 : : errmsg("tables can have at most %d columns",
3084 : : MaxHeapAttributeNumber)));
3085 : : }
3086 : :
3087 : : /*
3088 : : * Now that we have the column definition list for a partition, we can
3089 : : * check whether the columns referenced in the column constraint specs
3090 : : * actually exist. Also, merge column defaults.
3091 : : */
3092 [ + + ]: 42698 : if (is_partition)
3093 : : {
3094 [ + + + + : 6237 : foreach(lc, saved_columns)
+ + ]
3095 : : {
3096 : 155 : ColumnDef *restdef = lfirst(lc);
3097 : 155 : bool found = false;
3098 : : ListCell *l;
3099 : :
3100 [ + - + + : 561 : foreach(l, columns)
+ + ]
3101 : : {
3102 : 430 : ColumnDef *coldef = lfirst(l);
3103 : :
3104 [ + + ]: 430 : if (strcmp(coldef->colname, restdef->colname) == 0)
3105 : : {
3106 : 155 : found = true;
3107 : :
3108 : : /*
3109 : : * Check for conflicts related to generated columns.
3110 : : *
3111 : : * Same rules as above: generated-ness has to match the
3112 : : * parent, but the contents of the generation expression
3113 : : * can be different.
3114 : : */
3115 [ + + ]: 155 : if (coldef->generated)
3116 : : {
3117 [ + - + + ]: 84 : if (restdef->raw_default && !restdef->generated)
3118 [ + - ]: 8 : ereport(ERROR,
3119 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3120 : : errmsg("column \"%s\" inherits from generated column but specifies default",
3121 : : restdef->colname)));
3122 [ - + ]: 76 : if (restdef->identity)
3123 [ # # ]: 0 : ereport(ERROR,
3124 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3125 : : errmsg("column \"%s\" inherits from generated column but specifies identity",
3126 : : restdef->colname)));
3127 : : }
3128 : : else
3129 : : {
3130 [ + + ]: 71 : if (restdef->generated)
3131 [ + - ]: 8 : ereport(ERROR,
3132 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3133 : : errmsg("child column \"%s\" specifies generation expression",
3134 : : restdef->colname),
3135 : : errhint("A child table column cannot be generated unless its parent column is.")));
3136 : : }
3137 : :
3138 [ + + + - : 139 : if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
+ + ]
3139 [ + - + + : 8 : ereport(ERROR,
+ + ]
3140 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3141 : : errmsg("column \"%s\" inherits from generated column of different kind",
3142 : : restdef->colname),
3143 : : errdetail("Parent column is %s, child column is %s.",
3144 : : coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3145 : : restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3146 : :
3147 : : /*
3148 : : * Override the parent's default value for this column
3149 : : * (coldef->cooked_default) with the partition's local
3150 : : * definition (restdef->raw_default), if there's one. It
3151 : : * should be physically impossible to get a cooked default
3152 : : * in the local definition or a raw default in the
3153 : : * inherited definition, but make sure they're nulls, for
3154 : : * future-proofing.
3155 : : */
3156 : : Assert(restdef->cooked_default == NULL);
3157 : : Assert(coldef->raw_default == NULL);
3158 [ + + ]: 131 : if (restdef->raw_default)
3159 : : {
3160 : 83 : coldef->raw_default = restdef->raw_default;
3161 : 83 : coldef->cooked_default = NULL;
3162 : : }
3163 : : }
3164 : : }
3165 : :
3166 : : /* complain for constraints on columns not in parent */
3167 [ - + ]: 131 : if (!found)
3168 [ # # ]: 0 : ereport(ERROR,
3169 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3170 : : errmsg("column \"%s\" does not exist",
3171 : : restdef->colname)));
3172 : : }
3173 : : }
3174 : :
3175 : : /*
3176 : : * If we found any conflicting parent default values, check to make sure
3177 : : * they were overridden by the child.
3178 : : */
3179 [ + + ]: 42674 : if (have_bogus_defaults)
3180 : : {
3181 [ + - + + : 60 : foreach(lc, columns)
+ + ]
3182 : : {
3183 : 48 : ColumnDef *def = lfirst(lc);
3184 : :
3185 [ + + ]: 48 : if (def->cooked_default == &bogus_marker)
3186 : : {
3187 [ + + ]: 12 : if (def->generated)
3188 [ + - ]: 8 : ereport(ERROR,
3189 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3190 : : errmsg("column \"%s\" inherits conflicting generation expressions",
3191 : : def->colname),
3192 : : errhint("To resolve the conflict, specify a generation expression explicitly.")));
3193 : : else
3194 [ + - ]: 4 : ereport(ERROR,
3195 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3196 : : errmsg("column \"%s\" inherits conflicting default values",
3197 : : def->colname),
3198 : : errhint("To resolve the conflict, specify a default explicitly.")));
3199 : : }
3200 : : }
3201 : : }
3202 : :
3203 : 42662 : *supconstr = constraints;
3204 : 42662 : *supnotnulls = nnconstraints;
3205 : :
3206 : 42662 : return columns;
3207 : : }
3208 : :
3209 : :
3210 : : /*
3211 : : * MergeCheckConstraint
3212 : : * Try to merge an inherited CHECK constraint with previous ones
3213 : : *
3214 : : * If we inherit identically-named constraints from multiple parents, we must
3215 : : * merge them, or throw an error if they don't have identical definitions.
3216 : : *
3217 : : * constraints is a list of CookedConstraint structs for previous constraints.
3218 : : *
3219 : : * If the new constraint matches an existing one, then the existing
3220 : : * constraint's inheritance count is updated. If there is a conflict (same
3221 : : * name but different expression), throw an error. If the constraint neither
3222 : : * matches nor conflicts with an existing one, a new constraint is appended to
3223 : : * the list.
3224 : : */
3225 : : static List *
3226 : 529 : MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
3227 : : {
3228 : : ListCell *lc;
3229 : : CookedConstraint *newcon;
3230 : :
3231 [ + + + + : 1557 : foreach(lc, constraints)
+ + ]
3232 : : {
3233 : 1136 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
3234 : :
3235 : : Assert(ccon->contype == CONSTR_CHECK);
3236 : :
3237 : : /* Non-matching names never conflict */
3238 [ + + ]: 1136 : if (strcmp(ccon->name, name) != 0)
3239 : 1028 : continue;
3240 : :
3241 [ + - ]: 108 : if (equal(expr, ccon->expr))
3242 : : {
3243 : : /* OK to merge constraint with existing */
3244 [ - + ]: 108 : if (pg_add_s16_overflow(ccon->inhcount, 1,
3245 : : &ccon->inhcount))
3246 [ # # ]: 0 : ereport(ERROR,
3247 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3248 : : errmsg("too many inheritance parents"));
3249 : :
3250 : : /*
3251 : : * When enforceability differs, the merged constraint should be
3252 : : * marked as ENFORCED because one of the parents is ENFORCED.
3253 : : */
3254 [ + + + + ]: 108 : if (!ccon->is_enforced && is_enforced)
3255 : : {
3256 : 32 : ccon->is_enforced = true;
3257 : 32 : ccon->skip_validation = false;
3258 : : }
3259 : :
3260 : 108 : return constraints;
3261 : : }
3262 : :
3263 [ # # ]: 0 : ereport(ERROR,
3264 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3265 : : errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
3266 : : name)));
3267 : : }
3268 : :
3269 : : /*
3270 : : * Constraint couldn't be merged with an existing one and also didn't
3271 : : * conflict with an existing one, so add it as a new one to the list.
3272 : : */
3273 : 421 : newcon = palloc0_object(CookedConstraint);
3274 : 421 : newcon->contype = CONSTR_CHECK;
3275 : 421 : newcon->name = pstrdup(name);
3276 : 421 : newcon->expr = expr;
3277 : 421 : newcon->inhcount = 1;
3278 : 421 : newcon->is_enforced = is_enforced;
3279 : 421 : newcon->skip_validation = !is_enforced;
3280 : 421 : return lappend(constraints, newcon);
3281 : : }
3282 : :
3283 : : /*
3284 : : * MergeChildAttribute
3285 : : * Merge given child attribute definition into given inherited attribute.
3286 : : *
3287 : : * Input arguments:
3288 : : * 'inh_columns' is the list of inherited ColumnDefs.
3289 : : * 'exist_attno' is the number of the inherited attribute in inh_columns
3290 : : * 'newcol_attno' is the attribute number in child table's schema definition
3291 : : * 'newdef' is the column/attribute definition from the child table.
3292 : : *
3293 : : * The ColumnDef in 'inh_columns' list is modified. The child attribute's
3294 : : * ColumnDef remains unchanged.
3295 : : *
3296 : : * Notes:
3297 : : * - The attribute is merged according to the rules laid out in the prologue
3298 : : * of MergeAttributes().
3299 : : * - If matching inherited attribute exists but the child attribute can not be
3300 : : * merged into it, the function throws respective errors.
3301 : : * - A partition can not have its own column definitions. Hence this function
3302 : : * is applicable only to a regular inheritance child.
3303 : : */
3304 : : static void
3305 : 251 : MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
3306 : : {
3307 : 251 : char *attributeName = newdef->colname;
3308 : : ColumnDef *inhdef;
3309 : : Oid inhtypeid,
3310 : : newtypeid;
3311 : : int32 inhtypmod,
3312 : : newtypmod;
3313 : : Oid inhcollid,
3314 : : newcollid;
3315 : :
3316 [ + + ]: 251 : if (exist_attno == newcol_attno)
3317 [ + - ]: 229 : ereport(NOTICE,
3318 : : (errmsg("merging column \"%s\" with inherited definition",
3319 : : attributeName)));
3320 : : else
3321 [ + - ]: 22 : ereport(NOTICE,
3322 : : (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
3323 : : errdetail("User-specified column moved to the position of the inherited column.")));
3324 : :
3325 : 251 : inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3326 : :
3327 : : /*
3328 : : * Must have the same type and typmod
3329 : : */
3330 : 251 : typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
3331 : 251 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3332 [ + + + + ]: 251 : if (inhtypeid != newtypeid || inhtypmod != newtypmod)
3333 [ + - ]: 8 : ereport(ERROR,
3334 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3335 : : errmsg("column \"%s\" has a type conflict",
3336 : : attributeName),
3337 : : errdetail("%s versus %s",
3338 : : format_type_with_typemod(inhtypeid, inhtypmod),
3339 : : format_type_with_typemod(newtypeid, newtypmod))));
3340 : :
3341 : : /*
3342 : : * Must have the same collation
3343 : : */
3344 : 243 : inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
3345 : 243 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3346 [ + + ]: 243 : if (inhcollid != newcollid)
3347 [ + - ]: 4 : ereport(ERROR,
3348 : : (errcode(ERRCODE_COLLATION_MISMATCH),
3349 : : errmsg("column \"%s\" has a collation conflict",
3350 : : attributeName),
3351 : : errdetail("\"%s\" versus \"%s\"",
3352 : : get_collation_name(inhcollid),
3353 : : get_collation_name(newcollid))));
3354 : :
3355 : : /*
3356 : : * Identity is never inherited by a regular inheritance child. Pick
3357 : : * child's identity definition if there's one.
3358 : : */
3359 : 239 : inhdef->identity = newdef->identity;
3360 : :
3361 : : /*
3362 : : * Copy storage parameter
3363 : : */
3364 [ - + ]: 239 : if (inhdef->storage == 0)
3365 : 0 : inhdef->storage = newdef->storage;
3366 [ + + + + ]: 239 : else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
3367 [ + - ]: 4 : ereport(ERROR,
3368 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3369 : : errmsg("column \"%s\" has a storage parameter conflict",
3370 : : attributeName),
3371 : : errdetail("%s versus %s",
3372 : : storage_name(inhdef->storage),
3373 : : storage_name(newdef->storage))));
3374 : :
3375 : : /*
3376 : : * Copy compression parameter
3377 : : */
3378 [ + + ]: 235 : if (inhdef->compression == NULL)
3379 : 231 : inhdef->compression = newdef->compression;
3380 [ + - ]: 4 : else if (newdef->compression != NULL)
3381 : : {
3382 [ + - ]: 4 : if (strcmp(inhdef->compression, newdef->compression) != 0)
3383 [ + - ]: 4 : ereport(ERROR,
3384 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3385 : : errmsg("column \"%s\" has a compression method conflict",
3386 : : attributeName),
3387 : : errdetail("%s versus %s", inhdef->compression, newdef->compression)));
3388 : : }
3389 : :
3390 : : /*
3391 : : * Merge of not-null constraints = OR 'em together
3392 : : */
3393 : 231 : inhdef->is_not_null |= newdef->is_not_null;
3394 : :
3395 : : /*
3396 : : * Check for conflicts related to generated columns.
3397 : : *
3398 : : * If the parent column is generated, the child column will be made a
3399 : : * generated column if it isn't already. If it is a generated column,
3400 : : * we'll take its generation expression in preference to the parent's. We
3401 : : * must check that the child column doesn't specify a default value or
3402 : : * identity, which matches the rules for a single column in
3403 : : * parse_utilcmd.c.
3404 : : *
3405 : : * Conversely, if the parent column is not generated, the child column
3406 : : * can't be either. (We used to allow that, but it results in being able
3407 : : * to override the generation expression via UPDATEs through the parent.)
3408 : : */
3409 [ + + ]: 231 : if (inhdef->generated)
3410 : : {
3411 [ + + + + ]: 41 : if (newdef->raw_default && !newdef->generated)
3412 [ + - ]: 8 : ereport(ERROR,
3413 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3414 : : errmsg("column \"%s\" inherits from generated column but specifies default",
3415 : : inhdef->colname)));
3416 [ + + ]: 33 : if (newdef->identity)
3417 [ + - ]: 8 : ereport(ERROR,
3418 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3419 : : errmsg("column \"%s\" inherits from generated column but specifies identity",
3420 : : inhdef->colname)));
3421 : : }
3422 : : else
3423 : : {
3424 [ + + ]: 190 : if (newdef->generated)
3425 [ + - ]: 8 : ereport(ERROR,
3426 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3427 : : errmsg("child column \"%s\" specifies generation expression",
3428 : : inhdef->colname),
3429 : : errhint("A child table column cannot be generated unless its parent column is.")));
3430 : : }
3431 : :
3432 [ + + + + : 207 : if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
+ + ]
3433 [ + - + + : 8 : ereport(ERROR,
+ + ]
3434 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3435 : : errmsg("column \"%s\" inherits from generated column of different kind",
3436 : : inhdef->colname),
3437 : : errdetail("Parent column is %s, child column is %s.",
3438 : : inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3439 : : newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3440 : :
3441 : : /*
3442 : : * If new def has a default, override previous default
3443 : : */
3444 [ + + ]: 199 : if (newdef->raw_default != NULL)
3445 : : {
3446 : 20 : inhdef->raw_default = newdef->raw_default;
3447 : 20 : inhdef->cooked_default = newdef->cooked_default;
3448 : : }
3449 : :
3450 : : /* Mark the column as locally defined */
3451 : 199 : inhdef->is_local = true;
3452 : 199 : }
3453 : :
3454 : : /*
3455 : : * MergeInheritedAttribute
3456 : : * Merge given parent attribute definition into specified attribute
3457 : : * inherited from the previous parents.
3458 : : *
3459 : : * Input arguments:
3460 : : * 'inh_columns' is the list of previously inherited ColumnDefs.
3461 : : * 'exist_attno' is the number the existing matching attribute in inh_columns.
3462 : : * 'newdef' is the new parent column/attribute definition to be merged.
3463 : : *
3464 : : * The matching ColumnDef in 'inh_columns' list is modified and returned.
3465 : : *
3466 : : * Notes:
3467 : : * - The attribute is merged according to the rules laid out in the prologue
3468 : : * of MergeAttributes().
3469 : : * - If matching inherited attribute exists but the new attribute can not be
3470 : : * merged into it, the function throws respective errors.
3471 : : * - A partition inherits from only a single parent. Hence this function is
3472 : : * applicable only to a regular inheritance.
3473 : : */
3474 : : static ColumnDef *
3475 : 253 : MergeInheritedAttribute(List *inh_columns,
3476 : : int exist_attno,
3477 : : const ColumnDef *newdef)
3478 : : {
3479 : 253 : char *attributeName = newdef->colname;
3480 : : ColumnDef *prevdef;
3481 : : Oid prevtypeid,
3482 : : newtypeid;
3483 : : int32 prevtypmod,
3484 : : newtypmod;
3485 : : Oid prevcollid,
3486 : : newcollid;
3487 : :
3488 [ + - ]: 253 : ereport(NOTICE,
3489 : : (errmsg("merging multiple inherited definitions of column \"%s\"",
3490 : : attributeName)));
3491 : 253 : prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3492 : :
3493 : : /*
3494 : : * Must have the same type and typmod
3495 : : */
3496 : 253 : typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
3497 : 253 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3498 [ + - - + ]: 253 : if (prevtypeid != newtypeid || prevtypmod != newtypmod)
3499 [ # # ]: 0 : ereport(ERROR,
3500 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3501 : : errmsg("inherited column \"%s\" has a type conflict",
3502 : : attributeName),
3503 : : errdetail("%s versus %s",
3504 : : format_type_with_typemod(prevtypeid, prevtypmod),
3505 : : format_type_with_typemod(newtypeid, newtypmod))));
3506 : :
3507 : : /*
3508 : : * Must have the same collation
3509 : : */
3510 : 253 : prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
3511 : 253 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3512 [ - + ]: 253 : if (prevcollid != newcollid)
3513 [ # # ]: 0 : ereport(ERROR,
3514 : : (errcode(ERRCODE_COLLATION_MISMATCH),
3515 : : errmsg("inherited column \"%s\" has a collation conflict",
3516 : : attributeName),
3517 : : errdetail("\"%s\" versus \"%s\"",
3518 : : get_collation_name(prevcollid),
3519 : : get_collation_name(newcollid))));
3520 : :
3521 : : /*
3522 : : * Copy/check storage parameter
3523 : : */
3524 [ - + ]: 253 : if (prevdef->storage == 0)
3525 : 0 : prevdef->storage = newdef->storage;
3526 [ + + ]: 253 : else if (prevdef->storage != newdef->storage)
3527 [ + - ]: 4 : ereport(ERROR,
3528 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3529 : : errmsg("inherited column \"%s\" has a storage parameter conflict",
3530 : : attributeName),
3531 : : errdetail("%s versus %s",
3532 : : storage_name(prevdef->storage),
3533 : : storage_name(newdef->storage))));
3534 : :
3535 : : /*
3536 : : * Copy/check compression parameter
3537 : : */
3538 [ + + ]: 249 : if (prevdef->compression == NULL)
3539 : 237 : prevdef->compression = newdef->compression;
3540 [ + + ]: 12 : else if (newdef->compression != NULL)
3541 : : {
3542 [ + - ]: 4 : if (strcmp(prevdef->compression, newdef->compression) != 0)
3543 [ + - ]: 4 : ereport(ERROR,
3544 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3545 : : errmsg("column \"%s\" has a compression method conflict",
3546 : : attributeName),
3547 : : errdetail("%s versus %s",
3548 : : prevdef->compression, newdef->compression)));
3549 : : }
3550 : :
3551 : : /*
3552 : : * Check for GENERATED conflicts
3553 : : */
3554 [ + + ]: 245 : if (prevdef->generated != newdef->generated)
3555 [ + - ]: 16 : ereport(ERROR,
3556 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3557 : : errmsg("inherited column \"%s\" has a generation conflict",
3558 : : attributeName)));
3559 : :
3560 : : /*
3561 : : * Default and other constraints are handled by the caller.
3562 : : */
3563 : :
3564 [ - + ]: 229 : if (pg_add_s16_overflow(prevdef->inhcount, 1,
3565 : : &prevdef->inhcount))
3566 [ # # ]: 0 : ereport(ERROR,
3567 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3568 : : errmsg("too many inheritance parents"));
3569 : :
3570 : 229 : return prevdef;
3571 : : }
3572 : :
3573 : : /*
3574 : : * StoreCatalogInheritance
3575 : : * Updates the system catalogs with proper inheritance information.
3576 : : *
3577 : : * supers is a list of the OIDs of the new relation's direct ancestors.
3578 : : */
3579 : : static void
3580 : 42217 : StoreCatalogInheritance(Oid relationId, List *supers,
3581 : : bool child_is_partition)
3582 : : {
3583 : : Relation relation;
3584 : : int32 seqNumber;
3585 : : ListCell *entry;
3586 : :
3587 : : /*
3588 : : * sanity checks
3589 : : */
3590 : : Assert(OidIsValid(relationId));
3591 : :
3592 [ + + ]: 42217 : if (supers == NIL)
3593 : 35062 : return;
3594 : :
3595 : : /*
3596 : : * Store INHERITS information in pg_inherits using direct ancestors only.
3597 : : * Also enter dependencies on the direct ancestors, and make sure they are
3598 : : * marked with relhassubclass = true.
3599 : : *
3600 : : * (Once upon a time, both direct and indirect ancestors were found here
3601 : : * and then entered into pg_ipl. Since that catalog doesn't exist
3602 : : * anymore, there's no need to look for indirect ancestors.)
3603 : : */
3604 : 7155 : relation = table_open(InheritsRelationId, RowExclusiveLock);
3605 : :
3606 : 7155 : seqNumber = 1;
3607 [ + - + + : 14540 : foreach(entry, supers)
+ + ]
3608 : : {
3609 : 7385 : Oid parentOid = lfirst_oid(entry);
3610 : :
3611 : 7385 : StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
3612 : : child_is_partition);
3613 : 7385 : seqNumber++;
3614 : : }
3615 : :
3616 : 7155 : table_close(relation, RowExclusiveLock);
3617 : : }
3618 : :
3619 : : /*
3620 : : * Make catalog entries showing relationId as being an inheritance child
3621 : : * of parentOid. inhRelation is the already-opened pg_inherits catalog.
3622 : : */
3623 : : static void
3624 : 8981 : StoreCatalogInheritance1(Oid relationId, Oid parentOid,
3625 : : int32 seqNumber, Relation inhRelation,
3626 : : bool child_is_partition)
3627 : : {
3628 : : ObjectAddress childobject,
3629 : : parentobject;
3630 : :
3631 : : /* store the pg_inherits row */
3632 : 8981 : StoreSingleInheritance(relationId, parentOid, seqNumber);
3633 : :
3634 : : /*
3635 : : * Store a dependency too
3636 : : */
3637 : 8981 : parentobject.classId = RelationRelationId;
3638 : 8981 : parentobject.objectId = parentOid;
3639 : 8981 : parentobject.objectSubId = 0;
3640 : 8981 : childobject.classId = RelationRelationId;
3641 : 8981 : childobject.objectId = relationId;
3642 : 8981 : childobject.objectSubId = 0;
3643 : :
3644 [ + + ]: 8981 : recordDependencyOn(&childobject, &parentobject,
3645 : : child_dependency_type(child_is_partition));
3646 : :
3647 : : /*
3648 : : * Post creation hook of this inheritance. Since object_access_hook
3649 : : * doesn't take multiple object identifiers, we relay oid of parent
3650 : : * relation using auxiliary_id argument.
3651 : : */
3652 [ - + ]: 8981 : InvokeObjectPostAlterHookArg(InheritsRelationId,
3653 : : relationId, 0,
3654 : : parentOid, false);
3655 : :
3656 : : /*
3657 : : * Mark the parent as having subclasses.
3658 : : */
3659 : 8981 : SetRelationHasSubclass(parentOid, true);
3660 : 8981 : }
3661 : :
3662 : : /*
3663 : : * Look for an existing column entry with the given name.
3664 : : *
3665 : : * Returns the index (starting with 1) if attribute already exists in columns,
3666 : : * 0 if it doesn't.
3667 : : */
3668 : : static int
3669 : 15506 : findAttrByName(const char *attributeName, const List *columns)
3670 : : {
3671 : : ListCell *lc;
3672 : 15506 : int i = 1;
3673 : :
3674 [ + + + + : 27032 : foreach(lc, columns)
+ + ]
3675 : : {
3676 [ + + ]: 12030 : if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
3677 : 504 : return i;
3678 : :
3679 : 11526 : i++;
3680 : : }
3681 : 15002 : return 0;
3682 : : }
3683 : :
3684 : :
3685 : : /*
3686 : : * SetRelationHasSubclass
3687 : : * Set the value of the relation's relhassubclass field in pg_class.
3688 : : *
3689 : : * It's always safe to set this field to true, because all SQL commands are
3690 : : * ready to see true and then find no children. On the other hand, commands
3691 : : * generally assume zero children if this is false.
3692 : : *
3693 : : * Caller must hold any self-exclusive lock until end of transaction. If the
3694 : : * new value is false, caller must have acquired that lock before reading the
3695 : : * evidence that justified the false value. That way, it properly waits if
3696 : : * another backend is simultaneously concluding no need to change the tuple
3697 : : * (new and old values are true).
3698 : : *
3699 : : * NOTE: an important side-effect of this operation is that an SI invalidation
3700 : : * message is sent out to all backends --- including me --- causing plans
3701 : : * referencing the relation to be rebuilt with the new list of children.
3702 : : * This must happen even if we find that no change is needed in the pg_class
3703 : : * row.
3704 : : */
3705 : : void
3706 : 11061 : SetRelationHasSubclass(Oid relationId, bool relhassubclass)
3707 : : {
3708 : : Relation relationRelation;
3709 : : HeapTuple tuple;
3710 : : Form_pg_class classtuple;
3711 : :
3712 : : Assert(CheckRelationOidLockedByMe(relationId,
3713 : : ShareUpdateExclusiveLock, false) ||
3714 : : CheckRelationOidLockedByMe(relationId,
3715 : : ShareRowExclusiveLock, true));
3716 : :
3717 : : /*
3718 : : * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3719 : : */
3720 : 11061 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3721 : 11061 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3722 [ - + ]: 11061 : if (!HeapTupleIsValid(tuple))
3723 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationId);
3724 : 11061 : classtuple = (Form_pg_class) GETSTRUCT(tuple);
3725 : :
3726 [ + + ]: 11061 : if (classtuple->relhassubclass != relhassubclass)
3727 : : {
3728 : 5425 : classtuple->relhassubclass = relhassubclass;
3729 : 5425 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3730 : : }
3731 : : else
3732 : : {
3733 : : /* no need to change tuple, but force relcache rebuild anyway */
3734 : 5636 : CacheInvalidateRelcacheByTuple(tuple);
3735 : : }
3736 : :
3737 : 11061 : heap_freetuple(tuple);
3738 : 11061 : table_close(relationRelation, RowExclusiveLock);
3739 : 11061 : }
3740 : :
3741 : : /*
3742 : : * CheckRelationTableSpaceMove
3743 : : * Check if relation can be moved to new tablespace.
3744 : : *
3745 : : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3746 : : *
3747 : : * Returns true if the relation can be moved to the new tablespace; raises
3748 : : * an error if it is not possible to do the move; returns false if the move
3749 : : * would have no effect.
3750 : : */
3751 : : bool
3752 : 159 : CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
3753 : : {
3754 : : Oid oldTableSpaceId;
3755 : :
3756 : : /*
3757 : : * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3758 : : * stored as 0.
3759 : : */
3760 : 159 : oldTableSpaceId = rel->rd_rel->reltablespace;
3761 [ + + ]: 159 : if (newTableSpaceId == oldTableSpaceId ||
3762 [ + + + + ]: 154 : (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3763 : 10 : return false;
3764 : :
3765 : : /*
3766 : : * We cannot support moving mapped relations into different tablespaces.
3767 : : * (In particular this eliminates all shared catalogs.)
3768 : : */
3769 [ + + + + : 149 : if (RelationIsMapped(rel))
+ - + + +
+ - + ]
3770 [ # # ]: 0 : ereport(ERROR,
3771 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3772 : : errmsg("cannot move system relation \"%s\"",
3773 : : RelationGetRelationName(rel))));
3774 : :
3775 : : /* Cannot move a non-shared relation into pg_global */
3776 [ + + ]: 149 : if (newTableSpaceId == GLOBALTABLESPACE_OID)
3777 [ + - ]: 8 : ereport(ERROR,
3778 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3779 : : errmsg("only shared relations can be placed in pg_global tablespace")));
3780 : :
3781 : : /*
3782 : : * Do not allow moving temp tables of other backends ... their local
3783 : : * buffer manager is not going to cope.
3784 : : */
3785 [ + + - + ]: 141 : if (RELATION_IS_OTHER_TEMP(rel))
3786 [ # # ]: 0 : ereport(ERROR,
3787 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3788 : : errmsg("cannot move temporary tables of other sessions")));
3789 : :
3790 : 141 : return true;
3791 : : }
3792 : :
3793 : : /*
3794 : : * SetRelationTableSpace
3795 : : * Set new reltablespace and relfilenumber in pg_class entry.
3796 : : *
3797 : : * newTableSpaceId is the new tablespace for the relation, and
3798 : : * newRelFilenumber its new filenumber. If newRelFilenumber is
3799 : : * InvalidRelFileNumber, this field is not updated.
3800 : : *
3801 : : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3802 : : *
3803 : : * The caller of this routine had better check if a relation can be
3804 : : * moved to this new tablespace by calling CheckRelationTableSpaceMove()
3805 : : * first, and is responsible for making the change visible with
3806 : : * CommandCounterIncrement().
3807 : : */
3808 : : void
3809 : 141 : SetRelationTableSpace(Relation rel,
3810 : : Oid newTableSpaceId,
3811 : : RelFileNumber newRelFilenumber)
3812 : : {
3813 : : Relation pg_class;
3814 : : HeapTuple tuple;
3815 : : ItemPointerData otid;
3816 : : Form_pg_class rd_rel;
3817 : 141 : Oid reloid = RelationGetRelid(rel);
3818 : :
3819 : : Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3820 : :
3821 : : /* Get a modifiable copy of the relation's pg_class row. */
3822 : 141 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
3823 : :
3824 : 141 : tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3825 [ - + ]: 141 : if (!HeapTupleIsValid(tuple))
3826 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
3827 : 141 : otid = tuple->t_self;
3828 : 141 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3829 : :
3830 : : /* Update the pg_class row. */
3831 : 282 : rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3832 [ + + ]: 141 : InvalidOid : newTableSpaceId;
3833 [ + + ]: 141 : if (RelFileNumberIsValid(newRelFilenumber))
3834 : 112 : rd_rel->relfilenode = newRelFilenumber;
3835 : 141 : CatalogTupleUpdate(pg_class, &otid, tuple);
3836 : 141 : UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3837 : :
3838 : : /*
3839 : : * Record dependency on tablespace. This is only required for relations
3840 : : * that have no physical storage.
3841 : : */
3842 [ + + + + : 141 : if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
+ - + + +
+ ]
3843 : 20 : changeDependencyOnTablespace(RelationRelationId, reloid,
3844 : : rd_rel->reltablespace);
3845 : :
3846 : 141 : heap_freetuple(tuple);
3847 : 141 : table_close(pg_class, RowExclusiveLock);
3848 : 141 : }
3849 : :
3850 : : /*
3851 : : * renameatt_check - basic sanity checks before attribute rename
3852 : : */
3853 : : static void
3854 : 694 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3855 : : {
3856 : 694 : char relkind = classform->relkind;
3857 : :
3858 [ + + + + ]: 694 : if (classform->reloftype && !recursing)
3859 [ + - ]: 4 : ereport(ERROR,
3860 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3861 : : errmsg("cannot rename column of typed table")));
3862 : :
3863 : : /*
3864 : : * Renaming the columns of sequences or toast tables doesn't actually
3865 : : * break anything from the system's point of view, since internal
3866 : : * references are by attnum. But it doesn't seem right to allow users to
3867 : : * change names that are hardcoded into the system, hence the following
3868 : : * restriction.
3869 : : */
3870 [ + + + + ]: 690 : if (relkind != RELKIND_RELATION &&
3871 [ + - ]: 65 : relkind != RELKIND_VIEW &&
3872 [ + + ]: 65 : relkind != RELKIND_MATVIEW &&
3873 [ + - ]: 25 : relkind != RELKIND_COMPOSITE_TYPE &&
3874 [ + - ]: 25 : relkind != RELKIND_INDEX &&
3875 [ - + ]: 25 : relkind != RELKIND_PARTITIONED_INDEX &&
3876 [ # # ]: 0 : relkind != RELKIND_FOREIGN_TABLE &&
3877 : : relkind != RELKIND_PARTITIONED_TABLE)
3878 [ # # ]: 0 : ereport(ERROR,
3879 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3880 : : errmsg("cannot rename columns of relation \"%s\"",
3881 : : NameStr(classform->relname)),
3882 : : errdetail_relkind_not_supported(relkind)));
3883 : :
3884 : : /*
3885 : : * permissions checking. only the owner of a class can change its schema.
3886 : : */
3887 [ - + ]: 690 : if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
3888 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
3889 : 0 : NameStr(classform->relname));
3890 : :
3891 : : /*
3892 : : * Conflict log tables are used internally for logical replication
3893 : : * conflict logging and should not be modified directly, as it could
3894 : : * disrupt conflict logging.
3895 : : */
3896 [ + + ]: 690 : if (IsConflictLogTableClass(classform))
3897 [ + - ]: 4 : ereport(ERROR,
3898 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3899 : : errmsg("cannot rename columns of conflict log table \"%s\"",
3900 : : NameStr(classform->relname)),
3901 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
3902 : :
3903 [ + + + + ]: 686 : if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
3904 [ + - ]: 1 : ereport(ERROR,
3905 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3906 : : errmsg("permission denied: \"%s\" is a system catalog",
3907 : : NameStr(classform->relname))));
3908 : 685 : }
3909 : :
3910 : : /*
3911 : : * renameatt_internal - workhorse for renameatt
3912 : : *
3913 : : * Return value is the attribute number in the 'myrelid' relation.
3914 : : */
3915 : : static AttrNumber
3916 : 372 : renameatt_internal(Oid myrelid,
3917 : : const char *oldattname,
3918 : : const char *newattname,
3919 : : bool recurse,
3920 : : bool recursing,
3921 : : int expected_parents,
3922 : : DropBehavior behavior)
3923 : : {
3924 : : Relation targetrelation;
3925 : : Relation attrelation;
3926 : : HeapTuple atttup;
3927 : : Form_pg_attribute attform;
3928 : : AttrNumber attnum;
3929 : :
3930 : : /*
3931 : : * Grab an exclusive lock on the target table, which we will NOT release
3932 : : * until end of transaction.
3933 : : */
3934 : 372 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
3935 : 372 : renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
3936 : :
3937 : : /*
3938 : : * if the 'recurse' flag is set then we are supposed to rename this
3939 : : * attribute in all classes that inherit from 'relname' (as well as in
3940 : : * 'relname').
3941 : : *
3942 : : * any permissions or problems with duplicate attributes will cause the
3943 : : * whole transaction to abort, which is what we want -- all or nothing.
3944 : : */
3945 [ + + ]: 372 : if (recurse)
3946 : : {
3947 : : List *child_oids,
3948 : : *child_numparents;
3949 : : ListCell *lo,
3950 : : *li;
3951 : :
3952 : : /*
3953 : : * we need the number of parents for each child so that the recursive
3954 : : * calls to renameatt() can determine whether there are any parents
3955 : : * outside the inheritance hierarchy being processed.
3956 : : */
3957 : 166 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3958 : : &child_numparents);
3959 : :
3960 : : /*
3961 : : * find_all_inheritors does the recursive search of the inheritance
3962 : : * hierarchy, so all we have to do is process all of the relids in the
3963 : : * list that it returns.
3964 : : */
3965 [ + - + + : 490 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
3966 : : {
3967 : 344 : Oid childrelid = lfirst_oid(lo);
3968 : 344 : int numparents = lfirst_int(li);
3969 : :
3970 [ + + ]: 344 : if (childrelid == myrelid)
3971 : 166 : continue;
3972 : : /* note we need not recurse again */
3973 : 178 : renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
3974 : : }
3975 : : }
3976 : : else
3977 : : {
3978 : : /*
3979 : : * If we are told not to recurse, there had better not be any child
3980 : : * tables; else the rename would put them out of step.
3981 : : *
3982 : : * expected_parents will only be 0 if we are not already recursing.
3983 : : */
3984 [ + + + + ]: 234 : if (expected_parents == 0 &&
3985 : 28 : find_inheritance_children(myrelid, NoLock) != NIL)
3986 [ + - ]: 8 : ereport(ERROR,
3987 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3988 : : errmsg("inherited column \"%s\" must be renamed in child tables too",
3989 : : oldattname)));
3990 : : }
3991 : :
3992 : : /* rename attributes in typed tables of composite type */
3993 [ + + ]: 344 : if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
3994 : : {
3995 : : List *child_oids;
3996 : : ListCell *lo;
3997 : :
3998 : 20 : child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
3999 : 20 : RelationGetRelationName(targetrelation),
4000 : : behavior);
4001 : :
4002 [ + + + + : 20 : foreach(lo, child_oids)
+ + ]
4003 : 4 : renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
4004 : : }
4005 : :
4006 : 340 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
4007 : :
4008 : 340 : atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
4009 [ + + ]: 340 : if (!HeapTupleIsValid(atttup))
4010 [ + - ]: 16 : ereport(ERROR,
4011 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
4012 : : errmsg("column \"%s\" does not exist",
4013 : : oldattname)));
4014 : 324 : attform = (Form_pg_attribute) GETSTRUCT(atttup);
4015 : :
4016 : 324 : attnum = attform->attnum;
4017 [ - + ]: 324 : if (attnum <= 0)
4018 [ # # ]: 0 : ereport(ERROR,
4019 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4020 : : errmsg("cannot rename system column \"%s\"",
4021 : : oldattname)));
4022 : :
4023 : : /*
4024 : : * if the attribute is inherited, forbid the renaming. if this is a
4025 : : * top-level call to renameatt(), then expected_parents will be 0, so the
4026 : : * effect of this code will be to prohibit the renaming if the attribute
4027 : : * is inherited at all. if this is a recursive call to renameatt(),
4028 : : * expected_parents will be the number of parents the current relation has
4029 : : * within the inheritance hierarchy being processed, so we'll prohibit the
4030 : : * renaming only if there are additional parents from elsewhere.
4031 : : */
4032 [ + + ]: 324 : if (attform->attinhcount > expected_parents)
4033 [ + - ]: 20 : ereport(ERROR,
4034 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4035 : : errmsg("cannot rename inherited column \"%s\"",
4036 : : oldattname)));
4037 : :
4038 : : /* new name should not already exist */
4039 : 304 : (void) check_for_column_name_collision(targetrelation, newattname, false);
4040 : :
4041 : : /* apply the update */
4042 : 296 : namestrcpy(&(attform->attname), newattname);
4043 : :
4044 : 296 : CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
4045 : :
4046 [ - + ]: 296 : InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
4047 : :
4048 : 296 : heap_freetuple(atttup);
4049 : :
4050 : 296 : table_close(attrelation, RowExclusiveLock);
4051 : :
4052 : 296 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4053 : :
4054 : 296 : return attnum;
4055 : : }
4056 : :
4057 : : /*
4058 : : * Perform permissions and integrity checks before acquiring a relation lock.
4059 : : */
4060 : : static void
4061 : 287 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
4062 : : void *arg)
4063 : : {
4064 : : HeapTuple tuple;
4065 : : Form_pg_class form;
4066 : :
4067 : 287 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
4068 [ + + ]: 287 : if (!HeapTupleIsValid(tuple))
4069 : 25 : return; /* concurrently dropped */
4070 : 262 : form = (Form_pg_class) GETSTRUCT(tuple);
4071 : 262 : renameatt_check(relid, form, false);
4072 : 253 : ReleaseSysCache(tuple);
4073 : : }
4074 : :
4075 : : /*
4076 : : * renameatt - changes the name of an attribute in a relation
4077 : : *
4078 : : * The returned ObjectAddress is that of the renamed column.
4079 : : */
4080 : : ObjectAddress
4081 : 219 : renameatt(RenameStmt *stmt)
4082 : : {
4083 : : Oid relid;
4084 : : AttrNumber attnum;
4085 : : ObjectAddress address;
4086 : :
4087 : : /* lock level taken here should match renameatt_internal */
4088 : 219 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4089 : 219 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4090 : : RangeVarCallbackForRenameAttribute,
4091 : : NULL);
4092 : :
4093 [ + + ]: 206 : if (!OidIsValid(relid))
4094 : : {
4095 [ + - ]: 16 : ereport(NOTICE,
4096 : : (errmsg("relation \"%s\" does not exist, skipping",
4097 : : stmt->relation->relname)));
4098 : 16 : return InvalidObjectAddress;
4099 : : }
4100 : :
4101 : : attnum =
4102 : 190 : renameatt_internal(relid,
4103 : 190 : stmt->subname, /* old att name */
4104 : 190 : stmt->newname, /* new att name */
4105 : 190 : stmt->relation->inh, /* recursive? */
4106 : : false, /* recursing? */
4107 : : 0, /* expected inhcount */
4108 : : stmt->behavior);
4109 : :
4110 : 134 : ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4111 : :
4112 : 134 : return address;
4113 : : }
4114 : :
4115 : : /*
4116 : : * same logic as renameatt_internal
4117 : : */
4118 : : static ObjectAddress
4119 : 64 : rename_constraint_internal(Oid myrelid,
4120 : : Oid mytypid,
4121 : : const char *oldconname,
4122 : : const char *newconname,
4123 : : bool recurse,
4124 : : bool recursing,
4125 : : int expected_parents)
4126 : : {
4127 : 64 : Relation targetrelation = NULL;
4128 : : Oid constraintOid;
4129 : : HeapTuple tuple;
4130 : : Form_pg_constraint con;
4131 : : ObjectAddress address;
4132 : :
4133 : : Assert(!myrelid || !mytypid);
4134 : :
4135 [ + + ]: 64 : if (mytypid)
4136 : : {
4137 : 4 : constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
4138 : : }
4139 : : else
4140 : : {
4141 : 60 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
4142 : :
4143 : : /*
4144 : : * don't tell it whether we're recursing; we allow changing typed
4145 : : * tables here
4146 : : */
4147 : 60 : renameatt_check(myrelid, RelationGetForm(targetrelation), false);
4148 : :
4149 : 60 : constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
4150 : : }
4151 : :
4152 : 64 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
4153 [ - + ]: 64 : if (!HeapTupleIsValid(tuple))
4154 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
4155 : : constraintOid);
4156 : 64 : con = (Form_pg_constraint) GETSTRUCT(tuple);
4157 : :
4158 [ + + ]: 64 : if (myrelid &&
4159 [ + + ]: 60 : (con->contype == CONSTRAINT_CHECK ||
4160 [ + + ]: 20 : con->contype == CONSTRAINT_NOTNULL) &&
4161 [ + + ]: 44 : !con->connoinherit)
4162 : : {
4163 [ + + ]: 36 : if (recurse)
4164 : : {
4165 : : List *child_oids,
4166 : : *child_numparents;
4167 : : ListCell *lo,
4168 : : *li;
4169 : :
4170 : 24 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
4171 : : &child_numparents);
4172 : :
4173 [ + - + + : 56 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
4174 : : {
4175 : 32 : Oid childrelid = lfirst_oid(lo);
4176 : 32 : int numparents = lfirst_int(li);
4177 : :
4178 [ + + ]: 32 : if (childrelid == myrelid)
4179 : 24 : continue;
4180 : :
4181 : 8 : rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
4182 : : }
4183 : : }
4184 : : else
4185 : : {
4186 [ + + + - ]: 16 : if (expected_parents == 0 &&
4187 : 4 : find_inheritance_children(myrelid, NoLock) != NIL)
4188 [ + - ]: 4 : ereport(ERROR,
4189 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4190 : : errmsg("inherited constraint \"%s\" must be renamed in child tables too",
4191 : : oldconname)));
4192 : : }
4193 : :
4194 [ + + ]: 32 : if (con->coninhcount > expected_parents)
4195 [ + - ]: 4 : ereport(ERROR,
4196 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4197 : : errmsg("cannot rename inherited constraint \"%s\"",
4198 : : oldconname)));
4199 : : }
4200 : :
4201 [ + + ]: 56 : if (con->conindid
4202 [ + + ]: 16 : && (con->contype == CONSTRAINT_PRIMARY
4203 [ + + ]: 8 : || con->contype == CONSTRAINT_UNIQUE
4204 [ - + ]: 4 : || con->contype == CONSTRAINT_EXCLUSION))
4205 : : /* rename the index; this renames the constraint as well */
4206 : 12 : RenameRelationInternal(con->conindid, newconname, false, true);
4207 : : else
4208 : 44 : RenameConstraintById(constraintOid, newconname);
4209 : :
4210 : 56 : ObjectAddressSet(address, ConstraintRelationId, constraintOid);
4211 : :
4212 : 56 : ReleaseSysCache(tuple);
4213 : :
4214 [ + + ]: 56 : if (targetrelation)
4215 : : {
4216 : : /*
4217 : : * Invalidate relcache so as others can see the new constraint name.
4218 : : */
4219 : 52 : CacheInvalidateRelcache(targetrelation);
4220 : :
4221 : 52 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4222 : : }
4223 : :
4224 : 56 : return address;
4225 : : }
4226 : :
4227 : : ObjectAddress
4228 : 60 : RenameConstraint(RenameStmt *stmt)
4229 : : {
4230 : 60 : Oid relid = InvalidOid;
4231 : 60 : Oid typid = InvalidOid;
4232 : :
4233 [ + + ]: 60 : if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4234 : : {
4235 : : Relation rel;
4236 : : HeapTuple tup;
4237 : :
4238 : 4 : typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4239 : 4 : rel = table_open(TypeRelationId, RowExclusiveLock);
4240 : 4 : tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4241 [ - + ]: 4 : if (!HeapTupleIsValid(tup))
4242 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", typid);
4243 : 4 : checkDomainOwner(tup);
4244 : 4 : ReleaseSysCache(tup);
4245 : 4 : table_close(rel, NoLock);
4246 : : }
4247 : : else
4248 : : {
4249 : : /* lock level taken here should match rename_constraint_internal */
4250 : 56 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4251 : 56 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4252 : : RangeVarCallbackForRenameAttribute,
4253 : : NULL);
4254 [ + + ]: 56 : if (!OidIsValid(relid))
4255 : : {
4256 [ + - ]: 4 : ereport(NOTICE,
4257 : : (errmsg("relation \"%s\" does not exist, skipping",
4258 : : stmt->relation->relname)));
4259 : 4 : return InvalidObjectAddress;
4260 : : }
4261 : : }
4262 : :
4263 : : return
4264 : 56 : rename_constraint_internal(relid, typid,
4265 : 56 : stmt->subname,
4266 : 56 : stmt->newname,
4267 [ + + ]: 108 : (stmt->relation &&
4268 [ + + ]: 52 : stmt->relation->inh), /* recursive? */
4269 : : false, /* recursing? */
4270 : 56 : 0 /* expected inhcount */ );
4271 : : }
4272 : :
4273 : : /*
4274 : : * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
4275 : : * RENAME
4276 : : */
4277 : : ObjectAddress
4278 : 304 : RenameRelation(RenameStmt *stmt)
4279 : : {
4280 : 304 : bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4281 : : Oid relid;
4282 : : ObjectAddress address;
4283 : :
4284 : : /*
4285 : : * Grab an exclusive lock on the target table, index, sequence, view,
4286 : : * materialized view, or foreign table, which we will NOT release until
4287 : : * end of transaction.
4288 : : *
4289 : : * Lock level used here should match RenameRelationInternal, to avoid lock
4290 : : * escalation. However, because ALTER INDEX can be used with any relation
4291 : : * type, we mustn't believe without verification.
4292 : : */
4293 : : for (;;)
4294 : 8 : {
4295 : : LOCKMODE lockmode;
4296 : : char relkind;
4297 : : bool obj_is_index;
4298 : :
4299 [ + + ]: 312 : lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4300 : :
4301 : 312 : relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4302 : 312 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4303 : : RangeVarCallbackForAlterRelation,
4304 : : stmt);
4305 : :
4306 [ + + ]: 279 : if (!OidIsValid(relid))
4307 : : {
4308 [ + - ]: 12 : ereport(NOTICE,
4309 : : (errmsg("relation \"%s\" does not exist, skipping",
4310 : : stmt->relation->relname)));
4311 : 12 : return InvalidObjectAddress;
4312 : : }
4313 : :
4314 : : /*
4315 : : * We allow mismatched statement and object types (e.g., ALTER INDEX
4316 : : * to rename a table), but we might've used the wrong lock level. If
4317 : : * that happens, retry with the correct lock level. We don't bother
4318 : : * if we already acquired AccessExclusiveLock with an index, however.
4319 : : */
4320 : 267 : relkind = get_rel_relkind(relid);
4321 [ + + + + ]: 267 : obj_is_index = (relkind == RELKIND_INDEX ||
4322 : : relkind == RELKIND_PARTITIONED_INDEX);
4323 [ + + + + ]: 267 : if (obj_is_index || is_index_stmt == obj_is_index)
4324 : : break;
4325 : :
4326 : 8 : UnlockRelationOid(relid, lockmode);
4327 : 8 : is_index_stmt = obj_is_index;
4328 : : }
4329 : :
4330 : : /* Do the work */
4331 : 259 : RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4332 : :
4333 : 251 : ObjectAddressSet(address, RelationRelationId, relid);
4334 : :
4335 : 251 : return address;
4336 : : }
4337 : :
4338 : : /*
4339 : : * RenameRelationInternal - change the name of a relation
4340 : : */
4341 : : void
4342 : 1371 : RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
4343 : : {
4344 : : Relation targetrelation;
4345 : : Relation relrelation; /* for RELATION relation */
4346 : : ItemPointerData otid;
4347 : : HeapTuple reltup;
4348 : : Form_pg_class relform;
4349 : : Oid namespaceId;
4350 : :
4351 : : /*
4352 : : * Grab a lock on the target relation, which we will NOT release until end
4353 : : * of transaction. We need at least a self-exclusive lock so that
4354 : : * concurrent DDL doesn't overwrite the rename if they start updating
4355 : : * while still seeing the old version. The lock also guards against
4356 : : * triggering relcache reloads in concurrent sessions, which might not
4357 : : * handle this information changing under them. For indexes, we can use a
4358 : : * reduced lock level because RelationReloadIndexInfo() handles indexes
4359 : : * specially.
4360 : : */
4361 [ + + ]: 1371 : targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4362 : 1371 : namespaceId = RelationGetNamespace(targetrelation);
4363 : :
4364 : : /*
4365 : : * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4366 : : */
4367 : 1371 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4368 : :
4369 : 1371 : reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
4370 [ - + ]: 1371 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4371 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4372 : 1371 : otid = reltup->t_self;
4373 : 1371 : relform = (Form_pg_class) GETSTRUCT(reltup);
4374 : :
4375 [ + + ]: 1371 : if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4376 [ + - ]: 8 : ereport(ERROR,
4377 : : (errcode(ERRCODE_DUPLICATE_TABLE),
4378 : : errmsg("relation \"%s\" already exists",
4379 : : newrelname)));
4380 : :
4381 : : /*
4382 : : * RenameRelation is careful not to believe the caller's idea of the
4383 : : * relation kind being handled. We don't have to worry about this, but
4384 : : * let's not be totally oblivious to it. We can process an index as
4385 : : * not-an-index, but not the other way around.
4386 : : */
4387 : : Assert(!is_index ||
4388 : : is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4389 : : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4390 : :
4391 : : /*
4392 : : * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4393 : : * because it's a copy...)
4394 : : */
4395 : 1363 : namestrcpy(&(relform->relname), newrelname);
4396 : :
4397 : 1363 : CatalogTupleUpdate(relrelation, &otid, reltup);
4398 : 1363 : UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
4399 : :
4400 [ - + ]: 1363 : InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4401 : : InvalidOid, is_internal);
4402 : :
4403 : 1363 : heap_freetuple(reltup);
4404 : 1363 : table_close(relrelation, RowExclusiveLock);
4405 : :
4406 : : /*
4407 : : * Also rename the associated type, if any.
4408 : : */
4409 [ + + ]: 1363 : if (OidIsValid(targetrelation->rd_rel->reltype))
4410 : 87 : RenameTypeInternal(targetrelation->rd_rel->reltype,
4411 : : newrelname, namespaceId);
4412 : :
4413 : : /*
4414 : : * Also rename the associated constraint, if any.
4415 : : */
4416 [ + + ]: 1363 : if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4417 [ + + ]: 711 : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4418 : : {
4419 : 664 : Oid constraintId = get_index_constraint(myrelid);
4420 : :
4421 [ + + ]: 664 : if (OidIsValid(constraintId))
4422 : 24 : RenameConstraintById(constraintId, newrelname);
4423 : : }
4424 : :
4425 : : /*
4426 : : * Close rel, but keep lock!
4427 : : */
4428 : 1363 : relation_close(targetrelation, NoLock);
4429 : 1363 : }
4430 : :
4431 : : /*
4432 : : * ResetRelRewrite - reset relrewrite
4433 : : */
4434 : : void
4435 : 543 : ResetRelRewrite(Oid myrelid)
4436 : : {
4437 : : Relation relrelation; /* for RELATION relation */
4438 : : HeapTuple reltup;
4439 : : Form_pg_class relform;
4440 : :
4441 : : /*
4442 : : * Find relation's pg_class tuple.
4443 : : */
4444 : 543 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4445 : :
4446 : 543 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4447 [ - + ]: 543 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4448 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4449 : 543 : relform = (Form_pg_class) GETSTRUCT(reltup);
4450 : :
4451 : : /*
4452 : : * Update pg_class tuple.
4453 : : */
4454 : 543 : relform->relrewrite = InvalidOid;
4455 : :
4456 : 543 : CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4457 : :
4458 : 543 : heap_freetuple(reltup);
4459 : 543 : table_close(relrelation, RowExclusiveLock);
4460 : 543 : }
4461 : :
4462 : : /*
4463 : : * Disallow ALTER TABLE (and similar commands) when the current backend has
4464 : : * any open reference to the target table besides the one just acquired by
4465 : : * the calling command; this implies there's an open cursor or active plan.
4466 : : * We need this check because our lock doesn't protect us against stomping
4467 : : * on our own foot, only other people's feet!
4468 : : *
4469 : : * For ALTER TABLE, the only case known to cause serious trouble is ALTER
4470 : : * COLUMN TYPE, and some changes are obviously pretty benign, so this could
4471 : : * possibly be relaxed to only error out for certain types of alterations.
4472 : : * But the use-case for allowing any of these things is not obvious, so we
4473 : : * won't work hard at it for now.
4474 : : *
4475 : : * We also reject these commands if there are any pending AFTER trigger events
4476 : : * for the rel. This is certainly necessary for the rewriting variants of
4477 : : * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
4478 : : * events would try to fetch the wrong tuples. It might be overly cautious
4479 : : * in other cases, but again it seems better to err on the side of paranoia.
4480 : : *
4481 : : * REINDEX calls this with "rel" referencing the index to be rebuilt; here
4482 : : * we are worried about active indexscans on the index. The trigger-event
4483 : : * check can be skipped, since we are doing no damage to the parent table.
4484 : : *
4485 : : * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
4486 : : */
4487 : : void
4488 : 118929 : CheckTableNotInUse(Relation rel, const char *stmt)
4489 : : {
4490 : : int expected_refcnt;
4491 : :
4492 [ + + ]: 118929 : expected_refcnt = rel->rd_isnailed ? 2 : 1;
4493 [ + + ]: 118929 : if (rel->rd_refcnt != expected_refcnt)
4494 [ + - ]: 44 : ereport(ERROR,
4495 : : (errcode(ERRCODE_OBJECT_IN_USE),
4496 : : /* translator: first %s is a SQL command, eg ALTER TABLE */
4497 : : errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4498 : : stmt, RelationGetRelationName(rel))));
4499 : :
4500 [ + + ]: 118885 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
4501 [ + + + + ]: 195266 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4502 : 96912 : AfterTriggerPendingOnRel(RelationGetRelid(rel)))
4503 [ + - ]: 12 : ereport(ERROR,
4504 : : (errcode(ERRCODE_OBJECT_IN_USE),
4505 : : /* translator: first %s is a SQL command, eg ALTER TABLE */
4506 : : errmsg("cannot %s \"%s\" because it has pending trigger events",
4507 : : stmt, RelationGetRelationName(rel))));
4508 : 118873 : }
4509 : :
4510 : : /*
4511 : : * CheckAlterTableIsSafe
4512 : : * Verify that it's safe to allow ALTER TABLE on this relation.
4513 : : *
4514 : : * This consists of CheckTableNotInUse() plus a check that the relation
4515 : : * isn't another session's temp table. We must split out the temp-table
4516 : : * check because there are callers of CheckTableNotInUse() that don't want
4517 : : * that, notably DROP TABLE. (We must allow DROP or we couldn't clean out
4518 : : * an orphaned temp schema.) Compare truncate_check_activity().
4519 : : */
4520 : : static void
4521 : 43094 : CheckAlterTableIsSafe(Relation rel)
4522 : : {
4523 : : /*
4524 : : * Don't allow ALTER on temp tables of other backends. Their local buffer
4525 : : * manager is not going to cope if we need to change the table's contents.
4526 : : * Even if we don't, there may be optimizations that assume temp tables
4527 : : * aren't subject to such interference.
4528 : : */
4529 [ + + + + ]: 43094 : if (RELATION_IS_OTHER_TEMP(rel))
4530 [ + - ]: 2 : ereport(ERROR,
4531 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4532 : : errmsg("cannot alter temporary tables of other sessions")));
4533 : :
4534 : : /*
4535 : : * Also check for active uses of the relation in the current transaction,
4536 : : * including open scans and pending AFTER trigger events.
4537 : : */
4538 : 43092 : CheckTableNotInUse(rel, "ALTER TABLE");
4539 : 43060 : }
4540 : :
4541 : : /*
4542 : : * AlterTableLookupRelation
4543 : : * Look up, and lock, the OID for the relation named by an alter table
4544 : : * statement.
4545 : : */
4546 : : Oid
4547 : 24279 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
4548 : : {
4549 : 48492 : return RangeVarGetRelidExtended(stmt->relation, lockmode,
4550 : 24279 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4551 : : RangeVarCallbackForAlterRelation,
4552 : : stmt);
4553 : : }
4554 : :
4555 : : /*
4556 : : * AlterTable
4557 : : * Execute ALTER TABLE, which can be a list of subcommands
4558 : : *
4559 : : * ALTER TABLE is performed in three phases:
4560 : : * 1. Examine subcommands and perform pre-transformation checking.
4561 : : * 2. Validate and transform subcommands, and update system catalogs.
4562 : : * 3. Scan table(s) to check new constraints, and optionally recopy
4563 : : * the data into new table(s).
4564 : : * Phase 3 is not performed unless one or more of the subcommands requires
4565 : : * it. The intention of this design is to allow multiple independent
4566 : : * updates of the table schema to be performed with only one pass over the
4567 : : * data.
4568 : : *
4569 : : * ATPrepCmd performs phase 1. A "work queue" entry is created for
4570 : : * each table to be affected (there may be multiple affected tables if the
4571 : : * commands traverse a table inheritance hierarchy). Also we do preliminary
4572 : : * validation of the subcommands. Because earlier subcommands may change
4573 : : * the catalog state seen by later commands, there are limits to what can
4574 : : * be done in this phase. Generally, this phase acquires table locks,
4575 : : * checks permissions and relkind, and recurses to find child tables.
4576 : : *
4577 : : * ATRewriteCatalogs performs phase 2 for each affected table.
4578 : : * Certain subcommands need to be performed before others to avoid
4579 : : * unnecessary conflicts; for example, DROP COLUMN should come before
4580 : : * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
4581 : : * lists, one for each logical "pass" of phase 2.
4582 : : *
4583 : : * ATRewriteTables performs phase 3 for those tables that need it.
4584 : : *
4585 : : * For most subcommand types, phases 2 and 3 do no explicit recursion,
4586 : : * since phase 1 already does it. However, for certain subcommand types
4587 : : * it is only possible to determine how to recurse at phase 2 time; for
4588 : : * those cases, phase 1 sets the cmd->recurse flag.
4589 : : *
4590 : : * Thanks to the magic of MVCC, an error anywhere along the way rolls back
4591 : : * the whole operation; we don't have to do anything special to clean up.
4592 : : *
4593 : : * The caller must lock the relation, with an appropriate lock level
4594 : : * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
4595 : : * or higher. We pass the lock level down
4596 : : * so that we can apply it recursively to inherited tables. Note that the
4597 : : * lock level we want as we recurse might well be higher than required for
4598 : : * that specific subcommand. So we pass down the overall lock requirement,
4599 : : * rather than reassess it at lower levels.
4600 : : *
4601 : : * The caller also provides a "context" which is to be passed back to
4602 : : * utility.c when we need to execute a subcommand such as CREATE INDEX.
4603 : : * Some of the fields therein, such as the relid, are used here as well.
4604 : : */
4605 : : void
4606 : 24105 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
4607 : : AlterTableUtilityContext *context)
4608 : : {
4609 : : Relation rel;
4610 : :
4611 : : /* Caller is required to provide an adequate lock. */
4612 : 24105 : rel = relation_open(context->relid, NoLock);
4613 : :
4614 : 24105 : CheckAlterTableIsSafe(rel);
4615 : :
4616 : 24083 : ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4617 : 21250 : }
4618 : :
4619 : : /*
4620 : : * AlterTableInternal
4621 : : *
4622 : : * ALTER TABLE with target specified by OID
4623 : : *
4624 : : * We do not reject if the relation is already open, because it's quite
4625 : : * likely that one or more layers of caller have it open. That means it
4626 : : * is unsafe to use this entry point for alterations that could break
4627 : : * existing query plans. On the assumption it's not used for such, we
4628 : : * don't have to reject pending AFTER triggers, either.
4629 : : *
4630 : : * Also, since we don't have an AlterTableUtilityContext, this cannot be
4631 : : * used for any subcommand types that require parse transformation or
4632 : : * could generate subcommands that have to be passed to ProcessUtility.
4633 : : */
4634 : : void
4635 : 230 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
4636 : : {
4637 : : Relation rel;
4638 : 230 : LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4639 : :
4640 : 230 : rel = relation_open(relid, lockmode);
4641 : :
4642 : 230 : EventTriggerAlterTableRelid(relid);
4643 : :
4644 : 230 : ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4645 : 230 : }
4646 : :
4647 : : /*
4648 : : * AlterTableGetLockLevel
4649 : : *
4650 : : * Sets the overall lock level required for the supplied list of subcommands.
4651 : : * Policy for doing this set according to needs of AlterTable(), see
4652 : : * comments there for overall explanation.
4653 : : *
4654 : : * Function is called before and after parsing, so it must give same
4655 : : * answer each time it is called. Some subcommands are transformed
4656 : : * into other subcommand types, so the transform must never be made to a
4657 : : * lower lock level than previously assigned. All transforms are noted below.
4658 : : *
4659 : : * Since this is called before we lock the table we cannot use table metadata
4660 : : * to influence the type of lock we acquire.
4661 : : *
4662 : : * There should be no lockmodes hardcoded into the subcommand functions. All
4663 : : * lockmode decisions for ALTER TABLE are made here only. The one exception is
4664 : : * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
4665 : : * and does not travel through this section of code and cannot be combined with
4666 : : * any of the subcommands given here.
4667 : : *
4668 : : * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
4669 : : * so any changes that might affect SELECTs running on standbys need to use
4670 : : * AccessExclusiveLocks even if you think a lesser lock would do, unless you
4671 : : * have a solution for that also.
4672 : : *
4673 : : * Also note that pg_dump uses only an AccessShareLock, meaning that anything
4674 : : * that takes a lock less than AccessExclusiveLock can change object definitions
4675 : : * while pg_dump is running. Be careful to check that the appropriate data is
4676 : : * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
4677 : : * otherwise we might end up with an inconsistent dump that can't restore.
4678 : : */
4679 : : LOCKMODE
4680 : 24509 : AlterTableGetLockLevel(List *cmds)
4681 : : {
4682 : : /*
4683 : : * This only works if we read catalog tables using MVCC snapshots.
4684 : : */
4685 : : ListCell *lcmd;
4686 : 24509 : LOCKMODE lockmode = ShareUpdateExclusiveLock;
4687 : :
4688 [ + - + + : 49880 : foreach(lcmd, cmds)
+ + ]
4689 : : {
4690 : 25371 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4691 : 25371 : LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4692 : :
4693 [ + + + + : 25371 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + + + +
- ]
4694 : : {
4695 : : /*
4696 : : * These subcommands rewrite the heap, so require full locks.
4697 : : */
4698 : 5259 : case AT_AddColumn: /* may rewrite heap, in some cases and visible
4699 : : * to SELECT */
4700 : : case AT_SetAccessMethod: /* must rewrite heap */
4701 : : case AT_SetTableSpace: /* must rewrite heap */
4702 : : case AT_AlterColumnType: /* must rewrite heap */
4703 : 5259 : cmd_lockmode = AccessExclusiveLock;
4704 : 5259 : break;
4705 : :
4706 : : /*
4707 : : * These subcommands may require addition of toast tables. If
4708 : : * we add a toast table to a table currently being scanned, we
4709 : : * might miss data added to the new toast table by concurrent
4710 : : * insert transactions.
4711 : : */
4712 : 233 : case AT_SetStorage: /* may add toast tables, see
4713 : : * ATRewriteCatalogs() */
4714 : 233 : cmd_lockmode = AccessExclusiveLock;
4715 : 233 : break;
4716 : :
4717 : : /*
4718 : : * Removing constraints can affect SELECTs that have been
4719 : : * optimized assuming the constraint holds true. See also
4720 : : * CloneFkReferenced.
4721 : : */
4722 : 805 : case AT_DropConstraint: /* as DROP INDEX */
4723 : : case AT_DropNotNull: /* may change some SQL plans */
4724 : 805 : cmd_lockmode = AccessExclusiveLock;
4725 : 805 : break;
4726 : :
4727 : : /*
4728 : : * Subcommands that may be visible to concurrent SELECTs
4729 : : */
4730 : 1263 : case AT_DropColumn: /* change visible to SELECT */
4731 : : case AT_AddColumnToView: /* CREATE VIEW */
4732 : : case AT_DropOids: /* used to equiv to DropColumn */
4733 : : case AT_EnableAlwaysRule: /* may change SELECT rules */
4734 : : case AT_EnableReplicaRule: /* may change SELECT rules */
4735 : : case AT_EnableRule: /* may change SELECT rules */
4736 : : case AT_DisableRule: /* may change SELECT rules */
4737 : 1263 : cmd_lockmode = AccessExclusiveLock;
4738 : 1263 : break;
4739 : :
4740 : : /*
4741 : : * Changing owner may remove implicit SELECT privileges
4742 : : */
4743 : 1271 : case AT_ChangeOwner: /* change visible to SELECT */
4744 : 1271 : cmd_lockmode = AccessExclusiveLock;
4745 : 1271 : break;
4746 : :
4747 : : /*
4748 : : * Changing foreign table options may affect optimization.
4749 : : */
4750 : 144 : case AT_GenericOptions:
4751 : : case AT_AlterColumnGenericOptions:
4752 : 144 : cmd_lockmode = AccessExclusiveLock;
4753 : 144 : break;
4754 : :
4755 : : /*
4756 : : * These subcommands affect write operations only.
4757 : : */
4758 : 191 : case AT_EnableTrig:
4759 : : case AT_EnableAlwaysTrig:
4760 : : case AT_EnableReplicaTrig:
4761 : : case AT_EnableTrigAll:
4762 : : case AT_EnableTrigUser:
4763 : : case AT_DisableTrig:
4764 : : case AT_DisableTrigAll:
4765 : : case AT_DisableTrigUser:
4766 : 191 : cmd_lockmode = ShareRowExclusiveLock;
4767 : 191 : break;
4768 : :
4769 : : /*
4770 : : * These subcommands affect write operations only. XXX
4771 : : * Theoretically, these could be ShareRowExclusiveLock.
4772 : : */
4773 : 2205 : case AT_ColumnDefault:
4774 : : case AT_CookedColumnDefault:
4775 : : case AT_AlterConstraint:
4776 : : case AT_AddIndex: /* from ADD CONSTRAINT */
4777 : : case AT_AddIndexConstraint:
4778 : : case AT_ReplicaIdentity:
4779 : : case AT_SetNotNull:
4780 : : case AT_EnableRowSecurity:
4781 : : case AT_DisableRowSecurity:
4782 : : case AT_ForceRowSecurity:
4783 : : case AT_NoForceRowSecurity:
4784 : : case AT_AddIdentity:
4785 : : case AT_DropIdentity:
4786 : : case AT_SetIdentity:
4787 : : case AT_SetExpression:
4788 : : case AT_DropExpression:
4789 : : case AT_SetCompression:
4790 : 2205 : cmd_lockmode = AccessExclusiveLock;
4791 : 2205 : break;
4792 : :
4793 : 10022 : case AT_AddConstraint:
4794 : : case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4795 : : case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4796 [ + - ]: 10022 : if (IsA(cmd->def, Constraint))
4797 : : {
4798 : 10022 : Constraint *con = (Constraint *) cmd->def;
4799 : :
4800 [ + + + ]: 10022 : switch (con->contype)
4801 : : {
4802 : 7415 : case CONSTR_EXCLUSION:
4803 : : case CONSTR_PRIMARY:
4804 : : case CONSTR_UNIQUE:
4805 : :
4806 : : /*
4807 : : * Cases essentially the same as CREATE INDEX. We
4808 : : * could reduce the lock strength to ShareLock if
4809 : : * we can work out how to allow concurrent catalog
4810 : : * updates. XXX Might be set down to
4811 : : * ShareRowExclusiveLock but requires further
4812 : : * analysis.
4813 : : */
4814 : 7415 : cmd_lockmode = AccessExclusiveLock;
4815 : 7415 : break;
4816 : 1824 : case CONSTR_FOREIGN:
4817 : :
4818 : : /*
4819 : : * We add triggers to both tables when we add a
4820 : : * Foreign Key, so the lock level must be at least
4821 : : * as strong as CREATE TRIGGER.
4822 : : */
4823 : 1824 : cmd_lockmode = ShareRowExclusiveLock;
4824 : 1824 : break;
4825 : :
4826 : 783 : default:
4827 : 783 : cmd_lockmode = AccessExclusiveLock;
4828 : : }
4829 : : }
4830 : 10022 : break;
4831 : :
4832 : : /*
4833 : : * These subcommands affect inheritance behaviour. Queries
4834 : : * started before us will continue to see the old inheritance
4835 : : * behaviour, while queries started after we commit will see
4836 : : * new behaviour. No need to prevent reads or writes to the
4837 : : * subtable while we hook it up though. Changing the TupDesc
4838 : : * may be a problem, so keep highest lock.
4839 : : */
4840 : 379 : case AT_AddInherit:
4841 : : case AT_DropInherit:
4842 : 379 : cmd_lockmode = AccessExclusiveLock;
4843 : 379 : break;
4844 : :
4845 : : /*
4846 : : * These subcommands affect implicit row type conversion. They
4847 : : * have affects similar to CREATE/DROP CAST on queries. don't
4848 : : * provide for invalidating parse trees as a result of such
4849 : : * changes, so we keep these at AccessExclusiveLock.
4850 : : */
4851 : 55 : case AT_AddOf:
4852 : : case AT_DropOf:
4853 : 55 : cmd_lockmode = AccessExclusiveLock;
4854 : 55 : break;
4855 : :
4856 : : /*
4857 : : * Only used by CREATE OR REPLACE VIEW which must conflict
4858 : : * with an SELECTs currently using the view.
4859 : : */
4860 : 169 : case AT_ReplaceRelOptions:
4861 : 169 : cmd_lockmode = AccessExclusiveLock;
4862 : 169 : break;
4863 : :
4864 : : /*
4865 : : * These subcommands affect general strategies for performance
4866 : : * and maintenance, though don't change the semantic results
4867 : : * from normal data reads and writes. Delaying an ALTER TABLE
4868 : : * behind currently active writes only delays the point where
4869 : : * the new strategy begins to take effect, so there is no
4870 : : * benefit in waiting. In this case the minimum restriction
4871 : : * applies: we don't currently allow concurrent catalog
4872 : : * updates.
4873 : : */
4874 : 193 : case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4875 : : case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4876 : : case AT_DropCluster: /* Uses MVCC in getIndexes() */
4877 : : case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4878 : : case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4879 : 193 : cmd_lockmode = ShareUpdateExclusiveLock;
4880 : 193 : break;
4881 : :
4882 : 83 : case AT_SetLogged:
4883 : : case AT_SetUnLogged:
4884 : 83 : cmd_lockmode = AccessExclusiveLock;
4885 : 83 : break;
4886 : :
4887 : 292 : case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4888 : 292 : cmd_lockmode = ShareUpdateExclusiveLock;
4889 : 292 : break;
4890 : :
4891 : : /*
4892 : : * Rel options are more complex than first appears. Options
4893 : : * are set here for tables, views and indexes; for historical
4894 : : * reasons these can all be used with ALTER TABLE, so we can't
4895 : : * decide between them using the basic grammar.
4896 : : */
4897 : 541 : case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4898 : : * getTables() */
4899 : : case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4900 : : * getTables() */
4901 : 541 : cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4902 : 541 : break;
4903 : :
4904 : 1880 : case AT_AttachPartition:
4905 : 1880 : cmd_lockmode = ShareUpdateExclusiveLock;
4906 : 1880 : break;
4907 : :
4908 : 375 : case AT_DetachPartition:
4909 [ + + ]: 375 : if (((PartitionCmd *) cmd->def)->concurrent)
4910 : 89 : cmd_lockmode = ShareUpdateExclusiveLock;
4911 : : else
4912 : 286 : cmd_lockmode = AccessExclusiveLock;
4913 : 375 : break;
4914 : :
4915 : 11 : case AT_DetachPartitionFinalize:
4916 : 11 : cmd_lockmode = ShareUpdateExclusiveLock;
4917 : 11 : break;
4918 : :
4919 : 0 : default: /* oops */
4920 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
4921 : : (int) cmd->subtype);
4922 : : break;
4923 : : }
4924 : :
4925 : : /*
4926 : : * Take the greatest lockmode from any subcommand
4927 : : */
4928 [ + + ]: 25371 : if (cmd_lockmode > lockmode)
4929 : 21621 : lockmode = cmd_lockmode;
4930 : : }
4931 : :
4932 : 24509 : return lockmode;
4933 : : }
4934 : :
4935 : : /*
4936 : : * ATController provides top level control over the phases.
4937 : : *
4938 : : * parsetree is passed in to allow it to be passed to event triggers
4939 : : * when requested.
4940 : : */
4941 : : static void
4942 : 24313 : ATController(AlterTableStmt *parsetree,
4943 : : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4944 : : AlterTableUtilityContext *context)
4945 : : {
4946 : 24313 : List *wqueue = NIL;
4947 : : ListCell *lcmd;
4948 : :
4949 : : /* Phase 1: preliminary examination of commands, create work queue */
4950 [ + - + + : 49124 : foreach(lcmd, cmds)
+ + ]
4951 : : {
4952 : 25171 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4953 : :
4954 : 25171 : ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4955 : : }
4956 : :
4957 : : /* Close the relation, but keep lock until commit */
4958 : 23953 : relation_close(rel, NoLock);
4959 : :
4960 : : /* Phase 2: update system catalogs */
4961 : 23953 : ATRewriteCatalogs(&wqueue, lockmode, context);
4962 : :
4963 : : /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4964 : 21958 : ATRewriteTables(parsetree, &wqueue, lockmode, context);
4965 : 21480 : }
4966 : :
4967 : : /*
4968 : : * ATPrepCmd
4969 : : *
4970 : : * Traffic cop for ALTER TABLE Phase 1 operations, including simple
4971 : : * recursion and permission checks.
4972 : : *
4973 : : * Caller must have acquired appropriate lock type on relation already.
4974 : : * This lock should be held until commit.
4975 : : */
4976 : : static void
4977 : 25504 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4978 : : bool recurse, bool recursing, LOCKMODE lockmode,
4979 : : AlterTableUtilityContext *context)
4980 : : {
4981 : : AlteredTableInfo *tab;
4982 : 25504 : AlterTablePass pass = AT_PASS_UNSET;
4983 : :
4984 : : /* Find or create work queue entry for this table */
4985 : 25504 : tab = ATGetQueueEntry(wqueue, rel);
4986 : :
4987 : : /*
4988 : : * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
4989 : : * partitions that are pending detach.
4990 : : */
4991 [ + + ]: 25504 : if (rel->rd_rel->relispartition &&
4992 [ + - + + ]: 1780 : cmd->subtype != AT_DetachPartitionFinalize &&
4993 : 890 : PartitionHasPendingDetach(RelationGetRelid(rel)))
4994 [ + - ]: 1 : ereport(ERROR,
4995 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4996 : : errmsg("cannot alter partition \"%s\" with an incomplete detach",
4997 : : RelationGetRelationName(rel)),
4998 : : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
4999 : :
5000 : : /*
5001 : : * Copy the original subcommand for each table, so we can scribble on it.
5002 : : * This avoids conflicts when different child tables need to make
5003 : : * different parse transformations (for example, the same column may have
5004 : : * different column numbers in different children).
5005 : : */
5006 : 25503 : cmd = copyObject(cmd);
5007 : :
5008 : : /*
5009 : : * Do permissions and relkind checking, recursion to child tables if
5010 : : * needed, and any additional phase-1 processing needed. (But beware of
5011 : : * adding any processing that looks at table details that another
5012 : : * subcommand could change. In some cases we reject multiple subcommands
5013 : : * that could try to change the same state in contrary ways.)
5014 : : */
5015 [ + + + + : 25503 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + - + -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - ]
5016 : : {
5017 : 3691 : case AT_AddColumn: /* ADD COLUMN */
5018 : 3691 : ATSimplePermissions(cmd->subtype, rel,
5019 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5020 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5021 : 3691 : ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
5022 : : lockmode, context);
5023 : : /* Recursion occurs during execution phase */
5024 : 3683 : pass = AT_PASS_ADD_COL;
5025 : 3683 : break;
5026 : 26 : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5027 : 26 : ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
5028 : 26 : ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
5029 : : lockmode, context);
5030 : : /* Recursion occurs during execution phase */
5031 : 26 : pass = AT_PASS_ADD_COL;
5032 : 26 : break;
5033 : 411 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5034 : :
5035 : : /*
5036 : : * We allow defaults on views so that INSERT into a view can have
5037 : : * default-ish behavior. This works because the rewriter
5038 : : * substitutes default values into INSERTs before it expands
5039 : : * rules.
5040 : : */
5041 : 411 : ATSimplePermissions(cmd->subtype, rel,
5042 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5043 : : ATT_FOREIGN_TABLE);
5044 : 411 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5045 : : /* No command-specific prep needed */
5046 [ + + ]: 411 : pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
5047 : 411 : break;
5048 : 57 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5049 : : /* This is currently used only in CREATE TABLE */
5050 : : /* (so the permission check really isn't necessary) */
5051 : 57 : ATSimplePermissions(cmd->subtype, rel,
5052 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5053 : : /* This command never recurses */
5054 : 57 : pass = AT_PASS_ADD_OTHERCONSTR;
5055 : 57 : break;
5056 : 122 : case AT_AddIdentity:
5057 : 122 : ATSimplePermissions(cmd->subtype, rel,
5058 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5059 : : ATT_FOREIGN_TABLE);
5060 : : /* Set up recursion for phase 2; no other prep needed */
5061 [ + + ]: 122 : if (recurse)
5062 : 118 : cmd->recurse = true;
5063 : 122 : pass = AT_PASS_ADD_OTHERCONSTR;
5064 : 122 : break;
5065 : 41 : case AT_SetIdentity:
5066 : 41 : ATSimplePermissions(cmd->subtype, rel,
5067 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5068 : : ATT_FOREIGN_TABLE);
5069 : : /* Set up recursion for phase 2; no other prep needed */
5070 [ + + ]: 41 : if (recurse)
5071 : 37 : cmd->recurse = true;
5072 : : /* This should run after AddIdentity, so do it in MISC pass */
5073 : 41 : pass = AT_PASS_MISC;
5074 : 41 : break;
5075 : 37 : case AT_DropIdentity:
5076 : 37 : ATSimplePermissions(cmd->subtype, rel,
5077 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5078 : : ATT_FOREIGN_TABLE);
5079 : : /* Set up recursion for phase 2; no other prep needed */
5080 [ + + ]: 37 : if (recurse)
5081 : 33 : cmd->recurse = true;
5082 : 37 : pass = AT_PASS_DROP;
5083 : 37 : break;
5084 : 201 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5085 : 201 : ATSimplePermissions(cmd->subtype, rel,
5086 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5087 : : /* Set up recursion for phase 2; no other prep needed */
5088 [ + + ]: 197 : if (recurse)
5089 : 185 : cmd->recurse = true;
5090 : 197 : pass = AT_PASS_DROP;
5091 : 197 : break;
5092 : 280 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5093 : 280 : ATSimplePermissions(cmd->subtype, rel,
5094 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5095 : : /* Set up recursion for phase 2; no other prep needed */
5096 [ + + ]: 276 : if (recurse)
5097 : 256 : cmd->recurse = true;
5098 : 276 : pass = AT_PASS_COL_ATTRS;
5099 : 276 : break;
5100 : 201 : case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */
5101 : 201 : ATSimplePermissions(cmd->subtype, rel,
5102 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5103 : 201 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5104 : 201 : pass = AT_PASS_SET_EXPRESSION;
5105 : 201 : break;
5106 : 93 : case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
5107 : 93 : ATSimplePermissions(cmd->subtype, rel,
5108 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5109 : 93 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5110 : 93 : ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
5111 : 69 : pass = AT_PASS_DROP;
5112 : 69 : break;
5113 : 113 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5114 : 113 : ATSimplePermissions(cmd->subtype, rel,
5115 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
5116 : : ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
5117 : 113 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5118 : : /* No command-specific prep needed */
5119 : 113 : pass = AT_PASS_MISC;
5120 : 113 : break;
5121 : 62 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5122 : : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5123 : 62 : ATSimplePermissions(cmd->subtype, rel,
5124 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5125 : : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5126 : : /* This command never recurses */
5127 : 54 : pass = AT_PASS_MISC;
5128 : 54 : break;
5129 : 247 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5130 : 247 : ATSimplePermissions(cmd->subtype, rel,
5131 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5132 : : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5133 : 247 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5134 : : /* No command-specific prep needed */
5135 : 247 : pass = AT_PASS_MISC;
5136 : 247 : break;
5137 : 49 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5138 : 49 : ATSimplePermissions(cmd->subtype, rel,
5139 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5140 : : /* This command never recurses */
5141 : : /* No command-specific prep needed */
5142 : 49 : pass = AT_PASS_MISC;
5143 : 49 : break;
5144 : 1184 : case AT_DropColumn: /* DROP COLUMN */
5145 : 1184 : ATSimplePermissions(cmd->subtype, rel,
5146 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5147 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5148 : 1180 : ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
5149 : : lockmode, context);
5150 : : /* Recursion occurs during execution phase */
5151 : 1172 : pass = AT_PASS_DROP;
5152 : 1172 : break;
5153 : 0 : case AT_AddIndex: /* ADD INDEX */
5154 : 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5155 : : /* This command never recurses */
5156 : : /* No command-specific prep needed */
5157 : 0 : pass = AT_PASS_ADD_INDEX;
5158 : 0 : break;
5159 : 10004 : case AT_AddConstraint: /* ADD CONSTRAINT */
5160 : 10004 : ATSimplePermissions(cmd->subtype, rel,
5161 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5162 [ + + ]: 10004 : if (recurse)
5163 : : {
5164 : : /* recurses at exec time; lock descendants and set flag */
5165 : 9766 : (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5166 : 9766 : cmd->recurse = true;
5167 : : }
5168 : 10004 : pass = AT_PASS_ADD_CONSTR;
5169 : 10004 : break;
5170 : 0 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5171 : 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5172 : : /* This command never recurses */
5173 : : /* No command-specific prep needed */
5174 : 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5175 : 0 : break;
5176 : 579 : case AT_DropConstraint: /* DROP CONSTRAINT */
5177 : 579 : ATSimplePermissions(cmd->subtype, rel,
5178 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5179 : 579 : ATCheckPartitionsNotInUse(rel, lockmode);
5180 : : /* Other recursion occurs during execution phase */
5181 : : /* No command-specific prep needed except saving recurse flag */
5182 [ + + ]: 575 : if (recurse)
5183 : 539 : cmd->recurse = true;
5184 : 575 : pass = AT_PASS_DROP;
5185 : 575 : break;
5186 : 1477 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5187 : 1477 : ATSimplePermissions(cmd->subtype, rel,
5188 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5189 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5190 : : /* See comments for ATPrepAlterColumnType */
5191 : 1477 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
5192 : : AT_PASS_UNSET, context);
5193 : : Assert(cmd != NULL);
5194 : : /* Performs own recursion */
5195 : 1473 : ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
5196 : : lockmode, context);
5197 : 1267 : pass = AT_PASS_ALTER_TYPE;
5198 : 1267 : break;
5199 : 94 : case AT_AlterColumnGenericOptions:
5200 : 94 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5201 : : /* This command never recurses */
5202 : : /* No command-specific prep needed */
5203 : 94 : pass = AT_PASS_MISC;
5204 : 94 : break;
5205 : 1251 : case AT_ChangeOwner: /* ALTER OWNER */
5206 : : /* This command never recurses */
5207 : : /* No command-specific prep needed */
5208 : 1251 : pass = AT_PASS_MISC;
5209 : 1251 : break;
5210 : 43 : case AT_ClusterOn: /* CLUSTER ON */
5211 : : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5212 : 43 : ATSimplePermissions(cmd->subtype, rel,
5213 : : ATT_TABLE | ATT_MATVIEW);
5214 : : /* These commands never recurse */
5215 : : /* No command-specific prep needed */
5216 : 35 : pass = AT_PASS_MISC;
5217 : 35 : break;
5218 : 83 : case AT_SetLogged: /* SET LOGGED */
5219 : : case AT_SetUnLogged: /* SET UNLOGGED */
5220 : 83 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
5221 [ - + ]: 75 : if (tab->chgPersistence)
5222 [ # # ]: 0 : ereport(ERROR,
5223 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5224 : : errmsg("cannot change persistence setting twice")));
5225 : 75 : ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
5226 : 63 : pass = AT_PASS_MISC;
5227 : 63 : break;
5228 : 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5229 : 4 : ATSimplePermissions(cmd->subtype, rel,
5230 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5231 : 4 : pass = AT_PASS_DROP;
5232 : 4 : break;
5233 : 85 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5234 : 85 : ATSimplePermissions(cmd->subtype, rel,
5235 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5236 : :
5237 : : /* check if another access method change was already requested */
5238 [ + + ]: 85 : if (tab->chgAccessMethod)
5239 [ + - ]: 12 : ereport(ERROR,
5240 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5241 : : errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
5242 : :
5243 : 73 : ATPrepSetAccessMethod(tab, rel, cmd->name);
5244 : 73 : pass = AT_PASS_MISC; /* does not matter; no work in Phase 2 */
5245 : 73 : break;
5246 : 107 : case AT_SetTableSpace: /* SET TABLESPACE */
5247 : 107 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
5248 : : ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
5249 : : /* This command never recurses */
5250 : 107 : ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
5251 : 107 : pass = AT_PASS_MISC; /* doesn't actually matter */
5252 : 107 : break;
5253 : 708 : case AT_SetRelOptions: /* SET (...) */
5254 : : case AT_ResetRelOptions: /* RESET (...) */
5255 : : case AT_ReplaceRelOptions: /* reset them all, then set just these */
5256 : 708 : ATSimplePermissions(cmd->subtype, rel,
5257 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5258 : : ATT_MATVIEW | ATT_INDEX);
5259 : : /* This command never recurses */
5260 : : /* No command-specific prep needed */
5261 : 707 : pass = AT_PASS_MISC;
5262 : 707 : break;
5263 : 306 : case AT_AddInherit: /* INHERIT */
5264 : 306 : ATSimplePermissions(cmd->subtype, rel,
5265 : : ATT_TABLE | ATT_FOREIGN_TABLE);
5266 : : /* This command never recurses */
5267 : 302 : ATPrepChangeInherit(rel);
5268 : 290 : pass = AT_PASS_MISC;
5269 : 290 : break;
5270 : 73 : case AT_DropInherit: /* NO INHERIT */
5271 : 73 : ATSimplePermissions(cmd->subtype, rel,
5272 : : ATT_TABLE | ATT_FOREIGN_TABLE);
5273 : : /* This command never recurses */
5274 : 69 : ATPrepChangeInherit(rel);
5275 : 61 : pass = AT_PASS_MISC;
5276 : 61 : break;
5277 : 348 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5278 : 348 : ATSimplePermissions(cmd->subtype, rel,
5279 : : ATT_TABLE | ATT_PARTITIONED_TABLE);
5280 : : /* Recursion occurs during execution phase */
5281 [ + + ]: 344 : if (recurse)
5282 : 332 : cmd->recurse = true;
5283 : 344 : pass = AT_PASS_MISC;
5284 : 344 : break;
5285 : 292 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5286 : 292 : ATSimplePermissions(cmd->subtype, rel,
5287 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5288 : : /* Recursion occurs during execution phase */
5289 : : /* No command-specific prep needed except saving recurse flag */
5290 [ + - ]: 292 : if (recurse)
5291 : 292 : cmd->recurse = true;
5292 : 292 : pass = AT_PASS_MISC;
5293 : 292 : break;
5294 : 322 : case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
5295 : 322 : ATSimplePermissions(cmd->subtype, rel,
5296 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5297 : 322 : pass = AT_PASS_MISC;
5298 : : /* This command never recurses */
5299 : : /* No command-specific prep needed */
5300 : 322 : break;
5301 : 191 : case AT_EnableTrig: /* ENABLE TRIGGER variants */
5302 : : case AT_EnableAlwaysTrig:
5303 : : case AT_EnableReplicaTrig:
5304 : : case AT_EnableTrigAll:
5305 : : case AT_EnableTrigUser:
5306 : : case AT_DisableTrig: /* DISABLE TRIGGER variants */
5307 : : case AT_DisableTrigAll:
5308 : : case AT_DisableTrigUser:
5309 : 191 : ATSimplePermissions(cmd->subtype, rel,
5310 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5311 : : /* Set up recursion for phase 2; no other prep needed */
5312 [ + + ]: 191 : if (recurse)
5313 : 174 : cmd->recurse = true;
5314 : 191 : pass = AT_PASS_MISC;
5315 : 191 : break;
5316 : 429 : case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
5317 : : case AT_EnableAlwaysRule:
5318 : : case AT_EnableReplicaRule:
5319 : : case AT_DisableRule:
5320 : : case AT_AddOf: /* OF */
5321 : : case AT_DropOf: /* NOT OF */
5322 : : case AT_EnableRowSecurity:
5323 : : case AT_DisableRowSecurity:
5324 : : case AT_ForceRowSecurity:
5325 : : case AT_NoForceRowSecurity:
5326 : 429 : ATSimplePermissions(cmd->subtype, rel,
5327 : : ATT_TABLE | ATT_PARTITIONED_TABLE);
5328 : : /* These commands never recurse */
5329 : : /* No command-specific prep needed */
5330 : 429 : pass = AT_PASS_MISC;
5331 : 429 : break;
5332 : 34 : case AT_GenericOptions:
5333 : 34 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5334 : : /* No command-specific prep needed */
5335 : 34 : pass = AT_PASS_MISC;
5336 : 34 : break;
5337 : 1872 : case AT_AttachPartition:
5338 : 1872 : ATSimplePermissions(cmd->subtype, rel,
5339 : : ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
5340 : : /* No command-specific prep needed */
5341 : 1868 : pass = AT_PASS_MISC;
5342 : 1868 : break;
5343 : 375 : case AT_DetachPartition:
5344 : 375 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5345 : : /* No command-specific prep needed */
5346 : 363 : pass = AT_PASS_MISC;
5347 : 363 : break;
5348 : 11 : case AT_DetachPartitionFinalize:
5349 : 11 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5350 : : /* No command-specific prep needed */
5351 : 7 : pass = AT_PASS_MISC;
5352 : 7 : break;
5353 : 0 : default: /* oops */
5354 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
5355 : : (int) cmd->subtype);
5356 : : pass = AT_PASS_UNSET; /* keep compiler quiet */
5357 : : break;
5358 : : }
5359 : : Assert(pass > AT_PASS_UNSET);
5360 : :
5361 : : /* Add the subcommand to the appropriate list for phase 2 */
5362 : 25136 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
5363 : 25136 : }
5364 : :
5365 : : /*
5366 : : * ATRewriteCatalogs
5367 : : *
5368 : : * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
5369 : : * dispatched in a "safe" execution order (designed to avoid unnecessary
5370 : : * conflicts).
5371 : : */
5372 : : static void
5373 : 23953 : ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
5374 : : AlterTableUtilityContext *context)
5375 : : {
5376 : : ListCell *ltab;
5377 : :
5378 : : /*
5379 : : * We process all the tables "in parallel", one pass at a time. This is
5380 : : * needed because we may have to propagate work from one table to another
5381 : : * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
5382 : : * re-adding of the foreign key constraint to the other table). Work can
5383 : : * only be propagated into later passes, however.
5384 : : */
5385 [ + + ]: 302415 : for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
5386 : : {
5387 : : /* Go through each table that needs to be processed */
5388 [ + - + + : 570625 : foreach(ltab, *wqueue)
+ + ]
5389 : : {
5390 : 292163 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5391 : 292163 : List *subcmds = tab->subcmds[pass];
5392 : : ListCell *lcmd;
5393 : :
5394 [ + + ]: 292163 : if (subcmds == NIL)
5395 : 252991 : continue;
5396 : :
5397 : : /*
5398 : : * Open the relation and store it in tab. This allows subroutines
5399 : : * close and reopen, if necessary. Appropriate lock was obtained
5400 : : * by phase 1, needn't get it again.
5401 : : */
5402 : 39172 : tab->rel = relation_open(tab->relid, NoLock);
5403 : :
5404 [ + - + + : 78485 : foreach(lcmd, subcmds)
+ + ]
5405 : 41288 : ATExecCmd(wqueue, tab,
5406 : 41288 : lfirst_node(AlterTableCmd, lcmd),
5407 : : lockmode, pass, context);
5408 : :
5409 : : /*
5410 : : * For ADD PRIMARY KEY without USING INDEX, queue any required NOT
5411 : : * NULL constraints after transforming all explicit constraints.
5412 : : * This lets a named NOT NULL constraint take precedence
5413 : : * regardless of subcommand order. USING INDEX is handled during
5414 : : * transformation.
5415 : : */
5416 [ + + ]: 37197 : if (pass == AT_PASS_ADD_CONSTR)
5417 : : {
5418 [ + - + + : 29682 : foreach_node(AlterTableCmd, cmd, subcmds)
+ + ]
5419 : 9984 : ATPrepAddPrimaryKey(tab, tab->rel, cmd, lockmode);
5420 : : }
5421 : :
5422 : : /*
5423 : : * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
5424 : : * (this is not done in ATExecAlterColumnType since it should be
5425 : : * done only once if multiple columns of a table are altered).
5426 : : */
5427 [ + + + + ]: 37177 : if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
5428 : 1352 : ATPostAlterTypeCleanup(wqueue, tab, lockmode);
5429 : :
5430 [ + - ]: 37177 : if (tab->rel)
5431 : : {
5432 : 37177 : relation_close(tab->rel, NoLock);
5433 : 37177 : tab->rel = NULL;
5434 : : }
5435 : : }
5436 : : }
5437 : :
5438 : : /* Check to see if a toast table must be added. */
5439 [ + - + + : 46877 : foreach(ltab, *wqueue)
+ + ]
5440 : : {
5441 : 24919 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5442 : :
5443 : : /*
5444 : : * If the table is source table of ATTACH PARTITION command, we did
5445 : : * not modify anything about it that will change its toasting
5446 : : * requirement, so no need to check.
5447 : : */
5448 [ + + ]: 24919 : if (((tab->relkind == RELKIND_RELATION ||
5449 [ + + ]: 4439 : tab->relkind == RELKIND_PARTITIONED_TABLE) &&
5450 [ + + ]: 23304 : tab->partition_constraint == NULL) ||
5451 [ + + ]: 2968 : tab->relkind == RELKIND_MATVIEW)
5452 : 21981 : AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
5453 : : }
5454 : 21958 : }
5455 : :
5456 : : /*
5457 : : * ATExecCmd: dispatch a subcommand to appropriate execution routine
5458 : : */
5459 : : static void
5460 : 41288 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
5461 : : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
5462 : : AlterTableUtilityContext *context)
5463 : : {
5464 : 41288 : ObjectAddress address = InvalidObjectAddress;
5465 : 41288 : Relation rel = tab->rel;
5466 : :
5467 [ + + + + : 41288 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + - + -
+ + - + +
+ + + + +
+ + + + +
+ + + - ]
5468 : : {
5469 : 3705 : case AT_AddColumn: /* ADD COLUMN */
5470 : : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5471 : 3705 : address = ATExecAddColumn(wqueue, tab, rel, &cmd,
5472 : 3705 : cmd->recurse, false,
5473 : : lockmode, cur_pass, context);
5474 : 3609 : break;
5475 : 387 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5476 : 387 : address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
5477 : 339 : break;
5478 : 57 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5479 : 57 : address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
5480 : 53 : break;
5481 : 122 : case AT_AddIdentity:
5482 : 122 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5483 : : cur_pass, context);
5484 : : Assert(cmd != NULL);
5485 : 114 : address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5486 : 78 : break;
5487 : 41 : case AT_SetIdentity:
5488 : 41 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5489 : : cur_pass, context);
5490 : : Assert(cmd != NULL);
5491 : 41 : address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5492 : 25 : break;
5493 : 37 : case AT_DropIdentity:
5494 : 37 : address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
5495 : 25 : break;
5496 : 197 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5497 : 197 : address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
5498 : 129 : break;
5499 : 276 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5500 : 276 : address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
5501 : 276 : cmd->recurse, false, lockmode);
5502 : 256 : break;
5503 : 201 : case AT_SetExpression:
5504 : 201 : address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
5505 : 181 : break;
5506 : 61 : case AT_DropExpression:
5507 : 61 : address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
5508 : 45 : break;
5509 : 113 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5510 : 113 : address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
5511 : 81 : break;
5512 : 46 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5513 : 46 : address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
5514 : 42 : break;
5515 : 8 : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5516 : 8 : address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
5517 : 8 : break;
5518 : 247 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5519 : 247 : address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
5520 : 239 : break;
5521 : 49 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5522 : 49 : address = ATExecSetCompression(rel, cmd->name, cmd->def,
5523 : : lockmode);
5524 : 45 : break;
5525 : 1172 : case AT_DropColumn: /* DROP COLUMN */
5526 : 1172 : address = ATExecDropColumn(wqueue, rel, cmd->name,
5527 : 1172 : cmd->behavior, cmd->recurse, false,
5528 : 1172 : cmd->missing_ok, lockmode,
5529 : : NULL);
5530 : 1036 : break;
5531 : 817 : case AT_AddIndex: /* ADD INDEX */
5532 : 817 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
5533 : : lockmode);
5534 : 704 : break;
5535 : 338 : case AT_ReAddIndex: /* ADD INDEX */
5536 : 338 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
5537 : : lockmode);
5538 : 338 : break;
5539 : 57 : case AT_ReAddStatistics: /* ADD STATISTICS */
5540 : 57 : address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
5541 : : true, lockmode);
5542 : 57 : break;
5543 : 18115 : case AT_AddConstraint: /* ADD CONSTRAINT */
5544 : : /* Transform the command only during initial examination */
5545 [ + + ]: 18115 : if (cur_pass == AT_PASS_ADD_CONSTR)
5546 : 9984 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
5547 : 10004 : cmd->recurse, lockmode,
5548 : : cur_pass, context);
5549 : : /* Depending on constraint type, might be no more work to do now */
5550 [ + + ]: 18095 : if (cmd != NULL)
5551 : : address =
5552 : 8111 : ATExecAddConstraint(wqueue, tab, rel,
5553 : 8111 : (Constraint *) cmd->def,
5554 : 8111 : cmd->recurse, false, lockmode);
5555 : 17634 : break;
5556 : 269 : case AT_ReAddConstraint: /* Re-add pre-existing check constraint */
5557 : : address =
5558 : 269 : ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
5559 : : true, true, lockmode);
5560 : 261 : break;
5561 : 13 : case AT_ReAddDomainConstraint: /* Re-add pre-existing domain check
5562 : : * constraint */
5563 : : address =
5564 : 13 : AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
5565 : 13 : ((AlterDomainStmt *) cmd->def)->def,
5566 : : NULL, true);
5567 : 9 : break;
5568 : 52 : case AT_ReAddComment: /* Re-add existing comment */
5569 : 52 : address = CommentObject((CommentStmt *) cmd->def);
5570 : 52 : break;
5571 : 6543 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5572 : 6543 : address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
5573 : : lockmode);
5574 : 6535 : break;
5575 : 344 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5576 : 344 : address = ATExecAlterConstraint(wqueue, rel,
5577 : 344 : castNode(ATAlterConstraint, cmd->def),
5578 : 344 : cmd->recurse, lockmode);
5579 : 260 : break;
5580 : 292 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5581 : 292 : address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
5582 : : false, lockmode);
5583 : 288 : break;
5584 : 575 : case AT_DropConstraint: /* DROP CONSTRAINT */
5585 : 575 : ATExecDropConstraint(rel, cmd->name, cmd->behavior,
5586 : 575 : cmd->recurse,
5587 : 575 : cmd->missing_ok, lockmode);
5588 : 435 : break;
5589 : 1243 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5590 : : /* parse transformation was done earlier */
5591 : 1243 : address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
5592 : 1203 : break;
5593 : 94 : case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
5594 : : address =
5595 : 94 : ATExecAlterColumnGenericOptions(rel, cmd->name,
5596 : 94 : (List *) cmd->def, lockmode);
5597 : 90 : break;
5598 : 1251 : case AT_ChangeOwner: /* ALTER OWNER */
5599 : 1248 : ATExecChangeOwner(RelationGetRelid(rel),
5600 : 1251 : get_rolespec_oid(cmd->newowner, false),
5601 : : false, lockmode);
5602 : 1240 : break;
5603 : 39 : case AT_ClusterOn: /* CLUSTER ON */
5604 : 39 : address = ATExecClusterOn(rel, cmd->name, lockmode);
5605 : 39 : break;
5606 : 8 : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5607 : 8 : ATExecDropCluster(rel, lockmode);
5608 : 8 : break;
5609 : 63 : case AT_SetLogged: /* SET LOGGED */
5610 : : case AT_SetUnLogged: /* SET UNLOGGED */
5611 : 63 : break;
5612 : 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5613 : : /* nothing to do here, oid columns don't exist anymore */
5614 : 4 : break;
5615 : 61 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5616 : :
5617 : : /*
5618 : : * Only do this for partitioned tables, for which this is just a
5619 : : * catalog change. Tables with storage are handled by Phase 3.
5620 : : */
5621 [ + + ]: 61 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
5622 [ + + ]: 33 : tab->chgAccessMethod)
5623 : 29 : ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
5624 : 61 : break;
5625 : 107 : case AT_SetTableSpace: /* SET TABLESPACE */
5626 : :
5627 : : /*
5628 : : * Only do this for partitioned tables and indexes, for which this
5629 : : * is just a catalog change. Other relation types which have
5630 : : * storage are handled by Phase 3.
5631 : : */
5632 [ + + ]: 107 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
5633 [ + + ]: 99 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
5634 : 24 : ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
5635 : :
5636 : 103 : break;
5637 : 707 : case AT_SetRelOptions: /* SET (...) */
5638 : : case AT_ResetRelOptions: /* RESET (...) */
5639 : : case AT_ReplaceRelOptions: /* replace entire option list */
5640 : 707 : ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
5641 : 673 : break;
5642 : 65 : case AT_EnableTrig: /* ENABLE TRIGGER name */
5643 : 65 : ATExecEnableDisableTrigger(rel, cmd->name,
5644 : : TRIGGER_FIRES_ON_ORIGIN, false,
5645 : 65 : cmd->recurse,
5646 : : lockmode);
5647 : 65 : break;
5648 : 27 : case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
5649 : 27 : ATExecEnableDisableTrigger(rel, cmd->name,
5650 : : TRIGGER_FIRES_ALWAYS, false,
5651 : 27 : cmd->recurse,
5652 : : lockmode);
5653 : 27 : break;
5654 : 8 : case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
5655 : 8 : ATExecEnableDisableTrigger(rel, cmd->name,
5656 : : TRIGGER_FIRES_ON_REPLICA, false,
5657 : 8 : cmd->recurse,
5658 : : lockmode);
5659 : 8 : break;
5660 : 75 : case AT_DisableTrig: /* DISABLE TRIGGER name */
5661 : 75 : ATExecEnableDisableTrigger(rel, cmd->name,
5662 : : TRIGGER_DISABLED, false,
5663 : 75 : cmd->recurse,
5664 : : lockmode);
5665 : 75 : break;
5666 : 0 : case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
5667 : 0 : ATExecEnableDisableTrigger(rel, NULL,
5668 : : TRIGGER_FIRES_ON_ORIGIN, false,
5669 : 0 : cmd->recurse,
5670 : : lockmode);
5671 : 0 : break;
5672 : 8 : case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
5673 : 8 : ATExecEnableDisableTrigger(rel, NULL,
5674 : : TRIGGER_DISABLED, false,
5675 : 8 : cmd->recurse,
5676 : : lockmode);
5677 : 8 : break;
5678 : 0 : case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
5679 : 0 : ATExecEnableDisableTrigger(rel, NULL,
5680 : : TRIGGER_FIRES_ON_ORIGIN, true,
5681 : 0 : cmd->recurse,
5682 : : lockmode);
5683 : 0 : break;
5684 : 8 : case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
5685 : 8 : ATExecEnableDisableTrigger(rel, NULL,
5686 : : TRIGGER_DISABLED, true,
5687 : 8 : cmd->recurse,
5688 : : lockmode);
5689 : 8 : break;
5690 : :
5691 : 5 : case AT_EnableRule: /* ENABLE RULE name */
5692 : 5 : ATExecEnableDisableRule(rel, cmd->name,
5693 : : RULE_FIRES_ON_ORIGIN, lockmode);
5694 : 5 : break;
5695 : 0 : case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
5696 : 0 : ATExecEnableDisableRule(rel, cmd->name,
5697 : : RULE_FIRES_ALWAYS, lockmode);
5698 : 0 : break;
5699 : 4 : case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
5700 : 4 : ATExecEnableDisableRule(rel, cmd->name,
5701 : : RULE_FIRES_ON_REPLICA, lockmode);
5702 : 4 : break;
5703 : 20 : case AT_DisableRule: /* DISABLE RULE name */
5704 : 20 : ATExecEnableDisableRule(rel, cmd->name,
5705 : : RULE_DISABLED, lockmode);
5706 : 20 : break;
5707 : :
5708 : 290 : case AT_AddInherit:
5709 : 290 : address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
5710 : 210 : break;
5711 : 61 : case AT_DropInherit:
5712 : 61 : address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
5713 : 57 : break;
5714 : 51 : case AT_AddOf:
5715 : 51 : address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
5716 : 23 : break;
5717 : 4 : case AT_DropOf:
5718 : 4 : ATExecDropOf(rel, lockmode);
5719 : 4 : break;
5720 : 334 : case AT_ReplicaIdentity:
5721 : 334 : ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
5722 : 298 : break;
5723 : 250 : case AT_EnableRowSecurity:
5724 : 250 : ATExecSetRowSecurity(rel, true);
5725 : 250 : break;
5726 : 10 : case AT_DisableRowSecurity:
5727 : 10 : ATExecSetRowSecurity(rel, false);
5728 : 10 : break;
5729 : 65 : case AT_ForceRowSecurity:
5730 : 65 : ATExecForceNoForceRowSecurity(rel, true);
5731 : 65 : break;
5732 : 20 : case AT_NoForceRowSecurity:
5733 : 20 : ATExecForceNoForceRowSecurity(rel, false);
5734 : 20 : break;
5735 : 34 : case AT_GenericOptions:
5736 : 34 : ATExecGenericOptions(rel, (List *) cmd->def);
5737 : 33 : break;
5738 : 1868 : case AT_AttachPartition:
5739 : 1868 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5740 : : cur_pass, context);
5741 : : Assert(cmd != NULL);
5742 [ + + ]: 1852 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5743 : 1566 : address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
5744 : : context);
5745 : : else
5746 : 286 : address = ATExecAttachPartitionIdx(wqueue, rel,
5747 : 286 : ((PartitionCmd *) cmd->def)->name);
5748 : 1584 : break;
5749 : 363 : case AT_DetachPartition:
5750 : 363 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5751 : : cur_pass, context);
5752 : : Assert(cmd != NULL);
5753 : : /* ATPrepCmd ensures it must be a table */
5754 : : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5755 : 363 : address = ATExecDetachPartition(wqueue, tab, rel,
5756 : 363 : ((PartitionCmd *) cmd->def)->name,
5757 : 363 : ((PartitionCmd *) cmd->def)->concurrent);
5758 : 284 : break;
5759 : 7 : case AT_DetachPartitionFinalize:
5760 : 7 : address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
5761 : 7 : break;
5762 : 0 : default: /* oops */
5763 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
5764 : : (int) cmd->subtype);
5765 : : break;
5766 : : }
5767 : :
5768 : : /*
5769 : : * Report the subcommand to interested event triggers.
5770 : : */
5771 [ + + ]: 39313 : if (cmd)
5772 : 29329 : EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
5773 : :
5774 : : /*
5775 : : * Bump the command counter to ensure the next subcommand in the sequence
5776 : : * can see the changes so far
5777 : : */
5778 : 39313 : CommandCounterIncrement();
5779 : 39313 : }
5780 : :
5781 : : /*
5782 : : * ATParseTransformCmd: perform parse transformation for one subcommand
5783 : : *
5784 : : * Returns the transformed subcommand tree, if there is one, else NULL.
5785 : : *
5786 : : * The parser may hand back additional AlterTableCmd(s) and/or other
5787 : : * utility statements, either before or after the original subcommand.
5788 : : * Other AlterTableCmds are scheduled into the appropriate slot of the
5789 : : * AlteredTableInfo (they had better be for later passes than the current one).
5790 : : * Utility statements that are supposed to happen before the AlterTableCmd
5791 : : * are executed immediately. Those that are supposed to happen afterwards
5792 : : * are added to the tab->afterStmts list to be done at the very end.
5793 : : */
5794 : : static AlterTableCmd *
5795 : 17482 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
5796 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
5797 : : AlterTablePass cur_pass, AlterTableUtilityContext *context)
5798 : : {
5799 : 17482 : AlterTableCmd *newcmd = NULL;
5800 : 17482 : AlterTableStmt *atstmt = makeNode(AlterTableStmt);
5801 : : List *beforeStmts;
5802 : : List *afterStmts;
5803 : : ListCell *lc;
5804 : :
5805 : : /* Gin up an AlterTableStmt with just this subcommand and this table */
5806 : 17482 : atstmt->relation =
5807 : 17482 : makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5808 : 17482 : pstrdup(RelationGetRelationName(rel)),
5809 : : -1);
5810 : 17482 : atstmt->relation->inh = recurse;
5811 : 17482 : atstmt->cmds = list_make1(cmd);
5812 : 17482 : atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
5813 : 17482 : atstmt->missing_ok = false;
5814 : :
5815 : : /* Transform the AlterTableStmt */
5816 : 17482 : atstmt = transformAlterTableStmt(RelationGetRelid(rel),
5817 : : atstmt,
5818 : : context->queryString,
5819 : : &beforeStmts,
5820 : : &afterStmts);
5821 : :
5822 : : /* Execute any statements that should happen before these subcommand(s) */
5823 [ + + + + : 17775 : foreach(lc, beforeStmts)
+ + ]
5824 : : {
5825 : 345 : Node *stmt = (Node *) lfirst(lc);
5826 : :
5827 : 345 : ProcessUtilityForAlterTable(stmt, context);
5828 : 337 : CommandCounterIncrement();
5829 : : }
5830 : :
5831 : : /* Examine the transformed subcommands and schedule them appropriately */
5832 [ + - + + : 40051 : foreach(lc, atstmt->cmds)
+ + ]
5833 : : {
5834 : 22621 : AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
5835 : : AlterTablePass pass;
5836 : :
5837 : : /*
5838 : : * This switch need only cover the subcommand types that can be added
5839 : : * by parse_utilcmd.c; otherwise, we'll use the default strategy of
5840 : : * executing the subcommand immediately, as a substitute for the
5841 : : * original subcommand. (Note, however, that this does cause
5842 : : * AT_AddConstraint subcommands to be rescheduled into later passes,
5843 : : * which is important for index and foreign key constraints.)
5844 : : *
5845 : : * We assume we needn't do any phase-1 checks for added subcommands.
5846 : : */
5847 [ + + + - : 22621 : switch (cmd2->subtype)
+ ]
5848 : : {
5849 : 853 : case AT_AddIndex:
5850 : 853 : pass = AT_PASS_ADD_INDEX;
5851 : 853 : break;
5852 : 6543 : case AT_AddIndexConstraint:
5853 : 6543 : pass = AT_PASS_ADD_INDEXCONSTR;
5854 : 6543 : break;
5855 : 7779 : case AT_AddConstraint:
5856 : : /* Recursion occurs during execution phase */
5857 [ + + ]: 7779 : if (recurse)
5858 : 7752 : cmd2->recurse = true;
5859 [ + - + ]: 7779 : switch (castNode(Constraint, cmd2->def)->contype)
5860 : : {
5861 : 5307 : case CONSTR_NOTNULL:
5862 : 5307 : pass = AT_PASS_COL_ATTRS;
5863 : 5307 : break;
5864 : 0 : case CONSTR_PRIMARY:
5865 : : case CONSTR_UNIQUE:
5866 : : case CONSTR_EXCLUSION:
5867 : 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5868 : 0 : break;
5869 : 2472 : default:
5870 : 2472 : pass = AT_PASS_ADD_OTHERCONSTR;
5871 : 2472 : break;
5872 : : }
5873 : 7779 : break;
5874 : 0 : case AT_AlterColumnGenericOptions:
5875 : : /* This command never recurses */
5876 : : /* No command-specific prep needed */
5877 : 0 : pass = AT_PASS_MISC;
5878 : 0 : break;
5879 : 7446 : default:
5880 : 7446 : pass = cur_pass;
5881 : 7446 : break;
5882 : : }
5883 : :
5884 [ - + ]: 22621 : if (pass < cur_pass)
5885 : : {
5886 : : /* Cannot schedule into a pass we already finished */
5887 [ # # ]: 0 : elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
5888 : : pass);
5889 : : }
5890 [ + + ]: 22621 : else if (pass > cur_pass)
5891 : : {
5892 : : /* OK, queue it up for later */
5893 : 15175 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
5894 : : }
5895 : : else
5896 : : {
5897 : : /*
5898 : : * We should see at most one subcommand for the current pass,
5899 : : * which is the transformed version of the original subcommand.
5900 : : */
5901 [ + - + - ]: 7446 : if (newcmd == NULL && cmd->subtype == cmd2->subtype)
5902 : : {
5903 : : /* Found the transformed version of our subcommand */
5904 : 7446 : newcmd = cmd2;
5905 : : }
5906 : : else
5907 [ # # ]: 0 : elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
5908 : : pass);
5909 : : }
5910 : : }
5911 : :
5912 : : /* Queue up any after-statements to happen at the end */
5913 : 17430 : tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
5914 : :
5915 : 17430 : return newcmd;
5916 : : }
5917 : :
5918 : : /*
5919 : : * ATRewriteTables: ALTER TABLE phase 3
5920 : : */
5921 : : static void
5922 : 21958 : ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
5923 : : AlterTableUtilityContext *context)
5924 : : {
5925 : : ListCell *ltab;
5926 : :
5927 : : /* Go through each table that needs to be checked or rewritten */
5928 [ + - + + : 46398 : foreach(ltab, *wqueue)
+ + ]
5929 : : {
5930 : 24831 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5931 : :
5932 : : /* Relations without storage may be ignored here */
5933 [ + + + + : 24831 : if (!RELKIND_HAS_STORAGE(tab->relkind))
+ + + - +
+ ]
5934 : 4254 : continue;
5935 : :
5936 : : /*
5937 : : * If we change column data types, the operation has to be propagated
5938 : : * to tables that use this table's rowtype as a column type.
5939 : : * tab->newvals will also be non-NULL in the case where we're adding a
5940 : : * column with a default. We choose to forbid that case as well,
5941 : : * since composite types might eventually support defaults.
5942 : : *
5943 : : * (Eventually we'll probably need to check for composite type
5944 : : * dependencies even when we're just scanning the table without a
5945 : : * rewrite, but at the moment a composite type does not enforce any
5946 : : * constraints, so it's not necessary/appropriate to enforce them just
5947 : : * during ALTER.)
5948 : : */
5949 [ + + ]: 20577 : if (tab->newvals != NIL ||
5950 [ - + ]: 19082 : ((tab->rewrite & (AT_REWRITE_DEFAULT_VAL | AT_REWRITE_COLUMN_REWRITE)) != 0 &&
5951 [ # # ]: 0 : tab->relkind != RELKIND_SEQUENCE))
5952 : : {
5953 : : Relation rel;
5954 : :
5955 : 1495 : rel = table_open(tab->relid, NoLock);
5956 : 1495 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
5957 : 1398 : table_close(rel, NoLock);
5958 : : }
5959 : :
5960 : : /*
5961 : : * We only need to rewrite the table if at least one column needs to
5962 : : * be recomputed, or we are changing its persistence or access method.
5963 : : *
5964 : : * There are two reasons for requiring a rewrite when changing
5965 : : * persistence: on one hand, we need to ensure that the buffers
5966 : : * belonging to each of the two relations are marked with or without
5967 : : * BM_PERMANENT properly. On the other hand, since rewriting creates
5968 : : * and assigns a new relfilenumber, we automatically create or drop an
5969 : : * init fork for the relation as appropriate.
5970 : : */
5971 [ + + + + ]: 20480 : if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
5972 : 906 : {
5973 : : /* Build a temporary relation and copy data */
5974 : : Relation OldHeap;
5975 : : Oid OIDNewHeap;
5976 : : Oid NewAccessMethod;
5977 : : Oid NewTableSpace;
5978 : : char persistence;
5979 : :
5980 : 967 : OldHeap = table_open(tab->relid, NoLock);
5981 : :
5982 : : /*
5983 : : * We don't support rewriting of system catalogs; there are too
5984 : : * many corner cases and too little benefit. In particular this
5985 : : * is certainly not going to work for mapped catalogs.
5986 : : */
5987 [ - + ]: 967 : if (IsSystemRelation(OldHeap))
5988 [ # # ]: 0 : ereport(ERROR,
5989 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5990 : : errmsg("cannot rewrite system relation \"%s\"",
5991 : : RelationGetRelationName(OldHeap))));
5992 : :
5993 [ + + - + : 967 : if (RelationIsUsedAsCatalogTable(OldHeap))
- - + + ]
5994 [ + - ]: 1 : ereport(ERROR,
5995 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5996 : : errmsg("cannot rewrite table \"%s\" used as a catalog table",
5997 : : RelationGetRelationName(OldHeap))));
5998 : :
5999 : : /*
6000 : : * Don't allow rewrite on temp tables of other backends ... their
6001 : : * local buffer manager is not going to cope. (This is redundant
6002 : : * with the check in CheckAlterTableIsSafe, but for safety we'll
6003 : : * check here too.)
6004 : : */
6005 [ + + - + ]: 966 : if (RELATION_IS_OTHER_TEMP(OldHeap))
6006 [ # # ]: 0 : ereport(ERROR,
6007 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6008 : : errmsg("cannot rewrite temporary tables of other sessions")));
6009 : :
6010 : : /*
6011 : : * Select destination tablespace (same as original unless user
6012 : : * requested a change)
6013 : : */
6014 [ - + ]: 966 : if (tab->newTableSpace)
6015 : 0 : NewTableSpace = tab->newTableSpace;
6016 : : else
6017 : 966 : NewTableSpace = OldHeap->rd_rel->reltablespace;
6018 : :
6019 : : /*
6020 : : * Select destination access method (same as original unless user
6021 : : * requested a change)
6022 : : */
6023 [ + + ]: 966 : if (tab->chgAccessMethod)
6024 : 24 : NewAccessMethod = tab->newAccessMethod;
6025 : : else
6026 : 942 : NewAccessMethod = OldHeap->rd_rel->relam;
6027 : :
6028 : : /*
6029 : : * Select persistence of transient table (same as original unless
6030 : : * user requested a change)
6031 : : */
6032 [ + + ]: 966 : persistence = tab->chgPersistence ?
6033 : 927 : tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
6034 : :
6035 : 966 : table_close(OldHeap, NoLock);
6036 : :
6037 : : /*
6038 : : * Fire off an Event Trigger now, before actually rewriting the
6039 : : * table.
6040 : : *
6041 : : * We don't support Event Trigger for nested commands anywhere,
6042 : : * here included, and parsetree is given NULL when coming from
6043 : : * AlterTableInternal.
6044 : : *
6045 : : * And fire it only once.
6046 : : */
6047 [ + - ]: 966 : if (parsetree)
6048 : 966 : EventTriggerTableRewrite((Node *) parsetree,
6049 : : tab->relid,
6050 : : tab->rewrite);
6051 : :
6052 : : /*
6053 : : * Create transient table that will receive the modified data.
6054 : : *
6055 : : * Ensure it is marked correctly as logged or unlogged. We have
6056 : : * to do this here so that buffers for the new relfilenumber will
6057 : : * have the right persistence set, and at the same time ensure
6058 : : * that the original filenumbers's buffers will get read in with
6059 : : * the correct setting (i.e. the original one). Otherwise a
6060 : : * rollback after the rewrite would possibly result with buffers
6061 : : * for the original filenumbers having the wrong persistence
6062 : : * setting.
6063 : : *
6064 : : * NB: This relies on swap_relation_files() also swapping the
6065 : : * persistence. That wouldn't work for pg_class, but that can't be
6066 : : * unlogged anyway.
6067 : : */
6068 : 962 : OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
6069 : : persistence, lockmode);
6070 : :
6071 : : /*
6072 : : * Copy the heap data into the new table with the desired
6073 : : * modifications, and test the current data within the table
6074 : : * against new constraints generated by ALTER TABLE commands.
6075 : : */
6076 : 962 : ATRewriteTable(tab, OIDNewHeap);
6077 : :
6078 : : /*
6079 : : * Swap the physical files of the old and new heaps, then rebuild
6080 : : * indexes and discard the old heap. We can use RecentXmin for
6081 : : * the table's new relfrozenxid because we rewrote all the tuples
6082 : : * in ATRewriteTable, so no older Xid remains in the table. Also,
6083 : : * we never try to swap toast tables by content, since we have no
6084 : : * interest in letting this code work on system catalogs.
6085 : : */
6086 : 910 : finish_heap_swap(tab->relid, OIDNewHeap,
6087 : : false, false, true,
6088 : 910 : !OidIsValid(tab->newTableSpace),
6089 : : true, /* reindex */
6090 : : RecentXmin,
6091 : : ReadNextMultiXactId(),
6092 : : persistence);
6093 : :
6094 [ - + ]: 906 : InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
6095 : : }
6096 [ + + + - ]: 19513 : else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
6097 : : {
6098 [ + - ]: 16 : if (tab->chgPersistence)
6099 : 16 : SequenceChangePersistence(tab->relid, tab->newrelpersistence);
6100 : : }
6101 : : else
6102 : : {
6103 : : /*
6104 : : * If required, test the current data within the table against new
6105 : : * constraints generated by ALTER TABLE commands, but don't
6106 : : * rebuild data.
6107 : : */
6108 [ + + + + ]: 19497 : if (tab->constraints != NIL || tab->verify_new_notnull ||
6109 [ + + ]: 17328 : tab->partition_constraint != NULL)
6110 : 3424 : ATRewriteTable(tab, InvalidOid);
6111 : :
6112 : : /*
6113 : : * If we had SET TABLESPACE but no reason to reconstruct tuples,
6114 : : * just do a block-by-block copy.
6115 : : */
6116 [ + + ]: 19264 : if (tab->newTableSpace)
6117 : 83 : ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
6118 : : }
6119 : :
6120 : : /*
6121 : : * Also change persistence of owned sequences, so that it matches the
6122 : : * table persistence.
6123 : : */
6124 [ + + ]: 20186 : if (tab->chgPersistence)
6125 : : {
6126 : 55 : List *seqlist = getOwnedSequences(tab->relid);
6127 : : ListCell *lc;
6128 : :
6129 [ + + + + : 87 : foreach(lc, seqlist)
+ + ]
6130 : : {
6131 : 32 : Oid seq_relid = lfirst_oid(lc);
6132 : :
6133 : 32 : SequenceChangePersistence(seq_relid, tab->newrelpersistence);
6134 : : }
6135 : : }
6136 : : }
6137 : :
6138 : : /*
6139 : : * Foreign key constraints are checked in a final pass, since (a) it's
6140 : : * generally best to examine each one separately, and (b) it's at least
6141 : : * theoretically possible that we have changed both relations of the
6142 : : * foreign key, and we'd better have finished both rewrites before we try
6143 : : * to read the tables.
6144 : : */
6145 [ + - + + : 45742 : foreach(ltab, *wqueue)
+ + ]
6146 : : {
6147 : 24262 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6148 : 24262 : Relation rel = NULL;
6149 : : ListCell *lcon;
6150 : :
6151 : : /* Relations without storage may be ignored here too */
6152 [ + + + + : 24262 : if (!RELKIND_HAS_STORAGE(tab->relkind))
+ + + - +
+ ]
6153 : 4149 : continue;
6154 : :
6155 [ + + + + : 21435 : foreach(lcon, tab->constraints)
+ + ]
6156 : : {
6157 : 1409 : NewConstraint *con = lfirst(lcon);
6158 : :
6159 [ + + ]: 1409 : if (con->contype == CONSTR_FOREIGN)
6160 : : {
6161 : 839 : Constraint *fkconstraint = (Constraint *) con->qual;
6162 : : Relation refrel;
6163 : :
6164 [ + + ]: 839 : if (rel == NULL)
6165 : : {
6166 : : /* Long since locked, no need for another */
6167 : 831 : rel = table_open(tab->relid, NoLock);
6168 : : }
6169 : :
6170 : 839 : refrel = table_open(con->refrelid, RowShareLock);
6171 : :
6172 : 839 : validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
6173 : : con->refindid,
6174 : : con->conid,
6175 : 839 : con->conwithperiod);
6176 : :
6177 : : /*
6178 : : * No need to mark the constraint row as validated, we did
6179 : : * that when we inserted the row earlier.
6180 : : */
6181 : :
6182 : 752 : table_close(refrel, NoLock);
6183 : : }
6184 : : }
6185 : :
6186 [ + + ]: 20026 : if (rel)
6187 : 744 : table_close(rel, NoLock);
6188 : : }
6189 : :
6190 : : /* Finally, run any afterStmts that were queued up */
6191 [ + - + + : 45628 : foreach(ltab, *wqueue)
+ + ]
6192 : : {
6193 : 24148 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6194 : : ListCell *lc;
6195 : :
6196 [ + + + + : 24204 : foreach(lc, tab->afterStmts)
+ + ]
6197 : : {
6198 : 56 : Node *stmt = (Node *) lfirst(lc);
6199 : :
6200 : 56 : ProcessUtilityForAlterTable(stmt, context);
6201 : 56 : CommandCounterIncrement();
6202 : : }
6203 : : }
6204 : 21480 : }
6205 : :
6206 : : /*
6207 : : * ATRewriteTable: scan or rewrite one table
6208 : : *
6209 : : * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
6210 : : * must already hold AccessExclusiveLock on it.
6211 : : */
6212 : : static void
6213 : 4386 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
6214 : : {
6215 : : Relation oldrel;
6216 : : Relation newrel;
6217 : : TupleDesc oldTupDesc;
6218 : : TupleDesc newTupDesc;
6219 : 4386 : bool needscan = false;
6220 : : List *notnull_attrs;
6221 : : List *notnull_virtual_attrs;
6222 : : int i;
6223 : : ListCell *l;
6224 : : EState *estate;
6225 : : CommandId mycid;
6226 : : BulkInsertState bistate;
6227 : : uint32 ti_options;
6228 : 4386 : ExprState *partqualstate = NULL;
6229 : :
6230 : : /*
6231 : : * Open the relation(s). We have surely already locked the existing
6232 : : * table.
6233 : : */
6234 : 4386 : oldrel = table_open(tab->relid, NoLock);
6235 : 4386 : oldTupDesc = tab->oldDesc;
6236 : 4386 : newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
6237 : :
6238 [ + + ]: 4386 : if (OidIsValid(OIDNewHeap))
6239 : : {
6240 : : Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
6241 : : false));
6242 : 962 : newrel = table_open(OIDNewHeap, NoLock);
6243 : : }
6244 : : else
6245 : 3424 : newrel = NULL;
6246 : :
6247 : : /*
6248 : : * Prepare a BulkInsertState and options for table_tuple_insert. The FSM
6249 : : * is empty, so don't bother using it.
6250 : : */
6251 [ + + ]: 4386 : if (newrel)
6252 : : {
6253 : 962 : mycid = GetCurrentCommandId(true);
6254 : 962 : bistate = GetBulkInsertState();
6255 : 962 : ti_options = TABLE_INSERT_SKIP_FSM;
6256 : : }
6257 : : else
6258 : : {
6259 : : /* keep compiler quiet about using these uninitialized */
6260 : 3424 : mycid = 0;
6261 : 3424 : bistate = NULL;
6262 : 3424 : ti_options = 0;
6263 : : }
6264 : :
6265 : : /*
6266 : : * Generate the constraint and default execution states
6267 : : */
6268 : :
6269 : 4386 : estate = CreateExecutorState();
6270 : :
6271 : : /* Build the needed expression execution states */
6272 [ + + + + : 5959 : foreach(l, tab->constraints)
+ + ]
6273 : : {
6274 : 1573 : NewConstraint *con = lfirst(l);
6275 : :
6276 [ + + - ]: 1573 : switch (con->contype)
6277 : : {
6278 : 730 : case CONSTR_CHECK:
6279 : 730 : needscan = true;
6280 : 730 : con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
6281 : 730 : break;
6282 : 843 : case CONSTR_FOREIGN:
6283 : : /* Nothing to do here */
6284 : 843 : break;
6285 : 0 : default:
6286 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
6287 : : (int) con->contype);
6288 : : }
6289 : : }
6290 : :
6291 : : /* Build expression execution states for partition check quals */
6292 [ + + ]: 4386 : if (tab->partition_constraint)
6293 : : {
6294 : 1349 : needscan = true;
6295 : 1349 : partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
6296 : : }
6297 : :
6298 [ + + + + : 5405 : foreach(l, tab->newvals)
+ + ]
6299 : : {
6300 : 1019 : NewColumnValue *ex = lfirst(l);
6301 : :
6302 : : /* expr already planned */
6303 : 1019 : ex->exprstate = ExecInitExpr(ex->expr, NULL);
6304 : : }
6305 : :
6306 : 4386 : notnull_attrs = notnull_virtual_attrs = NIL;
6307 [ + + + + ]: 4386 : if (newrel || tab->verify_new_notnull)
6308 : : {
6309 : : /*
6310 : : * If we are rebuilding the tuples OR if we added any new but not
6311 : : * verified not-null constraints, check all *valid* not-null
6312 : : * constraints. This is a bit of overkill but it minimizes risk of
6313 : : * bugs.
6314 : : *
6315 : : * notnull_attrs does *not* collect attribute numbers for valid
6316 : : * not-null constraints over virtual generated columns; instead, they
6317 : : * are collected in notnull_virtual_attrs for verification elsewhere.
6318 : : */
6319 [ + + ]: 5942 : for (i = 0; i < newTupDesc->natts; i++)
6320 : : {
6321 : 4263 : CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
6322 : :
6323 [ + + ]: 4263 : if (attr->attnullability == ATTNULLABLE_VALID &&
6324 [ + - ]: 1500 : !attr->attisdropped)
6325 : : {
6326 : 1500 : Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
6327 : :
6328 [ + + ]: 1500 : if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
6329 : 1436 : notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
6330 : : else
6331 : 64 : notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
6332 : 64 : wholeatt->attnum);
6333 : : }
6334 : : }
6335 [ + + + + ]: 1679 : if (notnull_attrs || notnull_virtual_attrs)
6336 : 1099 : needscan = true;
6337 : : }
6338 : :
6339 [ + + + + ]: 4386 : if (newrel || needscan)
6340 : : {
6341 : : ExprContext *econtext;
6342 : : TupleTableSlot *oldslot;
6343 : : TupleTableSlot *newslot;
6344 : : TableScanDesc scan;
6345 : : MemoryContext oldCxt;
6346 : 3673 : List *dropped_attrs = NIL;
6347 : : ListCell *lc;
6348 : : Snapshot snapshot;
6349 : 3673 : ResultRelInfo *rInfo = NULL;
6350 : :
6351 : : /*
6352 : : * When adding or changing a virtual generated column with a not-null
6353 : : * constraint, we need to evaluate whether the generation expression
6354 : : * is null. For that, we borrow ExecRelGenVirtualNotNull(). Here, we
6355 : : * prepare a dummy ResultRelInfo.
6356 : : */
6357 [ + + ]: 3673 : if (notnull_virtual_attrs != NIL)
6358 : : {
6359 : : MemoryContext oldcontext;
6360 : :
6361 : : Assert(newTupDesc->constr->has_generated_virtual);
6362 : : Assert(newTupDesc->constr->has_not_null);
6363 : 44 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
6364 : 44 : rInfo = makeNode(ResultRelInfo);
6365 : 44 : InitResultRelInfo(rInfo,
6366 : : oldrel,
6367 : : 0, /* dummy rangetable index */
6368 : : NULL,
6369 : : estate->es_instrument);
6370 : 44 : MemoryContextSwitchTo(oldcontext);
6371 : : }
6372 : :
6373 [ + + ]: 3673 : if (newrel)
6374 [ - + ]: 962 : ereport(DEBUG1,
6375 : : (errmsg_internal("rewriting table \"%s\"",
6376 : : RelationGetRelationName(oldrel))));
6377 : : else
6378 [ + + ]: 2711 : ereport(DEBUG1,
6379 : : (errmsg_internal("verifying table \"%s\"",
6380 : : RelationGetRelationName(oldrel))));
6381 : :
6382 [ + + ]: 3673 : if (newrel)
6383 : : {
6384 : : /*
6385 : : * All predicate locks on the tuples or pages are about to be made
6386 : : * invalid, because we move tuples around. Promote them to
6387 : : * relation locks.
6388 : : */
6389 : 962 : TransferPredicateLocksToHeapRelation(oldrel);
6390 : : }
6391 : :
6392 [ - + ]: 3673 : econtext = GetPerTupleExprContext(estate);
6393 : :
6394 : : /*
6395 : : * Create necessary tuple slots. When rewriting, two slots are needed,
6396 : : * otherwise one suffices. In the case where one slot suffices, we
6397 : : * need to use the new tuple descriptor, otherwise some constraints
6398 : : * can't be evaluated. Note that even when the tuple layout is the
6399 : : * same and no rewrite is required, the tupDescs might not be
6400 : : * (consider ADD COLUMN without a default).
6401 : : */
6402 [ + + ]: 3673 : if (tab->rewrite)
6403 : : {
6404 : : Assert(newrel != NULL);
6405 : 962 : oldslot = MakeSingleTupleTableSlot(oldTupDesc,
6406 : : table_slot_callbacks(oldrel));
6407 : 962 : newslot = MakeSingleTupleTableSlot(newTupDesc,
6408 : : table_slot_callbacks(newrel));
6409 : :
6410 : : /*
6411 : : * Set all columns in the new slot to NULL initially, to ensure
6412 : : * columns added as part of the rewrite are initialized to NULL.
6413 : : * That is necessary as tab->newvals will not contain an
6414 : : * expression for columns with a NULL default, e.g. when adding a
6415 : : * column without a default together with a column with a default
6416 : : * requiring an actual rewrite.
6417 : : */
6418 : 962 : ExecStoreAllNullTuple(newslot);
6419 : : }
6420 : : else
6421 : : {
6422 : 2711 : oldslot = MakeSingleTupleTableSlot(newTupDesc,
6423 : : table_slot_callbacks(oldrel));
6424 : 2711 : newslot = NULL;
6425 : : }
6426 : :
6427 : : /*
6428 : : * Any attributes that are dropped according to the new tuple
6429 : : * descriptor can be set to NULL. We precompute the list of dropped
6430 : : * attributes to avoid needing to do so in the per-tuple loop.
6431 : : */
6432 [ + + ]: 12613 : for (i = 0; i < newTupDesc->natts; i++)
6433 : : {
6434 [ + + ]: 8940 : if (TupleDescAttr(newTupDesc, i)->attisdropped)
6435 : 520 : dropped_attrs = lappend_int(dropped_attrs, i);
6436 : : }
6437 : :
6438 : : /*
6439 : : * Scan through the rows, generating a new row if needed and then
6440 : : * checking all the constraints.
6441 : : */
6442 : 3673 : snapshot = RegisterSnapshot(GetLatestSnapshot());
6443 : 3673 : scan = table_beginscan(oldrel, snapshot, 0, NULL,
6444 : : SO_NONE);
6445 : :
6446 : : /*
6447 : : * Switch to per-tuple memory context and reset it for each tuple
6448 : : * produced, so we don't leak memory.
6449 : : */
6450 [ + - ]: 3673 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6451 : :
6452 [ + + ]: 491301 : while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
6453 : : {
6454 : : TupleTableSlot *insertslot;
6455 : :
6456 [ + + ]: 484240 : if (tab->rewrite > 0)
6457 : : {
6458 : : /* Extract data from old tuple */
6459 : 67507 : slot_getallattrs(oldslot);
6460 : 67507 : ExecClearTuple(newslot);
6461 : :
6462 : : /* copy attributes */
6463 : 67507 : memcpy(newslot->tts_values, oldslot->tts_values,
6464 : 67507 : sizeof(Datum) * oldslot->tts_nvalid);
6465 : 67507 : memcpy(newslot->tts_isnull, oldslot->tts_isnull,
6466 : 67507 : sizeof(bool) * oldslot->tts_nvalid);
6467 : :
6468 : : /* Set dropped attributes to null in new tuple */
6469 [ + + + + : 67592 : foreach(lc, dropped_attrs)
+ + ]
6470 : 85 : newslot->tts_isnull[lfirst_int(lc)] = true;
6471 : :
6472 : : /*
6473 : : * Constraints and GENERATED expressions might reference the
6474 : : * tableoid column, so fill tts_tableOid with the desired
6475 : : * value. (We must do this each time, because it gets
6476 : : * overwritten with newrel's OID during storing.)
6477 : : */
6478 : 67507 : newslot->tts_tableOid = RelationGetRelid(oldrel);
6479 : :
6480 : : /*
6481 : : * Process supplied expressions to replace selected columns.
6482 : : *
6483 : : * First, evaluate expressions whose inputs come from the old
6484 : : * tuple.
6485 : : */
6486 : 67507 : econtext->ecxt_scantuple = oldslot;
6487 : :
6488 [ + + + + : 138006 : foreach(l, tab->newvals)
+ + ]
6489 : : {
6490 : 70507 : NewColumnValue *ex = lfirst(l);
6491 : :
6492 [ + + ]: 70507 : if (ex->is_generated)
6493 : 284 : continue;
6494 : :
6495 : 70223 : newslot->tts_values[ex->attnum - 1]
6496 : 70215 : = ExecEvalExpr(ex->exprstate,
6497 : : econtext,
6498 : 70223 : &newslot->tts_isnull[ex->attnum - 1]);
6499 : : }
6500 : :
6501 : 67499 : ExecStoreVirtualTuple(newslot);
6502 : :
6503 : : /*
6504 : : * Now, evaluate any expressions whose inputs come from the
6505 : : * new tuple. We assume these columns won't reference each
6506 : : * other, so that there's no ordering dependency.
6507 : : */
6508 : 67499 : econtext->ecxt_scantuple = newslot;
6509 : :
6510 [ + + + + : 137998 : foreach(l, tab->newvals)
+ + ]
6511 : : {
6512 : 70499 : NewColumnValue *ex = lfirst(l);
6513 : :
6514 [ + + ]: 70499 : if (!ex->is_generated)
6515 : 70215 : continue;
6516 : :
6517 : 284 : newslot->tts_values[ex->attnum - 1]
6518 : 284 : = ExecEvalExpr(ex->exprstate,
6519 : : econtext,
6520 : 284 : &newslot->tts_isnull[ex->attnum - 1]);
6521 : : }
6522 : :
6523 : 67499 : insertslot = newslot;
6524 : : }
6525 : : else
6526 : : {
6527 : : /*
6528 : : * If there's no rewrite, old and new table are guaranteed to
6529 : : * have the same AM, so we can just use the old slot to verify
6530 : : * new constraints etc.
6531 : : */
6532 : 416733 : insertslot = oldslot;
6533 : : }
6534 : :
6535 : : /* Now check any constraints on the possibly-changed tuple */
6536 : 484232 : econtext->ecxt_scantuple = insertslot;
6537 : :
6538 [ + + + + : 2579330 : foreach_int(attn, notnull_attrs)
+ + ]
6539 : : {
6540 [ + + ]: 1611042 : if (slot_attisnull(insertslot, attn))
6541 : : {
6542 : 88 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
6543 : :
6544 [ + - ]: 88 : ereport(ERROR,
6545 : : (errcode(ERRCODE_NOT_NULL_VIOLATION),
6546 : : errmsg("column \"%s\" of relation \"%s\" contains null values",
6547 : : NameStr(attr->attname),
6548 : : RelationGetRelationName(oldrel)),
6549 : : errtablecol(oldrel, attn)));
6550 : : }
6551 : : }
6552 : :
6553 [ + + ]: 484144 : if (notnull_virtual_attrs != NIL)
6554 : : {
6555 : : AttrNumber attnum;
6556 : :
6557 : 60 : attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
6558 : : estate,
6559 : : notnull_virtual_attrs);
6560 [ + + ]: 60 : if (attnum != InvalidAttrNumber)
6561 : : {
6562 : 20 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
6563 : :
6564 [ + - ]: 20 : ereport(ERROR,
6565 : : errcode(ERRCODE_NOT_NULL_VIOLATION),
6566 : : errmsg("column \"%s\" of relation \"%s\" contains null values",
6567 : : NameStr(attr->attname),
6568 : : RelationGetRelationName(oldrel)),
6569 : : errtablecol(oldrel, attnum));
6570 : : }
6571 : : }
6572 : :
6573 [ + + + + : 489349 : foreach(l, tab->constraints)
+ + ]
6574 : : {
6575 : 5345 : NewConstraint *con = lfirst(l);
6576 : :
6577 [ + + - ]: 5345 : switch (con->contype)
6578 : : {
6579 : 5279 : case CONSTR_CHECK:
6580 [ + + ]: 5279 : if (!ExecCheck(con->qualstate, econtext))
6581 [ + - ]: 120 : ereport(ERROR,
6582 : : (errcode(ERRCODE_CHECK_VIOLATION),
6583 : : errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
6584 : : con->name,
6585 : : RelationGetRelationName(oldrel)),
6586 : : errtableconstraint(oldrel, con->name)));
6587 : 5159 : break;
6588 : 66 : case CONSTR_NOTNULL:
6589 : : case CONSTR_FOREIGN:
6590 : : /* Nothing to do here */
6591 : 66 : break;
6592 : 0 : default:
6593 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
6594 : : (int) con->contype);
6595 : : }
6596 : : }
6597 : :
6598 [ + + + + ]: 484004 : if (partqualstate && !ExecCheck(partqualstate, econtext))
6599 : : {
6600 [ + + ]: 49 : if (tab->validate_default)
6601 [ + - ]: 17 : ereport(ERROR,
6602 : : (errcode(ERRCODE_CHECK_VIOLATION),
6603 : : errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
6604 : : RelationGetRelationName(oldrel)),
6605 : : errtable(oldrel)));
6606 : : else
6607 [ + - ]: 32 : ereport(ERROR,
6608 : : (errcode(ERRCODE_CHECK_VIOLATION),
6609 : : errmsg("partition constraint of relation \"%s\" is violated by some row",
6610 : : RelationGetRelationName(oldrel)),
6611 : : errtable(oldrel)));
6612 : : }
6613 : :
6614 : : /* Write the tuple out to the new relation */
6615 [ + + ]: 483955 : if (newrel)
6616 : 67455 : table_tuple_insert(newrel, insertslot, mycid,
6617 : : ti_options, bistate);
6618 : :
6619 : 483955 : ResetExprContext(econtext);
6620 : :
6621 [ - + ]: 483955 : CHECK_FOR_INTERRUPTS();
6622 : : }
6623 : :
6624 : 3388 : MemoryContextSwitchTo(oldCxt);
6625 : 3388 : table_endscan(scan);
6626 : 3388 : UnregisterSnapshot(snapshot);
6627 : :
6628 : 3388 : ExecDropSingleTupleTableSlot(oldslot);
6629 [ + + ]: 3388 : if (newslot)
6630 : 910 : ExecDropSingleTupleTableSlot(newslot);
6631 : : }
6632 : :
6633 : 4101 : FreeExecutorState(estate);
6634 : :
6635 : 4101 : table_close(oldrel, NoLock);
6636 [ + + ]: 4101 : if (newrel)
6637 : : {
6638 : 910 : FreeBulkInsertState(bistate);
6639 : :
6640 : 910 : table_finish_bulk_insert(newrel, ti_options);
6641 : :
6642 : 910 : table_close(newrel, NoLock);
6643 : : }
6644 : 4101 : }
6645 : :
6646 : : /*
6647 : : * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
6648 : : */
6649 : : static AlteredTableInfo *
6650 : 30612 : ATGetQueueEntry(List **wqueue, Relation rel)
6651 : : {
6652 : 30612 : Oid relid = RelationGetRelid(rel);
6653 : : AlteredTableInfo *tab;
6654 : : ListCell *ltab;
6655 : :
6656 [ + + + + : 37400 : foreach(ltab, *wqueue)
+ + ]
6657 : : {
6658 : 10026 : tab = (AlteredTableInfo *) lfirst(ltab);
6659 [ + + ]: 10026 : if (tab->relid == relid)
6660 : 3238 : return tab;
6661 : : }
6662 : :
6663 : : /*
6664 : : * Not there, so add it. Note that we make a copy of the relation's
6665 : : * existing descriptor before anything interesting can happen to it.
6666 : : */
6667 : 27374 : tab = palloc0_object(AlteredTableInfo);
6668 : 27374 : tab->relid = relid;
6669 : 27374 : tab->rel = NULL; /* set later */
6670 : 27374 : tab->relkind = rel->rd_rel->relkind;
6671 : 27374 : tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
6672 : 27374 : tab->newAccessMethod = InvalidOid;
6673 : 27374 : tab->chgAccessMethod = false;
6674 : 27374 : tab->newTableSpace = InvalidOid;
6675 : 27374 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
6676 : 27374 : tab->chgPersistence = false;
6677 : :
6678 : 27374 : *wqueue = lappend(*wqueue, tab);
6679 : :
6680 : 27374 : return tab;
6681 : : }
6682 : :
6683 : : static const char *
6684 : 69 : alter_table_type_to_string(AlterTableType cmdtype)
6685 : : {
6686 [ - - + + : 69 : switch (cmdtype)
- - - + -
- - + - -
+ - - - -
- - + + -
+ + - - +
- - - - -
- - - - -
- - - - +
+ - - - -
- - - - +
+ + - - -
- - ]
6687 : : {
6688 : 0 : case AT_AddColumn:
6689 : : case AT_AddColumnToView:
6690 : 0 : return "ADD COLUMN";
6691 : 0 : case AT_ColumnDefault:
6692 : : case AT_CookedColumnDefault:
6693 : 0 : return "ALTER COLUMN ... SET DEFAULT";
6694 : 4 : case AT_DropNotNull:
6695 : 4 : return "ALTER COLUMN ... DROP NOT NULL";
6696 : 4 : case AT_SetNotNull:
6697 : 4 : return "ALTER COLUMN ... SET NOT NULL";
6698 : 0 : case AT_SetExpression:
6699 : 0 : return "ALTER COLUMN ... SET EXPRESSION";
6700 : 0 : case AT_DropExpression:
6701 : 0 : return "ALTER COLUMN ... DROP EXPRESSION";
6702 : 0 : case AT_SetStatistics:
6703 : 0 : return "ALTER COLUMN ... SET STATISTICS";
6704 : 8 : case AT_SetOptions:
6705 : 8 : return "ALTER COLUMN ... SET";
6706 : 0 : case AT_ResetOptions:
6707 : 0 : return "ALTER COLUMN ... RESET";
6708 : 0 : case AT_SetStorage:
6709 : 0 : return "ALTER COLUMN ... SET STORAGE";
6710 : 0 : case AT_SetCompression:
6711 : 0 : return "ALTER COLUMN ... SET COMPRESSION";
6712 : 4 : case AT_DropColumn:
6713 : 4 : return "DROP COLUMN";
6714 : 0 : case AT_AddIndex:
6715 : : case AT_ReAddIndex:
6716 : 0 : return NULL; /* not real grammar */
6717 : 0 : case AT_AddConstraint:
6718 : : case AT_ReAddConstraint:
6719 : : case AT_ReAddDomainConstraint:
6720 : : case AT_AddIndexConstraint:
6721 : 0 : return "ADD CONSTRAINT";
6722 : 4 : case AT_AlterConstraint:
6723 : 4 : return "ALTER CONSTRAINT";
6724 : 0 : case AT_ValidateConstraint:
6725 : 0 : return "VALIDATE CONSTRAINT";
6726 : 0 : case AT_DropConstraint:
6727 : 0 : return "DROP CONSTRAINT";
6728 : 0 : case AT_ReAddComment:
6729 : 0 : return NULL; /* not real grammar */
6730 : 0 : case AT_AlterColumnType:
6731 : 0 : return "ALTER COLUMN ... SET DATA TYPE";
6732 : 0 : case AT_AlterColumnGenericOptions:
6733 : 0 : return "ALTER COLUMN ... OPTIONS";
6734 : 0 : case AT_ChangeOwner:
6735 : 0 : return "OWNER TO";
6736 : 4 : case AT_ClusterOn:
6737 : 4 : return "CLUSTER ON";
6738 : 4 : case AT_DropCluster:
6739 : 4 : return "SET WITHOUT CLUSTER";
6740 : 0 : case AT_SetAccessMethod:
6741 : 0 : return "SET ACCESS METHOD";
6742 : 4 : case AT_SetLogged:
6743 : 4 : return "SET LOGGED";
6744 : 4 : case AT_SetUnLogged:
6745 : 4 : return "SET UNLOGGED";
6746 : 0 : case AT_DropOids:
6747 : 0 : return "SET WITHOUT OIDS";
6748 : 0 : case AT_SetTableSpace:
6749 : 0 : return "SET TABLESPACE";
6750 : 1 : case AT_SetRelOptions:
6751 : 1 : return "SET";
6752 : 0 : case AT_ResetRelOptions:
6753 : 0 : return "RESET";
6754 : 0 : case AT_ReplaceRelOptions:
6755 : 0 : return NULL; /* not real grammar */
6756 : 0 : case AT_EnableTrig:
6757 : 0 : return "ENABLE TRIGGER";
6758 : 0 : case AT_EnableAlwaysTrig:
6759 : 0 : return "ENABLE ALWAYS TRIGGER";
6760 : 0 : case AT_EnableReplicaTrig:
6761 : 0 : return "ENABLE REPLICA TRIGGER";
6762 : 0 : case AT_DisableTrig:
6763 : 0 : return "DISABLE TRIGGER";
6764 : 0 : case AT_EnableTrigAll:
6765 : 0 : return "ENABLE TRIGGER ALL";
6766 : 0 : case AT_DisableTrigAll:
6767 : 0 : return "DISABLE TRIGGER ALL";
6768 : 0 : case AT_EnableTrigUser:
6769 : 0 : return "ENABLE TRIGGER USER";
6770 : 0 : case AT_DisableTrigUser:
6771 : 0 : return "DISABLE TRIGGER USER";
6772 : 0 : case AT_EnableRule:
6773 : 0 : return "ENABLE RULE";
6774 : 0 : case AT_EnableAlwaysRule:
6775 : 0 : return "ENABLE ALWAYS RULE";
6776 : 0 : case AT_EnableReplicaRule:
6777 : 0 : return "ENABLE REPLICA RULE";
6778 : 0 : case AT_DisableRule:
6779 : 0 : return "DISABLE RULE";
6780 : 4 : case AT_AddInherit:
6781 : 4 : return "INHERIT";
6782 : 4 : case AT_DropInherit:
6783 : 4 : return "NO INHERIT";
6784 : 0 : case AT_AddOf:
6785 : 0 : return "OF";
6786 : 0 : case AT_DropOf:
6787 : 0 : return "NOT OF";
6788 : 0 : case AT_ReplicaIdentity:
6789 : 0 : return "REPLICA IDENTITY";
6790 : 0 : case AT_EnableRowSecurity:
6791 : 0 : return "ENABLE ROW SECURITY";
6792 : 0 : case AT_DisableRowSecurity:
6793 : 0 : return "DISABLE ROW SECURITY";
6794 : 0 : case AT_ForceRowSecurity:
6795 : 0 : return "FORCE ROW SECURITY";
6796 : 0 : case AT_NoForceRowSecurity:
6797 : 0 : return "NO FORCE ROW SECURITY";
6798 : 0 : case AT_GenericOptions:
6799 : 0 : return "OPTIONS";
6800 : 4 : case AT_AttachPartition:
6801 : 4 : return "ATTACH PARTITION";
6802 : 12 : case AT_DetachPartition:
6803 : 12 : return "DETACH PARTITION";
6804 : 4 : case AT_DetachPartitionFinalize:
6805 : 4 : return "DETACH PARTITION ... FINALIZE";
6806 : 0 : case AT_AddIdentity:
6807 : 0 : return "ALTER COLUMN ... ADD IDENTITY";
6808 : 0 : case AT_SetIdentity:
6809 : 0 : return "ALTER COLUMN ... SET";
6810 : 0 : case AT_DropIdentity:
6811 : 0 : return "ALTER COLUMN ... DROP IDENTITY";
6812 : 0 : case AT_ReAddStatistics:
6813 : 0 : return NULL; /* not real grammar */
6814 : : }
6815 : :
6816 : 0 : return NULL;
6817 : : }
6818 : :
6819 : : /*
6820 : : * ATSimplePermissions
6821 : : *
6822 : : * - Ensure that it is a relation (or possibly a view)
6823 : : * - Ensure this user is the owner
6824 : : * - Ensure that it is not a system table
6825 : : */
6826 : : static void
6827 : 27970 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
6828 : : {
6829 : : int actual_target;
6830 : :
6831 [ + + + + : 27970 : switch (rel->rd_rel->relkind)
+ + + + +
+ ]
6832 : : {
6833 : 22312 : case RELKIND_RELATION:
6834 : 22312 : actual_target = ATT_TABLE;
6835 : 22312 : break;
6836 : 3741 : case RELKIND_PARTITIONED_TABLE:
6837 : 3741 : actual_target = ATT_PARTITIONED_TABLE;
6838 : 3741 : break;
6839 : 317 : case RELKIND_VIEW:
6840 : 317 : actual_target = ATT_VIEW;
6841 : 317 : break;
6842 : 29 : case RELKIND_MATVIEW:
6843 : 29 : actual_target = ATT_MATVIEW;
6844 : 29 : break;
6845 : 142 : case RELKIND_INDEX:
6846 : 142 : actual_target = ATT_INDEX;
6847 : 142 : break;
6848 : 314 : case RELKIND_PARTITIONED_INDEX:
6849 : 314 : actual_target = ATT_PARTITIONED_INDEX;
6850 : 314 : break;
6851 : 505 : case RELKIND_COMPOSITE_TYPE:
6852 : 505 : actual_target = ATT_COMPOSITE_TYPE;
6853 : 505 : break;
6854 : 593 : case RELKIND_FOREIGN_TABLE:
6855 : 593 : actual_target = ATT_FOREIGN_TABLE;
6856 : 593 : break;
6857 : 16 : case RELKIND_SEQUENCE:
6858 : 16 : actual_target = ATT_SEQUENCE;
6859 : 16 : break;
6860 : 1 : default:
6861 : 1 : actual_target = 0;
6862 : 1 : break;
6863 : : }
6864 : :
6865 : : /* Wrong target type? */
6866 [ + + ]: 27970 : if ((actual_target & allowed_targets) == 0)
6867 : : {
6868 : 69 : const char *action_str = alter_table_type_to_string(cmdtype);
6869 : :
6870 [ + - ]: 69 : if (action_str)
6871 [ + - ]: 69 : ereport(ERROR,
6872 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6873 : : /* translator: %s is a group of some SQL keywords */
6874 : : errmsg("ALTER action %s cannot be performed on relation \"%s\"",
6875 : : action_str, RelationGetRelationName(rel)),
6876 : : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
6877 : : else
6878 : : /* internal error? */
6879 [ # # ]: 0 : elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
6880 : : RelationGetRelationName(rel));
6881 : : }
6882 : :
6883 : : /* Permissions checks */
6884 [ + + ]: 27901 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
6885 : 8 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
6886 : 8 : RelationGetRelationName(rel));
6887 : :
6888 : : /*
6889 : : * Conflict log tables are used internally for logical replication
6890 : : * conflict logging and should not be altered directly, as it could
6891 : : * disrupt conflict logging. Direct ALTER commands are already rejected
6892 : : * during relation lookup in RangeVarCallbackForAlterRelation(), and
6893 : : * AlterTableMoveAll() skips these tables, so a conflict log table does
6894 : : * not normally reach here; this check guards any internal caller that
6895 : : * arrives via AlterTableInternal().
6896 : : */
6897 [ - + ]: 27893 : if (IsConflictLogTableClass(rel->rd_rel))
6898 [ # # ]: 0 : ereport(ERROR,
6899 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6900 : : errmsg("cannot alter conflict log table \"%s\"",
6901 : : RelationGetRelationName(rel)),
6902 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
6903 : :
6904 [ + + - + ]: 27893 : if (!allowSystemTableMods && IsSystemRelation(rel))
6905 [ # # ]: 0 : ereport(ERROR,
6906 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6907 : : errmsg("permission denied: \"%s\" is a system catalog",
6908 : : RelationGetRelationName(rel))));
6909 : 27893 : }
6910 : :
6911 : : /*
6912 : : * ATSimpleRecursion
6913 : : *
6914 : : * Simple table recursion sufficient for most ALTER TABLE operations.
6915 : : * All direct and indirect children are processed in an unspecified order.
6916 : : * Note that if a child inherits from the original table via multiple
6917 : : * inheritance paths, it will be visited just once.
6918 : : */
6919 : : static void
6920 : 1065 : ATSimpleRecursion(List **wqueue, Relation rel,
6921 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
6922 : : AlterTableUtilityContext *context)
6923 : : {
6924 : : /*
6925 : : * Propagate to children, if desired and if there are (or might be) any
6926 : : * children.
6927 : : */
6928 [ + + + + ]: 1065 : if (recurse && rel->rd_rel->relhassubclass)
6929 : : {
6930 : 71 : Oid relid = RelationGetRelid(rel);
6931 : : ListCell *child;
6932 : : List *children;
6933 : :
6934 : 71 : children = find_all_inheritors(relid, lockmode, NULL);
6935 : :
6936 : : /*
6937 : : * find_all_inheritors does the recursive search of the inheritance
6938 : : * hierarchy, so all we have to do is process all of the relids in the
6939 : : * list that it returns.
6940 : : */
6941 [ + - + + : 300 : foreach(child, children)
+ + ]
6942 : : {
6943 : 229 : Oid childrelid = lfirst_oid(child);
6944 : : Relation childrel;
6945 : :
6946 [ + + ]: 229 : if (childrelid == relid)
6947 : 71 : continue;
6948 : : /* find_all_inheritors already got lock */
6949 : 158 : childrel = relation_open(childrelid, NoLock);
6950 : 158 : CheckAlterTableIsSafe(childrel);
6951 : 158 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
6952 : 158 : relation_close(childrel, NoLock);
6953 : : }
6954 : : }
6955 : 1065 : }
6956 : :
6957 : : /*
6958 : : * Obtain list of partitions of the given table, locking them all at the given
6959 : : * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
6960 : : *
6961 : : * This function is a no-op if the given relation is not a partitioned table;
6962 : : * in particular, nothing is done if it's a legacy inheritance parent.
6963 : : */
6964 : : static void
6965 : 579 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
6966 : : {
6967 [ + + ]: 579 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6968 : : {
6969 : : List *inh;
6970 : : ListCell *cell;
6971 : :
6972 : 121 : inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
6973 : : /* first element is the parent rel; must ignore it */
6974 [ + - + + : 398 : for_each_from(cell, inh, 1)
+ + ]
6975 : : {
6976 : : Relation childrel;
6977 : :
6978 : : /* find_all_inheritors already got lock */
6979 : 281 : childrel = table_open(lfirst_oid(cell), NoLock);
6980 : 281 : CheckAlterTableIsSafe(childrel);
6981 : 277 : table_close(childrel, NoLock);
6982 : : }
6983 : 117 : list_free(inh);
6984 : : }
6985 : 575 : }
6986 : :
6987 : : /*
6988 : : * ATTypedTableRecursion
6989 : : *
6990 : : * Propagate ALTER TYPE operations to the typed tables of that type.
6991 : : * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
6992 : : * recursion to inheritance children of the typed tables.
6993 : : */
6994 : : static void
6995 : 442 : ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
6996 : : LOCKMODE lockmode, AlterTableUtilityContext *context)
6997 : : {
6998 : : ListCell *child;
6999 : : List *children;
7000 : :
7001 : : Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7002 : :
7003 : 442 : children = find_typed_table_dependencies(rel->rd_rel->reltype,
7004 : 442 : RelationGetRelationName(rel),
7005 : : cmd->behavior);
7006 : :
7007 [ + + + + : 451 : foreach(child, children)
+ + ]
7008 : : {
7009 : 21 : Oid childrelid = lfirst_oid(child);
7010 : : Relation childrel;
7011 : :
7012 : 21 : childrel = relation_open(childrelid, lockmode);
7013 : 21 : CheckAlterTableIsSafe(childrel);
7014 : 21 : ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
7015 : 21 : relation_close(childrel, NoLock);
7016 : : }
7017 : 430 : }
7018 : :
7019 : :
7020 : : /*
7021 : : * find_composite_type_dependencies
7022 : : *
7023 : : * Check to see if the type "typeOid" is being used in a way that prevents
7024 : : * ALTER COLUMN / ALTER ATTRIBUTE on it. For example, if it's used as a
7025 : : * column in some table (possibly nested several levels deep in composite
7026 : : * types, arrays, etc!), we must not allow it. Eventually, we'd like to
7027 : : * propagate the check or rewrite operation into such tables, but for now,
7028 : : * just error out if we find any.
7029 : : *
7030 : : * Caller should provide either the associated relation of a rowtype, or a
7031 : : * type name (not both) for use in the error message, if any.
7032 : : *
7033 : : * Note that "typeOid" is not necessarily a composite type; it could also be
7034 : : * another container type such as an array or range, or a domain over one of
7035 : : * these things. The name of this function is therefore somewhat historical,
7036 : : * but it's not worth changing.
7037 : : */
7038 : : void
7039 : 2187 : find_composite_type_dependencies(Oid typeOid, Relation origRelation,
7040 : : const char *origTypeName)
7041 : : {
7042 : : HASHCTL hctl;
7043 : : HTAB *visited;
7044 : :
7045 : 2187 : memset(&hctl, 0, sizeof(HASHCTL));
7046 : 2187 : hctl.keysize = sizeof(Oid);
7047 : 2187 : hctl.entrysize = sizeof(Oid);
7048 : 2187 : hctl.hcxt = CurrentMemoryContext;
7049 : :
7050 : 2187 : visited = hash_create("visited types",
7051 : : 32, /* start small and extend */
7052 : : &hctl,
7053 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
7054 : :
7055 : 2187 : find_composite_type_dependencies_recurse(typeOid, origRelation, origTypeName,
7056 : : visited);
7057 : :
7058 : : /*
7059 : : * We used to not record pg_depend entries in some cases where we really
7060 : : * should have. Scan the catalog tables for those, too.
7061 : : */
7062 : 1963 : find_missing_composite_type_dependencies(visited, origRelation, origTypeName);
7063 : :
7064 : 1963 : hash_destroy(visited);
7065 : 1963 : }
7066 : :
7067 : : /*
7068 : : * Recursive part of find_composite_type_dependencies. 'visited' keeps track
7069 : : * of types that have already been visited, to avoid duplicating work.
7070 : : */
7071 : : static void
7072 : 4530 : find_composite_type_dependencies_recurse(Oid typeOid, Relation origRelation,
7073 : : const char *origTypeName, HTAB *visited)
7074 : : {
7075 : : Relation depRel;
7076 : : ScanKeyData key[2];
7077 : : SysScanDesc depScan;
7078 : : HeapTuple depTup;
7079 : : bool visited_already;
7080 : :
7081 : : Assert(OidIsValid(typeOid));
7082 : :
7083 : : /* since this function recurses, it could be driven to stack overflow */
7084 : 4530 : check_stack_depth();
7085 : :
7086 : : /* skip if we visited this type already */
7087 : 4530 : hash_search(visited, &typeOid, HASH_ENTER, &visited_already);
7088 [ + + ]: 4530 : if (visited_already)
7089 : 4 : return;
7090 : :
7091 : : /*
7092 : : * We already hold a lock on the relation being ALTERed, but also lock its
7093 : : * rowtype (on first call), and its array type, domains, composite types
7094 : : * etc. that depend on the ALTERed type (as we recurse). This ensures
7095 : : * that if a concurrent command is adding a new dependency to any of those
7096 : : * types, we will see it.
7097 : : */
7098 : 4526 : LockDatabaseObject(TypeRelationId, typeOid, 0, AccessExclusiveLock);
7099 : :
7100 : : /*
7101 : : * We scan pg_depend to find those things that depend on the given type.
7102 : : * (We assume we can ignore refobjsubid for a type.)
7103 : : */
7104 : 4526 : depRel = table_open(DependRelationId, AccessShareLock);
7105 : :
7106 : 4526 : ScanKeyInit(&key[0],
7107 : : Anum_pg_depend_refclassid,
7108 : : BTEqualStrategyNumber, F_OIDEQ,
7109 : : ObjectIdGetDatum(TypeRelationId));
7110 : 4526 : ScanKeyInit(&key[1],
7111 : : Anum_pg_depend_refobjid,
7112 : : BTEqualStrategyNumber, F_OIDEQ,
7113 : : ObjectIdGetDatum(typeOid));
7114 : :
7115 : 4526 : depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
7116 : : NULL, 2, key);
7117 : :
7118 [ + + ]: 7674 : while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
7119 : : {
7120 : 3412 : Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
7121 : : ObjectAddress depobj;
7122 : :
7123 : 3412 : ObjectAddressSubSet(depobj, pg_depend->classid, pg_depend->objid,
7124 : : pg_depend->objsubid);
7125 : :
7126 : 3412 : check_composite_type_dependency(&depobj, typeOid, origRelation, origTypeName,
7127 : : visited);
7128 : : }
7129 : :
7130 : 4262 : systable_endscan(depScan);
7131 : :
7132 : 4262 : relation_close(depRel, AccessShareLock);
7133 : : }
7134 : :
7135 : : /*
7136 : : * check_composite_type_dependency
7137 : : *
7138 : : * Subroutine of find_composite_type_dependencies, to check whether a
7139 : : * dependency from "depobj" makes it unsafe to alter a column of "typeOid".
7140 : : * Some dependencies that would prevent dropping a composite type entirely
7141 : : * don't prevent ALTERing it. This function is called after we have
7142 : : * established that there is a dependency, to look closer at whether the
7143 : : * dependency prevents ALTER or not.
7144 : : *
7145 : : * Caller should provide either the associated relation of a rowtype, or a
7146 : : * type name (not both) for use in the error message, if any.
7147 : : *
7148 : : * Note that "typeOid" is not necessarily a composite type; it could also be
7149 : : * another container type such as an array or range, or a domain over one of
7150 : : * these things.
7151 : : */
7152 : : static void
7153 : 3412 : check_composite_type_dependency(ObjectAddress *depobj, Oid typeOid,
7154 : : Relation origRelation, const char *origTypeName,
7155 : : HTAB *visited)
7156 : : {
7157 : 3412 : Oid classid = depobj->classId;
7158 : 3412 : Oid objid = depobj->objectId;
7159 : 3412 : int32 objsubid = depobj->objectSubId;
7160 : : HeapTuple catalog_tup;
7161 : : Node *expr;
7162 : : Relation rel;
7163 : : TupleDesc tupleDesc;
7164 : : Form_pg_attribute att;
7165 : : Form_pg_constraint cform;
7166 : :
7167 : : /*
7168 : : * By default, a dependency on a type prevents ALTERing it. But we make
7169 : : * many exceptions for cases that are safe:
7170 : : */
7171 [ + + + + : 3412 : switch (classid)
+ + - + ]
7172 : : {
7173 : 4 : case OperatorRelationId:
7174 : :
7175 : : /*
7176 : : * Operators are OK. The function implementing the operator will
7177 : : * have a dependency of its own and will be checked separately.
7178 : : */
7179 : 4 : break;
7180 : :
7181 : 52 : case CastRelationId:
7182 : :
7183 : : /*
7184 : : * Casts are also OK. If the cast uses a function, the function
7185 : : * will have a dependency of its own.
7186 : : */
7187 : 52 : break;
7188 : :
7189 : 431 : case ProcedureRelationId:
7190 : :
7191 : : /*
7192 : : * A function that uses the composite type as its return or
7193 : : * argument type doesn't prevent ALTERing it. But if the type is
7194 : : * used in the DEFAULT expressions or in a new-style SQL
7195 : : * function's body, we need to reject, because the expression
7196 : : * might contain Consts or other things that would become invalid.
7197 : : *
7198 : : * Fetch the procedure definition to see which parts are using the
7199 : : * type. Lock it to make sure that a DEFAULT expression is not
7200 : : * added to it concurrently with CREATE OR REPLACE FUNCTION.
7201 : : */
7202 : 431 : LockDatabaseObject(ProcedureRelationId, objid, 0, AccessShareLock);
7203 : 431 : catalog_tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(objid));
7204 [ - + ]: 431 : if (!HeapTupleIsValid(catalog_tup))
7205 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", objid);
7206 : :
7207 : : /* Is it used in the argument DEFAULTs? */
7208 : 431 : expr = get_node_tree_attr(PROCOID, catalog_tup, Anum_pg_proc_proargdefaults);
7209 [ + + + + ]: 431 : if (expr && CheckTypeDependencyInExpr(expr, NIL, typeOid))
7210 : 5 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7211 : :
7212 : : /* Is it used in the SQL body? */
7213 : 426 : expr = get_node_tree_attr(PROCOID, catalog_tup, Anum_pg_proc_prosqlbody);
7214 [ + + + - ]: 426 : if (expr && CheckTypeDependencyInExpr(expr, NIL, typeOid))
7215 : 4 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7216 : :
7217 : : /*
7218 : : * Otherwise, it must be used as a return or parameter type, which
7219 : : * is OK.
7220 : : */
7221 : 422 : ReleaseSysCache(catalog_tup);
7222 : 422 : break;
7223 : :
7224 : 29 : case ConstraintRelationId:
7225 : :
7226 : : /*
7227 : : * Constraints referencing the type usually forbid ALTERing it,
7228 : : * but there's one exception: a CHECK constraint on a domain
7229 : : * referencing the type itself is ignored, if the expression
7230 : : * doesn't refer to the type. In other words, if the dependency
7231 : : * exists just because it's a CHECK constraint on the domain, that
7232 : : * doesn't prevent altering the underlying type. (We assume that
7233 : : * the constraint cannot be reassigned to a different type, so no
7234 : : * need to hold the lock just to check 'contypid'.)
7235 : : */
7236 : 29 : catalog_tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(objid));
7237 [ - + ]: 29 : if (!HeapTupleIsValid(catalog_tup))
7238 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", objid);
7239 : 29 : cform = (Form_pg_constraint) GETSTRUCT(catalog_tup);
7240 [ + + ]: 29 : if (cform->contypid == typeOid)
7241 : : {
7242 : : /*
7243 : : * This is a CHECK constraint on the domain. Look closer if
7244 : : * the expression actually refers to the target type.
7245 : : */
7246 : 17 : LockDatabaseObject(ConstraintRelationId, objid, 0, AccessShareLock);
7247 : 17 : expr = get_node_tree_attr(CONSTROID, catalog_tup,
7248 : : Anum_pg_constraint_conbin);
7249 [ + - - + ]: 17 : if (expr && CheckTypeDependencyInExpr(expr, NIL, typeOid))
7250 : 0 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7251 : : }
7252 : : else
7253 : : {
7254 : : /* This is some other constraint using the type */
7255 : 12 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7256 : : }
7257 : 17 : ReleaseSysCache(catalog_tup);
7258 : 17 : break;
7259 : :
7260 : 2291 : case TypeRelationId:
7261 : :
7262 : : /*
7263 : : * An array, domain, or range containing the given type doesn't
7264 : : * prevent altering it. But recursively check for uses of this
7265 : : * type. Note that any error message will mention the original
7266 : : * type not the container; this is intentional.
7267 : : */
7268 : 2291 : find_composite_type_dependencies_recurse(objid,
7269 : : origRelation, origTypeName,
7270 : : visited);
7271 : :
7272 : : /*
7273 : : * A domain's default expression can embed a Const of the altered
7274 : : * type, however. We must reject that.
7275 : : *
7276 : : * find_composite_type_dependencies_recurse() acquired a lock on
7277 : : * the type, so we don't need to acquire it here again to inspect
7278 : : * the default.
7279 : : */
7280 : 2263 : catalog_tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(objid));
7281 [ - + ]: 2263 : if (!HeapTupleIsValid(catalog_tup))
7282 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", objid);
7283 : :
7284 : 2263 : expr = get_node_tree_attr(TYPEOID, catalog_tup, Anum_pg_type_typdefaultbin);
7285 [ + + + - ]: 2263 : if (expr && CheckTypeDependencyInExpr(expr, NIL, typeOid))
7286 : 12 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7287 : :
7288 : 2251 : ReleaseSysCache(catalog_tup);
7289 : 2251 : break;
7290 : :
7291 : 552 : case RelationRelationId:
7292 : 552 : rel = relation_open(objid, AccessShareLock);
7293 : 552 : tupleDesc = RelationGetDescr(rel);
7294 : :
7295 : : /*
7296 : : * First check for a dependency from a specific column. (We
7297 : : * assume system columns are never of interesting types.)
7298 : : */
7299 [ + + + - ]: 552 : if (objsubid > 0 && objsubid <= tupleDesc->natts)
7300 : 150 : att = TupleDescAttr(tupleDesc, objsubid - 1);
7301 : : else
7302 : : {
7303 : : /*
7304 : : * We treat a whole-row dependency the same as a dependency
7305 : : * from a specific column, if the relation also has a column
7306 : : * of the given type. This is because we used to have a gap
7307 : : * in dependency tracking: expression indexes didn't store a
7308 : : * dependency on the indexed type returned by the expression.
7309 : : * That was a bug, but in many typical cases, the expression
7310 : : * still had a dependency on the row type, so we can often
7311 : : * still catch it here. Treat it as if the dependency was on
7312 : : * the column. (It could also be that the target type is
7313 : : * embedded in some container type that is stored in an index
7314 : : * column, but the previous recursion should catch such
7315 : : * cases.)
7316 : : *
7317 : : * Any cases of missing dependencies not caught here are
7318 : : * handled by find_missing_composite_type_dependencies().
7319 : : */
7320 : 402 : att = NULL;
7321 [ + + ]: 1053 : for (int attno = 1; attno <= tupleDesc->natts; attno++)
7322 : : {
7323 : 663 : att = TupleDescAttr(tupleDesc, attno - 1);
7324 [ + + + - ]: 663 : if (att->atttypid == typeOid && !att->attisdropped)
7325 : 12 : break;
7326 : 651 : att = NULL;
7327 : : }
7328 : : }
7329 [ + + ]: 552 : if (att)
7330 : : {
7331 : : /*
7332 : : * A column uses the datatype.
7333 : : *
7334 : : * We definitely should reject if the relation has storage.
7335 : : *
7336 : : * If it's partitioned, then perhaps we wouldn't have to
7337 : : * reject: if there are partitions then we'll fail when we
7338 : : * find one, else there is no stored data to worry about.
7339 : : * However, it's possible that the type change would affect
7340 : : * conclusions about whether the type is sortable or hashable
7341 : : * and thus (if it's a partitioning column) break the
7342 : : * partitioning rule. For now, reject for partitioned rels
7343 : : * too.
7344 : : *
7345 : : * Foreign tables don't have storage as such, but they can
7346 : : * have statistics stored in the pg_statistic table. (It
7347 : : * might be better to remove the statistics than fail the
7348 : : * operation, but with the current code structure, it'd be
7349 : : * inconvenient to memorize the need for removing the
7350 : : * statistics. Note that if we allowed partitioned tables
7351 : : * here, they could also have statistics.)
7352 : : */
7353 [ + + + + : 162 : if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
+ - + - +
- ]
7354 [ + - + - ]: 52 : RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind) ||
7355 [ - + ]: 52 : rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7356 : : {
7357 : 110 : report_type_used_in_column(RelationGetRelationName(rel),
7358 : 110 : NameStr(att->attname),
7359 : : origRelation, origTypeName);
7360 : : }
7361 : :
7362 [ + - + - ]: 52 : if (OidIsValid(rel->rd_rel->reltype) && rel->rd_rel->reltype != typeOid)
7363 : : {
7364 : : /*
7365 : : * A view or composite type itself isn't a problem, but we
7366 : : * must recursively check for indirect dependencies via
7367 : : * its rowtype.
7368 : : */
7369 : 52 : find_composite_type_dependencies_recurse(rel->rd_rel->reltype,
7370 : : origRelation, origTypeName,
7371 : : visited);
7372 : : }
7373 : : }
7374 : :
7375 : : /*
7376 : : * If it's a dependency on the type as whole, look closer what
7377 : : * exactly in the relation uses it. Some uses don't prevent
7378 : : * ALTERing the rowtype, but others do.
7379 : : *
7380 : : * NOTE: We must not use the expressions cached in the relcache,
7381 : : * because they go through eval_const_expressions(), which could
7382 : : * fold away the thing that caused the dependency.
7383 : : */
7384 [ + + ]: 430 : if (objsubid == 0)
7385 : : {
7386 : : /*
7387 : : * If the type is used in a PARTITION BY expression, must be
7388 : : * rejected.
7389 : : */
7390 [ + + ]: 390 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7391 : : {
7392 : : List *partexprs;
7393 : : ListCell *lc;
7394 : :
7395 : 20 : catalog_tup = SearchSysCache1(PARTRELID,
7396 : : ObjectIdGetDatum(RelationGetRelid(rel)));
7397 [ - + ]: 20 : if (!HeapTupleIsValid(catalog_tup))
7398 [ # # ]: 0 : elog(ERROR, "cache lookup failed for partition key of relation %u",
7399 : : RelationGetRelid(rel));
7400 : : partexprs = (List *)
7401 : 20 : get_node_tree_attr(PARTRELID, catalog_tup,
7402 : : Anum_pg_partitioned_table_partexprs);
7403 [ + - + - : 20 : foreach(lc, partexprs)
+ - ]
7404 : : {
7405 : 20 : Node *partexpr = lfirst(lc);
7406 : :
7407 : : /*
7408 : : * Check if it's the PARTITION BY's return type.
7409 : : *
7410 : : * (This could be allowed as long as the table has no
7411 : : * partitions. The problem really only arises from
7412 : : * the partition bounds stored in the 'relpartbound'
7413 : : * of the partitions. But it's not worth
7414 : : * distinguishing that case.)
7415 : : *
7416 : : * We had a gap in our dependency tracking in the
7417 : : * past, and didn't record a pg_depend entry for
7418 : : * these. Any missing dependencies not caught here
7419 : : * are handled by
7420 : : * find_missing_composite_type_dependencies().
7421 : : */
7422 [ + + ]: 20 : if (exprType(partexpr) == typeOid)
7423 : 12 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7424 : :
7425 : : /*
7426 : : * Check if the expression uses the rowtype. We must
7427 : : * reject that case because otherwise we'd need to
7428 : : * rewrite the expression stored in the catalog, as
7429 : : * well as the partition bounds of all the partitions,
7430 : : * and also because the data might no longer be in the
7431 : : * correct partitions according to the new datatype's
7432 : : * sort order.
7433 : : */
7434 [ + - ]: 8 : if (CheckTypeDependencyInSingleRelExpr(partexpr, RelationGetRelid(rel), typeOid))
7435 : 8 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7436 : : }
7437 : 0 : ReleaseSysCache(catalog_tup);
7438 : : }
7439 : :
7440 : : /*
7441 : : * If it's an expression or partial index, must reject if the
7442 : : * expressions use the rowtype (it might include Consts).
7443 : : *
7444 : : * If an index uses the target type as a column, we will
7445 : : * rebuild it, but RememberAllDependentForRebuilding() doesn't
7446 : : * handle whole-row dependencies.
7447 : : */
7448 [ + + ]: 370 : if (rel->rd_indextuple)
7449 : : {
7450 : 8 : expr = get_node_tree_attr(INDEXRELID, rel->rd_indextuple,
7451 : : Anum_pg_index_indexprs);
7452 [ + - ]: 8 : if (expr)
7453 : : {
7454 [ + - ]: 8 : if (CheckTypeDependencyInSingleRelExpr(expr, RelationGetRelid(rel), typeOid))
7455 : 8 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7456 : :
7457 : : /*
7458 : : * If it's the *return type* of an index expression,
7459 : : * it becomes a column type and we checked that above
7460 : : * already.
7461 : : */
7462 : : }
7463 : 0 : expr = get_node_tree_attr(INDEXRELID, rel->rd_indextuple,
7464 : : Anum_pg_index_indpred);
7465 [ # # ]: 0 : if (expr)
7466 : : {
7467 [ # # ]: 0 : if (CheckTypeDependencyInSingleRelExpr(expr, RelationGetRelid(rel), typeOid))
7468 : 0 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7469 : : }
7470 : : }
7471 : :
7472 : : /*
7473 : : * We have now checked for all the known reasons that a
7474 : : * relation might depend on a type that prevents ALTERing it.
7475 : : * There are two reasons left that don't prevent ALTER: the
7476 : : * type is the table's reltype, or its TYPE OF type. (The
7477 : : * TYPE OF case might still prevent the operation, but that's
7478 : : * handled separately by find_typed_table_dependencies())
7479 : : */
7480 [ + + - + ]: 362 : if (rel->rd_rel->reltype == typeOid || rel->rd_rel->reloftype == typeOid)
7481 : : {
7482 : : /* ok */
7483 : : }
7484 : : else
7485 : : {
7486 : : /*
7487 : : * We've covered all reasons for this dependency to exist,
7488 : : * so why are we here? Better play safe and reject it.
7489 : : */
7490 : : Assert(false);
7491 : 0 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7492 : : }
7493 : : }
7494 : :
7495 : 402 : relation_close(rel, AccessShareLock);
7496 : 402 : break;
7497 : :
7498 : 0 : case PublicationRelRelationId:
7499 : :
7500 : : /*
7501 : : * pg_publication_rel.prqual contains an expression. It should
7502 : : * not contain user-defined types, but CREATE PUBLICATION's
7503 : : * definition of a user-defined type is different from a pinned
7504 : : * object, so we might see these.
7505 : : */
7506 : 0 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7507 : 0 : break;
7508 : :
7509 : 53 : case RewriteRelationId:
7510 : : case AttrDefaultRelationId:
7511 : : case TriggerRelationId:
7512 : : case PolicyRelationId:
7513 : : case StatisticExtRelationId:
7514 : : default:
7515 : : /* Forbid anything else */
7516 : 53 : report_type_used_in_expr(depobj, origRelation, origTypeName);
7517 : 0 : break;
7518 : : }
7519 : 3148 : }
7520 : :
7521 : : /*
7522 : : * report_type_used_in_column
7523 : : *
7524 : : * Complain that the ALTER can't proceed because a column uses the type being
7525 : : * altered.
7526 : : */
7527 : : static void
7528 : 110 : report_type_used_in_column(const char *relname, const char *attname,
7529 : : Relation origRelation, const char *origTypeName)
7530 : : {
7531 [ + + ]: 110 : if (origTypeName)
7532 [ + - ]: 20 : ereport(ERROR,
7533 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7534 : : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7535 : : origTypeName,
7536 : : relname, attname)));
7537 [ + + ]: 90 : else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7538 [ + - ]: 21 : ereport(ERROR,
7539 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7540 : : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7541 : : RelationGetRelationName(origRelation),
7542 : : relname, attname)));
7543 [ + + ]: 69 : else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7544 [ + - ]: 4 : ereport(ERROR,
7545 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7546 : : errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7547 : : RelationGetRelationName(origRelation),
7548 : : relname, attname)));
7549 : : else
7550 [ + - ]: 65 : ereport(ERROR,
7551 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7552 : : errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7553 : : RelationGetRelationName(origRelation),
7554 : : relname, attname)));
7555 : : }
7556 : :
7557 : : /*
7558 : : * report_type_used_in_expr
7559 : : *
7560 : : * Complain that the ALTER can't proceed because a stored expression holds a
7561 : : * value of the type being altered.
7562 : : */
7563 : : static void
7564 : 114 : report_type_used_in_expr(const ObjectAddress *obj, Relation origRelation,
7565 : : const char *origTypeName)
7566 : : {
7567 : 114 : char *objdesc = getObjectDescription(obj, false);
7568 : :
7569 [ - + ]: 114 : if (origTypeName)
7570 [ # # ]: 0 : ereport(ERROR,
7571 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7572 : : errmsg("cannot alter type \"%s\" because %s uses it",
7573 : : origTypeName, objdesc)));
7574 : :
7575 [ + + ]: 114 : if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7576 [ + - ]: 38 : ereport(ERROR,
7577 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7578 : : errmsg("cannot alter type \"%s\" because %s uses it",
7579 : : RelationGetRelationName(origRelation), objdesc)));
7580 : :
7581 [ - + ]: 76 : if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7582 [ # # ]: 0 : ereport(ERROR,
7583 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7584 : : errmsg("cannot alter foreign table \"%s\" because %s uses its row type",
7585 : : RelationGetRelationName(origRelation), objdesc)));
7586 : :
7587 [ + - ]: 76 : ereport(ERROR,
7588 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7589 : : errmsg("cannot alter table \"%s\" because %s uses its row type",
7590 : : RelationGetRelationName(origRelation), objdesc)));
7591 : : }
7592 : :
7593 : : /* Read a pg_node_tree column's value as a Node */
7594 : : static Node *
7595 : 1133488 : get_node_tree_attr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attnum)
7596 : : {
7597 : : Datum val;
7598 : : bool isnull;
7599 : :
7600 : 1133488 : val = SysCacheGetAttr(cacheId, tup, attnum, &isnull);
7601 [ + + ]: 1133488 : if (isnull)
7602 : 1105129 : return NULL;
7603 : :
7604 : 28359 : return stringToNode(TextDatumGetCString(val));
7605 : : }
7606 : :
7607 : : /*
7608 : : * find_missing_composite_type_dependencies
7609 : : *
7610 : : * In the past, we failed to record pg_depend entries for a few cases that
7611 : : * clearly form a dependency and should prevent you from ALTERing a rowtype.
7612 : : * This function scans the catalogs for the missing dependencies.
7613 : : * Unfortunately, these need to resort to sequential scans, which is slow.
7614 : : */
7615 : : static void
7616 : 1963 : find_missing_composite_type_dependencies(HTAB *types, Relation origRelation,
7617 : : const char *origTypeName)
7618 : : {
7619 : : Relation catalog_rel;
7620 : : SysScanDesc scan;
7621 : : HeapTuple tup;
7622 : :
7623 : : /*
7624 : : * A partition bound is stored as a Const of the PARTITION BY expression's
7625 : : * result type. However, we used to not record a pg_depend entry for
7626 : : * that. Often an expression depends on its result type for other
7627 : : * reasons, for example a Const does record a dependency on its type, but
7628 : : * as a counter-example, a function call records a dependency only on the
7629 : : * function, not on its return type.
7630 : : *
7631 : : * To find such missing dependencies, scan pg_partitioned_table directly
7632 : : * for a key expression that produces typeOid.
7633 : : *
7634 : : * The expression might return the target type directly, or wrapped in a
7635 : : * container such as an array or a range. We only check for the direct
7636 : : * case here, containers are handled by the recursion from
7637 : : * find_composite_type_dependencies()
7638 : : */
7639 : 1963 : catalog_rel = table_open(PartitionedRelationId, AccessShareLock);
7640 : 1963 : scan = systable_beginscan(catalog_rel, InvalidOid, false, NULL, 0, NULL);
7641 [ + + ]: 76510 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
7642 : : {
7643 : : List *exprs;
7644 : :
7645 : : /* Is the *result* of the PARTITION BY expression a problem? */
7646 : 74547 : exprs = (List *) get_node_tree_attr(PARTRELID, tup,
7647 : : Anum_pg_partitioned_table_partexprs);
7648 [ + + + + : 153361 : foreach_ptr(Node, expr, exprs)
+ + ]
7649 : : {
7650 : 4267 : Oid resultType = exprType(expr);
7651 : :
7652 [ - + ]: 4267 : if (hash_search(types, &resultType, HASH_FIND, NULL))
7653 : : {
7654 : : Form_pg_partitioned_table form =
7655 : 0 : (Form_pg_partitioned_table) GETSTRUCT(tup);
7656 : : ObjectAddress obj;
7657 : :
7658 : 0 : ObjectAddressSet(obj, RelationRelationId, form->partrelid);
7659 : 0 : report_type_used_in_expr(&obj, origRelation, origTypeName);
7660 : : }
7661 : : }
7662 : : }
7663 : 1963 : systable_endscan(scan);
7664 : 1963 : table_close(catalog_rel, AccessShareLock);
7665 : :
7666 : : /*
7667 : : * Similarly, an expression index whose expression returns the target type
7668 : : * stores datums of that type in the index, but we used to not record a
7669 : : * pg_depend entry for that. Scan pg_index for those.
7670 : : *
7671 : : * The predicate of a partial index always returns a boolean, so we don't
7672 : : * need to worry about that here.
7673 : : */
7674 : 1963 : catalog_rel = table_open(IndexRelationId, AccessShareLock);
7675 : 1963 : scan = systable_beginscan(catalog_rel, InvalidOid, false, NULL, 0, NULL);
7676 [ + + ]: 1051756 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
7677 : : {
7678 : : List *exprs;
7679 : :
7680 : 1049793 : exprs = (List *) get_node_tree_attr(INDEXRELID, tup, Anum_pg_index_indexprs);
7681 [ + + + + : 2121948 : foreach_ptr(Node, expr, exprs)
+ + ]
7682 : : {
7683 : 22362 : Oid resultType = exprType(expr);
7684 : :
7685 [ - + ]: 22362 : if (hash_search(types, &resultType, HASH_FIND, NULL))
7686 : : {
7687 : 0 : Form_pg_index index = (Form_pg_index) GETSTRUCT(tup);
7688 : : ObjectAddress obj;
7689 : :
7690 : 0 : ObjectAddressSet(obj, RelationRelationId, index->indexrelid);
7691 : 0 : report_type_used_in_expr(&obj, origRelation, origTypeName);
7692 : : }
7693 : : }
7694 : : }
7695 : 1963 : systable_endscan(scan);
7696 : 1963 : table_close(catalog_rel, AccessShareLock);
7697 : :
7698 : : /*
7699 : : * Similarly, extended statistics on an expression that returns the target
7700 : : * type stores a datum of the type into pg_statistic_ext_data at ANALYZE
7701 : : * time, and we used to not record a pg_depend entry for that either. Scan
7702 : : * pg_statistic_ext for those.
7703 : : */
7704 : 1963 : catalog_rel = table_open(StatisticExtRelationId, AccessShareLock);
7705 : 1963 : scan = systable_beginscan(catalog_rel, InvalidOid, false, NULL, 0, NULL);
7706 [ + + ]: 7946 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
7707 : : {
7708 : : List *exprs;
7709 : :
7710 : 5983 : exprs = (List *) get_node_tree_attr(STATEXTOID, tup,
7711 : : Anum_pg_statistic_ext_stxexprs);
7712 [ + + + + : 16521 : foreach_ptr(Node, expr, exprs)
+ + ]
7713 : : {
7714 : 4555 : Oid resultType = exprType(expr);
7715 : :
7716 [ - + ]: 4555 : if (hash_search(types, &resultType, HASH_FIND, NULL))
7717 : : {
7718 : 0 : Form_pg_statistic_ext form = (Form_pg_statistic_ext) GETSTRUCT(tup);
7719 : : ObjectAddress obj;
7720 : :
7721 : 0 : ObjectAddressSet(obj, StatisticExtRelationId, form->oid);
7722 : 0 : report_type_used_in_expr(&obj, origRelation, origTypeName);
7723 : : }
7724 : : }
7725 : : }
7726 : 1963 : systable_endscan(scan);
7727 : 1963 : table_close(catalog_rel, AccessShareLock);
7728 : 1963 : }
7729 : :
7730 : : /*
7731 : : * find_typed_table_dependencies
7732 : : *
7733 : : * Check to see if a composite type is being used as the type of a
7734 : : * typed table. Abort if any are found and behavior is RESTRICT.
7735 : : * Else return the list of tables.
7736 : : */
7737 : : static List *
7738 : 462 : find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
7739 : : {
7740 : : Relation classRel;
7741 : : ScanKeyData key[1];
7742 : : TableScanDesc scan;
7743 : : HeapTuple tuple;
7744 : 462 : List *result = NIL;
7745 : :
7746 : 462 : classRel = table_open(RelationRelationId, AccessShareLock);
7747 : :
7748 : 462 : ScanKeyInit(&key[0],
7749 : : Anum_pg_class_reloftype,
7750 : : BTEqualStrategyNumber, F_OIDEQ,
7751 : : ObjectIdGetDatum(typeOid));
7752 : :
7753 : 462 : scan = table_beginscan_catalog(classRel, 1, key);
7754 : :
7755 [ + + ]: 487 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7756 : : {
7757 : 41 : Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
7758 : :
7759 [ + + ]: 41 : if (behavior == DROP_RESTRICT)
7760 [ + - ]: 16 : ereport(ERROR,
7761 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
7762 : : errmsg("cannot alter type \"%s\" because it is the type of a typed table",
7763 : : typeName),
7764 : : errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
7765 : : else
7766 : 25 : result = lappend_oid(result, classform->oid);
7767 : : }
7768 : :
7769 : 446 : table_endscan(scan);
7770 : 446 : table_close(classRel, AccessShareLock);
7771 : :
7772 : 446 : return result;
7773 : : }
7774 : :
7775 : :
7776 : : /*
7777 : : * check_of_type
7778 : : *
7779 : : * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
7780 : : * isn't suitable, throw an error. Currently, we require that the type
7781 : : * originated with CREATE TYPE AS. We could support any row type, but doing so
7782 : : * would require handling a number of extra corner cases in the DDL commands.
7783 : : * (Also, allowing domain-over-composite would open up a can of worms about
7784 : : * whether and how the domain's constraints should apply to derived tables.)
7785 : : */
7786 : : void
7787 : 129 : check_of_type(HeapTuple typetuple)
7788 : : {
7789 : 129 : Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7790 : 129 : bool typeOk = false;
7791 : :
7792 [ + + ]: 129 : if (typ->typtype == TYPTYPE_COMPOSITE)
7793 : : {
7794 : : Relation typeRelation;
7795 : :
7796 : : Assert(OidIsValid(typ->typrelid));
7797 : 125 : typeRelation = relation_open(typ->typrelid, AccessShareLock);
7798 : 125 : typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7799 : :
7800 : : /*
7801 : : * Close the parent rel, but keep our AccessShareLock on it until xact
7802 : : * commit. That will prevent someone else from deleting or ALTERing
7803 : : * the type before the typed table creation/conversion commits.
7804 : : */
7805 : 125 : relation_close(typeRelation, NoLock);
7806 : :
7807 [ + + ]: 125 : if (!typeOk)
7808 [ + - ]: 4 : ereport(ERROR,
7809 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7810 : : errmsg("type %s is the row type of another table",
7811 : : format_type_be(typ->oid)),
7812 : : errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7813 : : }
7814 : : else
7815 [ + - ]: 4 : ereport(ERROR,
7816 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7817 : : errmsg("type %s is not a composite type",
7818 : : format_type_be(typ->oid))));
7819 : 121 : }
7820 : :
7821 : :
7822 : : /*
7823 : : * ALTER TABLE ADD COLUMN
7824 : : *
7825 : : * Adds an additional attribute to a relation making the assumption that
7826 : : * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
7827 : : * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
7828 : : * AlterTableCmd's.
7829 : : *
7830 : : * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
7831 : : * have to decide at runtime whether to recurse or not depending on whether we
7832 : : * actually add a column or merely merge with an existing column. (We can't
7833 : : * check this in a static pre-pass because it won't handle multiple inheritance
7834 : : * situations correctly.)
7835 : : */
7836 : : static void
7837 : 3717 : ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
7838 : : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
7839 : : AlterTableUtilityContext *context)
7840 : : {
7841 [ + + + + ]: 3717 : if (rel->rd_rel->reloftype && !recursing)
7842 [ + - ]: 4 : ereport(ERROR,
7843 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7844 : : errmsg("cannot add column to typed table")));
7845 : :
7846 [ + + ]: 3713 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7847 : 148 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
7848 : :
7849 [ + + + + ]: 3709 : if (recurse && !is_view)
7850 : 3523 : cmd->recurse = true;
7851 : 3709 : }
7852 : :
7853 : : /*
7854 : : * Add a column to a table. The return value is the address of the
7855 : : * new column in the parent relation.
7856 : : *
7857 : : * cmd is pass-by-ref so that we can replace it with the parse-transformed
7858 : : * copy (but that happens only after we check for IF NOT EXISTS).
7859 : : */
7860 : : static ObjectAddress
7861 : 4228 : ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
7862 : : AlterTableCmd **cmd, bool recurse, bool recursing,
7863 : : LOCKMODE lockmode, AlterTablePass cur_pass,
7864 : : AlterTableUtilityContext *context)
7865 : : {
7866 : 4228 : Oid myrelid = RelationGetRelid(rel);
7867 : 4228 : ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
7868 : 4228 : bool if_not_exists = (*cmd)->missing_ok;
7869 : : Relation pgclass,
7870 : : attrdesc;
7871 : : HeapTuple reltup;
7872 : : Form_pg_class relform;
7873 : : Form_pg_attribute attribute;
7874 : : int newattnum;
7875 : : char relkind;
7876 : : Expr *defval;
7877 : : List *children;
7878 : : ListCell *child;
7879 : : AlterTableCmd *childcmd;
7880 : : ObjectAddress address;
7881 : : TupleDesc tupdesc;
7882 : :
7883 : : /* since this function recurses, it could be driven to stack overflow */
7884 : 4228 : check_stack_depth();
7885 : :
7886 : : /* At top level, permission check was done in ATPrepCmd, else do it */
7887 [ + + ]: 4228 : if (recursing)
7888 : 523 : ATSimplePermissions((*cmd)->subtype, rel,
7889 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
7890 : :
7891 [ + + + + ]: 4228 : if (rel->rd_rel->relispartition && !recursing)
7892 [ + - ]: 8 : ereport(ERROR,
7893 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7894 : : errmsg("cannot add column to a partition")));
7895 : :
7896 : 4220 : attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
7897 : :
7898 : : /*
7899 : : * Are we adding the column to a recursion child? If so, check whether to
7900 : : * merge with an existing definition for the column. If we do merge, we
7901 : : * must not recurse. Children will already have the column, and recursing
7902 : : * into them would mess up attinhcount.
7903 : : */
7904 [ + + ]: 4220 : if (colDef->inhcount > 0)
7905 : : {
7906 : : HeapTuple tuple;
7907 : :
7908 : : /* Does child already have a column by this name? */
7909 : 523 : tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
7910 [ + + ]: 523 : if (HeapTupleIsValid(tuple))
7911 : : {
7912 : 40 : Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7913 : : Oid ctypeId;
7914 : : int32 ctypmod;
7915 : : Oid ccollid;
7916 : :
7917 : : /* Child column must match on type, typmod, and collation */
7918 : 40 : typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
7919 [ + - ]: 40 : if (ctypeId != childatt->atttypid ||
7920 [ - + ]: 40 : ctypmod != childatt->atttypmod)
7921 [ # # ]: 0 : ereport(ERROR,
7922 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
7923 : : errmsg("child table \"%s\" has different type for column \"%s\"",
7924 : : RelationGetRelationName(rel), colDef->colname)));
7925 : 40 : ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
7926 [ - + ]: 40 : if (ccollid != childatt->attcollation)
7927 [ # # ]: 0 : ereport(ERROR,
7928 : : (errcode(ERRCODE_COLLATION_MISMATCH),
7929 : : errmsg("child table \"%s\" has different collation for column \"%s\"",
7930 : : RelationGetRelationName(rel), colDef->colname),
7931 : : errdetail("\"%s\" versus \"%s\"",
7932 : : get_collation_name(ccollid),
7933 : : get_collation_name(childatt->attcollation))));
7934 : :
7935 : : /* Bump the existing child att's inhcount */
7936 [ - + ]: 40 : if (pg_add_s16_overflow(childatt->attinhcount, 1,
7937 : : &childatt->attinhcount))
7938 [ # # ]: 0 : ereport(ERROR,
7939 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7940 : : errmsg("too many inheritance parents"));
7941 : 40 : CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
7942 : :
7943 : 40 : heap_freetuple(tuple);
7944 : :
7945 : : /* Inform the user about the merge */
7946 [ + - ]: 40 : ereport(NOTICE,
7947 : : (errmsg("merging definition of column \"%s\" for child \"%s\"",
7948 : : colDef->colname, RelationGetRelationName(rel))));
7949 : :
7950 : 40 : table_close(attrdesc, RowExclusiveLock);
7951 : :
7952 : : /* Make the child column change visible */
7953 : 40 : CommandCounterIncrement();
7954 : :
7955 : 40 : return InvalidObjectAddress;
7956 : : }
7957 : : }
7958 : :
7959 : : /* skip if the name already exists and if_not_exists is true */
7960 [ + + ]: 4180 : if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
7961 : : {
7962 : 44 : table_close(attrdesc, RowExclusiveLock);
7963 : 44 : return InvalidObjectAddress;
7964 : : }
7965 : :
7966 : : /*
7967 : : * Okay, we need to add the column, so go ahead and do parse
7968 : : * transformation. This can result in queueing up, or even immediately
7969 : : * executing, subsidiary operations (such as creation of unique indexes);
7970 : : * so we mustn't do it until we have made the if_not_exists check.
7971 : : *
7972 : : * When recursing, the command was already transformed and we needn't do
7973 : : * so again. Also, if context isn't given we can't transform. (That
7974 : : * currently happens only for AT_AddColumnToView; we expect that view.c
7975 : : * passed us a ColumnDef that doesn't need work.)
7976 : : */
7977 [ + + + + ]: 4116 : if (context != NULL && !recursing)
7978 : : {
7979 : 3607 : *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
7980 : : cur_pass, context);
7981 : : Assert(*cmd != NULL);
7982 : 3603 : colDef = castNode(ColumnDef, (*cmd)->def);
7983 : : }
7984 : :
7985 : : /*
7986 : : * Regular inheritance children are independent enough not to inherit the
7987 : : * identity column from parent hence cannot recursively add identity
7988 : : * column if the table has inheritance children.
7989 : : *
7990 : : * Partitions, on the other hand, are integral part of a partitioned table
7991 : : * and inherit identity column. Hence propagate identity column down the
7992 : : * partition hierarchy.
7993 : : */
7994 [ + + + - ]: 4112 : if (colDef->identity &&
7995 : 36 : recurse &&
7996 [ + + + + ]: 68 : rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
7997 : 32 : find_inheritance_children(myrelid, NoLock) != NIL)
7998 [ + - ]: 4 : ereport(ERROR,
7999 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8000 : : errmsg("cannot recursively add identity column to table that has child tables")));
8001 : :
8002 : 4108 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
8003 : :
8004 : 4108 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
8005 [ - + ]: 4108 : if (!HeapTupleIsValid(reltup))
8006 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
8007 : 4108 : relform = (Form_pg_class) GETSTRUCT(reltup);
8008 : 4108 : relkind = relform->relkind;
8009 : :
8010 : : /* Determine the new attribute's number */
8011 : 4108 : newattnum = relform->relnatts + 1;
8012 [ - + ]: 4108 : if (newattnum > MaxHeapAttributeNumber)
8013 [ # # ]: 0 : ereport(ERROR,
8014 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
8015 : : errmsg("tables can have at most %d columns",
8016 : : MaxHeapAttributeNumber)));
8017 : :
8018 : : /*
8019 : : * Construct new attribute's pg_attribute entry.
8020 : : */
8021 : 4108 : tupdesc = BuildDescForRelation(list_make1(colDef));
8022 : :
8023 : 4100 : attribute = TupleDescAttr(tupdesc, 0);
8024 : :
8025 : : /* Fix up attribute number */
8026 : 4100 : attribute->attnum = newattnum;
8027 : :
8028 : : /* make sure datatype is legal for a column */
8029 : 8200 : CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
8030 : 4100 : list_make1_oid(rel->rd_rel->reltype),
8031 [ + + ]: 4100 : (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
8032 : :
8033 : : /*
8034 : : * Set up information to set the new attribute's version, if needed (the
8035 : : * relation has a versioned rowtype).
8036 : : */
8037 : : Assert(HasVersionedAttributes(rel) || allowSystemTableMods);
8038 [ + - ]: 4072 : if (HasVersionedAttributes(rel))
8039 : : {
8040 : 4072 : XLogRecPtr attversion = GetNextAttributeVersion();
8041 : :
8042 : : /*
8043 : : * We rely on the version to be monotonic, so make sure that's true,
8044 : : * like SetAttributeVersionInTuple() does.
8045 : : */
8046 [ - + ]: 4072 : if (attversion <= TupleDescGetVersion(rel->rd_att))
8047 [ # # ]: 0 : elog(ERROR, "version of attribute is not increasing");
8048 : :
8049 : 4072 : attribute->attversion = attversion;
8050 : : }
8051 : :
8052 : 4072 : InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
8053 : :
8054 : 4072 : table_close(attrdesc, RowExclusiveLock);
8055 : :
8056 : : /*
8057 : : * Update pg_class tuple as appropriate
8058 : : */
8059 : 4072 : relform->relnatts = newattnum;
8060 : :
8061 : 4072 : CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
8062 : :
8063 : 4072 : heap_freetuple(reltup);
8064 : :
8065 : : /* Post creation hook for new attribute */
8066 [ - + ]: 4072 : InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
8067 : :
8068 : 4072 : table_close(pgclass, RowExclusiveLock);
8069 : :
8070 : : /* Make the attribute's catalog entry visible */
8071 : 4072 : CommandCounterIncrement();
8072 : :
8073 : : /*
8074 : : * Store the DEFAULT, if any, in the catalogs
8075 : : */
8076 [ + + ]: 4072 : if (colDef->raw_default)
8077 : : {
8078 : : RawColumnDefault *rawEnt;
8079 : :
8080 : 703 : rawEnt = palloc_object(RawColumnDefault);
8081 : 703 : rawEnt->attnum = attribute->attnum;
8082 : 703 : rawEnt->raw_default = copyObject(colDef->raw_default);
8083 : 703 : rawEnt->generated = colDef->generated;
8084 : :
8085 : : /*
8086 : : * This function is intended for CREATE TABLE, so it processes a
8087 : : * _list_ of defaults, but we just do one.
8088 : : */
8089 : 703 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8090 : : false, true, false, NULL);
8091 : :
8092 : : /* Make the additional catalog changes visible */
8093 : 687 : CommandCounterIncrement();
8094 : : }
8095 : :
8096 : : /*
8097 : : * Tell Phase 3 to fill in the default expression, if there is one.
8098 : : *
8099 : : * If there is no default, Phase 3 doesn't have to do anything, because
8100 : : * that effectively means that the default is NULL. The heap tuple access
8101 : : * routines always check for attnum > # of attributes in tuple, and return
8102 : : * NULL if so, so without any modification of the tuple data we will get
8103 : : * the effect of NULL values in the new column.
8104 : : *
8105 : : * An exception occurs when the new column is of a domain type: the domain
8106 : : * might have a not-null constraint, or a check constraint that indirectly
8107 : : * rejects nulls. If there are any domain constraints then we construct
8108 : : * an explicit NULL default value that will be passed through
8109 : : * CoerceToDomain processing. (This is a tad inefficient, since it causes
8110 : : * rewriting the table which we really wouldn't have to do; but we do it
8111 : : * to preserve the historical behavior that such a failure will be raised
8112 : : * only if the table currently contains some rows.)
8113 : : *
8114 : : * Note: we use build_column_default, and not just the cooked default
8115 : : * returned by AddRelationNewConstraints, so that the right thing happens
8116 : : * when a datatype's default applies.
8117 : : *
8118 : : * Note: it might seem that this should happen at the end of Phase 2, so
8119 : : * that the effects of subsequent subcommands can be taken into account.
8120 : : * It's intentional that we do it now, though. The new column should be
8121 : : * filled according to what is said in the ADD COLUMN subcommand, so that
8122 : : * the effects are the same as if this subcommand had been run by itself
8123 : : * and the later subcommands had been issued in new ALTER TABLE commands.
8124 : : *
8125 : : * We can skip this entirely for relations without storage, since Phase 3
8126 : : * is certainly not going to touch them.
8127 : : */
8128 [ + + + - : 4056 : if (RELKIND_HAS_STORAGE(relkind))
+ - + - -
+ ]
8129 : : {
8130 : : bool has_domain_constraints;
8131 : 3671 : bool has_missing = false;
8132 : :
8133 : : /*
8134 : : * For an identity column, we can't use build_column_default(),
8135 : : * because the sequence ownership isn't set yet. So do it manually.
8136 : : */
8137 [ + + ]: 3671 : if (colDef->identity)
8138 : : {
8139 : 28 : NextValueExpr *nve = makeNode(NextValueExpr);
8140 : :
8141 : 28 : nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
8142 : 28 : nve->typeId = attribute->atttypid;
8143 : :
8144 : 28 : defval = (Expr *) nve;
8145 : : }
8146 : : else
8147 : 3643 : defval = (Expr *) build_column_default(rel, attribute->attnum);
8148 : :
8149 : : /* Build CoerceToDomain(NULL) expression if needed */
8150 : 3671 : has_domain_constraints = DomainHasConstraints(attribute->atttypid, NULL);
8151 [ + + + + ]: 3671 : if (!defval && has_domain_constraints)
8152 : : {
8153 : : Oid baseTypeId;
8154 : : int32 baseTypeMod;
8155 : : Oid baseTypeColl;
8156 : :
8157 : 4 : baseTypeMod = attribute->atttypmod;
8158 : 4 : baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
8159 : 4 : baseTypeColl = get_typcollation(baseTypeId);
8160 : 4 : defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
8161 : 4 : defval = (Expr *) coerce_to_target_type(NULL,
8162 : : (Node *) defval,
8163 : : baseTypeId,
8164 : : attribute->atttypid,
8165 : : attribute->atttypmod,
8166 : : COERCION_ASSIGNMENT,
8167 : : COERCE_IMPLICIT_CAST,
8168 : : -1);
8169 [ - + ]: 4 : if (defval == NULL) /* should not happen */
8170 [ # # ]: 0 : elog(ERROR, "failed to coerce base type to domain");
8171 : : }
8172 : :
8173 [ + + ]: 3671 : if (defval)
8174 : : {
8175 : : NewColumnValue *newval;
8176 : :
8177 : : /* Prepare defval for execution, either here or in Phase 3 */
8178 : 624 : defval = expression_planner(defval);
8179 : :
8180 : : /* Add the new default to the newvals list */
8181 : 624 : newval = palloc0_object(NewColumnValue);
8182 : 624 : newval->attnum = attribute->attnum;
8183 : 624 : newval->expr = defval;
8184 : 624 : newval->is_generated = (colDef->generated != '\0');
8185 : :
8186 : 624 : tab->newvals = lappend(tab->newvals, newval);
8187 : :
8188 : : /*
8189 : : * Attempt to skip a complete table rewrite by storing the
8190 : : * specified DEFAULT value outside of the heap. This is only
8191 : : * allowed for plain relations and non-generated columns, and the
8192 : : * default expression can't be volatile (stable is OK). Note that
8193 : : * contain_volatile_functions deems CoerceToDomain immutable, but
8194 : : * here we consider that coercion to a domain with constraints is
8195 : : * volatile; else it might fail even when the table is empty.
8196 : : */
8197 [ + - ]: 624 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
8198 [ + + ]: 624 : !colDef->generated &&
8199 [ + + ]: 495 : !has_domain_constraints &&
8200 [ + + ]: 487 : !contain_volatile_functions((Node *) defval))
8201 : 377 : {
8202 : : EState *estate;
8203 : : ExprState *exprState;
8204 : : Datum missingval;
8205 : : bool missingIsNull;
8206 : :
8207 : : /* Evaluate the default expression */
8208 : 377 : estate = CreateExecutorState();
8209 : 377 : exprState = ExecPrepareExpr(defval, estate);
8210 : 377 : missingval = ExecEvalExpr(exprState,
8211 [ - + ]: 377 : GetPerTupleExprContext(estate),
8212 : : &missingIsNull);
8213 : : /* If it turns out NULL, nothing to do; else store it */
8214 [ + - ]: 377 : if (!missingIsNull)
8215 : : {
8216 : 377 : StoreAttrMissingVal(rel, attribute->attnum, missingval);
8217 : : /* Make the additional catalog change visible */
8218 : 377 : CommandCounterIncrement();
8219 : 377 : has_missing = true;
8220 : : }
8221 : 377 : FreeExecutorState(estate);
8222 : : }
8223 : : else
8224 : : {
8225 : : /*
8226 : : * Failed to use missing mode. We have to do a table rewrite
8227 : : * to install the value --- unless it's a virtual generated
8228 : : * column.
8229 : : */
8230 [ + + ]: 247 : if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
8231 : 178 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
8232 : : }
8233 : : }
8234 : :
8235 [ + + ]: 3671 : if (!has_missing)
8236 : : {
8237 : : /*
8238 : : * If the new column is NOT NULL, and there is no missing value,
8239 : : * tell Phase 3 it needs to check for NULLs.
8240 : : */
8241 : 3294 : tab->verify_new_notnull |= colDef->is_not_null;
8242 : : }
8243 : : }
8244 : :
8245 : : /*
8246 : : * Add needed dependency entries for the new column.
8247 : : */
8248 : 4056 : add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
8249 : 4056 : add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
8250 : :
8251 : : /*
8252 : : * Propagate to children as appropriate. Unlike most other ALTER
8253 : : * routines, we have to do this one level of recursion at a time; we can't
8254 : : * use find_all_inheritors to do it in one pass.
8255 : : */
8256 : : children =
8257 : 4056 : find_inheritance_children(RelationGetRelid(rel), lockmode);
8258 : :
8259 : : /*
8260 : : * If we are told not to recurse, there had better not be any child
8261 : : * tables; else the addition would put them out of step.
8262 : : */
8263 [ + + + + ]: 4056 : if (children && !recurse)
8264 [ + - ]: 8 : ereport(ERROR,
8265 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8266 : : errmsg("column must be added to child tables too")));
8267 : :
8268 : : /* Children should see column as singly inherited */
8269 [ + + ]: 4048 : if (!recursing)
8270 : : {
8271 : 3565 : childcmd = copyObject(*cmd);
8272 : 3565 : colDef = castNode(ColumnDef, childcmd->def);
8273 : 3565 : colDef->inhcount = 1;
8274 : 3565 : colDef->is_local = false;
8275 : : }
8276 : : else
8277 : 483 : childcmd = *cmd; /* no need to copy again */
8278 : :
8279 [ + + + + : 4571 : foreach(child, children)
+ + ]
8280 : : {
8281 : 523 : Oid childrelid = lfirst_oid(child);
8282 : : Relation childrel;
8283 : : AlteredTableInfo *childtab;
8284 : :
8285 : : /* find_inheritance_children already got lock */
8286 : 523 : childrel = table_open(childrelid, NoLock);
8287 : 523 : CheckAlterTableIsSafe(childrel);
8288 : :
8289 : : /* Find or create work queue entry for this table */
8290 : 523 : childtab = ATGetQueueEntry(wqueue, childrel);
8291 : :
8292 : : /* Recurse to child; return value is ignored */
8293 : 523 : ATExecAddColumn(wqueue, childtab, childrel,
8294 : : &childcmd, recurse, true,
8295 : : lockmode, cur_pass, context);
8296 : :
8297 : 523 : table_close(childrel, NoLock);
8298 : : }
8299 : :
8300 : 4048 : ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
8301 : 4048 : return address;
8302 : : }
8303 : :
8304 : : /*
8305 : : * If a new or renamed column will collide with the name of an existing
8306 : : * column and if_not_exists is false then error out, else do nothing.
8307 : : */
8308 : : static bool
8309 : 4484 : check_for_column_name_collision(Relation rel, const char *colname,
8310 : : bool if_not_exists)
8311 : : {
8312 : : HeapTuple attTuple;
8313 : : int attnum;
8314 : :
8315 : : /*
8316 : : * this test is deliberately not attisdropped-aware, since if one tries to
8317 : : * add a column matching a dropped column name, it's gonna fail anyway.
8318 : : */
8319 : 4484 : attTuple = SearchSysCache2(ATTNAME,
8320 : : ObjectIdGetDatum(RelationGetRelid(rel)),
8321 : : PointerGetDatum(colname));
8322 [ + + ]: 4484 : if (!HeapTupleIsValid(attTuple))
8323 : 4412 : return true;
8324 : :
8325 : 72 : attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
8326 : 72 : ReleaseSysCache(attTuple);
8327 : :
8328 : : /*
8329 : : * We throw a different error message for conflicts with system column
8330 : : * names, since they are normally not shown and the user might otherwise
8331 : : * be confused about the reason for the conflict.
8332 : : */
8333 [ + + ]: 72 : if (attnum <= 0)
8334 [ + - ]: 8 : ereport(ERROR,
8335 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
8336 : : errmsg("column name \"%s\" conflicts with a system column name",
8337 : : colname)));
8338 : : else
8339 : : {
8340 [ + + ]: 64 : if (if_not_exists)
8341 : : {
8342 [ + - ]: 44 : ereport(NOTICE,
8343 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
8344 : : errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
8345 : : colname, RelationGetRelationName(rel))));
8346 : 44 : return false;
8347 : : }
8348 : :
8349 [ + - ]: 20 : ereport(ERROR,
8350 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
8351 : : errmsg("column \"%s\" of relation \"%s\" already exists",
8352 : : colname, RelationGetRelationName(rel))));
8353 : : }
8354 : :
8355 : : return true;
8356 : : }
8357 : :
8358 : : /*
8359 : : * Install a column's dependency on its datatype.
8360 : : */
8361 : : static void
8362 : 5259 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
8363 : : {
8364 : : ObjectAddress myself,
8365 : : referenced;
8366 : :
8367 : 5259 : myself.classId = RelationRelationId;
8368 : 5259 : myself.objectId = relid;
8369 : 5259 : myself.objectSubId = attnum;
8370 : 5259 : referenced.classId = TypeRelationId;
8371 : 5259 : referenced.objectId = typid;
8372 : 5259 : referenced.objectSubId = 0;
8373 : 5259 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
8374 : 5259 : }
8375 : :
8376 : : /*
8377 : : * Install a column's dependency on its collation.
8378 : : */
8379 : : static void
8380 : 5259 : add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
8381 : : {
8382 : : ObjectAddress myself,
8383 : : referenced;
8384 : :
8385 : : /* We know the default collation is pinned, so don't bother recording it */
8386 [ + + + + ]: 5259 : if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
8387 : : {
8388 : 12 : myself.classId = RelationRelationId;
8389 : 12 : myself.objectId = relid;
8390 : 12 : myself.objectSubId = attnum;
8391 : 12 : referenced.classId = CollationRelationId;
8392 : 12 : referenced.objectId = collid;
8393 : 12 : referenced.objectSubId = 0;
8394 : 12 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
8395 : : }
8396 : 5259 : }
8397 : :
8398 : : /*
8399 : : * ALTER TABLE ALTER COLUMN DROP NOT NULL
8400 : : *
8401 : : * Return the address of the modified column. If the column was already
8402 : : * nullable, InvalidObjectAddress is returned.
8403 : : */
8404 : : static ObjectAddress
8405 : 197 : ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
8406 : : LOCKMODE lockmode)
8407 : : {
8408 : : HeapTuple tuple;
8409 : : HeapTuple conTup;
8410 : : Form_pg_attribute attTup;
8411 : : AttrNumber attnum;
8412 : : Relation attr_rel;
8413 : : ObjectAddress address;
8414 : :
8415 : : /*
8416 : : * lookup the attribute
8417 : : */
8418 : 197 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
8419 : :
8420 : 197 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8421 [ + + ]: 197 : if (!HeapTupleIsValid(tuple))
8422 [ + - ]: 12 : ereport(ERROR,
8423 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8424 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8425 : : colName, RelationGetRelationName(rel))));
8426 : 185 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8427 : 185 : attnum = attTup->attnum;
8428 : 185 : ObjectAddressSubSet(address, RelationRelationId,
8429 : : RelationGetRelid(rel), attnum);
8430 : :
8431 : : /* If the column is already nullable there's nothing to do. */
8432 [ - + ]: 185 : if (!attTup->attnotnull)
8433 : : {
8434 : 0 : table_close(attr_rel, RowExclusiveLock);
8435 : 0 : return InvalidObjectAddress;
8436 : : }
8437 : :
8438 : : /* Prevent them from altering a system attribute */
8439 [ - + ]: 185 : if (attnum <= 0)
8440 [ # # ]: 0 : ereport(ERROR,
8441 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8442 : : errmsg("cannot alter system column \"%s\"",
8443 : : colName)));
8444 : :
8445 [ + + ]: 185 : if (attTup->attidentity)
8446 [ + - ]: 12 : ereport(ERROR,
8447 : : (errcode(ERRCODE_SYNTAX_ERROR),
8448 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
8449 : : colName, RelationGetRelationName(rel))));
8450 : :
8451 : : /*
8452 : : * If rel is partition, shouldn't drop NOT NULL if parent has the same.
8453 : : */
8454 [ + + ]: 173 : if (rel->rd_rel->relispartition)
8455 : : {
8456 : 8 : Oid parentId = get_partition_parent(RelationGetRelid(rel), false);
8457 : 8 : Relation parent = table_open(parentId, AccessShareLock);
8458 : 8 : TupleDesc tupDesc = RelationGetDescr(parent);
8459 : : AttrNumber parent_attnum;
8460 : :
8461 : 8 : parent_attnum = get_attnum(parentId, colName);
8462 [ + - ]: 8 : if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
8463 [ + - ]: 8 : ereport(ERROR,
8464 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8465 : : errmsg("column \"%s\" is marked NOT NULL in parent table",
8466 : : colName)));
8467 : 0 : table_close(parent, AccessShareLock);
8468 : : }
8469 : :
8470 : : /*
8471 : : * Find the constraint that makes this column NOT NULL, and drop it.
8472 : : * dropconstraint_internal() resets attnotnull.
8473 : : */
8474 : 165 : conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
8475 [ - + ]: 165 : if (conTup == NULL)
8476 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
8477 : : colName, RelationGetRelationName(rel));
8478 : :
8479 : : /* The normal case: we have a pg_constraint row, remove it */
8480 : 165 : dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
8481 : : false, lockmode);
8482 : 129 : heap_freetuple(conTup);
8483 : :
8484 [ - + ]: 129 : InvokeObjectPostAlterHook(RelationRelationId,
8485 : : RelationGetRelid(rel), attnum);
8486 : :
8487 : 129 : table_close(attr_rel, RowExclusiveLock);
8488 : :
8489 : 129 : return address;
8490 : : }
8491 : :
8492 : : /*
8493 : : * set_attnotnull
8494 : : * Helper to update/validate the pg_attribute status of a not-null
8495 : : * constraint
8496 : : *
8497 : : * pg_attribute.attnotnull is set true, if it isn't already.
8498 : : * If queue_validation is true, also set up wqueue to validate the constraint.
8499 : : * wqueue may be given as NULL when validation is not needed (e.g., on table
8500 : : * creation).
8501 : : */
8502 : : static void
8503 : 16153 : set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
8504 : : bool queue_validation)
8505 : : {
8506 : : Form_pg_attribute attr;
8507 : :
8508 : : Assert(!queue_validation || wqueue);
8509 : :
8510 : 16153 : CheckAlterTableIsSafe(rel);
8511 : :
8512 : : /*
8513 : : * Exit quickly by testing attnotnull from the tupledesc's copy of the
8514 : : * attribute.
8515 : : */
8516 : 16153 : attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
8517 [ - + ]: 16153 : if (attr->attisdropped)
8518 : 0 : return;
8519 : :
8520 [ + + ]: 16153 : if (!attr->attnotnull)
8521 : : {
8522 : : Relation attr_rel;
8523 : : HeapTuple tuple;
8524 : :
8525 : 999 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
8526 : :
8527 : 999 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
8528 [ - + ]: 999 : if (!HeapTupleIsValid(tuple))
8529 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
8530 : : attnum, RelationGetRelid(rel));
8531 : :
8532 : 999 : attr = (Form_pg_attribute) GETSTRUCT(tuple);
8533 : :
8534 : 999 : attr->attnotnull = true;
8535 : 999 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
8536 : :
8537 : : /*
8538 : : * If the nullness isn't already proven by validated constraints, have
8539 : : * ALTER TABLE phase 3 test for it.
8540 : : */
8541 [ + + + - ]: 999 : if (queue_validation && wqueue &&
8542 [ + + ]: 848 : !NotNullImpliedByRelConstraints(rel, attr))
8543 : : {
8544 : : AlteredTableInfo *tab;
8545 : :
8546 : 816 : tab = ATGetQueueEntry(wqueue, rel);
8547 : 816 : tab->verify_new_notnull = true;
8548 : : }
8549 : :
8550 : 999 : CommandCounterIncrement();
8551 : :
8552 : 999 : table_close(attr_rel, RowExclusiveLock);
8553 : 999 : heap_freetuple(tuple);
8554 : : }
8555 : : else
8556 : : {
8557 : 15154 : CacheInvalidateRelcache(rel);
8558 : : }
8559 : : }
8560 : :
8561 : : /*
8562 : : * ALTER TABLE ALTER COLUMN SET NOT NULL
8563 : : *
8564 : : * Add a not-null constraint to a single table and its children. Returns
8565 : : * the address of the constraint added to the parent relation, if one gets
8566 : : * added, or InvalidObjectAddress otherwise.
8567 : : *
8568 : : * We must recurse to child tables during execution, rather than using
8569 : : * ALTER TABLE's normal prep-time recursion.
8570 : : */
8571 : : static ObjectAddress
8572 : 473 : ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
8573 : : bool recurse, bool recursing, LOCKMODE lockmode)
8574 : : {
8575 : : HeapTuple tuple;
8576 : : AttrNumber attnum;
8577 : : ObjectAddress address;
8578 : : Constraint *constraint;
8579 : : CookedConstraint *ccon;
8580 : : List *cooked;
8581 : 473 : bool is_no_inherit = false;
8582 : :
8583 : : /* Guard against stack overflow due to overly deep inheritance tree. */
8584 : 473 : check_stack_depth();
8585 : :
8586 : : /* At top level, permission check was done in ATPrepCmd, else do it */
8587 [ + + ]: 473 : if (recursing)
8588 : : {
8589 : 197 : ATSimplePermissions(AT_AddConstraint, rel,
8590 : : ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
8591 : : Assert(conName != NULL);
8592 : : }
8593 : :
8594 : 473 : attnum = get_attnum(RelationGetRelid(rel), colName);
8595 [ + + ]: 473 : if (attnum == InvalidAttrNumber)
8596 [ + - ]: 12 : ereport(ERROR,
8597 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8598 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8599 : : colName, RelationGetRelationName(rel))));
8600 : :
8601 : : /* Prevent them from altering a system attribute */
8602 [ - + ]: 461 : if (attnum <= 0)
8603 [ # # ]: 0 : ereport(ERROR,
8604 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8605 : : errmsg("cannot alter system column \"%s\"",
8606 : : colName)));
8607 : :
8608 : : /* See if there's already a constraint */
8609 : 461 : tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
8610 [ + + ]: 461 : if (HeapTupleIsValid(tuple))
8611 : : {
8612 : 105 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
8613 : 105 : bool changed = false;
8614 : :
8615 : : /*
8616 : : * Don't let a NO INHERIT constraint be changed into inherit.
8617 : : */
8618 [ + + + - ]: 105 : if (conForm->connoinherit && recurse)
8619 [ + - ]: 8 : ereport(ERROR,
8620 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8621 : : errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
8622 : : NameStr(conForm->conname),
8623 : : RelationGetRelationName(rel)));
8624 : :
8625 : : /*
8626 : : * If we find an appropriate constraint, we're almost done, but just
8627 : : * need to change some properties on it: if we're recursing, increment
8628 : : * coninhcount; if not, set conislocal if not already set.
8629 : : */
8630 [ + + ]: 97 : if (recursing)
8631 : : {
8632 [ - + ]: 68 : if (pg_add_s16_overflow(conForm->coninhcount, 1,
8633 : : &conForm->coninhcount))
8634 [ # # ]: 0 : ereport(ERROR,
8635 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
8636 : : errmsg("too many inheritance parents"));
8637 : 68 : changed = true;
8638 : : }
8639 [ - + ]: 29 : else if (!conForm->conislocal)
8640 : : {
8641 : 0 : conForm->conislocal = true;
8642 : 0 : changed = true;
8643 : : }
8644 [ + + ]: 29 : else if (!conForm->convalidated)
8645 : : {
8646 : : /*
8647 : : * Flip attnotnull and convalidated, and also validate the
8648 : : * constraint.
8649 : : */
8650 : 16 : return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
8651 : : recurse, recursing, lockmode);
8652 : : }
8653 : :
8654 [ + + ]: 81 : if (changed)
8655 : : {
8656 : : Relation constr_rel;
8657 : :
8658 : 68 : constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
8659 : :
8660 : 68 : CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
8661 : 68 : ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
8662 : 68 : table_close(constr_rel, RowExclusiveLock);
8663 : : }
8664 : :
8665 [ + + ]: 81 : if (changed)
8666 : 68 : return address;
8667 : : else
8668 : 13 : return InvalidObjectAddress;
8669 : : }
8670 : :
8671 : : /*
8672 : : * If we're asked not to recurse, and children exist, raise an error for
8673 : : * partitioned tables. For inheritance, we act as if NO INHERIT had been
8674 : : * specified.
8675 : : */
8676 [ + + + + ]: 376 : if (!recurse &&
8677 : 20 : find_inheritance_children(RelationGetRelid(rel),
8678 : : NoLock) != NIL)
8679 : : {
8680 [ + + ]: 12 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8681 [ + - ]: 4 : ereport(ERROR,
8682 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8683 : : errmsg("constraint must be added to child tables too"),
8684 : : errhint("Do not specify the ONLY keyword."));
8685 : : else
8686 : 8 : is_no_inherit = true;
8687 : : }
8688 : :
8689 : : /*
8690 : : * No constraint exists; we must add one. First determine a name to use,
8691 : : * if we haven't already.
8692 : : */
8693 [ + + ]: 352 : if (!recursing)
8694 : : {
8695 : : Assert(conName == NULL);
8696 : 227 : conName = ChooseConstraintName(RelationGetRelationName(rel),
8697 : : colName, "not_null",
8698 : 227 : RelationGetNamespace(rel),
8699 : : NIL);
8700 : : }
8701 : :
8702 : 352 : constraint = makeNotNullConstraint(makeString(colName));
8703 : 352 : constraint->is_no_inherit = is_no_inherit;
8704 : 352 : constraint->conname = conName;
8705 : :
8706 : : /* and do it */
8707 : 352 : cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
8708 : 352 : false, !recursing, false, NULL);
8709 : 352 : ccon = linitial(cooked);
8710 : 352 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8711 : :
8712 : : /* Mark pg_attribute.attnotnull for the column and queue validation */
8713 : 352 : set_attnotnull(wqueue, rel, attnum, true);
8714 : :
8715 [ - + ]: 352 : InvokeObjectPostAlterHook(RelationRelationId,
8716 : : RelationGetRelid(rel), attnum);
8717 : :
8718 : : /*
8719 : : * Recurse to propagate the constraint to children that don't have one.
8720 : : */
8721 [ + + ]: 352 : if (recurse)
8722 : : {
8723 : : List *children;
8724 : :
8725 : 336 : children = find_inheritance_children(RelationGetRelid(rel),
8726 : : lockmode);
8727 : :
8728 [ + + + + : 825 : foreach_oid(childoid, children)
+ + ]
8729 : : {
8730 : 161 : Relation childrel = table_open(childoid, NoLock);
8731 : :
8732 : 161 : CommandCounterIncrement();
8733 : :
8734 : 161 : ATExecSetNotNull(wqueue, childrel, conName, colName,
8735 : : recurse, true, lockmode);
8736 : 157 : table_close(childrel, NoLock);
8737 : : }
8738 : : }
8739 : :
8740 : 348 : return address;
8741 : : }
8742 : :
8743 : : /*
8744 : : * NotNullImpliedByRelConstraints
8745 : : * Does rel's existing constraints imply NOT NULL for the given attribute?
8746 : : */
8747 : : static bool
8748 : 848 : NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
8749 : : {
8750 : 848 : NullTest *nnulltest = makeNode(NullTest);
8751 : :
8752 : 1696 : nnulltest->arg = (Expr *) makeVar(1,
8753 : 848 : attr->attnum,
8754 : : attr->atttypid,
8755 : : attr->atttypmod,
8756 : : attr->attcollation,
8757 : : 0);
8758 : 848 : nnulltest->nulltesttype = IS_NOT_NULL;
8759 : :
8760 : : /*
8761 : : * argisrow = false is correct even for a composite column, because
8762 : : * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
8763 : : * case, just IS DISTINCT FROM NULL.
8764 : : */
8765 : 848 : nnulltest->argisrow = false;
8766 : 848 : nnulltest->location = -1;
8767 : :
8768 [ + + ]: 848 : if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
8769 : : {
8770 [ + + ]: 32 : ereport(DEBUG1,
8771 : : (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
8772 : : RelationGetRelationName(rel), NameStr(attr->attname))));
8773 : 32 : return true;
8774 : : }
8775 : :
8776 : 816 : return false;
8777 : : }
8778 : :
8779 : : /*
8780 : : * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
8781 : : *
8782 : : * Return the address of the affected column.
8783 : : */
8784 : : static ObjectAddress
8785 : 387 : ATExecColumnDefault(Relation rel, const char *colName,
8786 : : Node *newDefault, LOCKMODE lockmode)
8787 : : {
8788 : 387 : TupleDesc tupdesc = RelationGetDescr(rel);
8789 : : AttrNumber attnum;
8790 : : ObjectAddress address;
8791 : :
8792 : : /*
8793 : : * get the number of the attribute
8794 : : */
8795 : 387 : attnum = get_attnum(RelationGetRelid(rel), colName);
8796 [ + + ]: 387 : if (attnum == InvalidAttrNumber)
8797 [ + - ]: 20 : ereport(ERROR,
8798 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8799 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8800 : : colName, RelationGetRelationName(rel))));
8801 : :
8802 : : /* Prevent them from altering a system attribute */
8803 [ - + ]: 367 : if (attnum <= 0)
8804 [ # # ]: 0 : ereport(ERROR,
8805 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8806 : : errmsg("cannot alter system column \"%s\"",
8807 : : colName)));
8808 : :
8809 [ + + ]: 367 : if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
8810 [ + - - + ]: 12 : ereport(ERROR,
8811 : : (errcode(ERRCODE_SYNTAX_ERROR),
8812 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
8813 : : colName, RelationGetRelationName(rel)),
8814 : : /* translator: %s is an SQL ALTER command */
8815 : : newDefault ? 0 : errhint("Use %s instead.",
8816 : : "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
8817 : :
8818 [ + + ]: 355 : if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
8819 [ + - - + : 8 : ereport(ERROR,
+ + ]
8820 : : (errcode(ERRCODE_SYNTAX_ERROR),
8821 : : errmsg("column \"%s\" of relation \"%s\" is a generated column",
8822 : : colName, RelationGetRelationName(rel)),
8823 : : newDefault ?
8824 : : /* translator: %s is an SQL ALTER command */
8825 : : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
8826 : : (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
8827 : : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
8828 : :
8829 : : /*
8830 : : * Remove any old default for the column. We use RESTRICT here for
8831 : : * safety, but at present we do not expect anything to depend on the
8832 : : * default.
8833 : : *
8834 : : * We treat removing the existing default as an internal operation when it
8835 : : * is preparatory to adding a new default, but as a user-initiated
8836 : : * operation when the user asked for a drop.
8837 : : */
8838 : 347 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8839 : : newDefault != NULL);
8840 : :
8841 [ + + ]: 347 : if (newDefault)
8842 : : {
8843 : : /* SET DEFAULT */
8844 : : RawColumnDefault *rawEnt;
8845 : :
8846 : 231 : rawEnt = palloc_object(RawColumnDefault);
8847 : 231 : rawEnt->attnum = attnum;
8848 : 231 : rawEnt->raw_default = newDefault;
8849 : 231 : rawEnt->generated = '\0';
8850 : :
8851 : : /*
8852 : : * This function is intended for CREATE TABLE, so it processes a
8853 : : * _list_ of defaults, but we just do one.
8854 : : */
8855 : 231 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8856 : : false, true, false, NULL);
8857 : : }
8858 : :
8859 : 339 : ObjectAddressSubSet(address, RelationRelationId,
8860 : : RelationGetRelid(rel), attnum);
8861 : 339 : return address;
8862 : : }
8863 : :
8864 : : /*
8865 : : * Add a pre-cooked default expression.
8866 : : *
8867 : : * Return the address of the affected column.
8868 : : */
8869 : : static ObjectAddress
8870 : 57 : ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
8871 : : Node *newDefault)
8872 : : {
8873 : : ObjectAddress address;
8874 : :
8875 : : /*
8876 : : * This is used for a cooked default copied by CREATE TABLE ... LIKE,
8877 : : * which adds new type dependencies. Such a default doesn't go through
8878 : : * AddRelationNewConstraints(), and StoreAttrDefault() leaves the
8879 : : * privilege checks to its caller, so we must check for USAGE on the types
8880 : : * here.
8881 : : */
8882 : 57 : CheckUsageOnTypesInSingleRelExpr(newDefault, RelationGetRelid(rel), GetUserId());
8883 : :
8884 : : /*
8885 : : * Remove any old default for the column. We use RESTRICT here for
8886 : : * safety, but at present we do not expect anything to depend on the
8887 : : * default. (In ordinary cases, there could not be a default in place
8888 : : * anyway, but it's possible when combining LIKE with inheritance.)
8889 : : */
8890 : 53 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8891 : : true);
8892 : :
8893 : 53 : (void) StoreAttrDefault(rel, attnum, newDefault, true);
8894 : :
8895 : 53 : ObjectAddressSubSet(address, RelationRelationId,
8896 : : RelationGetRelid(rel), attnum);
8897 : 53 : return address;
8898 : : }
8899 : :
8900 : : /*
8901 : : * ALTER TABLE ALTER COLUMN ADD IDENTITY
8902 : : *
8903 : : * Return the address of the affected column.
8904 : : */
8905 : : static ObjectAddress
8906 : 118 : ATExecAddIdentity(Relation rel, const char *colName,
8907 : : Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
8908 : : {
8909 : : Relation attrelation;
8910 : : HeapTuple tuple;
8911 : : Form_pg_attribute attTup;
8912 : : AttrNumber attnum;
8913 : : ObjectAddress address;
8914 : 118 : ColumnDef *cdef = castNode(ColumnDef, def);
8915 : : bool ispartitioned;
8916 : :
8917 : 118 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8918 [ + + + + ]: 118 : if (ispartitioned && !recurse)
8919 [ + - ]: 4 : ereport(ERROR,
8920 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8921 : : errmsg("cannot add identity to a column of only the partitioned table"),
8922 : : errhint("Do not specify the ONLY keyword.")));
8923 : :
8924 [ + + + + ]: 114 : if (rel->rd_rel->relispartition && !recursing)
8925 [ + - ]: 8 : ereport(ERROR,
8926 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8927 : : errmsg("cannot add identity to a column of a partition"));
8928 : :
8929 : 106 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8930 : :
8931 : 106 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8932 [ - + ]: 106 : if (!HeapTupleIsValid(tuple))
8933 [ # # ]: 0 : ereport(ERROR,
8934 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8935 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8936 : : colName, RelationGetRelationName(rel))));
8937 : 106 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8938 : 106 : attnum = attTup->attnum;
8939 : :
8940 : : /* Can't alter a system attribute */
8941 [ - + ]: 106 : if (attnum <= 0)
8942 [ # # ]: 0 : ereport(ERROR,
8943 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8944 : : errmsg("cannot alter system column \"%s\"",
8945 : : colName)));
8946 : :
8947 : : /*
8948 : : * Creating a column as identity implies NOT NULL, so adding the identity
8949 : : * to an existing column that is not NOT NULL would create a state that
8950 : : * cannot be reproduced without contortions.
8951 : : */
8952 [ + + ]: 106 : if (!attTup->attnotnull)
8953 [ + - ]: 4 : ereport(ERROR,
8954 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8955 : : errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
8956 : : colName, RelationGetRelationName(rel))));
8957 : :
8958 : : /*
8959 : : * On the other hand, if a not-null constraint exists, then verify that
8960 : : * it's compatible.
8961 : : */
8962 [ + - ]: 102 : if (attTup->attnotnull)
8963 : : {
8964 : : HeapTuple contup;
8965 : : Form_pg_constraint conForm;
8966 : :
8967 : 102 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel),
8968 : : attnum);
8969 [ - + ]: 102 : if (!HeapTupleIsValid(contup))
8970 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
8971 : : colName, RelationGetRelationName(rel));
8972 : :
8973 : 102 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
8974 [ + + ]: 102 : if (!conForm->convalidated)
8975 [ + - ]: 4 : ereport(ERROR,
8976 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8977 : : errmsg("incompatible NOT VALID constraint \"%s\" on relation \"%s\"",
8978 : : NameStr(conForm->conname), RelationGetRelationName(rel)),
8979 : : errhint("You might need to validate it using %s.",
8980 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
8981 : : }
8982 : :
8983 [ + + ]: 98 : if (attTup->attidentity)
8984 [ + - ]: 12 : ereport(ERROR,
8985 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8986 : : errmsg("column \"%s\" of relation \"%s\" is already an identity column",
8987 : : colName, RelationGetRelationName(rel))));
8988 : :
8989 [ + + ]: 86 : if (attTup->atthasdef)
8990 [ + - ]: 4 : ereport(ERROR,
8991 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8992 : : errmsg("column \"%s\" of relation \"%s\" already has a default value",
8993 : : colName, RelationGetRelationName(rel))));
8994 : :
8995 : 82 : attTup->attidentity = cdef->identity;
8996 : 82 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8997 : :
8998 [ - + ]: 82 : InvokeObjectPostAlterHook(RelationRelationId,
8999 : : RelationGetRelid(rel),
9000 : : attTup->attnum);
9001 : 82 : ObjectAddressSubSet(address, RelationRelationId,
9002 : : RelationGetRelid(rel), attnum);
9003 : 82 : heap_freetuple(tuple);
9004 : :
9005 : 82 : table_close(attrelation, RowExclusiveLock);
9006 : :
9007 : : /*
9008 : : * Recurse to propagate the identity column to partitions. Identity is
9009 : : * not inherited in regular inheritance children.
9010 : : */
9011 [ + - + + ]: 82 : if (recurse && ispartitioned)
9012 : : {
9013 : : List *children;
9014 : : ListCell *lc;
9015 : :
9016 : 6 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
9017 : :
9018 [ + + + + : 10 : foreach(lc, children)
+ + ]
9019 : : {
9020 : : Relation childrel;
9021 : :
9022 : 4 : childrel = table_open(lfirst_oid(lc), NoLock);
9023 : 4 : ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
9024 : 4 : table_close(childrel, NoLock);
9025 : : }
9026 : : }
9027 : :
9028 : 82 : return address;
9029 : : }
9030 : :
9031 : : /*
9032 : : * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
9033 : : *
9034 : : * Return the address of the affected column.
9035 : : */
9036 : : static ObjectAddress
9037 : 49 : ATExecSetIdentity(Relation rel, const char *colName, Node *def,
9038 : : LOCKMODE lockmode, bool recurse, bool recursing)
9039 : : {
9040 : : ListCell *option;
9041 : 49 : DefElem *generatedEl = NULL;
9042 : : HeapTuple tuple;
9043 : : Form_pg_attribute attTup;
9044 : : AttrNumber attnum;
9045 : : Relation attrelation;
9046 : : ObjectAddress address;
9047 : : bool ispartitioned;
9048 : :
9049 : 49 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
9050 [ + + + + ]: 49 : if (ispartitioned && !recurse)
9051 [ + - ]: 4 : ereport(ERROR,
9052 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9053 : : errmsg("cannot change identity column of only the partitioned table"),
9054 : : errhint("Do not specify the ONLY keyword.")));
9055 : :
9056 [ + + + + ]: 45 : if (rel->rd_rel->relispartition && !recursing)
9057 [ + - ]: 8 : ereport(ERROR,
9058 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9059 : : errmsg("cannot change identity column of a partition"));
9060 : :
9061 [ + + + + : 66 : foreach(option, castNode(List, def))
+ + ]
9062 : : {
9063 : 29 : DefElem *defel = lfirst_node(DefElem, option);
9064 : :
9065 [ + - ]: 29 : if (strcmp(defel->defname, "generated") == 0)
9066 : : {
9067 [ - + ]: 29 : if (generatedEl)
9068 [ # # ]: 0 : ereport(ERROR,
9069 : : (errcode(ERRCODE_SYNTAX_ERROR),
9070 : : errmsg("conflicting or redundant options")));
9071 : 29 : generatedEl = defel;
9072 : : }
9073 : : else
9074 [ # # ]: 0 : elog(ERROR, "option \"%s\" not recognized",
9075 : : defel->defname);
9076 : : }
9077 : :
9078 : : /*
9079 : : * Even if there is nothing to change here, we run all the checks. There
9080 : : * will be a subsequent ALTER SEQUENCE that relies on everything being
9081 : : * there.
9082 : : */
9083 : :
9084 : 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9085 : 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9086 [ - + ]: 37 : if (!HeapTupleIsValid(tuple))
9087 [ # # ]: 0 : ereport(ERROR,
9088 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9089 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9090 : : colName, RelationGetRelationName(rel))));
9091 : :
9092 : 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
9093 : 37 : attnum = attTup->attnum;
9094 : :
9095 [ - + ]: 37 : if (attnum <= 0)
9096 [ # # ]: 0 : ereport(ERROR,
9097 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9098 : : errmsg("cannot alter system column \"%s\"",
9099 : : colName)));
9100 : :
9101 [ + + ]: 37 : if (!attTup->attidentity)
9102 [ + - ]: 4 : ereport(ERROR,
9103 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9104 : : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
9105 : : colName, RelationGetRelationName(rel))));
9106 : :
9107 [ + + ]: 33 : if (generatedEl)
9108 : : {
9109 : 29 : attTup->attidentity = defGetInt32(generatedEl);
9110 : 29 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9111 : :
9112 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
9113 : : RelationGetRelid(rel),
9114 : : attTup->attnum);
9115 : 29 : ObjectAddressSubSet(address, RelationRelationId,
9116 : : RelationGetRelid(rel), attnum);
9117 : : }
9118 : : else
9119 : 4 : address = InvalidObjectAddress;
9120 : :
9121 : 33 : heap_freetuple(tuple);
9122 : 33 : table_close(attrelation, RowExclusiveLock);
9123 : :
9124 : : /*
9125 : : * Recurse to propagate the identity change to partitions. Identity is not
9126 : : * inherited in regular inheritance children.
9127 : : */
9128 [ + + + - : 33 : if (generatedEl && recurse && ispartitioned)
+ + ]
9129 : : {
9130 : : List *children;
9131 : : ListCell *lc;
9132 : :
9133 : 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
9134 : :
9135 [ + - + + : 12 : foreach(lc, children)
+ + ]
9136 : : {
9137 : : Relation childrel;
9138 : :
9139 : 8 : childrel = table_open(lfirst_oid(lc), NoLock);
9140 : 8 : ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
9141 : 8 : table_close(childrel, NoLock);
9142 : : }
9143 : : }
9144 : :
9145 : 33 : return address;
9146 : : }
9147 : :
9148 : : /*
9149 : : * ALTER TABLE ALTER COLUMN DROP IDENTITY
9150 : : *
9151 : : * Return the address of the affected column.
9152 : : */
9153 : : static ObjectAddress
9154 : 45 : ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
9155 : : bool recurse, bool recursing)
9156 : : {
9157 : : HeapTuple tuple;
9158 : : Form_pg_attribute attTup;
9159 : : AttrNumber attnum;
9160 : : Relation attrelation;
9161 : : ObjectAddress address;
9162 : : Oid seqid;
9163 : : ObjectAddress seqaddress;
9164 : : bool ispartitioned;
9165 : :
9166 : 45 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
9167 [ + + + + ]: 45 : if (ispartitioned && !recurse)
9168 [ + - ]: 4 : ereport(ERROR,
9169 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9170 : : errmsg("cannot drop identity from a column of only the partitioned table"),
9171 : : errhint("Do not specify the ONLY keyword.")));
9172 : :
9173 [ + + + + ]: 41 : if (rel->rd_rel->relispartition && !recursing)
9174 [ + - ]: 4 : ereport(ERROR,
9175 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9176 : : errmsg("cannot drop identity from a column of a partition"));
9177 : :
9178 : 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9179 : 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9180 [ - + ]: 37 : if (!HeapTupleIsValid(tuple))
9181 [ # # ]: 0 : ereport(ERROR,
9182 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9183 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9184 : : colName, RelationGetRelationName(rel))));
9185 : :
9186 : 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
9187 : 37 : attnum = attTup->attnum;
9188 : :
9189 [ - + ]: 37 : if (attnum <= 0)
9190 [ # # ]: 0 : ereport(ERROR,
9191 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9192 : : errmsg("cannot alter system column \"%s\"",
9193 : : colName)));
9194 : :
9195 [ + + ]: 37 : if (!attTup->attidentity)
9196 : : {
9197 [ + + ]: 8 : if (!missing_ok)
9198 [ + - ]: 4 : ereport(ERROR,
9199 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9200 : : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
9201 : : colName, RelationGetRelationName(rel))));
9202 : : else
9203 : : {
9204 [ + - ]: 4 : ereport(NOTICE,
9205 : : (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
9206 : : colName, RelationGetRelationName(rel))));
9207 : 4 : heap_freetuple(tuple);
9208 : 4 : table_close(attrelation, RowExclusiveLock);
9209 : 4 : return InvalidObjectAddress;
9210 : : }
9211 : : }
9212 : :
9213 : 29 : attTup->attidentity = '\0';
9214 : 29 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9215 : :
9216 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
9217 : : RelationGetRelid(rel),
9218 : : attTup->attnum);
9219 : 29 : ObjectAddressSubSet(address, RelationRelationId,
9220 : : RelationGetRelid(rel), attnum);
9221 : 29 : heap_freetuple(tuple);
9222 : :
9223 : 29 : table_close(attrelation, RowExclusiveLock);
9224 : :
9225 : : /*
9226 : : * Recurse to drop the identity from column in partitions. Identity is
9227 : : * not inherited in regular inheritance children so ignore them.
9228 : : */
9229 [ + - + + ]: 29 : if (recurse && ispartitioned)
9230 : : {
9231 : : List *children;
9232 : : ListCell *lc;
9233 : :
9234 : 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
9235 : :
9236 [ + - + + : 8 : foreach(lc, children)
+ + ]
9237 : : {
9238 : : Relation childrel;
9239 : :
9240 : 4 : childrel = table_open(lfirst_oid(lc), NoLock);
9241 : 4 : ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
9242 : 4 : table_close(childrel, NoLock);
9243 : : }
9244 : : }
9245 : :
9246 [ + + ]: 29 : if (!recursing)
9247 : : {
9248 : : /* drop the internal sequence */
9249 : 21 : seqid = getIdentitySequence(rel, attnum, false);
9250 : 21 : deleteDependencyRecordsForClass(RelationRelationId, seqid,
9251 : : RelationRelationId, DEPENDENCY_INTERNAL);
9252 : 21 : CommandCounterIncrement();
9253 : 21 : seqaddress.classId = RelationRelationId;
9254 : 21 : seqaddress.objectId = seqid;
9255 : 21 : seqaddress.objectSubId = 0;
9256 : 21 : performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
9257 : : }
9258 : :
9259 : 29 : return address;
9260 : : }
9261 : :
9262 : : /*
9263 : : * ALTER TABLE ALTER COLUMN SET EXPRESSION
9264 : : *
9265 : : * Return the address of the affected column.
9266 : : */
9267 : : static ObjectAddress
9268 : 201 : ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
9269 : : Node *newExpr, LOCKMODE lockmode)
9270 : : {
9271 : : HeapTuple tuple;
9272 : : Form_pg_attribute attTup;
9273 : : AttrNumber attnum;
9274 : : char attgenerated;
9275 : : bool rewrite;
9276 : : Oid attrdefoid;
9277 : : ObjectAddress address;
9278 : : Expr *defval;
9279 : : NewColumnValue *newval;
9280 : : RawColumnDefault *rawEnt;
9281 : :
9282 : 201 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9283 [ - + ]: 201 : if (!HeapTupleIsValid(tuple))
9284 [ # # ]: 0 : ereport(ERROR,
9285 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9286 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9287 : : colName, RelationGetRelationName(rel))));
9288 : :
9289 : 201 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
9290 : :
9291 : 201 : attnum = attTup->attnum;
9292 [ - + ]: 201 : if (attnum <= 0)
9293 [ # # ]: 0 : ereport(ERROR,
9294 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9295 : : errmsg("cannot alter system column \"%s\"",
9296 : : colName)));
9297 : :
9298 : 201 : attgenerated = attTup->attgenerated;
9299 [ + + ]: 201 : if (!attgenerated)
9300 [ + - ]: 8 : ereport(ERROR,
9301 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9302 : : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
9303 : : colName, RelationGetRelationName(rel))));
9304 : :
9305 [ + + + + ]: 193 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
9306 : 16 : tab->verify_new_notnull = true;
9307 : :
9308 : : /*
9309 : : * We need to prevent this because a change of expression could affect a
9310 : : * row filter and inject expressions that are not permitted in a row
9311 : : * filter. XXX We could try to have a more precise check to catch only
9312 : : * publications with row filters, or even re-verify the row filter
9313 : : * expressions.
9314 : : */
9315 [ + + + + ]: 289 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
9316 : 96 : GetRelationIncludedPublications(RelationGetRelid(rel)) != NIL)
9317 [ + - ]: 4 : ereport(ERROR,
9318 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9319 : : errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
9320 : : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
9321 : : colName, RelationGetRelationName(rel))));
9322 : :
9323 : 189 : rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
9324 : :
9325 : 189 : ReleaseSysCache(tuple);
9326 : :
9327 [ + + ]: 189 : if (rewrite)
9328 : : {
9329 : : /*
9330 : : * Clear all the missing values if we're rewriting the table, since
9331 : : * this renders them pointless.
9332 : : */
9333 : 97 : RelationClearMissing(rel);
9334 : :
9335 : : /* make sure we don't conflict with later attribute modifications */
9336 : 97 : CommandCounterIncrement();
9337 : : }
9338 : :
9339 : : /*
9340 : : * Find everything that depends on the column (constraints, indexes, etc),
9341 : : * and record enough information to let us recreate the objects.
9342 : : */
9343 : 189 : RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
9344 : :
9345 : : /*
9346 : : * Find whole-row referenced objects that depend on the column
9347 : : * (constraints, indexes, etc.), and record enough information to let us
9348 : : * recreate the objects.
9349 : : */
9350 : 181 : RememberWholeRowDependentForRebuilding(tab, AT_SetExpression, rel);
9351 : :
9352 : : /*
9353 : : * Drop the dependency records of the GENERATED expression, in particular
9354 : : * its INTERNAL dependency on the column, which would otherwise cause
9355 : : * dependency.c to refuse to perform the deletion.
9356 : : */
9357 : 181 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
9358 [ - + ]: 181 : if (!OidIsValid(attrdefoid))
9359 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
9360 : : RelationGetRelid(rel), attnum);
9361 : 181 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
9362 : :
9363 : : /* Make above changes visible */
9364 : 181 : CommandCounterIncrement();
9365 : :
9366 : : /*
9367 : : * Get rid of the GENERATED expression itself. We use RESTRICT here for
9368 : : * safety, but at present we do not expect anything to depend on the
9369 : : * expression.
9370 : : */
9371 : 181 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
9372 : : false, false);
9373 : :
9374 : : /* Prepare to store the new expression, in the catalogs */
9375 : 181 : rawEnt = palloc_object(RawColumnDefault);
9376 : 181 : rawEnt->attnum = attnum;
9377 : 181 : rawEnt->raw_default = newExpr;
9378 : 181 : rawEnt->generated = attgenerated;
9379 : :
9380 : : /* Store the generated expression */
9381 : 181 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
9382 : : false, true, false, NULL);
9383 : :
9384 : : /* Make above new expression visible */
9385 : 181 : CommandCounterIncrement();
9386 : :
9387 [ + + ]: 181 : if (rewrite)
9388 : : {
9389 : : /* Prepare for table rewrite */
9390 : 97 : defval = (Expr *) build_column_default(rel, attnum);
9391 : :
9392 : 97 : newval = palloc0_object(NewColumnValue);
9393 : 97 : newval->attnum = attnum;
9394 : 97 : newval->expr = expression_planner(defval);
9395 : 97 : newval->is_generated = true;
9396 : :
9397 : 97 : tab->newvals = lappend(tab->newvals, newval);
9398 : 97 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
9399 : : }
9400 : :
9401 : : /* Drop any pg_statistic entry for the column */
9402 : 181 : RemoveStatistics(RelationGetRelid(rel), attnum);
9403 : :
9404 [ - + ]: 181 : InvokeObjectPostAlterHook(RelationRelationId,
9405 : : RelationGetRelid(rel), attnum);
9406 : :
9407 : 181 : ObjectAddressSubSet(address, RelationRelationId,
9408 : : RelationGetRelid(rel), attnum);
9409 : 181 : return address;
9410 : : }
9411 : :
9412 : : /*
9413 : : * ALTER TABLE ALTER COLUMN DROP EXPRESSION
9414 : : */
9415 : : static void
9416 : 93 : ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
9417 : : {
9418 : : /*
9419 : : * Reject ONLY if there are child tables -- but only, of course, at the
9420 : : * top of the tree, otherwise it'd be impossible to run this command with
9421 : : * trees deeper than two levels. Caller already got lock.
9422 : : */
9423 [ + + + + : 105 : if (!recurse && !recursing &&
+ - ]
9424 : 12 : find_inheritance_children(RelationGetRelid(rel), NoLock))
9425 [ + - ]: 12 : ereport(ERROR,
9426 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9427 : : errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
9428 : :
9429 : : /*
9430 : : * Cannot drop generation expression from inherited columns.
9431 : : */
9432 [ + + ]: 81 : if (!recursing)
9433 : : {
9434 : : HeapTuple tuple;
9435 : : Form_pg_attribute attTup;
9436 : :
9437 : 53 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
9438 [ - + ]: 53 : if (!HeapTupleIsValid(tuple))
9439 [ # # ]: 0 : ereport(ERROR,
9440 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9441 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9442 : : cmd->name, RelationGetRelationName(rel))));
9443 : :
9444 : 53 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
9445 : :
9446 [ + + ]: 53 : if (attTup->attinhcount > 0)
9447 [ + - ]: 12 : ereport(ERROR,
9448 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9449 : : errmsg("cannot drop generation expression from inherited column")));
9450 : : }
9451 : 69 : }
9452 : :
9453 : : /*
9454 : : * Return the address of the affected column.
9455 : : */
9456 : : static ObjectAddress
9457 : 61 : ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
9458 : : {
9459 : : HeapTuple tuple;
9460 : : Form_pg_attribute attTup;
9461 : : AttrNumber attnum;
9462 : : Relation attrelation;
9463 : : Oid attrdefoid;
9464 : : ObjectAddress address;
9465 : :
9466 : 61 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9467 : 61 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9468 [ - + ]: 61 : if (!HeapTupleIsValid(tuple))
9469 [ # # ]: 0 : ereport(ERROR,
9470 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9471 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9472 : : colName, RelationGetRelationName(rel))));
9473 : :
9474 : 61 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
9475 : 61 : attnum = attTup->attnum;
9476 : :
9477 [ - + ]: 61 : if (attnum <= 0)
9478 [ # # ]: 0 : ereport(ERROR,
9479 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9480 : : errmsg("cannot alter system column \"%s\"",
9481 : : colName)));
9482 : :
9483 : : /*
9484 : : * TODO: This could be done, but it would need a table rewrite to
9485 : : * materialize the generated values. Note that for the time being, we
9486 : : * still error with missing_ok, so that we don't silently leave the column
9487 : : * as generated.
9488 : : */
9489 [ + + ]: 61 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
9490 [ + - ]: 8 : ereport(ERROR,
9491 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9492 : : errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
9493 : : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
9494 : : colName, RelationGetRelationName(rel))));
9495 : :
9496 [ + + ]: 53 : if (!attTup->attgenerated)
9497 : : {
9498 [ + + ]: 16 : if (!missing_ok)
9499 [ + - ]: 8 : ereport(ERROR,
9500 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9501 : : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
9502 : : colName, RelationGetRelationName(rel))));
9503 : : else
9504 : : {
9505 [ + - ]: 8 : ereport(NOTICE,
9506 : : (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
9507 : : colName, RelationGetRelationName(rel))));
9508 : 8 : heap_freetuple(tuple);
9509 : 8 : table_close(attrelation, RowExclusiveLock);
9510 : 8 : return InvalidObjectAddress;
9511 : : }
9512 : : }
9513 : :
9514 : : /*
9515 : : * Mark the column as no longer generated. (The atthasdef flag needs to
9516 : : * get cleared too, but RemoveAttrDefault will handle that.)
9517 : : */
9518 : 37 : attTup->attgenerated = '\0';
9519 : 37 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9520 : :
9521 [ - + ]: 37 : InvokeObjectPostAlterHook(RelationRelationId,
9522 : : RelationGetRelid(rel),
9523 : : attnum);
9524 : 37 : heap_freetuple(tuple);
9525 : :
9526 : 37 : table_close(attrelation, RowExclusiveLock);
9527 : :
9528 : : /*
9529 : : * Drop the dependency records of the GENERATED expression, in particular
9530 : : * its INTERNAL dependency on the column, which would otherwise cause
9531 : : * dependency.c to refuse to perform the deletion.
9532 : : */
9533 : 37 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
9534 [ - + ]: 37 : if (!OidIsValid(attrdefoid))
9535 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
9536 : : RelationGetRelid(rel), attnum);
9537 : 37 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
9538 : :
9539 : : /* Make above changes visible */
9540 : 37 : CommandCounterIncrement();
9541 : :
9542 : : /*
9543 : : * Get rid of the GENERATED expression itself. We use RESTRICT here for
9544 : : * safety, but at present we do not expect anything to depend on the
9545 : : * default.
9546 : : */
9547 : 37 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
9548 : : false, false);
9549 : :
9550 : 37 : ObjectAddressSubSet(address, RelationRelationId,
9551 : : RelationGetRelid(rel), attnum);
9552 : 37 : return address;
9553 : : }
9554 : :
9555 : : /*
9556 : : * ALTER TABLE ALTER COLUMN SET STATISTICS
9557 : : *
9558 : : * Return value is the address of the modified column
9559 : : */
9560 : : static ObjectAddress
9561 : 113 : ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
9562 : : {
9563 : 113 : int newtarget = 0;
9564 : : bool newtarget_default;
9565 : : Relation attrelation;
9566 : : HeapTuple tuple,
9567 : : newtuple;
9568 : : Form_pg_attribute attrtuple;
9569 : : AttrNumber attnum;
9570 : : ObjectAddress address;
9571 : : Datum repl_val[Natts_pg_attribute];
9572 : : bool repl_null[Natts_pg_attribute];
9573 : : bool repl_repl[Natts_pg_attribute];
9574 : :
9575 : : /*
9576 : : * We allow referencing columns by numbers only for indexes, since table
9577 : : * column numbers could contain gaps if columns are later dropped.
9578 : : */
9579 [ + + ]: 113 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
9580 [ + - - + ]: 69 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
9581 : : !colName)
9582 [ # # ]: 0 : ereport(ERROR,
9583 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9584 : : errmsg("cannot refer to non-index column by number")));
9585 : :
9586 : : /* -1 was used in previous versions for the default setting */
9587 [ + + + + ]: 113 : if (newValue && intVal(newValue) != -1)
9588 : : {
9589 : 82 : newtarget = intVal(newValue);
9590 : 82 : newtarget_default = false;
9591 : : }
9592 : : else
9593 : 31 : newtarget_default = true;
9594 : :
9595 [ + + ]: 113 : if (!newtarget_default)
9596 : : {
9597 : : /*
9598 : : * Limit target to a sane range
9599 : : */
9600 [ - + ]: 82 : if (newtarget < 0)
9601 : : {
9602 [ # # ]: 0 : ereport(ERROR,
9603 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9604 : : errmsg("statistics target %d is too low",
9605 : : newtarget)));
9606 : : }
9607 [ - + ]: 82 : else if (newtarget > MAX_STATISTICS_TARGET)
9608 : : {
9609 : 0 : newtarget = MAX_STATISTICS_TARGET;
9610 [ # # ]: 0 : ereport(WARNING,
9611 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9612 : : errmsg("lowering statistics target to %d",
9613 : : newtarget)));
9614 : : }
9615 : : }
9616 : :
9617 : 113 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9618 : :
9619 [ + + ]: 113 : if (colName)
9620 : : {
9621 : 69 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9622 : :
9623 [ + + ]: 69 : if (!HeapTupleIsValid(tuple))
9624 [ + - ]: 8 : ereport(ERROR,
9625 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9626 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9627 : : colName, RelationGetRelationName(rel))));
9628 : : }
9629 : : else
9630 : : {
9631 : 44 : tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
9632 : :
9633 [ + + ]: 44 : if (!HeapTupleIsValid(tuple))
9634 [ + - ]: 8 : ereport(ERROR,
9635 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9636 : : errmsg("column number %d of relation \"%s\" does not exist",
9637 : : colNum, RelationGetRelationName(rel))));
9638 : : }
9639 : :
9640 : 97 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9641 : :
9642 : 97 : attnum = attrtuple->attnum;
9643 [ - + ]: 97 : if (attnum <= 0)
9644 [ # # ]: 0 : ereport(ERROR,
9645 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9646 : : errmsg("cannot alter system column \"%s\"",
9647 : : colName)));
9648 : :
9649 : : /*
9650 : : * Prevent this as long as the ANALYZE code skips virtual generated
9651 : : * columns.
9652 : : */
9653 [ - + ]: 97 : if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
9654 [ # # ]: 0 : ereport(ERROR,
9655 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9656 : : errmsg("cannot alter statistics on virtual generated column \"%s\"",
9657 : : colName)));
9658 : :
9659 [ + + ]: 97 : if (rel->rd_rel->relkind == RELKIND_INDEX ||
9660 [ - + ]: 61 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
9661 : : {
9662 [ + + ]: 36 : if (attnum > rel->rd_index->indnkeyatts)
9663 [ + - ]: 4 : ereport(ERROR,
9664 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9665 : : errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
9666 : : NameStr(attrtuple->attname), RelationGetRelationName(rel))));
9667 [ + + ]: 32 : else if (rel->rd_index->indkey.values[attnum - 1] != 0)
9668 [ + - ]: 12 : ereport(ERROR,
9669 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9670 : : errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
9671 : : NameStr(attrtuple->attname), RelationGetRelationName(rel)),
9672 : : errhint("Alter statistics on table column instead.")));
9673 : : }
9674 : :
9675 : : /* Build new tuple. */
9676 : 81 : memset(repl_null, false, sizeof(repl_null));
9677 : 81 : memset(repl_repl, false, sizeof(repl_repl));
9678 [ + + ]: 81 : if (!newtarget_default)
9679 : 50 : repl_val[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(newtarget);
9680 : : else
9681 : 31 : repl_null[Anum_pg_attribute_attstattarget - 1] = true;
9682 : 81 : repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
9683 : 81 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9684 : : repl_val, repl_null, repl_repl);
9685 : 81 : CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
9686 : :
9687 [ - + ]: 81 : InvokeObjectPostAlterHook(RelationRelationId,
9688 : : RelationGetRelid(rel),
9689 : : attrtuple->attnum);
9690 : 81 : ObjectAddressSubSet(address, RelationRelationId,
9691 : : RelationGetRelid(rel), attnum);
9692 : :
9693 : 81 : heap_freetuple(newtuple);
9694 : :
9695 : 81 : ReleaseSysCache(tuple);
9696 : :
9697 : 81 : table_close(attrelation, RowExclusiveLock);
9698 : :
9699 : 81 : return address;
9700 : : }
9701 : :
9702 : : /*
9703 : : * Return value is the address of the modified column
9704 : : */
9705 : : static ObjectAddress
9706 : 54 : ATExecSetOptions(Relation rel, const char *colName, Node *options,
9707 : : bool isReset, LOCKMODE lockmode)
9708 : : {
9709 : : Relation attrelation;
9710 : : HeapTuple tuple,
9711 : : newtuple;
9712 : : Form_pg_attribute attrtuple;
9713 : : AttrNumber attnum;
9714 : : Datum datum,
9715 : : newOptions;
9716 : : bool isnull;
9717 : : ObjectAddress address;
9718 : : Datum repl_val[Natts_pg_attribute];
9719 : : bool repl_null[Natts_pg_attribute];
9720 : : bool repl_repl[Natts_pg_attribute];
9721 : :
9722 : 54 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9723 : :
9724 : 54 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9725 : :
9726 [ - + ]: 54 : if (!HeapTupleIsValid(tuple))
9727 [ # # ]: 0 : ereport(ERROR,
9728 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9729 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9730 : : colName, RelationGetRelationName(rel))));
9731 : 54 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9732 : :
9733 : 54 : attnum = attrtuple->attnum;
9734 [ - + ]: 54 : if (attnum <= 0)
9735 [ # # ]: 0 : ereport(ERROR,
9736 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9737 : : errmsg("cannot alter system column \"%s\"",
9738 : : colName)));
9739 : :
9740 : : /*
9741 : : * Build the list of column options, ignoring spuriously passed attribute
9742 : : * versions.
9743 : : *
9744 : : * See src/backend/catalog/README.attver.md's "Version storage in the
9745 : : * catalog" section.
9746 : : */
9747 : : {
9748 : 54 : List *filtered = NIL;
9749 : : ListCell *lc;
9750 : 54 : bool found = false;
9751 : :
9752 [ + - + + : 120 : foreach(lc, castNode(List, options))
+ + ]
9753 : : {
9754 : 66 : DefElem *def = lfirst_node(DefElem, lc);
9755 : :
9756 [ + + ]: 66 : if (def->defnamespace == NULL &&
9757 [ + + ]: 62 : strcmp(def->defname, ATTRIBUTE_VERSION_ATTOPTION) == 0)
9758 : 12 : found = true;
9759 : : else
9760 : 54 : filtered = lappend(filtered, def);
9761 : : }
9762 : :
9763 [ + + ]: 54 : if (found)
9764 : : {
9765 : : /*
9766 : : * It'd be too verbose to warn every time an option is ignored,
9767 : : * therefore just use DEBUG1 for now.
9768 : : */
9769 [ - + ]: 12 : ereport(DEBUG1,
9770 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9771 : : errmsg("ignoring reserved attribute option \"%s\"",
9772 : : ATTRIBUTE_VERSION_ATTOPTION)));
9773 : 12 : options = (Node *) filtered;
9774 : : }
9775 : : }
9776 : :
9777 : : /* Generate new proposed attoptions (text array) */
9778 : 54 : datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
9779 : : &isnull);
9780 [ + + ]: 54 : newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9781 : : castNode(List, options), NULL, NULL,
9782 : : false, isReset);
9783 : : /* Validate new options */
9784 : 50 : (void) attribute_reloptions(newOptions, true);
9785 : :
9786 : : /* Build new tuple. */
9787 : 50 : memset(repl_null, false, sizeof(repl_null));
9788 : 50 : memset(repl_repl, false, sizeof(repl_repl));
9789 [ + + ]: 50 : if (newOptions != (Datum) 0)
9790 : 42 : repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
9791 : : else
9792 : 8 : repl_null[Anum_pg_attribute_attoptions - 1] = true;
9793 : 50 : repl_repl[Anum_pg_attribute_attoptions - 1] = true;
9794 : 50 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9795 : : repl_val, repl_null, repl_repl);
9796 : :
9797 : : /* Update system catalog. */
9798 : 50 : CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
9799 : :
9800 [ - + ]: 50 : InvokeObjectPostAlterHook(RelationRelationId,
9801 : : RelationGetRelid(rel),
9802 : : attrtuple->attnum);
9803 : 50 : ObjectAddressSubSet(address, RelationRelationId,
9804 : : RelationGetRelid(rel), attnum);
9805 : :
9806 : 50 : heap_freetuple(newtuple);
9807 : :
9808 : 50 : ReleaseSysCache(tuple);
9809 : :
9810 : 50 : table_close(attrelation, RowExclusiveLock);
9811 : :
9812 : 50 : return address;
9813 : : }
9814 : :
9815 : : /*
9816 : : * Helper function for ATExecSetStorage and ATExecSetCompression
9817 : : *
9818 : : * Set the attstorage and/or attcompression fields for index columns
9819 : : * associated with the specified table column.
9820 : : */
9821 : : static void
9822 : 284 : SetIndexStorageProperties(Relation rel, Relation attrelation,
9823 : : AttrNumber attnum,
9824 : : bool setstorage, char newstorage,
9825 : : bool setcompression, char newcompression,
9826 : : LOCKMODE lockmode)
9827 : : {
9828 : : ListCell *lc;
9829 : :
9830 [ + + + + : 347 : foreach(lc, RelationGetIndexList(rel))
+ + ]
9831 : : {
9832 : 63 : Oid indexoid = lfirst_oid(lc);
9833 : : Relation indrel;
9834 : 63 : AttrNumber indattnum = 0;
9835 : : HeapTuple tuple;
9836 : :
9837 : 63 : indrel = index_open(indexoid, lockmode);
9838 : :
9839 [ + + ]: 107 : for (int i = 0; i < indrel->rd_index->indnatts; i++)
9840 : : {
9841 [ + + ]: 67 : if (indrel->rd_index->indkey.values[i] == attnum)
9842 : : {
9843 : 23 : indattnum = i + 1;
9844 : 23 : break;
9845 : : }
9846 : : }
9847 : :
9848 [ + + ]: 63 : if (indattnum == 0)
9849 : : {
9850 : 40 : index_close(indrel, lockmode);
9851 : 40 : continue;
9852 : : }
9853 : :
9854 : 23 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
9855 : :
9856 [ + - ]: 23 : if (HeapTupleIsValid(tuple))
9857 : : {
9858 : 23 : Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9859 : :
9860 [ + + ]: 23 : if (setstorage)
9861 : 15 : attrtuple->attstorage = newstorage;
9862 : :
9863 [ + + ]: 23 : if (setcompression)
9864 : 8 : attrtuple->attcompression = newcompression;
9865 : :
9866 : 23 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9867 : :
9868 [ - + ]: 23 : InvokeObjectPostAlterHook(RelationRelationId,
9869 : : RelationGetRelid(rel),
9870 : : attrtuple->attnum);
9871 : :
9872 : 23 : heap_freetuple(tuple);
9873 : : }
9874 : :
9875 : 23 : index_close(indrel, lockmode);
9876 : : }
9877 : 284 : }
9878 : :
9879 : : /*
9880 : : * ALTER TABLE ALTER COLUMN SET STORAGE
9881 : : *
9882 : : * Return value is the address of the modified column
9883 : : */
9884 : : static ObjectAddress
9885 : 247 : ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
9886 : : {
9887 : : Relation attrelation;
9888 : : HeapTuple tuple;
9889 : : Form_pg_attribute attrtuple;
9890 : : AttrNumber attnum;
9891 : : ObjectAddress address;
9892 : :
9893 : 247 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9894 : :
9895 : 247 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9896 : :
9897 [ + + ]: 247 : if (!HeapTupleIsValid(tuple))
9898 [ + - ]: 8 : ereport(ERROR,
9899 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9900 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9901 : : colName, RelationGetRelationName(rel))));
9902 : 239 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9903 : :
9904 : 239 : attnum = attrtuple->attnum;
9905 [ - + ]: 239 : if (attnum <= 0)
9906 [ # # ]: 0 : ereport(ERROR,
9907 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9908 : : errmsg("cannot alter system column \"%s\"",
9909 : : colName)));
9910 : :
9911 : 239 : attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
9912 : :
9913 : 239 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9914 : :
9915 [ - + ]: 239 : InvokeObjectPostAlterHook(RelationRelationId,
9916 : : RelationGetRelid(rel),
9917 : : attrtuple->attnum);
9918 : :
9919 : : /*
9920 : : * Apply the change to indexes as well (only for simple index columns,
9921 : : * matching behavior of index.c ConstructTupleDescriptor()).
9922 : : */
9923 : 239 : SetIndexStorageProperties(rel, attrelation, attnum,
9924 : 239 : true, attrtuple->attstorage,
9925 : : false, 0,
9926 : : lockmode);
9927 : :
9928 : 239 : heap_freetuple(tuple);
9929 : :
9930 : 239 : table_close(attrelation, RowExclusiveLock);
9931 : :
9932 : 239 : ObjectAddressSubSet(address, RelationRelationId,
9933 : : RelationGetRelid(rel), attnum);
9934 : 239 : return address;
9935 : : }
9936 : :
9937 : :
9938 : : /*
9939 : : * ALTER TABLE DROP COLUMN
9940 : : *
9941 : : * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
9942 : : * because we have to decide at runtime whether to recurse or not depending
9943 : : * on whether attinhcount goes to zero or not. (We can't check this in a
9944 : : * static pre-pass because it won't handle multiple inheritance situations
9945 : : * correctly.)
9946 : : */
9947 : : static void
9948 : 1180 : ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
9949 : : AlterTableCmd *cmd, LOCKMODE lockmode,
9950 : : AlterTableUtilityContext *context)
9951 : : {
9952 [ + + + + ]: 1180 : if (rel->rd_rel->reloftype && !recursing)
9953 [ + - ]: 4 : ereport(ERROR,
9954 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9955 : : errmsg("cannot drop column from typed table")));
9956 : :
9957 [ + + ]: 1176 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
9958 : 67 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
9959 : :
9960 [ + + ]: 1172 : if (recurse)
9961 : 994 : cmd->recurse = true;
9962 : 1172 : }
9963 : :
9964 : : /*
9965 : : * Drops column 'colName' from relation 'rel' and returns the address of the
9966 : : * dropped column. The column is also dropped (or marked as no longer
9967 : : * inherited from relation) from the relation's inheritance children, if any.
9968 : : *
9969 : : * In the recursive invocations for inheritance child relations, instead of
9970 : : * dropping the column directly (if to be dropped at all), its object address
9971 : : * is added to 'addrs', which must be non-NULL in such invocations. All
9972 : : * columns are dropped at the same time after all the children have been
9973 : : * checked recursively.
9974 : : */
9975 : : static ObjectAddress
9976 : 1545 : ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
9977 : : DropBehavior behavior,
9978 : : bool recurse, bool recursing,
9979 : : bool missing_ok, LOCKMODE lockmode,
9980 : : ObjectAddresses *addrs)
9981 : : {
9982 : : HeapTuple tuple;
9983 : : Form_pg_attribute targetatt;
9984 : : AttrNumber attnum;
9985 : : List *children;
9986 : : ObjectAddress object;
9987 : : bool is_expr;
9988 : :
9989 : : /* At top level, permission check was done in ATPrepCmd, else do it */
9990 [ + + ]: 1545 : if (recursing)
9991 : 373 : ATSimplePermissions(AT_DropColumn, rel,
9992 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9993 : :
9994 : : /* Initialize addrs on the first invocation */
9995 : : Assert(!recursing || addrs != NULL);
9996 : :
9997 : : /* since this function recurses, it could be driven to stack overflow */
9998 : 1545 : check_stack_depth();
9999 : :
10000 [ + + ]: 1545 : if (!recursing)
10001 : 1172 : addrs = new_object_addresses();
10002 : :
10003 : : /*
10004 : : * get the number of the attribute
10005 : : */
10006 : 1545 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
10007 [ + + ]: 1545 : if (!HeapTupleIsValid(tuple))
10008 : : {
10009 [ + + ]: 40 : if (!missing_ok)
10010 : : {
10011 [ + - ]: 24 : ereport(ERROR,
10012 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
10013 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
10014 : : colName, RelationGetRelationName(rel))));
10015 : : }
10016 : : else
10017 : : {
10018 [ + - ]: 16 : ereport(NOTICE,
10019 : : (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
10020 : : colName, RelationGetRelationName(rel))));
10021 : 16 : return InvalidObjectAddress;
10022 : : }
10023 : : }
10024 : 1505 : targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
10025 : :
10026 : 1505 : attnum = targetatt->attnum;
10027 : :
10028 : : /* Can't drop a system attribute */
10029 [ + + ]: 1505 : if (attnum <= 0)
10030 [ + - ]: 4 : ereport(ERROR,
10031 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10032 : : errmsg("cannot drop system column \"%s\"",
10033 : : colName)));
10034 : :
10035 : : /*
10036 : : * Don't drop inherited columns, unless recursing (presumably from a drop
10037 : : * of the parent column)
10038 : : */
10039 [ + + + + ]: 1501 : if (targetatt->attinhcount > 0 && !recursing)
10040 [ + - ]: 32 : ereport(ERROR,
10041 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10042 : : errmsg("cannot drop inherited column \"%s\"",
10043 : : colName)));
10044 : :
10045 : : /*
10046 : : * Don't drop columns used in the partition key, either. (If we let this
10047 : : * go through, the key column's dependencies would cause a cascaded drop
10048 : : * of the whole table, which is surely not what the user expected.)
10049 : : */
10050 [ + + ]: 1469 : if (has_partition_attrs(rel,
10051 : : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
10052 : : &is_expr))
10053 [ + - ]: 20 : ereport(ERROR,
10054 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10055 : : errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
10056 : : colName, RelationGetRelationName(rel))));
10057 : :
10058 : 1449 : ReleaseSysCache(tuple);
10059 : :
10060 : : /*
10061 : : * Propagate to children as appropriate. Unlike most other ALTER
10062 : : * routines, we have to do this one level of recursion at a time; we can't
10063 : : * use find_all_inheritors to do it in one pass.
10064 : : */
10065 : : children =
10066 : 1449 : find_inheritance_children(RelationGetRelid(rel), lockmode);
10067 : :
10068 [ + + ]: 1449 : if (children)
10069 : : {
10070 : : Relation attr_rel;
10071 : : ListCell *child;
10072 : :
10073 : : /*
10074 : : * In case of a partitioned table, the column must be dropped from the
10075 : : * partitions as well.
10076 : : */
10077 [ + + + + ]: 204 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
10078 [ + - ]: 4 : ereport(ERROR,
10079 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10080 : : errmsg("cannot drop column from only the partitioned table when partitions exist"),
10081 : : errhint("Do not specify the ONLY keyword.")));
10082 : :
10083 : 200 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
10084 [ + - + + : 593 : foreach(child, children)
+ + ]
10085 : : {
10086 : 397 : Oid childrelid = lfirst_oid(child);
10087 : : Relation childrel;
10088 : : Form_pg_attribute childatt;
10089 : :
10090 : : /* find_inheritance_children already got lock */
10091 : 397 : childrel = table_open(childrelid, NoLock);
10092 : 397 : CheckAlterTableIsSafe(childrel);
10093 : :
10094 : 397 : tuple = SearchSysCacheCopyAttName(childrelid, colName);
10095 [ - + ]: 397 : if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
10096 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
10097 : : colName, childrelid);
10098 : 397 : childatt = (Form_pg_attribute) GETSTRUCT(tuple);
10099 : :
10100 [ - + ]: 397 : if (childatt->attinhcount <= 0) /* shouldn't happen */
10101 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
10102 : : childrelid, colName);
10103 : :
10104 [ + + ]: 397 : if (recurse)
10105 : : {
10106 : : /*
10107 : : * If the child column has other definition sources, just
10108 : : * decrement its inheritance count; if not, recurse to delete
10109 : : * it.
10110 : : */
10111 [ + - + + ]: 381 : if (childatt->attinhcount == 1 && !childatt->attislocal)
10112 : : {
10113 : : /* Time to delete this child column, too */
10114 : 373 : ATExecDropColumn(wqueue, childrel, colName,
10115 : : behavior, true, true,
10116 : : false, lockmode, addrs);
10117 : : }
10118 : : else
10119 : : {
10120 : : /* Child column must survive my deletion */
10121 : 8 : childatt->attinhcount--;
10122 : :
10123 : 8 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
10124 : :
10125 : : /* Make update visible */
10126 : 8 : CommandCounterIncrement();
10127 : : }
10128 : : }
10129 : : else
10130 : : {
10131 : : /*
10132 : : * If we were told to drop ONLY in this table (no recursion),
10133 : : * we need to mark the inheritors' attributes as locally
10134 : : * defined rather than inherited.
10135 : : */
10136 : 16 : childatt->attinhcount--;
10137 : 16 : childatt->attislocal = true;
10138 : :
10139 : 16 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
10140 : :
10141 : : /* Make update visible */
10142 : 16 : CommandCounterIncrement();
10143 : : }
10144 : :
10145 : 393 : heap_freetuple(tuple);
10146 : :
10147 : 393 : table_close(childrel, NoLock);
10148 : : }
10149 : 196 : table_close(attr_rel, RowExclusiveLock);
10150 : : }
10151 : :
10152 : : /* Add object to delete */
10153 : 1441 : object.classId = RelationRelationId;
10154 : 1441 : object.objectId = RelationGetRelid(rel);
10155 : 1441 : object.objectSubId = attnum;
10156 : 1441 : add_exact_object_address(&object, addrs);
10157 : :
10158 [ + + ]: 1441 : if (!recursing)
10159 : : {
10160 : : /* Recursion has ended, drop everything that was collected */
10161 : 1072 : performMultipleDeletions(addrs, behavior, 0);
10162 : 1020 : free_object_addresses(addrs);
10163 : : }
10164 : :
10165 : 1389 : return object;
10166 : : }
10167 : :
10168 : : /*
10169 : : * Prepare to add a primary key on a table, by adding not-null constraints
10170 : : * on all columns.
10171 : : *
10172 : : * The not-null constraints for a primary key must cover the whole inheritance
10173 : : * hierarchy (failing to ensure that leads to funny corner cases). For the
10174 : : * normal case where we're asked to recurse, this routine checks if the
10175 : : * not-null constraints exist already, and if not queues a requirement for
10176 : : * them to be created in the AT_PASS_COL_ATTRS pass.
10177 : : *
10178 : : * For the case where we're asked not to recurse, we verify that a not-null
10179 : : * constraint exists on each column of each (direct) child table, throwing an
10180 : : * error if not. Not throwing an error would also work, because a not-null
10181 : : * constraint would be created anyway, but it'd cause a silent scan of the
10182 : : * child table to verify absence of nulls. We prefer to let the user know so
10183 : : * that they can add the constraint manually without having to hold
10184 : : * AccessExclusiveLock while at it.
10185 : : *
10186 : : * However, it's also important that we do not acquire locks on children if
10187 : : * the not-null constraints already exist on the parent, to avoid risking
10188 : : * deadlocks during parallel pg_restore of PKs on partitioned tables.
10189 : : */
10190 : : static void
10191 : 9984 : ATPrepAddPrimaryKey(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd,
10192 : : LOCKMODE lockmode)
10193 : : {
10194 : : Constraint *pkconstr;
10195 : 9984 : List *children = NIL;
10196 : 9984 : bool got_children = false;
10197 : :
10198 : 9984 : pkconstr = castNode(Constraint, cmd->def);
10199 : :
10200 : : /* USING INDEX queues its own NOT NULL constraints during transformation */
10201 [ + + + + ]: 9984 : if (pkconstr->contype != CONSTR_PRIMARY || pkconstr->indexname != NULL)
10202 : 9447 : return;
10203 : :
10204 : : /* Verify that columns are not-null, or request that they be made so */
10205 [ + - + + : 1689 : foreach_node(String, column, pkconstr->keys)
+ + ]
10206 : : {
10207 : : AlterTableCmd *newcmd;
10208 : : Constraint *nnconstr;
10209 : : HeapTuple tuple;
10210 : :
10211 : : /*
10212 : : * First check if a suitable constraint exists. If it does, we don't
10213 : : * need to request another one. We do need to bail out if it's not
10214 : : * valid, though.
10215 : : */
10216 : 655 : tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
10217 [ + + ]: 655 : if (tuple != NULL)
10218 : : {
10219 : 307 : verifyNotNullPKCompatible(tuple, strVal(column));
10220 : :
10221 : : /* All good with this one; don't request another */
10222 : 299 : heap_freetuple(tuple);
10223 : 299 : continue;
10224 : : }
10225 [ + + ]: 348 : else if (!cmd->recurse)
10226 : : {
10227 : : /*
10228 : : * No constraint on this column. Asked not to recurse, we won't
10229 : : * create one here, but verify that all children have one.
10230 : : */
10231 [ + - ]: 24 : if (!got_children)
10232 : : {
10233 : 24 : children = find_inheritance_children(RelationGetRelid(rel),
10234 : : lockmode);
10235 : : /* only search for children on the first time through */
10236 : 24 : got_children = true;
10237 : : }
10238 : :
10239 [ + - + + : 48 : foreach_oid(childrelid, children)
+ + ]
10240 : : {
10241 : : HeapTuple tup;
10242 : :
10243 : 24 : tup = findNotNullConstraint(childrelid, strVal(column));
10244 [ + + ]: 24 : if (!tup)
10245 [ + - ]: 4 : ereport(ERROR,
10246 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10247 : : errmsg("column \"%s\" in child table \"%s\" is not marked NOT NULL",
10248 : : strVal(column), get_rel_name(childrelid)));
10249 : : /* verify it's good enough */
10250 : 20 : verifyNotNullPKCompatible(tup, strVal(column));
10251 : : }
10252 : : }
10253 : :
10254 : : /* This column is not already not-null, so add it to the queue */
10255 : 336 : nnconstr = makeNotNullConstraint(column);
10256 : :
10257 : 336 : newcmd = makeNode(AlterTableCmd);
10258 : 336 : newcmd->subtype = AT_AddConstraint;
10259 : : /* note we force recurse=true here; see above */
10260 : 336 : newcmd->recurse = true;
10261 : 336 : newcmd->def = (Node *) nnconstr;
10262 : :
10263 : 336 : tab->subcmds[AT_PASS_COL_ATTRS] =
10264 : 336 : lappend(tab->subcmds[AT_PASS_COL_ATTRS], newcmd);
10265 : : }
10266 : : }
10267 : :
10268 : : /*
10269 : : * Verify whether the given not-null constraint is compatible with a
10270 : : * primary key. If not, an error is thrown.
10271 : : */
10272 : : static void
10273 : 327 : verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
10274 : : {
10275 : 327 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
10276 : :
10277 [ - + ]: 327 : if (conForm->contype != CONSTRAINT_NOTNULL)
10278 [ # # ]: 0 : elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
10279 : :
10280 : : /* a NO INHERIT constraint is no good */
10281 [ + + ]: 327 : if (conForm->connoinherit)
10282 [ + - ]: 8 : ereport(ERROR,
10283 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10284 : : errmsg("cannot create primary key on column \"%s\"", colname),
10285 : : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
10286 : : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
10287 : : NameStr(conForm->conname), colname,
10288 : : get_rel_name(conForm->conrelid), "NO INHERIT"),
10289 : : errhint("You might need to make the existing constraint inheritable using %s.",
10290 : : "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
10291 : :
10292 : : /* an unvalidated constraint is no good */
10293 [ + + ]: 319 : if (!conForm->convalidated)
10294 [ + - ]: 8 : ereport(ERROR,
10295 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10296 : : errmsg("cannot create primary key on column \"%s\"", colname),
10297 : : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
10298 : : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
10299 : : NameStr(conForm->conname), colname,
10300 : : get_rel_name(conForm->conrelid), "NOT VALID"),
10301 : : errhint("You might need to validate it using %s.",
10302 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
10303 : 311 : }
10304 : :
10305 : : /*
10306 : : * ALTER TABLE ADD INDEX
10307 : : *
10308 : : * There is no such command in the grammar, but parse_utilcmd.c converts
10309 : : * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
10310 : : * us schedule creation of the index at the appropriate time during ALTER.
10311 : : *
10312 : : * Return value is the address of the new index.
10313 : : */
10314 : : static ObjectAddress
10315 : 1155 : ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
10316 : : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
10317 : : {
10318 : : bool check_rights;
10319 : : bool skip_build;
10320 : : bool quiet;
10321 : : ObjectAddress address;
10322 : :
10323 : : Assert(IsA(stmt, IndexStmt));
10324 : : Assert(!stmt->concurrent);
10325 : :
10326 : : /* The IndexStmt has already been through transformIndexStmt */
10327 : : Assert(stmt->transformed);
10328 : :
10329 : : /* suppress schema rights check when rebuilding existing index */
10330 : 1155 : check_rights = !is_rebuild;
10331 : : /* skip index build if phase 3 will do it or we're reusing an old one */
10332 [ + + + + ]: 1155 : skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
10333 : : /* suppress notices when rebuilding existing index */
10334 : 1155 : quiet = is_rebuild;
10335 : :
10336 : 1155 : address = DefineIndex(NULL,
10337 : : RelationGetRelid(rel),
10338 : : stmt,
10339 : : InvalidOid, /* no predefined OID */
10340 : : InvalidOid, /* no parent index */
10341 : : InvalidOid, /* no parent constraint */
10342 : : -1, /* total_parts unknown */
10343 : : true, /* is_alter_table */
10344 : : check_rights,
10345 : : false, /* check_not_in_use - we did it already */
10346 : : skip_build,
10347 : : quiet);
10348 : :
10349 : : /*
10350 : : * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
10351 : : * new index instead of building from scratch. Restore associated fields.
10352 : : * This may store InvalidSubTransactionId in both fields, in which case
10353 : : * relcache.c will assume it can rebuild the relcache entry. Hence, do
10354 : : * this after the CCI that made catalog rows visible to any rebuild. The
10355 : : * DROP of the old edition of this index will have scheduled the storage
10356 : : * for deletion at commit, so cancel that pending deletion.
10357 : : */
10358 [ + + ]: 1042 : if (RelFileNumberIsValid(stmt->oldNumber))
10359 : : {
10360 : 49 : Relation irel = index_open(address.objectId, NoLock);
10361 : :
10362 : 49 : irel->rd_createSubid = stmt->oldCreateSubid;
10363 : 49 : irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
10364 : 49 : RelationPreserveStorage(irel->rd_locator, true);
10365 : 49 : index_close(irel, NoLock);
10366 : : }
10367 : :
10368 : 1042 : return address;
10369 : : }
10370 : :
10371 : : /*
10372 : : * ALTER TABLE ADD STATISTICS
10373 : : *
10374 : : * This is no such command in the grammar, but we use this internally to add
10375 : : * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
10376 : : * column type change.
10377 : : */
10378 : : static ObjectAddress
10379 : 57 : ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
10380 : : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
10381 : : {
10382 : : ObjectAddress address;
10383 : :
10384 : : Assert(IsA(stmt, CreateStatsStmt));
10385 : :
10386 : : /* The CreateStatsStmt has already been through transformStatsStmt */
10387 : : Assert(stmt->transformed);
10388 : :
10389 : : /* The owner must be set to the original statistics owner */
10390 : : Assert(OidIsValid(stmt->owner));
10391 : :
10392 : 57 : address = CreateStatistics(list_make1_oid(RelationGetRelid(rel)),
10393 : 57 : stmt, !is_rebuild);
10394 : :
10395 : 57 : return address;
10396 : : }
10397 : :
10398 : : /*
10399 : : * ALTER TABLE ADD CONSTRAINT USING INDEX
10400 : : *
10401 : : * Returns the address of the new constraint.
10402 : : */
10403 : : static ObjectAddress
10404 : 6543 : ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
10405 : : IndexStmt *stmt, LOCKMODE lockmode)
10406 : : {
10407 : 6543 : Oid index_oid = stmt->indexOid;
10408 : : Relation indexRel;
10409 : : char *indexName;
10410 : : IndexInfo *indexInfo;
10411 : : char *constraintName;
10412 : : char constraintType;
10413 : : ObjectAddress address;
10414 : : uint16 flags;
10415 : :
10416 : : Assert(IsA(stmt, IndexStmt));
10417 : : Assert(OidIsValid(index_oid));
10418 : : Assert(stmt->isconstraint);
10419 : :
10420 : : /*
10421 : : * Doing this on partitioned tables is not a simple feature to implement,
10422 : : * so let's punt for now.
10423 : : */
10424 [ + + ]: 6543 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10425 [ + - ]: 4 : ereport(ERROR,
10426 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10427 : : errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
10428 : :
10429 : 6539 : indexRel = index_open(index_oid, AccessShareLock);
10430 : :
10431 : 6539 : indexName = pstrdup(RelationGetRelationName(indexRel));
10432 : :
10433 : 6539 : indexInfo = BuildIndexInfo(indexRel);
10434 : :
10435 : : /* this should have been checked at parse time */
10436 [ - + ]: 6539 : if (!indexInfo->ii_Unique)
10437 [ # # ]: 0 : elog(ERROR, "index \"%s\" is not unique", indexName);
10438 : :
10439 : : /*
10440 : : * Determine name to assign to constraint. We require a constraint to
10441 : : * have the same name as the underlying index; therefore, use the index's
10442 : : * existing name as the default constraint name, and if the user
10443 : : * explicitly gives some other name for the constraint, rename the index
10444 : : * to match.
10445 : : */
10446 : 6539 : constraintName = stmt->idxname;
10447 [ + + ]: 6539 : if (constraintName == NULL)
10448 : 6522 : constraintName = indexName;
10449 [ + + ]: 17 : else if (strcmp(constraintName, indexName) != 0)
10450 : : {
10451 [ + - ]: 13 : ereport(NOTICE,
10452 : : (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
10453 : : indexName, constraintName)));
10454 : 13 : RenameRelationInternal(index_oid, constraintName, false, true);
10455 : : }
10456 : :
10457 : : /* Extra checks needed if making primary key */
10458 [ + + ]: 6539 : if (stmt->primary)
10459 : 3694 : index_check_primary_key(rel, indexInfo, true, stmt);
10460 : :
10461 : : /* Note we currently don't support EXCLUSION constraints here */
10462 [ + + ]: 6535 : if (stmt->primary)
10463 : 3690 : constraintType = CONSTRAINT_PRIMARY;
10464 : : else
10465 : 2845 : constraintType = CONSTRAINT_UNIQUE;
10466 : :
10467 : : /* Create the catalog entries for the constraint */
10468 : 6535 : flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
10469 : : INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
10470 [ - + ]: 13070 : (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
10471 [ - + ]: 6535 : (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
10472 : 6535 : (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
10473 : :
10474 : 6535 : address = index_constraint_create(rel,
10475 : : index_oid,
10476 : : InvalidOid,
10477 : : indexInfo,
10478 : : constraintName,
10479 : : constraintType,
10480 : : flags,
10481 : : allowSystemTableMods,
10482 : : false); /* is_internal */
10483 : :
10484 : 6535 : index_close(indexRel, NoLock);
10485 : :
10486 : 6535 : return address;
10487 : : }
10488 : :
10489 : : /*
10490 : : * ALTER TABLE ADD CONSTRAINT
10491 : : *
10492 : : * Return value is the address of the new constraint; if no constraint was
10493 : : * added, InvalidObjectAddress is returned.
10494 : : */
10495 : : static ObjectAddress
10496 : 8380 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10497 : : Constraint *newConstraint, bool recurse, bool is_readd,
10498 : : LOCKMODE lockmode)
10499 : : {
10500 : 8380 : ObjectAddress address = InvalidObjectAddress;
10501 : :
10502 : : Assert(IsA(newConstraint, Constraint));
10503 : :
10504 : : /*
10505 : : * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
10506 : : * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
10507 : : * parse_utilcmd.c).
10508 : : */
10509 [ + + - ]: 8380 : switch (newConstraint->contype)
10510 : : {
10511 : 6504 : case CONSTR_CHECK:
10512 : : case CONSTR_NOTNULL:
10513 : : address =
10514 : 6504 : ATAddCheckNNConstraint(wqueue, tab, rel,
10515 : : newConstraint, recurse, false, is_readd,
10516 : : lockmode);
10517 : 6404 : break;
10518 : :
10519 : 1876 : case CONSTR_FOREIGN:
10520 : :
10521 : : /*
10522 : : * Assign or validate constraint name
10523 : : */
10524 [ + + ]: 1876 : if (newConstraint->conname)
10525 : : {
10526 [ - + ]: 754 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
10527 : : RelationGetRelid(rel),
10528 : 754 : newConstraint->conname))
10529 [ # # ]: 0 : ereport(ERROR,
10530 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
10531 : : errmsg("constraint \"%s\" for relation \"%s\" already exists",
10532 : : newConstraint->conname,
10533 : : RelationGetRelationName(rel))));
10534 : : }
10535 : : else
10536 : 1122 : newConstraint->conname =
10537 : 1122 : ChooseConstraintName(RelationGetRelationName(rel),
10538 : 1122 : ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
10539 : : "fkey",
10540 : 1122 : RelationGetNamespace(rel),
10541 : : NIL);
10542 : :
10543 : 1876 : address = ATAddForeignKeyConstraint(wqueue, tab, rel,
10544 : : newConstraint,
10545 : : recurse, false,
10546 : : lockmode);
10547 : 1507 : break;
10548 : :
10549 : 0 : default:
10550 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
10551 : : (int) newConstraint->contype);
10552 : : }
10553 : :
10554 : 7911 : return address;
10555 : : }
10556 : :
10557 : : /*
10558 : : * Generate the column-name portion of the constraint name for a new foreign
10559 : : * key given the list of column names that reference the referenced
10560 : : * table. This will be passed to ChooseConstraintName along with the parent
10561 : : * table name and the "fkey" suffix.
10562 : : *
10563 : : * We know that less than NAMEDATALEN characters will actually be used, so we
10564 : : * can truncate the result once we've generated that many.
10565 : : *
10566 : : * XXX see also ChooseExtendedStatisticNameAddition and
10567 : : * ChooseIndexNameAddition.
10568 : : */
10569 : : static char *
10570 : 1122 : ChooseForeignKeyConstraintNameAddition(List *colnames)
10571 : : {
10572 : : char buf[NAMEDATALEN * 2];
10573 : 1122 : int buflen = 0;
10574 : : ListCell *lc;
10575 : :
10576 : 1122 : buf[0] = '\0';
10577 [ + - + + : 2538 : foreach(lc, colnames)
+ + ]
10578 : : {
10579 : 1416 : const char *name = strVal(lfirst(lc));
10580 : :
10581 [ + + ]: 1416 : if (buflen > 0)
10582 : 294 : buf[buflen++] = '_'; /* insert _ between names */
10583 : :
10584 : : /*
10585 : : * At this point we have buflen <= NAMEDATALEN. name should be less
10586 : : * than NAMEDATALEN already, but use strlcpy for paranoia.
10587 : : */
10588 : 1416 : strlcpy(buf + buflen, name, NAMEDATALEN);
10589 : 1416 : buflen += strlen(buf + buflen);
10590 [ - + ]: 1416 : if (buflen >= NAMEDATALEN)
10591 : 0 : break;
10592 : : }
10593 : 1122 : return pstrdup(buf);
10594 : : }
10595 : :
10596 : : /*
10597 : : * Add a check or not-null constraint to a single table and its children.
10598 : : * Returns the address of the constraint added to the parent relation,
10599 : : * if one gets added, or InvalidObjectAddress otherwise.
10600 : : *
10601 : : * Subroutine for ATExecAddConstraint.
10602 : : *
10603 : : * We must recurse to child tables during execution, rather than using
10604 : : * ALTER TABLE's normal prep-time recursion. The reason is that all the
10605 : : * constraints *must* be given the same name, else they won't be seen as
10606 : : * related later. If the user didn't explicitly specify a name, then
10607 : : * AddRelationNewConstraints would normally assign different names to the
10608 : : * child constraints. To fix that, we must capture the name assigned at
10609 : : * the parent table and pass that down.
10610 : : */
10611 : : static ObjectAddress
10612 : 7114 : ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10613 : : Constraint *constr, bool recurse, bool recursing,
10614 : : bool is_readd, LOCKMODE lockmode)
10615 : : {
10616 : : List *newcons;
10617 : : ListCell *lcon;
10618 : : List *children;
10619 : : ListCell *child;
10620 : 7114 : ObjectAddress address = InvalidObjectAddress;
10621 : :
10622 : : /* Guard against stack overflow due to overly deep inheritance tree. */
10623 : 7114 : check_stack_depth();
10624 : :
10625 : : /* At top level, permission check was done in ATPrepCmd, else do it */
10626 [ + + ]: 7114 : if (recursing)
10627 : 610 : ATSimplePermissions(AT_AddConstraint, rel,
10628 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
10629 : :
10630 : : /*
10631 : : * Call AddRelationNewConstraints to do the work, making sure it works on
10632 : : * a copy of the Constraint so transformExpr can't modify the original. It
10633 : : * returns a list of cooked constraints.
10634 : : *
10635 : : * If the constraint ends up getting merged with a pre-existing one, it's
10636 : : * omitted from the returned list, which is what we want: we do not need
10637 : : * to do any validation work. That can only happen at child tables,
10638 : : * though, since we disallow merging at the top level.
10639 : : */
10640 : 7114 : newcons = AddRelationNewConstraints(rel, NIL,
10641 : : list_make1(copyObject(constr)),
10642 [ + + ]: 7114 : recursing || is_readd, /* allow_merge */
10643 : : !recursing, /* is_local */
10644 : : is_readd, /* is_internal */
10645 [ + + ]: 14228 : NULL); /* queryString not available
10646 : : * here */
10647 : :
10648 : : /* we don't expect more than one constraint here */
10649 : : Assert(list_length(newcons) <= 1);
10650 : :
10651 : : /* Add each to-be-validated constraint to Phase 3's queue */
10652 [ + + + + : 13898 : foreach(lcon, newcons)
+ + ]
10653 : : {
10654 : 6880 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
10655 : :
10656 [ + + + + ]: 6880 : if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
10657 : : {
10658 : : NewConstraint *newcon;
10659 : :
10660 : 695 : newcon = palloc0_object(NewConstraint);
10661 : 695 : newcon->name = ccon->name;
10662 : 695 : newcon->contype = ccon->contype;
10663 : 695 : newcon->qual = ccon->expr;
10664 : :
10665 : 695 : tab->constraints = lappend(tab->constraints, newcon);
10666 : : }
10667 : :
10668 : : /* Save the actually assigned name if it was defaulted */
10669 [ + + ]: 6880 : if (constr->conname == NULL)
10670 : 5563 : constr->conname = ccon->name;
10671 : :
10672 : : /*
10673 : : * If adding a valid not-null constraint, set the pg_attribute flag
10674 : : * and tell phase 3 to verify existing rows, if needed. For an
10675 : : * invalid constraint, just set attnotnull, without queueing
10676 : : * verification.
10677 : : */
10678 [ + + ]: 6880 : if (constr->contype == CONSTR_NOTNULL)
10679 : 5912 : set_attnotnull(wqueue, rel, ccon->attnum,
10680 : 5912 : !constr->skip_validation);
10681 : :
10682 : 6880 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
10683 : : }
10684 : :
10685 : : /* At this point we must have a locked-down name to use */
10686 : : Assert(newcons == NIL || constr->conname != NULL);
10687 : :
10688 : : /* Advance command counter in case same table is visited multiple times */
10689 : 7018 : CommandCounterIncrement();
10690 : :
10691 : : /*
10692 : : * If the constraint got merged with an existing constraint, we're done.
10693 : : * We mustn't recurse to child tables in this case, because they've
10694 : : * already got the constraint, and visiting them again would lead to an
10695 : : * incorrect value for coninhcount.
10696 : : */
10697 [ + + ]: 7018 : if (newcons == NIL)
10698 : 138 : return address;
10699 : :
10700 : : /*
10701 : : * If adding a NO INHERIT constraint, no need to find our children.
10702 : : */
10703 [ + + ]: 6880 : if (constr->is_no_inherit)
10704 : 56 : return address;
10705 : :
10706 : : /*
10707 : : * Propagate to children as appropriate. Unlike most other ALTER
10708 : : * routines, we have to do this one level of recursion at a time; we can't
10709 : : * use find_all_inheritors to do it in one pass.
10710 : : */
10711 : : children =
10712 : 6824 : find_inheritance_children(RelationGetRelid(rel), lockmode);
10713 : :
10714 : : /*
10715 : : * Check if ONLY was specified with ALTER TABLE. If so, allow the
10716 : : * constraint creation only if there are no children currently. Error out
10717 : : * otherwise.
10718 : : */
10719 [ + + + + ]: 6824 : if (!recurse && children != NIL)
10720 [ + - ]: 4 : ereport(ERROR,
10721 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10722 : : errmsg("constraint must be added to child tables too")));
10723 : :
10724 : : /*
10725 : : * Recurse to create the constraint on each child.
10726 : : */
10727 [ + + + + : 7410 : foreach(child, children)
+ + ]
10728 : : {
10729 : 610 : Oid childrelid = lfirst_oid(child);
10730 : : Relation childrel;
10731 : : AlteredTableInfo *childtab;
10732 : :
10733 : : /* find_inheritance_children already got lock */
10734 : 610 : childrel = table_open(childrelid, NoLock);
10735 : 610 : CheckAlterTableIsSafe(childrel);
10736 : :
10737 : : /* Find or create work queue entry for this table */
10738 : 610 : childtab = ATGetQueueEntry(wqueue, childrel);
10739 : :
10740 : : /* Recurse to this child */
10741 : 610 : ATAddCheckNNConstraint(wqueue, childtab, childrel,
10742 : : constr, recurse, true, is_readd, lockmode);
10743 : :
10744 : 590 : table_close(childrel, NoLock);
10745 : : }
10746 : :
10747 : 6800 : return address;
10748 : : }
10749 : :
10750 : : /*
10751 : : * Add a foreign-key constraint to a single table; return the new constraint's
10752 : : * address.
10753 : : *
10754 : : * Subroutine for ATExecAddConstraint. Must already hold exclusive
10755 : : * lock on the rel, and have done appropriate validity checks for it.
10756 : : * We do permissions checks here, however.
10757 : : *
10758 : : * When the referenced or referencing tables (or both) are partitioned,
10759 : : * multiple pg_constraint rows are required -- one for each partitioned table
10760 : : * and each partition on each side (fortunately, not one for every combination
10761 : : * thereof). We also need action triggers on each leaf partition on the
10762 : : * referenced side, and check triggers on each leaf partition on the
10763 : : * referencing side.
10764 : : */
10765 : : static ObjectAddress
10766 : 1876 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10767 : : Constraint *fkconstraint,
10768 : : bool recurse, bool recursing, LOCKMODE lockmode)
10769 : : {
10770 : : Relation pkrel;
10771 : 1876 : int16 pkattnum[INDEX_MAX_KEYS] = {0};
10772 : 1876 : int16 fkattnum[INDEX_MAX_KEYS] = {0};
10773 : 1876 : Oid pktypoid[INDEX_MAX_KEYS] = {0};
10774 : 1876 : Oid fktypoid[INDEX_MAX_KEYS] = {0};
10775 : 1876 : Oid pkcolloid[INDEX_MAX_KEYS] = {0};
10776 : 1876 : Oid fkcolloid[INDEX_MAX_KEYS] = {0};
10777 : 1876 : Oid opclasses[INDEX_MAX_KEYS] = {0};
10778 : 1876 : Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
10779 : 1876 : Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
10780 : 1876 : Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
10781 : 1876 : int16 fkdelsetcols[INDEX_MAX_KEYS] = {0};
10782 : : bool with_period;
10783 : : bool pk_has_without_overlaps;
10784 : : int i;
10785 : : int numfks,
10786 : : numpks,
10787 : : numfkdelsetcols;
10788 : : Oid indexOid;
10789 : : bool old_check_ok;
10790 : : ObjectAddress address;
10791 : 1876 : ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
10792 : :
10793 : : /*
10794 : : * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
10795 : : * delete rows out from under us.
10796 : : */
10797 [ + + ]: 1876 : if (OidIsValid(fkconstraint->old_pktable_oid))
10798 : 48 : pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
10799 : : else
10800 : 1828 : pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
10801 : :
10802 : : /*
10803 : : * Validity checks (permission checks wait till we have the column
10804 : : * numbers)
10805 : : */
10806 [ + + + + ]: 1872 : if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10807 [ + - ]: 4 : ereport(ERROR,
10808 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
10809 : : errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
10810 : : RelationGetRelationName(rel),
10811 : : RelationGetRelationName(pkrel)));
10812 : :
10813 [ + + ]: 1868 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10814 [ - + ]: 226 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10815 [ # # ]: 0 : ereport(ERROR,
10816 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10817 : : errmsg("referenced relation \"%s\" is not a table",
10818 : : RelationGetRelationName(pkrel))));
10819 : :
10820 : : /*
10821 : : * Conflict log tables are used internally for logical replication
10822 : : * conflict logging and should not be referenced by foreign keys, as it
10823 : : * could disrupt conflict logging.
10824 : : */
10825 [ + + ]: 1868 : if (IsConflictLogTableClass(pkrel->rd_rel))
10826 [ + - ]: 4 : ereport(ERROR,
10827 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10828 : : errmsg("cannot reference conflict log table \"%s\"",
10829 : : RelationGetRelationName(pkrel)),
10830 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
10831 : :
10832 [ + + + + ]: 1864 : if (!allowSystemTableMods && IsSystemRelation(pkrel))
10833 [ + - ]: 1 : ereport(ERROR,
10834 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10835 : : errmsg("permission denied: \"%s\" is a system catalog",
10836 : : RelationGetRelationName(pkrel))));
10837 : :
10838 : : /*
10839 : : * References from permanent or unlogged tables to temp tables, and from
10840 : : * permanent tables to unlogged tables, are disallowed because the
10841 : : * referenced data can vanish out from under us. References from temp
10842 : : * tables to any other table type are also disallowed, because other
10843 : : * backends might need to run the RI triggers on the perm table, but they
10844 : : * can't reliably see tuples in the local buffers of other backends.
10845 : : */
10846 [ + + + - ]: 1863 : switch (rel->rd_rel->relpersistence)
10847 : : {
10848 : 1666 : case RELPERSISTENCE_PERMANENT:
10849 [ - + ]: 1666 : if (!RelationIsPermanent(pkrel))
10850 [ # # ]: 0 : ereport(ERROR,
10851 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10852 : : errmsg("constraints on permanent tables may reference only permanent tables")));
10853 : 1666 : break;
10854 : 8 : case RELPERSISTENCE_UNLOGGED:
10855 [ + - ]: 8 : if (!RelationIsPermanent(pkrel)
10856 [ - + ]: 8 : && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
10857 [ # # ]: 0 : ereport(ERROR,
10858 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10859 : : errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
10860 : 8 : break;
10861 : 189 : case RELPERSISTENCE_TEMP:
10862 [ - + ]: 189 : if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10863 [ # # ]: 0 : ereport(ERROR,
10864 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10865 : : errmsg("constraints on temporary tables may reference only temporary tables")));
10866 [ + - - + ]: 189 : if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
10867 [ # # ]: 0 : ereport(ERROR,
10868 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10869 : : errmsg("constraints on temporary tables must involve temporary tables of this session")));
10870 : 189 : break;
10871 : : }
10872 : :
10873 : : /*
10874 : : * Look up the referencing attributes to make sure they exist, and record
10875 : : * their attnums and type and collation OIDs.
10876 : : */
10877 : 1863 : numfks = transformColumnNameList(RelationGetRelid(rel),
10878 : : fkconstraint->fk_attrs,
10879 : : fkattnum, fktypoid, fkcolloid);
10880 [ + + + + ]: 1843 : with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
10881 [ + + + + ]: 1843 : if (with_period && !fkconstraint->fk_with_period)
10882 [ + - ]: 16 : ereport(ERROR,
10883 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10884 : : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10885 : :
10886 : 1827 : numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
10887 : : fkconstraint->fk_del_set_cols,
10888 : : fkdelsetcols, NULL, NULL);
10889 : 1823 : numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
10890 : : numfkdelsetcols,
10891 : : fkdelsetcols,
10892 : : fkconstraint->fk_del_set_cols);
10893 : :
10894 : : /*
10895 : : * If the attribute list for the referenced table was omitted, lookup the
10896 : : * definition of the primary key and use it. Otherwise, validate the
10897 : : * supplied attribute list. In either case, discover the index OID and
10898 : : * index opclasses, and the attnums and type and collation OIDs of the
10899 : : * attributes.
10900 : : */
10901 [ + + ]: 1819 : if (fkconstraint->pk_attrs == NIL)
10902 : : {
10903 : 908 : numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
10904 : : &fkconstraint->pk_attrs,
10905 : : pkattnum, pktypoid, pkcolloid,
10906 : : opclasses, &pk_has_without_overlaps);
10907 : :
10908 : : /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
10909 [ + + + + ]: 908 : if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
10910 [ + - ]: 16 : ereport(ERROR,
10911 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10912 : : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10913 : : }
10914 : : else
10915 : : {
10916 : 911 : numpks = transformColumnNameList(RelationGetRelid(pkrel),
10917 : : fkconstraint->pk_attrs,
10918 : : pkattnum, pktypoid, pkcolloid);
10919 : :
10920 : : /* Since we got pk_attrs, one should be a period. */
10921 [ + + + + ]: 891 : if (with_period && !fkconstraint->pk_with_period)
10922 [ + - ]: 16 : ereport(ERROR,
10923 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10924 : : errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
10925 : :
10926 : : /* Look for an index matching the column list */
10927 : 875 : indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
10928 : : with_period, opclasses, &pk_has_without_overlaps);
10929 : : }
10930 : :
10931 : : /*
10932 : : * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
10933 : : * must use PERIOD.
10934 : : */
10935 [ + + + + ]: 1743 : if (pk_has_without_overlaps && !with_period)
10936 [ + - ]: 8 : ereport(ERROR,
10937 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10938 : : errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
10939 : :
10940 : : /*
10941 : : * Now we can check permissions.
10942 : : */
10943 : 1735 : checkFkeyPermissions(pkrel, pkattnum, numpks);
10944 : :
10945 : : /*
10946 : : * Check some things for generated columns.
10947 : : */
10948 [ + + ]: 4063 : for (i = 0; i < numfks; i++)
10949 : : {
10950 : 2348 : char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
10951 : :
10952 [ + + ]: 2348 : if (attgenerated)
10953 : : {
10954 : : /*
10955 : : * Check restrictions on UPDATE/DELETE actions, per SQL standard
10956 : : */
10957 [ + - ]: 32 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10958 [ + - ]: 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
10959 [ + + ]: 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
10960 [ + - ]: 8 : ereport(ERROR,
10961 : : (errcode(ERRCODE_SYNTAX_ERROR),
10962 : : errmsg("invalid %s action for foreign key constraint containing generated column",
10963 : : "ON UPDATE")));
10964 [ + + ]: 24 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10965 [ - + ]: 16 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10966 [ + - ]: 8 : ereport(ERROR,
10967 : : (errcode(ERRCODE_SYNTAX_ERROR),
10968 : : errmsg("invalid %s action for foreign key constraint containing generated column",
10969 : : "ON DELETE")));
10970 : : }
10971 : :
10972 : : /*
10973 : : * FKs on virtual columns are not supported. This would require
10974 : : * various additional support in ri_triggers.c, including special
10975 : : * handling in ri_NullCheck(), ri_KeysEqual(),
10976 : : * RI_FKey_fk_upd_check_required() (since all virtual columns appear
10977 : : * as NULL there). Also not really practical as long as you can't
10978 : : * index virtual columns.
10979 : : */
10980 [ + + ]: 2332 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
10981 [ + - ]: 4 : ereport(ERROR,
10982 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10983 : : errmsg("foreign key constraints on virtual generated columns are not supported")));
10984 : : }
10985 : :
10986 : : /*
10987 : : * Some actions are currently unsupported for foreign keys using PERIOD.
10988 : : */
10989 [ + + ]: 1715 : if (fkconstraint->fk_with_period)
10990 : : {
10991 [ + + ]: 178 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
10992 [ + + ]: 170 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
10993 [ + + ]: 158 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10994 [ + + ]: 146 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
10995 [ + - ]: 44 : ereport(ERROR,
10996 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10997 : : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10998 : : "ON UPDATE"));
10999 : :
11000 [ + + ]: 134 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
11001 [ + - ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
11002 [ + - ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
11003 [ - + ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
11004 [ + - ]: 4 : ereport(ERROR,
11005 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11006 : : errmsg("unsupported %s action for foreign key constraint using PERIOD",
11007 : : "ON DELETE"));
11008 : : }
11009 : :
11010 : : /*
11011 : : * Look up the equality operators to use in the constraint.
11012 : : *
11013 : : * Note that we have to be careful about the difference between the actual
11014 : : * PK column type and the opclass' declared input type, which might be
11015 : : * only binary-compatible with it. The declared opcintype is the right
11016 : : * thing to probe pg_amop with.
11017 : : */
11018 [ - + ]: 1667 : if (numfks != numpks)
11019 [ # # ]: 0 : ereport(ERROR,
11020 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
11021 : : errmsg("number of referencing and referenced columns for foreign key disagree")));
11022 : :
11023 : : /*
11024 : : * On the strength of a previous constraint, we might avoid scanning
11025 : : * tables to validate this one. See below.
11026 : : */
11027 : 1667 : old_check_ok = (fkconstraint->old_conpfeqop != NIL);
11028 : : Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
11029 : :
11030 [ + + ]: 3643 : for (i = 0; i < numpks; i++)
11031 : : {
11032 : 2136 : Oid pktype = pktypoid[i];
11033 : 2136 : Oid fktype = fktypoid[i];
11034 : : Oid fktyped;
11035 : 2136 : Oid pkcoll = pkcolloid[i];
11036 : 2136 : Oid fkcoll = fkcolloid[i];
11037 : : HeapTuple cla_ht;
11038 : : Form_pg_opclass cla_tup;
11039 : : Oid amid;
11040 : : Oid opfamily;
11041 : : Oid opcintype;
11042 : : bool for_overlaps;
11043 : : CompareType cmptype;
11044 : : Oid pfeqop;
11045 : : Oid ppeqop;
11046 : : Oid ffeqop;
11047 : : int16 eqstrategy;
11048 : : Oid pfeqop_right;
11049 : :
11050 : : /* We need several fields out of the pg_opclass entry */
11051 : 2136 : cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
11052 [ - + ]: 2136 : if (!HeapTupleIsValid(cla_ht))
11053 [ # # ]: 0 : elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
11054 : 2136 : cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
11055 : 2136 : amid = cla_tup->opcmethod;
11056 : 2136 : opfamily = cla_tup->opcfamily;
11057 : 2136 : opcintype = cla_tup->opcintype;
11058 : 2136 : ReleaseSysCache(cla_ht);
11059 : :
11060 : : /*
11061 : : * Get strategy number from index AM.
11062 : : *
11063 : : * For a normal foreign-key constraint, this should not fail, since we
11064 : : * already checked that the index is unique and should therefore have
11065 : : * appropriate equal operators. For a period foreign key, this could
11066 : : * fail if we selected a non-matching exclusion constraint earlier.
11067 : : * (XXX Maybe we should do these lookups earlier so we don't end up
11068 : : * doing that.)
11069 : : */
11070 [ + + + + ]: 2136 : for_overlaps = with_period && i == numpks - 1;
11071 [ + + ]: 2136 : cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
11072 : 2136 : eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
11073 [ - + ]: 2136 : if (eqstrategy == InvalidStrategy)
11074 [ # # # # ]: 0 : ereport(ERROR,
11075 : : errcode(ERRCODE_UNDEFINED_OBJECT),
11076 : : for_overlaps
11077 : : ? errmsg("could not identify an overlaps operator for foreign key")
11078 : : : errmsg("could not identify an equality operator for foreign key"),
11079 : : errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
11080 : : cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
11081 : :
11082 : : /*
11083 : : * There had better be a primary equality operator for the index.
11084 : : * We'll use it for PK = PK comparisons.
11085 : : */
11086 : 2136 : ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
11087 : : eqstrategy);
11088 : :
11089 [ - + ]: 2136 : if (!OidIsValid(ppeqop))
11090 [ # # ]: 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
11091 : : eqstrategy, opcintype, opcintype, opfamily);
11092 : :
11093 : : /*
11094 : : * Are there equality operators that take exactly the FK type? Assume
11095 : : * we should look through any domain here.
11096 : : */
11097 : 2136 : fktyped = getBaseType(fktype);
11098 : :
11099 : 2136 : pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
11100 : : eqstrategy);
11101 [ + + ]: 2136 : if (OidIsValid(pfeqop))
11102 : : {
11103 : 1647 : pfeqop_right = fktyped;
11104 : 1647 : ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
11105 : : eqstrategy);
11106 : : }
11107 : : else
11108 : : {
11109 : : /* keep compiler quiet */
11110 : 489 : pfeqop_right = InvalidOid;
11111 : 489 : ffeqop = InvalidOid;
11112 : : }
11113 : :
11114 [ + + - + ]: 2136 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
11115 : : {
11116 : : /*
11117 : : * Otherwise, look for an implicit cast from the FK type to the
11118 : : * opcintype, and if found, use the primary equality operator.
11119 : : * This is a bit tricky because opcintype might be a polymorphic
11120 : : * type such as ANYARRAY or ANYENUM; so what we have to test is
11121 : : * whether the two actual column types can be concurrently cast to
11122 : : * that type. (Otherwise, we'd fail to reject combinations such
11123 : : * as int[] and point[].)
11124 : : */
11125 : : Oid input_typeids[2];
11126 : : Oid target_typeids[2];
11127 : :
11128 : 489 : input_typeids[0] = pktype;
11129 : 489 : input_typeids[1] = fktype;
11130 : 489 : target_typeids[0] = opcintype;
11131 : 489 : target_typeids[1] = opcintype;
11132 [ + + ]: 489 : if (can_coerce_type(2, input_typeids, target_typeids,
11133 : : COERCION_IMPLICIT))
11134 : : {
11135 : 337 : pfeqop = ffeqop = ppeqop;
11136 : 337 : pfeqop_right = opcintype;
11137 : : }
11138 : : }
11139 : :
11140 [ + + - + ]: 2136 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
11141 [ + - ]: 152 : ereport(ERROR,
11142 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
11143 : : errmsg("foreign key constraint \"%s\" cannot be implemented",
11144 : : fkconstraint->conname),
11145 : : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
11146 : : "are of incompatible types: %s and %s.",
11147 : : strVal(list_nth(fkconstraint->fk_attrs, i)),
11148 : : strVal(list_nth(fkconstraint->pk_attrs, i)),
11149 : : format_type_be(fktype),
11150 : : format_type_be(pktype))));
11151 : :
11152 : : /*
11153 : : * This shouldn't be possible, but better check to make sure we have a
11154 : : * consistent state for the check below.
11155 : : */
11156 [ + + + - : 1984 : if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
+ + - + ]
11157 [ # # ]: 0 : elog(ERROR, "key columns are not both collatable");
11158 : :
11159 [ + + + - ]: 1984 : if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
11160 : : {
11161 : : bool pkcolldet;
11162 : : bool fkcolldet;
11163 : :
11164 : 89 : pkcolldet = get_collation_isdeterministic(pkcoll);
11165 : 89 : fkcolldet = get_collation_isdeterministic(fkcoll);
11166 : :
11167 : : /*
11168 : : * SQL requires that both collations are the same. This is
11169 : : * because we need a consistent notion of equality on both
11170 : : * columns. We relax this by allowing different collations if
11171 : : * they are both deterministic. (This is also for backward
11172 : : * compatibility, because PostgreSQL has always allowed this.)
11173 : : */
11174 [ + + + + : 89 : if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
+ + ]
11175 [ + - ]: 8 : ereport(ERROR,
11176 : : (errcode(ERRCODE_COLLATION_MISMATCH),
11177 : : errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
11178 : : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
11179 : : "have incompatible collations: \"%s\" and \"%s\". "
11180 : : "If either collation is nondeterministic, then both collations have to be the same.",
11181 : : strVal(list_nth(fkconstraint->fk_attrs, i)),
11182 : : strVal(list_nth(fkconstraint->pk_attrs, i)),
11183 : : get_collation_name(fkcoll),
11184 : : get_collation_name(pkcoll))));
11185 : : }
11186 : :
11187 [ + + ]: 1976 : if (old_check_ok)
11188 : : {
11189 : : /*
11190 : : * When a pfeqop changes, revalidate the constraint. We could
11191 : : * permit intra-opfamily changes, but that adds subtle complexity
11192 : : * without any concrete benefit for core types. We need not
11193 : : * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
11194 : : */
11195 : 4 : old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
11196 : 4 : old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
11197 : : old_pfeqop_item);
11198 : : }
11199 [ + + ]: 1976 : if (old_check_ok)
11200 : : {
11201 : : Oid old_fktype;
11202 : : Oid new_fktype;
11203 : : CoercionPathType old_pathtype;
11204 : : CoercionPathType new_pathtype;
11205 : : Oid old_castfunc;
11206 : : Oid new_castfunc;
11207 : : Oid old_fkcoll;
11208 : : Oid new_fkcoll;
11209 : 4 : Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
11210 : 4 : fkattnum[i] - 1);
11211 : :
11212 : : /*
11213 : : * Identify coercion pathways from each of the old and new FK-side
11214 : : * column types to the right (foreign) operand type of the pfeqop.
11215 : : * We may assume that pg_constraint.conkey is not changing.
11216 : : */
11217 : 4 : old_fktype = attr->atttypid;
11218 : 4 : new_fktype = fktype;
11219 : 4 : old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
11220 : : &old_castfunc);
11221 : 4 : new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
11222 : : &new_castfunc);
11223 : :
11224 : 4 : old_fkcoll = attr->attcollation;
11225 : 4 : new_fkcoll = fkcoll;
11226 : :
11227 : : /*
11228 : : * Upon a change to the cast from the FK column to its pfeqop
11229 : : * operand, revalidate the constraint. For this evaluation, a
11230 : : * binary coercion cast is equivalent to no cast at all. While
11231 : : * type implementors should design implicit casts with an eye
11232 : : * toward consistency of operations like equality, we cannot
11233 : : * assume here that they have done so.
11234 : : *
11235 : : * A function with a polymorphic argument could change behavior
11236 : : * arbitrarily in response to get_fn_expr_argtype(). Therefore,
11237 : : * when the cast destination is polymorphic, we only avoid
11238 : : * revalidation if the input type has not changed at all. Given
11239 : : * just the core data types and operator classes, this requirement
11240 : : * prevents no would-be optimizations.
11241 : : *
11242 : : * If the cast converts from a base type to a domain thereon, then
11243 : : * that domain type must be the opcintype of the unique index.
11244 : : * Necessarily, the primary key column must then be of the domain
11245 : : * type. Since the constraint was previously valid, all values on
11246 : : * the foreign side necessarily exist on the primary side and in
11247 : : * turn conform to the domain. Consequently, we need not treat
11248 : : * domains specially here.
11249 : : *
11250 : : * If the collation changes, revalidation is required, unless both
11251 : : * collations are deterministic, because those share the same
11252 : : * notion of equality (because texteq reduces to bitwise
11253 : : * equality).
11254 : : *
11255 : : * We need not directly consider the PK type. It's necessarily
11256 : : * binary coercible to the opcintype of the unique index column,
11257 : : * and ri_triggers.c will only deal with PK datums in terms of
11258 : : * that opcintype. Changing the opcintype also changes pfeqop.
11259 : : */
11260 : 4 : old_check_ok = (new_pathtype == old_pathtype &&
11261 [ + - + - ]: 4 : new_castfunc == old_castfunc &&
11262 [ + - + - : 4 : (!IsPolymorphicType(pfeqop_right) ||
+ - + - +
- + - + -
+ - + - -
+ - - ]
11263 [ + - - + ]: 8 : new_fktype == old_fktype) &&
11264 [ # # ]: 0 : (new_fkcoll == old_fkcoll ||
11265 [ # # ]: 0 : (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
11266 : : }
11267 : :
11268 : 1976 : pfeqoperators[i] = pfeqop;
11269 : 1976 : ppeqoperators[i] = ppeqop;
11270 : 1976 : ffeqoperators[i] = ffeqop;
11271 : : }
11272 : :
11273 : : /*
11274 : : * For FKs with PERIOD we need additional operators to check whether the
11275 : : * referencing row's range is contained by the aggregated ranges of the
11276 : : * referenced row(s). For rangetypes and multirangetypes this is
11277 : : * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
11278 : : * support for now. FKs will look these up at "runtime", but we should
11279 : : * make sure the lookup works here, even if we don't use the values.
11280 : : */
11281 [ + + ]: 1507 : if (with_period)
11282 : : {
11283 : : Oid periodoperoid;
11284 : : Oid aggedperiodoperoid;
11285 : : Oid intersectoperoid;
11286 : :
11287 : 118 : FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
11288 : : &intersectoperoid);
11289 : : }
11290 : :
11291 : : /* First, create the constraint catalog entry itself. */
11292 : 1507 : address = addFkConstraint(addFkBothSides,
11293 : : fkconstraint->conname, fkconstraint, rel, pkrel,
11294 : : indexOid,
11295 : : InvalidOid, /* no parent constraint */
11296 : : numfks,
11297 : : pkattnum,
11298 : : fkattnum,
11299 : : pfeqoperators,
11300 : : ppeqoperators,
11301 : : ffeqoperators,
11302 : : numfkdelsetcols,
11303 : : fkdelsetcols,
11304 : : false,
11305 : : with_period);
11306 : :
11307 : : /* Next process the action triggers at the referenced side and recurse */
11308 : 1507 : addFkRecurseReferenced(fkconstraint, rel, pkrel,
11309 : : indexOid,
11310 : : address.objectId,
11311 : : numfks,
11312 : : pkattnum,
11313 : : fkattnum,
11314 : : pfeqoperators,
11315 : : ppeqoperators,
11316 : : ffeqoperators,
11317 : : numfkdelsetcols,
11318 : : fkdelsetcols,
11319 : : old_check_ok,
11320 : : InvalidOid, InvalidOid,
11321 : : with_period);
11322 : :
11323 : : /* Lastly create the check triggers at the referencing side and recurse */
11324 : 1507 : addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
11325 : : indexOid,
11326 : : address.objectId,
11327 : : numfks,
11328 : : pkattnum,
11329 : : fkattnum,
11330 : : pfeqoperators,
11331 : : ppeqoperators,
11332 : : ffeqoperators,
11333 : : numfkdelsetcols,
11334 : : fkdelsetcols,
11335 : : old_check_ok,
11336 : : lockmode,
11337 : : InvalidOid, InvalidOid,
11338 : : with_period);
11339 : :
11340 : : /*
11341 : : * Done. Close pk table, but keep lock until we've committed.
11342 : : */
11343 : 1507 : table_close(pkrel, NoLock);
11344 : :
11345 : 1507 : return address;
11346 : : }
11347 : :
11348 : : /*
11349 : : * validateFkOnDeleteSetColumns
11350 : : * Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
11351 : : * column lists are valid.
11352 : : *
11353 : : * If there are duplicates in the fksetcolsattnums[] array, this silently
11354 : : * removes the dups. The new count of numfksetcols is returned.
11355 : : */
11356 : : static int
11357 : 1823 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
11358 : : int numfksetcols, int16 *fksetcolsattnums,
11359 : : List *fksetcols)
11360 : : {
11361 : 1823 : int numcolsout = 0;
11362 : :
11363 [ + + ]: 1843 : for (int i = 0; i < numfksetcols; i++)
11364 : : {
11365 : 24 : int16 setcol_attnum = fksetcolsattnums[i];
11366 : 24 : bool seen = false;
11367 : :
11368 : : /* Make sure it's in fkattnums[] */
11369 [ + + ]: 44 : for (int j = 0; j < numfks; j++)
11370 : : {
11371 [ + + ]: 40 : if (fkattnums[j] == setcol_attnum)
11372 : : {
11373 : 20 : seen = true;
11374 : 20 : break;
11375 : : }
11376 : : }
11377 : :
11378 [ + + ]: 24 : if (!seen)
11379 : : {
11380 : 4 : char *col = strVal(list_nth(fksetcols, i));
11381 : :
11382 [ + - ]: 4 : ereport(ERROR,
11383 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
11384 : : errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
11385 : : }
11386 : :
11387 : : /* Now check for dups */
11388 : 20 : seen = false;
11389 [ + + ]: 20 : for (int j = 0; j < numcolsout; j++)
11390 : : {
11391 [ + - ]: 4 : if (fksetcolsattnums[j] == setcol_attnum)
11392 : : {
11393 : 4 : seen = true;
11394 : 4 : break;
11395 : : }
11396 : : }
11397 [ + + ]: 20 : if (!seen)
11398 : 16 : fksetcolsattnums[numcolsout++] = setcol_attnum;
11399 : : }
11400 : 1819 : return numcolsout;
11401 : : }
11402 : :
11403 : : /*
11404 : : * addFkConstraint
11405 : : * Install pg_constraint entries to implement a foreign key constraint.
11406 : : * Caller must separately invoke addFkRecurseReferenced and
11407 : : * addFkRecurseReferencing, as appropriate, to install pg_trigger entries
11408 : : * and (for partitioned tables) recurse to partitions.
11409 : : *
11410 : : * fkside: the side of the FK (or both) to create. Caller should
11411 : : * call addFkRecurseReferenced if this is addFkReferencedSide,
11412 : : * addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
11413 : : * addFkBothSides.
11414 : : * constraintname: the base name for the constraint being added,
11415 : : * copied to fkconstraint->conname if the latter is not set
11416 : : * fkconstraint: the constraint being added
11417 : : * rel: the root referencing relation
11418 : : * pkrel: the referenced relation; might be a partition, if recursing
11419 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
11420 : : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
11421 : : * top-level constraint
11422 : : * numfks: the number of columns in the foreign key
11423 : : * pkattnum: the attnum array of referenced attributes
11424 : : * fkattnum: the attnum array of referencing attributes
11425 : : * pf/pp/ffeqoperators: OID array of operators between columns
11426 : : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
11427 : : * (...) clause
11428 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
11429 : : * NULL/DEFAULT clause
11430 : : * with_period: true if this is a temporal FK
11431 : : */
11432 : : static ObjectAddress
11433 : 2774 : addFkConstraint(addFkConstraintSides fkside,
11434 : : char *constraintname, Constraint *fkconstraint,
11435 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
11436 : : int numfks, int16 *pkattnum,
11437 : : int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
11438 : : Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
11439 : : bool is_internal, bool with_period)
11440 : : {
11441 : : ObjectAddress address;
11442 : : Oid constrOid;
11443 : : char *conname;
11444 : : bool conislocal;
11445 : : int16 coninhcount;
11446 : : bool connoinherit;
11447 : :
11448 : : /*
11449 : : * Verify relkind for each referenced partition. At the top level, this
11450 : : * is redundant with a previous check, but we need it when recursing.
11451 : : */
11452 [ + + ]: 2774 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
11453 [ - + ]: 559 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
11454 [ # # ]: 0 : ereport(ERROR,
11455 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11456 : : errmsg("referenced relation \"%s\" is not a table",
11457 : : RelationGetRelationName(pkrel))));
11458 : :
11459 : : /*
11460 : : * Caller supplies us with a constraint name; however, it may be used in
11461 : : * this partition, so come up with a different one in that case. Unless
11462 : : * truncation to NAMEDATALEN dictates otherwise, the new name will be the
11463 : : * supplied name with an underscore and digit(s) appended.
11464 : : */
11465 [ + + ]: 2774 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
11466 : : RelationGetRelid(rel),
11467 : : constraintname))
11468 : 755 : conname = ChooseConstraintName(constraintname,
11469 : : NULL,
11470 : : "",
11471 : 755 : RelationGetNamespace(rel), NIL);
11472 : : else
11473 : 2019 : conname = constraintname;
11474 : :
11475 [ + + ]: 2774 : if (fkconstraint->conname == NULL)
11476 : 243 : fkconstraint->conname = pstrdup(conname);
11477 : :
11478 [ + + ]: 2774 : if (OidIsValid(parentConstr))
11479 : : {
11480 : 1267 : conislocal = false;
11481 : 1267 : coninhcount = 1;
11482 : 1267 : connoinherit = false;
11483 : : }
11484 : : else
11485 : : {
11486 : 1507 : conislocal = true;
11487 : 1507 : coninhcount = 0;
11488 : :
11489 : : /*
11490 : : * always inherit for partitioned tables, never for legacy inheritance
11491 : : */
11492 : 1507 : connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
11493 : : }
11494 : :
11495 : : /*
11496 : : * Record the FK constraint in pg_constraint.
11497 : : */
11498 : 2774 : constrOid = CreateConstraintEntry(conname,
11499 : 2774 : RelationGetNamespace(rel),
11500 : : CONSTRAINT_FOREIGN,
11501 : 2774 : fkconstraint->deferrable,
11502 : 2774 : fkconstraint->initdeferred,
11503 : 2774 : fkconstraint->is_enforced,
11504 : 2774 : fkconstraint->initially_valid,
11505 : : parentConstr,
11506 : : RelationGetRelid(rel),
11507 : : fkattnum,
11508 : : numfks,
11509 : : numfks,
11510 : : InvalidOid, /* not a domain constraint */
11511 : : indexOid,
11512 : : RelationGetRelid(pkrel),
11513 : : pkattnum,
11514 : : pfeqoperators,
11515 : : ppeqoperators,
11516 : : ffeqoperators,
11517 : : numfks,
11518 : 2774 : fkconstraint->fk_upd_action,
11519 : 2774 : fkconstraint->fk_del_action,
11520 : : fkdelsetcols,
11521 : : numfkdelsetcols,
11522 : 2774 : fkconstraint->fk_matchtype,
11523 : : NULL, /* no exclusion constraint */
11524 : : NULL, /* no check constraint */
11525 : : NULL,
11526 : : conislocal, /* islocal */
11527 : : coninhcount, /* inhcount */
11528 : : connoinherit, /* conNoInherit */
11529 : : with_period, /* conPeriod */
11530 : : is_internal); /* is_internal */
11531 : :
11532 : 2774 : ObjectAddressSet(address, ConstraintRelationId, constrOid);
11533 : :
11534 : : /*
11535 : : * In partitioning cases, create the dependency entries for this
11536 : : * constraint. (For non-partitioned cases, relevant entries were created
11537 : : * by CreateConstraintEntry.)
11538 : : *
11539 : : * On the referenced side, we need the constraint to have an internal
11540 : : * dependency on its parent constraint; this means that this constraint
11541 : : * cannot be dropped on its own -- only through the parent constraint. It
11542 : : * also means the containing partition cannot be dropped on its own, but
11543 : : * it can be detached, at which point this dependency is removed (after
11544 : : * verifying that no rows are referenced via this FK.)
11545 : : *
11546 : : * When processing the referencing side, we link the constraint via the
11547 : : * special partitioning dependencies: the parent constraint is the primary
11548 : : * dependent, and the partition on which the foreign key exists is the
11549 : : * secondary dependency. That way, this constraint is dropped if either
11550 : : * of these objects is.
11551 : : *
11552 : : * Note that this is only necessary for the subsidiary pg_constraint rows
11553 : : * in partitions; the topmost row doesn't need any of this.
11554 : : */
11555 [ + + ]: 2774 : if (OidIsValid(parentConstr))
11556 : : {
11557 : : ObjectAddress referenced;
11558 : :
11559 : 1267 : ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
11560 : :
11561 : : Assert(fkside != addFkBothSides);
11562 [ + + ]: 1267 : if (fkside == addFkReferencedSide)
11563 : 751 : recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
11564 : : else
11565 : : {
11566 : 516 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
11567 : 516 : ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
11568 : 516 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
11569 : : }
11570 : : }
11571 : :
11572 : : /* make new constraint visible, in case we add more */
11573 : 2774 : CommandCounterIncrement();
11574 : :
11575 : 2774 : return address;
11576 : : }
11577 : :
11578 : : /*
11579 : : * addFkRecurseReferenced
11580 : : * Recursive helper for the referenced side of foreign key creation,
11581 : : * which creates the action triggers and recurses
11582 : : *
11583 : : * If the referenced relation is a plain relation, create the necessary action
11584 : : * triggers that implement the constraint. If the referenced relation is a
11585 : : * partitioned table, then we create a pg_constraint row referencing the parent
11586 : : * of the referencing side for it and recurse on this routine for each
11587 : : * partition.
11588 : : *
11589 : : * fkconstraint: the constraint being added
11590 : : * rel: the root referencing relation
11591 : : * pkrel: the referenced relation; might be a partition, if recursing
11592 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
11593 : : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
11594 : : * top-level constraint
11595 : : * numfks: the number of columns in the foreign key
11596 : : * pkattnum: the attnum array of referenced attributes
11597 : : * fkattnum: the attnum array of referencing attributes
11598 : : * numfkdelsetcols: the number of columns in the ON DELETE SET
11599 : : * NULL/DEFAULT (...) clause
11600 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
11601 : : * NULL/DEFAULT clause
11602 : : * pf/pp/ffeqoperators: OID array of operators between columns
11603 : : * old_check_ok: true if this constraint replaces an existing one that
11604 : : * was already validated (thus this one doesn't need validation)
11605 : : * parentDelTrigger and parentUpdTrigger: when recursively called on a
11606 : : * partition, the OIDs of the parent action triggers for DELETE and
11607 : : * UPDATE respectively.
11608 : : * with_period: true if this is a temporal FK
11609 : : */
11610 : : static void
11611 : 2326 : addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
11612 : : Relation pkrel, Oid indexOid, Oid parentConstr,
11613 : : int numfks,
11614 : : int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
11615 : : Oid *ppeqoperators, Oid *ffeqoperators,
11616 : : int numfkdelsetcols, int16 *fkdelsetcols,
11617 : : bool old_check_ok,
11618 : : Oid parentDelTrigger, Oid parentUpdTrigger,
11619 : : bool with_period)
11620 : : {
11621 : 2326 : Oid deleteTriggerOid = InvalidOid,
11622 : 2326 : updateTriggerOid = InvalidOid;
11623 : :
11624 : : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11625 : : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11626 : :
11627 : : /*
11628 : : * Create action triggers to enforce the constraint, or skip them if the
11629 : : * constraint is NOT ENFORCED.
11630 : : */
11631 [ + + ]: 2326 : if (fkconstraint->is_enforced)
11632 : 2289 : createForeignKeyActionTriggers(RelationGetRelid(rel),
11633 : : RelationGetRelid(pkrel),
11634 : : fkconstraint,
11635 : : parentConstr, indexOid,
11636 : : parentDelTrigger, parentUpdTrigger,
11637 : : &deleteTriggerOid, &updateTriggerOid);
11638 : :
11639 : : /*
11640 : : * If the referenced table is partitioned, recurse on ourselves to handle
11641 : : * each partition. We need one pg_constraint row created for each
11642 : : * partition in addition to the pg_constraint row for the parent table.
11643 : : */
11644 [ + + ]: 2326 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11645 : : {
11646 : 363 : PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
11647 : :
11648 [ + + ]: 1010 : for (int i = 0; i < pd->nparts; i++)
11649 : : {
11650 : : Relation partRel;
11651 : : AttrMap *map;
11652 : : AttrNumber *mapped_pkattnum;
11653 : : Oid partIndexId;
11654 : : ObjectAddress address;
11655 : :
11656 : : /* XXX would it be better to acquire these locks beforehand? */
11657 : 647 : partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
11658 : :
11659 : : /*
11660 : : * Map the attribute numbers in the referenced side of the FK
11661 : : * definition to match the partition's column layout.
11662 : : */
11663 : 647 : map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
11664 : : RelationGetDescr(pkrel),
11665 : : false);
11666 [ + + ]: 647 : if (map)
11667 : : {
11668 : 89 : mapped_pkattnum = palloc_array(AttrNumber, numfks);
11669 [ + + ]: 186 : for (int j = 0; j < numfks; j++)
11670 : 97 : mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
11671 : : }
11672 : : else
11673 : 558 : mapped_pkattnum = pkattnum;
11674 : :
11675 : : /* Determine the index to use at this level */
11676 : 647 : partIndexId = index_get_partition(partRel, indexOid);
11677 [ - + ]: 647 : if (!OidIsValid(partIndexId))
11678 [ # # ]: 0 : elog(ERROR, "index for %u not found in partition %s",
11679 : : indexOid, RelationGetRelationName(partRel));
11680 : :
11681 : : /* Create entry at this level ... */
11682 : 647 : address = addFkConstraint(addFkReferencedSide,
11683 : : fkconstraint->conname, fkconstraint, rel,
11684 : : partRel, partIndexId, parentConstr,
11685 : : numfks, mapped_pkattnum,
11686 : : fkattnum, pfeqoperators, ppeqoperators,
11687 : : ffeqoperators, numfkdelsetcols,
11688 : : fkdelsetcols, true, with_period);
11689 : : /* ... and recurse to our children */
11690 : 647 : addFkRecurseReferenced(fkconstraint, rel, partRel,
11691 : : partIndexId, address.objectId, numfks,
11692 : : mapped_pkattnum, fkattnum,
11693 : : pfeqoperators, ppeqoperators, ffeqoperators,
11694 : : numfkdelsetcols, fkdelsetcols,
11695 : : old_check_ok,
11696 : : deleteTriggerOid, updateTriggerOid,
11697 : : with_period);
11698 : :
11699 : : /* Done -- clean up (but keep the lock) */
11700 : 647 : table_close(partRel, NoLock);
11701 [ + + ]: 647 : if (map)
11702 : : {
11703 : 89 : pfree(mapped_pkattnum);
11704 : 89 : free_attrmap(map);
11705 : : }
11706 : : }
11707 : : }
11708 : 2326 : }
11709 : :
11710 : : /*
11711 : : * addFkRecurseReferencing
11712 : : * Recursive helper for the referencing side of foreign key creation,
11713 : : * which creates the check triggers and recurses
11714 : : *
11715 : : * If the referencing relation is a plain relation, create the necessary check
11716 : : * triggers that implement the constraint, and set up for Phase 3 constraint
11717 : : * verification. If the referencing relation is a partitioned table, then
11718 : : * we create a pg_constraint row for it and recurse on this routine for each
11719 : : * partition.
11720 : : *
11721 : : * We assume that the referenced relation is locked against concurrent
11722 : : * deletions. If it's a partitioned relation, every partition must be so
11723 : : * locked.
11724 : : *
11725 : : * wqueue: the ALTER TABLE work queue; NULL when not running as part
11726 : : * of an ALTER TABLE sequence.
11727 : : * fkconstraint: the constraint being added
11728 : : * rel: the referencing relation; might be a partition, if recursing
11729 : : * pkrel: the root referenced relation
11730 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
11731 : : * parentConstr: the OID of the parent constraint (there is always one)
11732 : : * numfks: the number of columns in the foreign key
11733 : : * pkattnum: the attnum array of referenced attributes
11734 : : * fkattnum: the attnum array of referencing attributes
11735 : : * pf/pp/ffeqoperators: OID array of operators between columns
11736 : : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
11737 : : * (...) clause
11738 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
11739 : : * NULL/DEFAULT clause
11740 : : * old_check_ok: true if this constraint replaces an existing one that
11741 : : * was already validated (thus this one doesn't need validation)
11742 : : * lockmode: the lockmode to acquire on partitions when recursing
11743 : : * parentInsTrigger and parentUpdTrigger: when being recursively called on
11744 : : * a partition, the OIDs of the parent check triggers for INSERT and
11745 : : * UPDATE respectively.
11746 : : * with_period: true if this is a temporal FK
11747 : : */
11748 : : static void
11749 : 2023 : addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
11750 : : Relation pkrel, Oid indexOid, Oid parentConstr,
11751 : : int numfks, int16 *pkattnum, int16 *fkattnum,
11752 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
11753 : : int numfkdelsetcols, int16 *fkdelsetcols,
11754 : : bool old_check_ok, LOCKMODE lockmode,
11755 : : Oid parentInsTrigger, Oid parentUpdTrigger,
11756 : : bool with_period)
11757 : : {
11758 : 2023 : Oid insertTriggerOid = InvalidOid,
11759 : 2023 : updateTriggerOid = InvalidOid;
11760 : :
11761 : : Assert(OidIsValid(parentConstr));
11762 : : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11763 : : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11764 : :
11765 [ - + ]: 2023 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11766 [ # # ]: 0 : ereport(ERROR,
11767 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11768 : : errmsg("foreign key constraints are not supported on foreign tables")));
11769 : :
11770 : : /*
11771 : : * Add check triggers if the constraint is ENFORCED, and if needed,
11772 : : * schedule them to be checked in Phase 3.
11773 : : *
11774 : : * If the relation is partitioned, drill down to do it to its partitions.
11775 : : */
11776 [ + + ]: 2023 : if (fkconstraint->is_enforced)
11777 : 1990 : createForeignKeyCheckTriggers(RelationGetRelid(rel),
11778 : : RelationGetRelid(pkrel),
11779 : : fkconstraint,
11780 : : parentConstr,
11781 : : indexOid,
11782 : : parentInsTrigger, parentUpdTrigger,
11783 : : &insertTriggerOid, &updateTriggerOid);
11784 : :
11785 [ + + ]: 2023 : if (rel->rd_rel->relkind == RELKIND_RELATION)
11786 : : {
11787 : : /*
11788 : : * Tell Phase 3 to check that the constraint is satisfied by existing
11789 : : * rows. We can skip this during table creation, when constraint is
11790 : : * specified as NOT ENFORCED, or when requested explicitly by
11791 : : * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
11792 : : * recreating a constraint following a SET DATA TYPE operation that
11793 : : * did not impugn its validity.
11794 : : */
11795 [ + + + + : 1714 : if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
+ + ]
11796 [ + - ]: 605 : fkconstraint->is_enforced)
11797 : : {
11798 : : NewConstraint *newcon;
11799 : : AlteredTableInfo *tab;
11800 : :
11801 : 605 : tab = ATGetQueueEntry(wqueue, rel);
11802 : :
11803 : 605 : newcon = palloc0_object(NewConstraint);
11804 : 605 : newcon->name = get_constraint_name(parentConstr);
11805 : 605 : newcon->contype = CONSTR_FOREIGN;
11806 : 605 : newcon->refrelid = RelationGetRelid(pkrel);
11807 : 605 : newcon->refindid = indexOid;
11808 : 605 : newcon->conid = parentConstr;
11809 : 605 : newcon->conwithperiod = fkconstraint->fk_with_period;
11810 : 605 : newcon->qual = (Node *) fkconstraint;
11811 : :
11812 : 605 : tab->constraints = lappend(tab->constraints, newcon);
11813 : : }
11814 : : }
11815 [ + - ]: 309 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11816 : : {
11817 : 309 : PartitionDesc pd = RelationGetPartitionDesc(rel, true);
11818 : : Relation trigrel;
11819 : :
11820 : : /*
11821 : : * Triggers of the foreign keys will be manipulated a bunch of times
11822 : : * in the loop below. To avoid repeatedly opening/closing the trigger
11823 : : * catalog relation, we open it here and pass it to the subroutines
11824 : : * called below.
11825 : : */
11826 : 309 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11827 : :
11828 : : /*
11829 : : * Recurse to take appropriate action on each partition; either we
11830 : : * find an existing constraint to reparent to ours, or we create a new
11831 : : * one.
11832 : : */
11833 [ + + ]: 590 : for (int i = 0; i < pd->nparts; i++)
11834 : : {
11835 : 285 : Relation partition = table_open(pd->oids[i], lockmode);
11836 : : List *partFKs;
11837 : : AttrMap *attmap;
11838 : : AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
11839 : : bool attached;
11840 : : ObjectAddress address;
11841 : :
11842 : 285 : CheckAlterTableIsSafe(partition);
11843 : :
11844 : 281 : attmap = build_attrmap_by_name(RelationGetDescr(partition),
11845 : : RelationGetDescr(rel),
11846 : : false);
11847 [ + + ]: 706 : for (int j = 0; j < numfks; j++)
11848 : 425 : mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
11849 : :
11850 : : /* Check whether an existing constraint can be repurposed */
11851 : 281 : partFKs = copyObject(RelationGetFKeyList(partition));
11852 : 281 : attached = false;
11853 [ + + + + : 571 : foreach_node(ForeignKeyCacheInfo, fk, partFKs)
+ + ]
11854 : : {
11855 [ + + ]: 17 : if (tryAttachPartitionForeignKey(wqueue,
11856 : : fk,
11857 : : partition,
11858 : : parentConstr,
11859 : : numfks,
11860 : : mapped_fkattnum,
11861 : : pkattnum,
11862 : : pfeqoperators,
11863 : : insertTriggerOid,
11864 : : updateTriggerOid,
11865 : : trigrel))
11866 : : {
11867 : 8 : attached = true;
11868 : 8 : break;
11869 : : }
11870 : : }
11871 [ + + ]: 281 : if (attached)
11872 : : {
11873 : 8 : table_close(partition, NoLock);
11874 : 8 : continue;
11875 : : }
11876 : :
11877 : : /*
11878 : : * No luck finding a good constraint to reuse; create our own.
11879 : : */
11880 : 273 : address = addFkConstraint(addFkReferencingSide,
11881 : : fkconstraint->conname, fkconstraint,
11882 : : partition, pkrel, indexOid, parentConstr,
11883 : : numfks, pkattnum,
11884 : : mapped_fkattnum, pfeqoperators,
11885 : : ppeqoperators, ffeqoperators,
11886 : : numfkdelsetcols, fkdelsetcols, true,
11887 : : with_period);
11888 : :
11889 : : /* call ourselves to finalize the creation and we're done */
11890 : 273 : addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
11891 : : indexOid,
11892 : : address.objectId,
11893 : : numfks,
11894 : : pkattnum,
11895 : : mapped_fkattnum,
11896 : : pfeqoperators,
11897 : : ppeqoperators,
11898 : : ffeqoperators,
11899 : : numfkdelsetcols,
11900 : : fkdelsetcols,
11901 : : old_check_ok,
11902 : : lockmode,
11903 : : insertTriggerOid,
11904 : : updateTriggerOid,
11905 : : with_period);
11906 : :
11907 : 273 : table_close(partition, NoLock);
11908 : : }
11909 : :
11910 : 305 : table_close(trigrel, RowExclusiveLock);
11911 : : }
11912 : 2019 : }
11913 : :
11914 : : /*
11915 : : * CloneForeignKeyConstraints
11916 : : * Clone foreign keys from a partitioned table to a newly acquired
11917 : : * partition.
11918 : : *
11919 : : * partitionRel is a partition of parentRel, so we can be certain that it has
11920 : : * the same columns with the same datatypes. The columns may be in different
11921 : : * order, though.
11922 : : *
11923 : : * wqueue must be passed to set up phase 3 constraint checking, unless the
11924 : : * referencing-side partition is known to be empty (such as in CREATE TABLE /
11925 : : * PARTITION OF).
11926 : : */
11927 : : static void
11928 : 7192 : CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
11929 : : Relation partitionRel)
11930 : : {
11931 : : /* This only works for declarative partitioning */
11932 : : Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
11933 : :
11934 : : /*
11935 : : * First, clone constraints where the parent is on the referencing side.
11936 : : */
11937 : 7192 : CloneFkReferencing(wqueue, parentRel, partitionRel);
11938 : :
11939 : : /*
11940 : : * Clone constraints for which the parent is on the referenced side.
11941 : : */
11942 : 7180 : CloneFkReferenced(parentRel, partitionRel);
11943 : 7180 : }
11944 : :
11945 : : /*
11946 : : * CloneFkReferenced
11947 : : * Subroutine for CloneForeignKeyConstraints
11948 : : *
11949 : : * Find all the FKs that have the parent relation on the referenced side;
11950 : : * clone those constraints to the given partition. This is to be called
11951 : : * when the partition is being created or attached.
11952 : : *
11953 : : * This recurses to partitions, if the relation being attached is partitioned.
11954 : : * Recursion is done by calling addFkRecurseReferenced.
11955 : : */
11956 : : static void
11957 : 7180 : CloneFkReferenced(Relation parentRel, Relation partitionRel)
11958 : : {
11959 : : Relation pg_constraint;
11960 : : AttrMap *attmap;
11961 : : ListCell *cell;
11962 : : SysScanDesc scan;
11963 : : ScanKeyData key;
11964 : : HeapTuple tuple;
11965 : 7180 : List *clone = NIL;
11966 : : Relation trigrel;
11967 : :
11968 : : /*
11969 : : * Search for any constraints where this partition's parent is in the
11970 : : * referenced side. However, we must not clone any constraint whose
11971 : : * parent constraint is also going to be cloned, to avoid duplicates. So
11972 : : * do it in two steps: first construct the list of constraints to clone,
11973 : : * then go over that list cloning those whose parents are not in the list.
11974 : : * (We must not rely on the parent being seen first, since the catalog
11975 : : * scan could return children first.)
11976 : : */
11977 : 7180 : pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11978 : 7180 : ScanKeyInit(&key,
11979 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
11980 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
11981 : :
11982 : : /*
11983 : : * Scan pg_constraint using the index on confrelid, which is only set
11984 : : * nonzero by FK constraints. Filtering on contype in the loop is
11985 : : * therefore just a safety check.
11986 : : */
11987 : 7180 : scan = systable_beginscan(pg_constraint, ConstraintForeignRelIndexId, true,
11988 : : NULL, 1, &key);
11989 [ + + ]: 7432 : while ((tuple = systable_getnext(scan)) != NULL)
11990 : : {
11991 : 252 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11992 : :
11993 [ - + ]: 252 : if (constrForm->contype != CONSTRAINT_FOREIGN)
11994 : 0 : continue;
11995 : 252 : clone = lappend_oid(clone, constrForm->oid);
11996 : : }
11997 : 7180 : systable_endscan(scan);
11998 : 7180 : table_close(pg_constraint, RowShareLock);
11999 : :
12000 : : /*
12001 : : * Triggers of the foreign keys will be manipulated a bunch of times in
12002 : : * the loop below. To avoid repeatedly opening/closing the trigger
12003 : : * catalog relation, we open it here and pass it to the subroutines called
12004 : : * below.
12005 : : */
12006 : 7180 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
12007 : :
12008 : 7180 : attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
12009 : : RelationGetDescr(parentRel),
12010 : : false);
12011 [ + + + + : 7432 : foreach(cell, clone)
+ + ]
12012 : : {
12013 : 252 : Oid constrOid = lfirst_oid(cell);
12014 : : Form_pg_constraint constrForm;
12015 : : Relation fkRel;
12016 : : Oid indexOid;
12017 : : Oid partIndexId;
12018 : : int numfks;
12019 : : AttrNumber conkey[INDEX_MAX_KEYS];
12020 : : AttrNumber mapped_confkey[INDEX_MAX_KEYS];
12021 : : AttrNumber confkey[INDEX_MAX_KEYS];
12022 : : Oid conpfeqop[INDEX_MAX_KEYS];
12023 : : Oid conppeqop[INDEX_MAX_KEYS];
12024 : : Oid conffeqop[INDEX_MAX_KEYS];
12025 : : int numfkdelsetcols;
12026 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
12027 : : Constraint *fkconstraint;
12028 : : ObjectAddress address;
12029 : 252 : Oid deleteTriggerOid = InvalidOid,
12030 : 252 : updateTriggerOid = InvalidOid;
12031 : :
12032 : 252 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
12033 [ - + ]: 252 : if (!HeapTupleIsValid(tuple))
12034 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
12035 : 252 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
12036 : :
12037 : : /*
12038 : : * As explained above: don't try to clone a constraint for which we're
12039 : : * going to clone the parent.
12040 : : */
12041 [ + + ]: 252 : if (list_member_oid(clone, constrForm->conparentid))
12042 : : {
12043 : 148 : ReleaseSysCache(tuple);
12044 : 148 : continue;
12045 : : }
12046 : :
12047 : : /* We need the same lock level that CreateTrigger will acquire */
12048 : 104 : fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
12049 : :
12050 : 104 : indexOid = constrForm->conindid;
12051 : 104 : DeconstructFkConstraintRow(tuple,
12052 : : &numfks,
12053 : : conkey,
12054 : : confkey,
12055 : : conpfeqop,
12056 : : conppeqop,
12057 : : conffeqop,
12058 : : &numfkdelsetcols,
12059 : : confdelsetcols);
12060 : :
12061 [ + + ]: 236 : for (int i = 0; i < numfks; i++)
12062 : 132 : mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
12063 : :
12064 : 104 : fkconstraint = makeNode(Constraint);
12065 : 104 : fkconstraint->contype = CONSTRAINT_FOREIGN;
12066 : 104 : fkconstraint->conname = NameStr(constrForm->conname);
12067 : 104 : fkconstraint->deferrable = constrForm->condeferrable;
12068 : 104 : fkconstraint->initdeferred = constrForm->condeferred;
12069 : 104 : fkconstraint->location = -1;
12070 : 104 : fkconstraint->pktable = NULL;
12071 : : /* ->fk_attrs determined below */
12072 : 104 : fkconstraint->pk_attrs = NIL;
12073 : 104 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
12074 : 104 : fkconstraint->fk_upd_action = constrForm->confupdtype;
12075 : 104 : fkconstraint->fk_del_action = constrForm->confdeltype;
12076 : 104 : fkconstraint->fk_del_set_cols = NIL;
12077 : 104 : fkconstraint->old_conpfeqop = NIL;
12078 : 104 : fkconstraint->old_pktable_oid = InvalidOid;
12079 : 104 : fkconstraint->is_enforced = constrForm->conenforced;
12080 : 104 : fkconstraint->skip_validation = false;
12081 : 104 : fkconstraint->initially_valid = constrForm->convalidated;
12082 : :
12083 : : /* set up colnames that are used to generate the constraint name */
12084 [ + + ]: 236 : for (int i = 0; i < numfks; i++)
12085 : : {
12086 : : Form_pg_attribute att;
12087 : :
12088 : 132 : att = TupleDescAttr(RelationGetDescr(fkRel),
12089 : 132 : conkey[i] - 1);
12090 : 132 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
12091 : 132 : makeString(NameStr(att->attname)));
12092 : : }
12093 : :
12094 : : /*
12095 : : * Add the new foreign key constraint pointing to the new partition.
12096 : : * Because this new partition appears in the referenced side of the
12097 : : * constraint, we don't need to set up for Phase 3 check.
12098 : : */
12099 : 104 : partIndexId = index_get_partition(partitionRel, indexOid);
12100 [ - + ]: 104 : if (!OidIsValid(partIndexId))
12101 [ # # ]: 0 : elog(ERROR, "index for %u not found in partition %s",
12102 : : indexOid, RelationGetRelationName(partitionRel));
12103 : :
12104 : : /*
12105 : : * Get the "action" triggers belonging to the constraint to pass as
12106 : : * parent OIDs for similar triggers that will be created on the
12107 : : * partition in addFkRecurseReferenced().
12108 : : */
12109 [ + - ]: 104 : if (constrForm->conenforced)
12110 : 104 : GetForeignKeyActionTriggers(trigrel, constrOid,
12111 : : constrForm->confrelid, constrForm->conrelid,
12112 : : &deleteTriggerOid, &updateTriggerOid);
12113 : :
12114 : : /* Add this constraint ... */
12115 : 104 : address = addFkConstraint(addFkReferencedSide,
12116 : : fkconstraint->conname, fkconstraint, fkRel,
12117 : : partitionRel, partIndexId, constrOid,
12118 : : numfks, mapped_confkey,
12119 : : conkey, conpfeqop, conppeqop, conffeqop,
12120 : : numfkdelsetcols, confdelsetcols, false,
12121 : 104 : constrForm->conperiod);
12122 : : /* ... and recurse */
12123 : 104 : addFkRecurseReferenced(fkconstraint,
12124 : : fkRel,
12125 : : partitionRel,
12126 : : partIndexId,
12127 : : address.objectId,
12128 : : numfks,
12129 : : mapped_confkey,
12130 : : conkey,
12131 : : conpfeqop,
12132 : : conppeqop,
12133 : : conffeqop,
12134 : : numfkdelsetcols,
12135 : : confdelsetcols,
12136 : : true,
12137 : : deleteTriggerOid,
12138 : : updateTriggerOid,
12139 : 104 : constrForm->conperiod);
12140 : :
12141 : 104 : table_close(fkRel, NoLock);
12142 : 104 : ReleaseSysCache(tuple);
12143 : : }
12144 : :
12145 : 7180 : table_close(trigrel, RowExclusiveLock);
12146 : 7180 : }
12147 : :
12148 : : /*
12149 : : * CloneFkReferencing
12150 : : * Subroutine for CloneForeignKeyConstraints
12151 : : *
12152 : : * For each FK constraint of the parent relation in the given list, find an
12153 : : * equivalent constraint in its partition relation that can be reparented;
12154 : : * if one cannot be found, create a new constraint in the partition as its
12155 : : * child.
12156 : : *
12157 : : * If wqueue is given, it is used to set up phase-3 verification for each
12158 : : * cloned constraint; omit it if such verification is not needed
12159 : : * (example: the partition is being created anew).
12160 : : */
12161 : : static void
12162 : 7192 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
12163 : : {
12164 : : AttrMap *attmap;
12165 : : List *partFKs;
12166 : 7192 : List *clone = NIL;
12167 : : ListCell *cell;
12168 : : Relation trigrel;
12169 : :
12170 : : /* obtain a list of constraints that we need to clone */
12171 [ + + + + : 7979 : foreach(cell, RelationGetFKeyList(parentRel))
+ + ]
12172 : : {
12173 : 791 : ForeignKeyCacheInfo *fk = lfirst(cell);
12174 : :
12175 : : /*
12176 : : * Refuse to attach a table as partition that this partitioned table
12177 : : * already has a foreign key to. This isn't useful schema, which is
12178 : : * proven by the fact that there have been no user complaints that
12179 : : * it's already impossible to achieve this in the opposite direction,
12180 : : * i.e., creating a foreign key that references a partition. This
12181 : : * restriction allows us to dodge some complexities around
12182 : : * pg_constraint and pg_trigger row creations that would be needed
12183 : : * during ATTACH/DETACH for this kind of relationship.
12184 : : */
12185 [ + + ]: 791 : if (fk->confrelid == RelationGetRelid(partRel))
12186 [ + - ]: 4 : ereport(ERROR,
12187 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12188 : : errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
12189 : : RelationGetRelationName(partRel),
12190 : : get_constraint_name(fk->conoid))));
12191 : :
12192 : 787 : clone = lappend_oid(clone, fk->conoid);
12193 : : }
12194 : :
12195 : : /*
12196 : : * Silently do nothing if there's nothing to do. In particular, this
12197 : : * avoids throwing a spurious error for foreign tables.
12198 : : */
12199 [ + + ]: 7188 : if (clone == NIL)
12200 : 6865 : return;
12201 : :
12202 [ - + ]: 323 : if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
12203 [ # # ]: 0 : ereport(ERROR,
12204 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12205 : : errmsg("foreign key constraints are not supported on foreign tables")));
12206 : :
12207 : : /*
12208 : : * Triggers of the foreign keys will be manipulated a bunch of times in
12209 : : * the loop below. To avoid repeatedly opening/closing the trigger
12210 : : * catalog relation, we open it here and pass it to the subroutines called
12211 : : * below.
12212 : : */
12213 : 323 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
12214 : :
12215 : : /*
12216 : : * The constraint key may differ, if the columns in the partition are
12217 : : * different. This map is used to convert them.
12218 : : */
12219 : 323 : attmap = build_attrmap_by_name(RelationGetDescr(partRel),
12220 : : RelationGetDescr(parentRel),
12221 : : false);
12222 : :
12223 : 323 : partFKs = copyObject(RelationGetFKeyList(partRel));
12224 : :
12225 [ + - + + : 1102 : foreach(cell, clone)
+ + ]
12226 : : {
12227 : 787 : Oid parentConstrOid = lfirst_oid(cell);
12228 : : Form_pg_constraint constrForm;
12229 : : Relation pkrel;
12230 : : HeapTuple tuple;
12231 : : int numfks;
12232 : : AttrNumber conkey[INDEX_MAX_KEYS];
12233 : : AttrNumber mapped_conkey[INDEX_MAX_KEYS];
12234 : : AttrNumber confkey[INDEX_MAX_KEYS];
12235 : : Oid conpfeqop[INDEX_MAX_KEYS];
12236 : : Oid conppeqop[INDEX_MAX_KEYS];
12237 : : Oid conffeqop[INDEX_MAX_KEYS];
12238 : : int numfkdelsetcols;
12239 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
12240 : : Constraint *fkconstraint;
12241 : : bool attached;
12242 : : Oid indexOid;
12243 : : ObjectAddress address;
12244 : : ListCell *lc;
12245 : 787 : Oid insertTriggerOid = InvalidOid,
12246 : 787 : updateTriggerOid = InvalidOid;
12247 : : bool with_period;
12248 : :
12249 : 787 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
12250 [ - + ]: 787 : if (!HeapTupleIsValid(tuple))
12251 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
12252 : : parentConstrOid);
12253 : 787 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
12254 : :
12255 : : /* Don't clone constraints whose parents are being cloned */
12256 [ + + ]: 787 : if (list_member_oid(clone, constrForm->conparentid))
12257 : : {
12258 : 440 : ReleaseSysCache(tuple);
12259 : 540 : continue;
12260 : : }
12261 : :
12262 : : /*
12263 : : * Need to prevent concurrent deletions. If pkrel is a partitioned
12264 : : * relation, that means to lock all partitions.
12265 : : */
12266 : 347 : pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
12267 [ + + ]: 347 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12268 : 148 : (void) find_all_inheritors(RelationGetRelid(pkrel),
12269 : : ShareRowExclusiveLock, NULL);
12270 : :
12271 : 347 : DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
12272 : : conpfeqop, conppeqop, conffeqop,
12273 : : &numfkdelsetcols, confdelsetcols);
12274 [ + + ]: 850 : for (int i = 0; i < numfks; i++)
12275 : 503 : mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
12276 : :
12277 : : /*
12278 : : * Get the "check" triggers belonging to the constraint, if it is
12279 : : * ENFORCED, to pass as parent OIDs for similar triggers that will be
12280 : : * created on the partition in addFkRecurseReferencing(). They are
12281 : : * also passed to tryAttachPartitionForeignKey() below to simply
12282 : : * assign as parents to the partition's existing "check" triggers,
12283 : : * that is, if the corresponding constraints is deemed attachable to
12284 : : * the parent constraint.
12285 : : */
12286 [ + + ]: 347 : if (constrForm->conenforced)
12287 : 339 : GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
12288 : : constrForm->confrelid, constrForm->conrelid,
12289 : : &insertTriggerOid, &updateTriggerOid);
12290 : :
12291 : : /*
12292 : : * Before creating a new constraint, see whether any existing FKs are
12293 : : * fit for the purpose. If one is, attach the parent constraint to
12294 : : * it, and don't clone anything. This way we avoid the expensive
12295 : : * verification step and don't end up with a duplicate FK, and we
12296 : : * don't need to recurse to partitions for this constraint.
12297 : : */
12298 : 347 : attached = false;
12299 [ + + + + : 407 : foreach(lc, partFKs)
+ + ]
12300 : : {
12301 : 164 : ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
12302 : :
12303 [ + + ]: 164 : if (tryAttachPartitionForeignKey(wqueue,
12304 : : fk,
12305 : : partRel,
12306 : : parentConstrOid,
12307 : : numfks,
12308 : : mapped_conkey,
12309 : : confkey,
12310 : : conpfeqop,
12311 : : insertTriggerOid,
12312 : : updateTriggerOid,
12313 : : trigrel))
12314 : : {
12315 : 100 : attached = true;
12316 : 100 : table_close(pkrel, NoLock);
12317 : 100 : break;
12318 : : }
12319 : : }
12320 [ + + ]: 343 : if (attached)
12321 : : {
12322 : 100 : ReleaseSysCache(tuple);
12323 : 100 : continue;
12324 : : }
12325 : :
12326 : : /* No dice. Set up to create our own constraint */
12327 : 243 : fkconstraint = makeNode(Constraint);
12328 : 243 : fkconstraint->contype = CONSTRAINT_FOREIGN;
12329 : : /* ->conname determined below */
12330 : 243 : fkconstraint->deferrable = constrForm->condeferrable;
12331 : 243 : fkconstraint->initdeferred = constrForm->condeferred;
12332 : 243 : fkconstraint->location = -1;
12333 : 243 : fkconstraint->pktable = NULL;
12334 : : /* ->fk_attrs determined below */
12335 : 243 : fkconstraint->pk_attrs = NIL;
12336 : 243 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
12337 : 243 : fkconstraint->fk_upd_action = constrForm->confupdtype;
12338 : 243 : fkconstraint->fk_del_action = constrForm->confdeltype;
12339 : 243 : fkconstraint->fk_del_set_cols = NIL;
12340 : 243 : fkconstraint->old_conpfeqop = NIL;
12341 : 243 : fkconstraint->old_pktable_oid = InvalidOid;
12342 : 243 : fkconstraint->is_enforced = constrForm->conenforced;
12343 : 243 : fkconstraint->skip_validation = false;
12344 : 243 : fkconstraint->initially_valid = constrForm->convalidated;
12345 [ + + ]: 566 : for (int i = 0; i < numfks; i++)
12346 : : {
12347 : : Form_pg_attribute att;
12348 : :
12349 : 323 : att = TupleDescAttr(RelationGetDescr(partRel),
12350 : 323 : mapped_conkey[i] - 1);
12351 : 323 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
12352 : 323 : makeString(NameStr(att->attname)));
12353 : : }
12354 : :
12355 : 243 : indexOid = constrForm->conindid;
12356 : 243 : with_period = constrForm->conperiod;
12357 : :
12358 : : /* Create the pg_constraint entry at this level */
12359 : 243 : address = addFkConstraint(addFkReferencingSide,
12360 : 243 : NameStr(constrForm->conname), fkconstraint,
12361 : : partRel, pkrel, indexOid, parentConstrOid,
12362 : : numfks, confkey,
12363 : : mapped_conkey, conpfeqop,
12364 : : conppeqop, conffeqop,
12365 : : numfkdelsetcols, confdelsetcols,
12366 : : false, with_period);
12367 : :
12368 : : /* Done with the cloned constraint's tuple */
12369 : 243 : ReleaseSysCache(tuple);
12370 : :
12371 : : /* Create the check triggers, and recurse to partitions, if any */
12372 : 243 : addFkRecurseReferencing(wqueue,
12373 : : fkconstraint,
12374 : : partRel,
12375 : : pkrel,
12376 : : indexOid,
12377 : : address.objectId,
12378 : : numfks,
12379 : : confkey,
12380 : : mapped_conkey,
12381 : : conpfeqop,
12382 : : conppeqop,
12383 : : conffeqop,
12384 : : numfkdelsetcols,
12385 : : confdelsetcols,
12386 : : false, /* no old check exists */
12387 : : AccessExclusiveLock,
12388 : : insertTriggerOid,
12389 : : updateTriggerOid,
12390 : : with_period);
12391 : 239 : table_close(pkrel, NoLock);
12392 : : }
12393 : :
12394 : 315 : table_close(trigrel, RowExclusiveLock);
12395 : : }
12396 : :
12397 : : /*
12398 : : * When the parent of a partition receives [the referencing side of] a foreign
12399 : : * key, we must propagate that foreign key to the partition. However, the
12400 : : * partition might already have an equivalent foreign key; this routine
12401 : : * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
12402 : : * by the other parameters. If they are equivalent, create the link between
12403 : : * the two constraints and return true.
12404 : : *
12405 : : * If the given FK does not match the one defined by rest of the params,
12406 : : * return false.
12407 : : */
12408 : : static bool
12409 : 181 : tryAttachPartitionForeignKey(List **wqueue,
12410 : : ForeignKeyCacheInfo *fk,
12411 : : Relation partition,
12412 : : Oid parentConstrOid,
12413 : : int numfks,
12414 : : AttrNumber *mapped_conkey,
12415 : : AttrNumber *confkey,
12416 : : Oid *conpfeqop,
12417 : : Oid parentInsTrigger,
12418 : : Oid parentUpdTrigger,
12419 : : Relation trigrel)
12420 : : {
12421 : : HeapTuple parentConstrTup;
12422 : : Form_pg_constraint parentConstr;
12423 : : HeapTuple partcontup;
12424 : : Form_pg_constraint partConstr;
12425 : :
12426 : 181 : parentConstrTup = SearchSysCache1(CONSTROID,
12427 : : ObjectIdGetDatum(parentConstrOid));
12428 [ - + ]: 181 : if (!HeapTupleIsValid(parentConstrTup))
12429 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
12430 : 181 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
12431 : :
12432 : : /*
12433 : : * Do some quick & easy initial checks. If any of these fail, we cannot
12434 : : * use this constraint.
12435 : : */
12436 [ + - - + ]: 181 : if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
12437 : : {
12438 : 0 : ReleaseSysCache(parentConstrTup);
12439 : 0 : return false;
12440 : : }
12441 [ + + ]: 503 : for (int i = 0; i < numfks; i++)
12442 : : {
12443 [ + - ]: 322 : if (fk->conkey[i] != mapped_conkey[i] ||
12444 [ + - ]: 322 : fk->confkey[i] != confkey[i] ||
12445 [ - + ]: 322 : fk->conpfeqop[i] != conpfeqop[i])
12446 : : {
12447 : 0 : ReleaseSysCache(parentConstrTup);
12448 : 0 : return false;
12449 : : }
12450 : : }
12451 : :
12452 : : /* Looks good so far; perform more extensive checks. */
12453 : 181 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
12454 [ - + ]: 181 : if (!HeapTupleIsValid(partcontup))
12455 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
12456 : 181 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
12457 : :
12458 : : /*
12459 : : * An error should be raised if the constraint enforceability is
12460 : : * different. Returning false without raising an error, as we do for other
12461 : : * attributes, could lead to a duplicate constraint with the same
12462 : : * enforceability as the parent. While this may be acceptable, it may not
12463 : : * be ideal. Therefore, it's better to raise an error and allow the user
12464 : : * to correct the enforceability before proceeding.
12465 : : */
12466 [ + + ]: 181 : if (partConstr->conenforced != parentConstr->conenforced)
12467 [ + - ]: 4 : ereport(ERROR,
12468 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
12469 : : errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
12470 : : NameStr(parentConstr->conname),
12471 : : NameStr(partConstr->conname),
12472 : : RelationGetRelationName(partition))));
12473 : :
12474 [ + + ]: 177 : if (OidIsValid(partConstr->conparentid) ||
12475 [ + + ]: 158 : partConstr->condeferrable != parentConstr->condeferrable ||
12476 [ + - ]: 140 : partConstr->condeferred != parentConstr->condeferred ||
12477 [ + + ]: 140 : partConstr->confupdtype != parentConstr->confupdtype ||
12478 [ + - ]: 117 : partConstr->confdeltype != parentConstr->confdeltype ||
12479 [ + + ]: 117 : partConstr->confmatchtype != parentConstr->confmatchtype)
12480 : : {
12481 : 69 : ReleaseSysCache(parentConstrTup);
12482 : 69 : ReleaseSysCache(partcontup);
12483 : 69 : return false;
12484 : : }
12485 : :
12486 : 108 : ReleaseSysCache(parentConstrTup);
12487 : 108 : ReleaseSysCache(partcontup);
12488 : :
12489 : : /* Looks good! Attach this constraint. */
12490 : 108 : AttachPartitionForeignKey(wqueue, partition, fk->conoid,
12491 : : parentConstrOid, parentInsTrigger,
12492 : : parentUpdTrigger, trigrel);
12493 : :
12494 : 108 : return true;
12495 : : }
12496 : :
12497 : : /*
12498 : : * AttachPartitionForeignKey
12499 : : *
12500 : : * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
12501 : : * attaching the constraint, removing redundant triggers and entries from
12502 : : * pg_constraint, and setting the constraint's parent.
12503 : : */
12504 : : static void
12505 : 108 : AttachPartitionForeignKey(List **wqueue,
12506 : : Relation partition,
12507 : : Oid partConstrOid,
12508 : : Oid parentConstrOid,
12509 : : Oid parentInsTrigger,
12510 : : Oid parentUpdTrigger,
12511 : : Relation trigrel)
12512 : : {
12513 : : HeapTuple parentConstrTup;
12514 : : Form_pg_constraint parentConstr;
12515 : : HeapTuple partcontup;
12516 : : Form_pg_constraint partConstr;
12517 : : bool queueValidation;
12518 : : Oid partConstrFrelid;
12519 : : Oid partConstrRelid;
12520 : : bool parentConstrIsEnforced;
12521 : :
12522 : : /* Fetch the parent constraint tuple */
12523 : 108 : parentConstrTup = SearchSysCache1(CONSTROID,
12524 : : ObjectIdGetDatum(parentConstrOid));
12525 [ - + ]: 108 : if (!HeapTupleIsValid(parentConstrTup))
12526 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
12527 : 108 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
12528 : 108 : parentConstrIsEnforced = parentConstr->conenforced;
12529 : :
12530 : : /* Fetch the child constraint tuple */
12531 : 108 : partcontup = SearchSysCache1(CONSTROID,
12532 : : ObjectIdGetDatum(partConstrOid));
12533 [ - + ]: 108 : if (!HeapTupleIsValid(partcontup))
12534 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
12535 : 108 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
12536 : 108 : partConstrFrelid = partConstr->confrelid;
12537 : 108 : partConstrRelid = partConstr->conrelid;
12538 : :
12539 : : /*
12540 : : * If the referenced table is partitioned, then the partition we're
12541 : : * attaching now has extra pg_constraint rows and action triggers that are
12542 : : * no longer needed. Remove those.
12543 : : */
12544 [ + + ]: 108 : if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
12545 : : {
12546 : 24 : Relation pg_constraint = table_open(ConstraintRelationId, RowShareLock);
12547 : :
12548 : 24 : RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
12549 : : partConstrRelid);
12550 : :
12551 : 24 : table_close(pg_constraint, RowShareLock);
12552 : : }
12553 : :
12554 : : /*
12555 : : * Will we need to validate this constraint? A valid parent constraint
12556 : : * implies that all child constraints have been validated, so if this one
12557 : : * isn't, we must trigger phase 3 validation.
12558 : : */
12559 [ + + + + ]: 108 : queueValidation = parentConstr->convalidated && !partConstr->convalidated;
12560 : :
12561 : 108 : ReleaseSysCache(partcontup);
12562 : 108 : ReleaseSysCache(parentConstrTup);
12563 : :
12564 : : /*
12565 : : * The action triggers in the new partition become redundant -- the parent
12566 : : * table already has equivalent ones, and those will be able to reach the
12567 : : * partition. Remove the ones in the partition. We identify them because
12568 : : * they have our constraint OID, as well as being on the referenced rel.
12569 : : */
12570 : 108 : DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
12571 : : partConstrRelid);
12572 : :
12573 : 108 : ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
12574 : : RelationGetRelid(partition));
12575 : :
12576 : : /*
12577 : : * Like the constraint, attach partition's "check" triggers to the
12578 : : * corresponding parent triggers if the constraint is ENFORCED. NOT
12579 : : * ENFORCED constraints do not have these triggers.
12580 : : */
12581 [ + + ]: 108 : if (parentConstrIsEnforced)
12582 : : {
12583 : : Oid insertTriggerOid,
12584 : : updateTriggerOid;
12585 : :
12586 : 100 : GetForeignKeyCheckTriggers(trigrel,
12587 : : partConstrOid, partConstrFrelid, partConstrRelid,
12588 : : &insertTriggerOid, &updateTriggerOid);
12589 : : Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
12590 : 100 : TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
12591 : : RelationGetRelid(partition));
12592 : : Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
12593 : 100 : TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
12594 : : RelationGetRelid(partition));
12595 : : }
12596 : :
12597 : : /*
12598 : : * We updated this pg_constraint row above to set its parent; validating
12599 : : * it will cause its convalidated flag to change, so we need CCI here. In
12600 : : * addition, we need it unconditionally for the rare case where the parent
12601 : : * table has *two* identical constraints; when reaching this function for
12602 : : * the second one, we must have made our changes visible, otherwise we
12603 : : * would try to attach both to this one.
12604 : : */
12605 : 108 : CommandCounterIncrement();
12606 : :
12607 : : /* If validation is needed, put it in the queue now. */
12608 [ + + ]: 108 : if (queueValidation)
12609 : : {
12610 : : Relation conrel;
12611 : : Oid confrelid;
12612 : :
12613 : 12 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12614 : :
12615 : 12 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
12616 [ - + ]: 12 : if (!HeapTupleIsValid(partcontup))
12617 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
12618 : :
12619 : 12 : confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
12620 : :
12621 : : /* Use the same lock as for AT_ValidateConstraint */
12622 : 12 : QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
12623 : : partcontup, ShareUpdateExclusiveLock);
12624 : 12 : ReleaseSysCache(partcontup);
12625 : 12 : table_close(conrel, RowExclusiveLock);
12626 : : }
12627 : 108 : }
12628 : :
12629 : : /*
12630 : : * RemoveInheritedConstraint
12631 : : *
12632 : : * Removes the constraint and its associated trigger from the specified
12633 : : * relation, which inherited the given constraint.
12634 : : */
12635 : : static void
12636 : 24 : RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
12637 : : Oid conrelid)
12638 : : {
12639 : : ObjectAddresses *objs;
12640 : : HeapTuple consttup;
12641 : : ScanKeyData key;
12642 : : SysScanDesc scan;
12643 : : HeapTuple trigtup;
12644 : :
12645 : 24 : ScanKeyInit(&key,
12646 : : Anum_pg_constraint_conrelid,
12647 : : BTEqualStrategyNumber, F_OIDEQ,
12648 : : ObjectIdGetDatum(conrelid));
12649 : :
12650 : 24 : scan = systable_beginscan(conrel,
12651 : : ConstraintRelidTypidNameIndexId,
12652 : : true, NULL, 1, &key);
12653 : 24 : objs = new_object_addresses();
12654 [ + + ]: 216 : while ((consttup = systable_getnext(scan)) != NULL)
12655 : : {
12656 : 192 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
12657 : :
12658 [ + + ]: 192 : if (conform->conparentid != conoid)
12659 : 140 : continue;
12660 : : else
12661 : : {
12662 : : ObjectAddress addr;
12663 : : SysScanDesc scan2;
12664 : : ScanKeyData key2;
12665 : : int n PG_USED_FOR_ASSERTS_ONLY;
12666 : :
12667 : 52 : ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
12668 : 52 : add_exact_object_address(&addr, objs);
12669 : :
12670 : : /*
12671 : : * First we must delete the dependency record that binds the
12672 : : * constraint records together.
12673 : : */
12674 : 52 : n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
12675 : : conform->oid,
12676 : : DEPENDENCY_INTERNAL,
12677 : : ConstraintRelationId,
12678 : : conoid);
12679 : : Assert(n == 1); /* actually only one is expected */
12680 : :
12681 : : /*
12682 : : * Now search for the triggers for this constraint and set them up
12683 : : * for deletion too
12684 : : */
12685 : 52 : ScanKeyInit(&key2,
12686 : : Anum_pg_trigger_tgconstraint,
12687 : : BTEqualStrategyNumber, F_OIDEQ,
12688 : : ObjectIdGetDatum(conform->oid));
12689 : 52 : scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
12690 : : true, NULL, 1, &key2);
12691 [ + + ]: 156 : while ((trigtup = systable_getnext(scan2)) != NULL)
12692 : : {
12693 : 104 : ObjectAddressSet(addr, TriggerRelationId,
12694 : : ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
12695 : 104 : add_exact_object_address(&addr, objs);
12696 : : }
12697 : 52 : systable_endscan(scan2);
12698 : : }
12699 : : }
12700 : : /* make the dependency deletions visible */
12701 : 24 : CommandCounterIncrement();
12702 : 24 : performMultipleDeletions(objs, DROP_RESTRICT,
12703 : : PERFORM_DELETION_INTERNAL);
12704 : 24 : systable_endscan(scan);
12705 : 24 : }
12706 : :
12707 : : /*
12708 : : * DropForeignKeyConstraintTriggers
12709 : : *
12710 : : * The subroutine for tryAttachPartitionForeignKey handles the deletion of
12711 : : * action triggers for the foreign key constraint.
12712 : : *
12713 : : * If valid confrelid and conrelid values are not provided, the respective
12714 : : * trigger check will be skipped, and the trigger will be considered for
12715 : : * removal.
12716 : : */
12717 : : static void
12718 : 160 : DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
12719 : : Oid conrelid)
12720 : : {
12721 : : ScanKeyData key;
12722 : : SysScanDesc scan;
12723 : : HeapTuple trigtup;
12724 : :
12725 : 160 : ScanKeyInit(&key,
12726 : : Anum_pg_trigger_tgconstraint,
12727 : : BTEqualStrategyNumber, F_OIDEQ,
12728 : : ObjectIdGetDatum(conoid));
12729 : 160 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12730 : : NULL, 1, &key);
12731 [ + + ]: 696 : while ((trigtup = systable_getnext(scan)) != NULL)
12732 : : {
12733 : 536 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12734 : : ObjectAddress trigger;
12735 : :
12736 : : /* Invalid if trigger is not for a referential integrity constraint */
12737 [ - + ]: 536 : if (!OidIsValid(trgform->tgconstrrelid))
12738 : 200 : continue;
12739 [ + + + + ]: 536 : if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
12740 : 200 : continue;
12741 [ + + - + ]: 336 : if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
12742 : 0 : continue;
12743 : :
12744 : : /* We should be dropping trigger related to foreign key constraint */
12745 : : Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
12746 : : trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
12747 : : trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
12748 : : trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
12749 : : trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
12750 : : trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
12751 : : trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
12752 : : trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
12753 : : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
12754 : : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
12755 : : trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
12756 : : trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
12757 : :
12758 : : /*
12759 : : * The constraint is originally set up to contain this trigger as an
12760 : : * implementation object, so there's a dependency record that links
12761 : : * the two; however, since the trigger is no longer needed, we remove
12762 : : * the dependency link in order to be able to drop the trigger while
12763 : : * keeping the constraint intact.
12764 : : */
12765 : 336 : deleteDependencyRecordsFor(TriggerRelationId,
12766 : : trgform->oid,
12767 : : false);
12768 : : /* make dependency deletion visible to performDeletion */
12769 : 336 : CommandCounterIncrement();
12770 : 336 : ObjectAddressSet(trigger, TriggerRelationId,
12771 : : trgform->oid);
12772 : 336 : performDeletion(&trigger, DROP_RESTRICT, 0);
12773 : : /* make trigger drop visible, in case the loop iterates */
12774 : 336 : CommandCounterIncrement();
12775 : : }
12776 : :
12777 : 160 : systable_endscan(scan);
12778 : 160 : }
12779 : :
12780 : : /*
12781 : : * GetForeignKeyActionTriggers
12782 : : * Returns delete and update "action" triggers of the given relation
12783 : : * belonging to the given constraint
12784 : : */
12785 : : static void
12786 : 104 : GetForeignKeyActionTriggers(Relation trigrel,
12787 : : Oid conoid, Oid confrelid, Oid conrelid,
12788 : : Oid *deleteTriggerOid,
12789 : : Oid *updateTriggerOid)
12790 : : {
12791 : : ScanKeyData key;
12792 : : SysScanDesc scan;
12793 : : HeapTuple trigtup;
12794 : :
12795 : 104 : *deleteTriggerOid = *updateTriggerOid = InvalidOid;
12796 : 104 : ScanKeyInit(&key,
12797 : : Anum_pg_trigger_tgconstraint,
12798 : : BTEqualStrategyNumber, F_OIDEQ,
12799 : : ObjectIdGetDatum(conoid));
12800 : :
12801 : 104 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12802 : : NULL, 1, &key);
12803 [ + - ]: 217 : while ((trigtup = systable_getnext(scan)) != NULL)
12804 : : {
12805 : 217 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12806 : :
12807 [ + + ]: 217 : if (trgform->tgconstrrelid != conrelid)
12808 : 8 : continue;
12809 [ - + ]: 209 : if (trgform->tgrelid != confrelid)
12810 : 0 : continue;
12811 : : /* Only ever look at "action" triggers on the PK side. */
12812 [ + + ]: 209 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
12813 : 1 : continue;
12814 [ + + ]: 208 : if (TRIGGER_FOR_DELETE(trgform->tgtype))
12815 : : {
12816 : : Assert(*deleteTriggerOid == InvalidOid);
12817 : 104 : *deleteTriggerOid = trgform->oid;
12818 : : }
12819 [ + - ]: 104 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12820 : : {
12821 : : Assert(*updateTriggerOid == InvalidOid);
12822 : 104 : *updateTriggerOid = trgform->oid;
12823 : : }
12824 : : #ifndef USE_ASSERT_CHECKING
12825 : : /* In an assert-enabled build, continue looking to find duplicates */
12826 [ + + + + ]: 208 : if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
12827 : 104 : break;
12828 : : #endif
12829 : : }
12830 : :
12831 [ - + ]: 104 : if (!OidIsValid(*deleteTriggerOid))
12832 [ # # ]: 0 : elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
12833 : : conoid);
12834 [ - + ]: 104 : if (!OidIsValid(*updateTriggerOid))
12835 [ # # ]: 0 : elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
12836 : : conoid);
12837 : :
12838 : 104 : systable_endscan(scan);
12839 : 104 : }
12840 : :
12841 : : /*
12842 : : * GetForeignKeyCheckTriggers
12843 : : * Returns insert and update "check" triggers of the given relation
12844 : : * belonging to the given constraint
12845 : : */
12846 : : static void
12847 : 507 : GetForeignKeyCheckTriggers(Relation trigrel,
12848 : : Oid conoid, Oid confrelid, Oid conrelid,
12849 : : Oid *insertTriggerOid,
12850 : : Oid *updateTriggerOid)
12851 : : {
12852 : : ScanKeyData key;
12853 : : SysScanDesc scan;
12854 : : HeapTuple trigtup;
12855 : :
12856 : 507 : *insertTriggerOid = *updateTriggerOid = InvalidOid;
12857 : 507 : ScanKeyInit(&key,
12858 : : Anum_pg_trigger_tgconstraint,
12859 : : BTEqualStrategyNumber, F_OIDEQ,
12860 : : ObjectIdGetDatum(conoid));
12861 : :
12862 : 507 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12863 : : NULL, 1, &key);
12864 [ + - ]: 1604 : while ((trigtup = systable_getnext(scan)) != NULL)
12865 : : {
12866 : 1604 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12867 : :
12868 [ + + ]: 1604 : if (trgform->tgconstrrelid != confrelid)
12869 : 518 : continue;
12870 [ - + ]: 1086 : if (trgform->tgrelid != conrelid)
12871 : 0 : continue;
12872 : : /* Only ever look at "check" triggers on the FK side. */
12873 [ + + ]: 1086 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
12874 : 72 : continue;
12875 [ + + ]: 1014 : if (TRIGGER_FOR_INSERT(trgform->tgtype))
12876 : : {
12877 : : Assert(*insertTriggerOid == InvalidOid);
12878 : 507 : *insertTriggerOid = trgform->oid;
12879 : : }
12880 [ + - ]: 507 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12881 : : {
12882 : : Assert(*updateTriggerOid == InvalidOid);
12883 : 507 : *updateTriggerOid = trgform->oid;
12884 : : }
12885 : : #ifndef USE_ASSERT_CHECKING
12886 : : /* In an assert-enabled build, continue looking to find duplicates. */
12887 [ + + + + ]: 1014 : if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
12888 : 507 : break;
12889 : : #endif
12890 : : }
12891 : :
12892 [ - + ]: 507 : if (!OidIsValid(*insertTriggerOid))
12893 [ # # ]: 0 : elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
12894 : : conoid);
12895 [ - + ]: 507 : if (!OidIsValid(*updateTriggerOid))
12896 [ # # ]: 0 : elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
12897 : : conoid);
12898 : :
12899 : 507 : systable_endscan(scan);
12900 : 507 : }
12901 : :
12902 : : /*
12903 : : * ALTER TABLE ALTER CONSTRAINT
12904 : : *
12905 : : * Update the attributes of a constraint.
12906 : : *
12907 : : * Currently works for Foreign Key, Check, and not null constraints.
12908 : : *
12909 : : * If the constraint is modified, returns its address; otherwise, return
12910 : : * InvalidObjectAddress.
12911 : : */
12912 : : static ObjectAddress
12913 : 344 : ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
12914 : : bool recurse, LOCKMODE lockmode)
12915 : : {
12916 : : Relation conrel;
12917 : : Relation tgrel;
12918 : : SysScanDesc scan;
12919 : : ScanKeyData skey[3];
12920 : : HeapTuple contuple;
12921 : : Form_pg_constraint currcon;
12922 : : ObjectAddress address;
12923 : :
12924 : : /*
12925 : : * Disallow altering ONLY a partitioned table, as it would make no sense.
12926 : : * This is okay for legacy inheritance.
12927 : : */
12928 [ + + - + ]: 344 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
12929 [ # # ]: 0 : ereport(ERROR,
12930 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12931 : : errmsg("constraint must be altered in child tables too"),
12932 : : errhint("Do not specify the ONLY keyword."));
12933 : :
12934 : :
12935 : 344 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12936 : 344 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
12937 : :
12938 : : /*
12939 : : * Find and check the target constraint
12940 : : */
12941 : 344 : ScanKeyInit(&skey[0],
12942 : : Anum_pg_constraint_conrelid,
12943 : : BTEqualStrategyNumber, F_OIDEQ,
12944 : : ObjectIdGetDatum(RelationGetRelid(rel)));
12945 : 344 : ScanKeyInit(&skey[1],
12946 : : Anum_pg_constraint_contypid,
12947 : : BTEqualStrategyNumber, F_OIDEQ,
12948 : : ObjectIdGetDatum(InvalidOid));
12949 : 344 : ScanKeyInit(&skey[2],
12950 : : Anum_pg_constraint_conname,
12951 : : BTEqualStrategyNumber, F_NAMEEQ,
12952 : 344 : CStringGetDatum(cmdcon->conname));
12953 : 344 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12954 : : true, NULL, 3, skey);
12955 : :
12956 : : /* There can be at most one matching row */
12957 [ + + ]: 344 : if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
12958 [ + - ]: 4 : ereport(ERROR,
12959 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
12960 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12961 : : cmdcon->conname, RelationGetRelationName(rel))));
12962 : :
12963 : 340 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12964 [ + + - + ]: 340 : if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
12965 [ # # ]: 0 : ereport(ERROR,
12966 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12967 : : errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
12968 : : cmdcon->conname, RelationGetRelationName(rel))));
12969 [ + + ]: 340 : if (cmdcon->alterEnforceability &&
12970 [ + + + + ]: 204 : (currcon->contype != CONSTRAINT_FOREIGN && currcon->contype != CONSTRAINT_CHECK))
12971 [ + - ]: 8 : ereport(ERROR,
12972 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12973 : : errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
12974 : : cmdcon->conname, RelationGetRelationName(rel)),
12975 : : errhint("Only foreign key and check constraints can change enforceability.")));
12976 [ + + ]: 332 : if (cmdcon->alterInheritability &&
12977 [ + + ]: 64 : currcon->contype != CONSTRAINT_NOTNULL)
12978 [ + - ]: 16 : ereport(ERROR,
12979 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
12980 : : errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
12981 : : cmdcon->conname, RelationGetRelationName(rel)));
12982 [ + + ]: 316 : if (cmdcon->alterInheritability &&
12983 [ + + + + ]: 48 : cmdcon->noinherit && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12984 [ + - ]: 4 : ereport(ERROR,
12985 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12986 : : errmsg("not-null constraint \"%s\" on partitioned table \"%s\" cannot be NO INHERIT",
12987 : : cmdcon->conname, RelationGetRelationName(rel)));
12988 : :
12989 : : /* Refuse to modify inheritability of inherited constraints */
12990 [ + + ]: 312 : if (cmdcon->alterInheritability &&
12991 [ + + + + ]: 44 : cmdcon->noinherit && currcon->coninhcount > 0)
12992 [ + - ]: 4 : ereport(ERROR,
12993 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12994 : : errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
12995 : : NameStr(currcon->conname),
12996 : : RelationGetRelationName(rel)));
12997 : :
12998 : : /*
12999 : : * If it's not the topmost constraint, raise an error.
13000 : : *
13001 : : * Altering a non-topmost constraint leaves some triggers untouched, since
13002 : : * they are not directly connected to this constraint; also, pg_dump would
13003 : : * ignore the deferrability status of the individual constraint, since it
13004 : : * only dumps topmost constraints. Avoid these problems by refusing this
13005 : : * operation and telling the user to alter the parent constraint instead.
13006 : : */
13007 [ + + ]: 308 : if (OidIsValid(currcon->conparentid))
13008 : : {
13009 : : HeapTuple tp;
13010 : 8 : Oid parent = currcon->conparentid;
13011 : 8 : char *ancestorname = NULL;
13012 : 8 : char *ancestortable = NULL;
13013 : :
13014 : : /* Loop to find the topmost constraint */
13015 [ + - ]: 16 : while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
13016 : : {
13017 : 16 : Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
13018 : :
13019 : : /* If no parent, this is the constraint we want */
13020 [ + + ]: 16 : if (!OidIsValid(contup->conparentid))
13021 : : {
13022 : 8 : ancestorname = pstrdup(NameStr(contup->conname));
13023 : 8 : ancestortable = get_rel_name(contup->conrelid);
13024 : 8 : ReleaseSysCache(tp);
13025 : 8 : break;
13026 : : }
13027 : :
13028 : 8 : parent = contup->conparentid;
13029 : 8 : ReleaseSysCache(tp);
13030 : : }
13031 : :
13032 [ + - + - : 8 : ereport(ERROR,
+ - ]
13033 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13034 : : errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
13035 : : cmdcon->conname, RelationGetRelationName(rel)),
13036 : : ancestorname && ancestortable ?
13037 : : errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
13038 : : cmdcon->conname, ancestorname, ancestortable) : 0,
13039 : : errhint("You may alter the constraint it derives from instead.")));
13040 : : }
13041 : :
13042 : 300 : address = InvalidObjectAddress;
13043 : :
13044 : : /*
13045 : : * Do the actual catalog work, and recurse if necessary.
13046 : : */
13047 [ + + ]: 300 : if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
13048 : : contuple, recurse, lockmode))
13049 : 244 : ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
13050 : :
13051 : 260 : systable_endscan(scan);
13052 : :
13053 : 260 : table_close(tgrel, RowExclusiveLock);
13054 : 260 : table_close(conrel, RowExclusiveLock);
13055 : :
13056 : 260 : return address;
13057 : : }
13058 : :
13059 : : /*
13060 : : * A subroutine of ATExecAlterConstraint that calls the respective routines for
13061 : : * altering constraint's enforceability, deferrability or inheritability.
13062 : : */
13063 : : static bool
13064 : 300 : ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
13065 : : Relation conrel, Relation tgrel, Relation rel,
13066 : : HeapTuple contuple, bool recurse,
13067 : : LOCKMODE lockmode)
13068 : : {
13069 : : Form_pg_constraint currcon;
13070 : 300 : bool changed = false;
13071 : 300 : List *otherrelids = NIL;
13072 : :
13073 : 300 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13074 : :
13075 : : /*
13076 : : * Do the catalog work for the enforceability or deferrability change,
13077 : : * recurse if necessary.
13078 : : *
13079 : : * Note that even if deferrability is requested to be altered along with
13080 : : * enforceability, we don't need to explicitly update multiple entries in
13081 : : * pg_trigger related to deferrability.
13082 : : *
13083 : : * Modifying foreign key enforceability involves either creating or
13084 : : * dropping the trigger, during which the deferrability setting will be
13085 : : * adjusted automatically.
13086 : : */
13087 [ + + ]: 300 : if (cmdcon->alterEnforceability)
13088 : : {
13089 [ + + ]: 196 : if (currcon->contype == CONSTRAINT_FOREIGN)
13090 : 56 : changed = ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
13091 : : currcon->conrelid,
13092 : : currcon->confrelid,
13093 : : contuple, lockmode,
13094 : : InvalidOid, InvalidOid,
13095 : : InvalidOid, InvalidOid);
13096 [ + - ]: 140 : else if (currcon->contype == CONSTRAINT_CHECK)
13097 : 140 : changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel,
13098 : : contuple, recurse, false,
13099 : : NIL, lockmode);
13100 : : }
13101 [ + + + - ]: 168 : else if (cmdcon->alterDeferrability &&
13102 : 64 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
13103 : : contuple, recurse, &otherrelids,
13104 : : lockmode))
13105 : : {
13106 : : /*
13107 : : * AlterConstrUpdateConstraintEntry already invalidated relcache for
13108 : : * the relations having the constraint itself; here we also invalidate
13109 : : * for relations that have any triggers that are part of the
13110 : : * constraint.
13111 : : */
13112 [ + + + + : 204 : foreach_oid(relid, otherrelids)
+ + ]
13113 : 76 : CacheInvalidateRelcacheByRelid(relid);
13114 : :
13115 : 64 : changed = true;
13116 : : }
13117 : :
13118 : : /*
13119 : : * Do the catalog work for the inheritability change.
13120 : : */
13121 [ + + + - ]: 300 : if (cmdcon->alterInheritability &&
13122 : 40 : ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
13123 : : lockmode))
13124 : 36 : changed = true;
13125 : :
13126 : 260 : return changed;
13127 : : }
13128 : :
13129 : : /*
13130 : : * Returns true if the foreign key constraint's enforceability is altered.
13131 : : *
13132 : : * Depending on whether the constraint is being set to ENFORCED or NOT
13133 : : * ENFORCED, it creates or drops the trigger accordingly.
13134 : : *
13135 : : * Note that we must recurse even when trying to change a constraint to not
13136 : : * enforced if it is already not enforced, in case descendant constraints
13137 : : * might be enforced and need to be changed to not enforced. Conversely, we
13138 : : * should do nothing if a constraint is being set to enforced and is already
13139 : : * enforced, as descendant constraints cannot be different in that case.
13140 : : */
13141 : : static bool
13142 : 120 : ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
13143 : : Relation conrel, Relation tgrel,
13144 : : Oid fkrelid, Oid pkrelid,
13145 : : HeapTuple contuple, LOCKMODE lockmode,
13146 : : Oid ReferencedParentDelTrigger,
13147 : : Oid ReferencedParentUpdTrigger,
13148 : : Oid ReferencingParentInsTrigger,
13149 : : Oid ReferencingParentUpdTrigger)
13150 : : {
13151 : : Form_pg_constraint currcon;
13152 : : Oid conoid;
13153 : : Relation rel;
13154 : 120 : bool changed = false;
13155 : :
13156 : : /* Since this function recurses, it could be driven to stack overflow */
13157 : 120 : check_stack_depth();
13158 : :
13159 : : Assert(cmdcon->alterEnforceability);
13160 : :
13161 : 120 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13162 : 120 : conoid = currcon->oid;
13163 : :
13164 : : /* Should be foreign key constraint */
13165 : : Assert(currcon->contype == CONSTRAINT_FOREIGN);
13166 : :
13167 : 120 : rel = table_open(currcon->conrelid, lockmode);
13168 : :
13169 [ + + ]: 120 : if (currcon->conenforced != cmdcon->is_enforced)
13170 : : {
13171 : 116 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13172 : 116 : changed = true;
13173 : : }
13174 : :
13175 : : /* Drop triggers */
13176 [ + + ]: 120 : if (!cmdcon->is_enforced)
13177 : : {
13178 : : /*
13179 : : * When setting a constraint to NOT ENFORCED, the constraint triggers
13180 : : * need to be dropped. Therefore, we must process the child relations
13181 : : * first, followed by the parent, to account for dependencies.
13182 : : */
13183 [ + + - + ]: 92 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13184 : 40 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
13185 : 12 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
13186 : : fkrelid, pkrelid, contuple,
13187 : : lockmode, InvalidOid, InvalidOid,
13188 : : InvalidOid, InvalidOid);
13189 : :
13190 : : /* Drop all the triggers */
13191 : 52 : DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
13192 : : }
13193 [ + - ]: 68 : else if (changed) /* Create triggers */
13194 : : {
13195 : 68 : Oid ReferencedDelTriggerOid = InvalidOid,
13196 : 68 : ReferencedUpdTriggerOid = InvalidOid,
13197 : 68 : ReferencingInsTriggerOid = InvalidOid,
13198 : 68 : ReferencingUpdTriggerOid = InvalidOid;
13199 : :
13200 : : /* Prepare the minimal information required for trigger creation. */
13201 : 68 : Constraint *fkconstraint = makeNode(Constraint);
13202 : :
13203 : 68 : fkconstraint->conname = pstrdup(NameStr(currcon->conname));
13204 : 68 : fkconstraint->fk_matchtype = currcon->confmatchtype;
13205 : 68 : fkconstraint->fk_upd_action = currcon->confupdtype;
13206 : 68 : fkconstraint->fk_del_action = currcon->confdeltype;
13207 : 68 : fkconstraint->deferrable = currcon->condeferrable;
13208 : 68 : fkconstraint->initdeferred = currcon->condeferred;
13209 : :
13210 : : /* Create referenced triggers */
13211 [ + + ]: 68 : if (currcon->conrelid == fkrelid)
13212 : 40 : createForeignKeyActionTriggers(currcon->conrelid,
13213 : : currcon->confrelid,
13214 : : fkconstraint,
13215 : : conoid,
13216 : : currcon->conindid,
13217 : : ReferencedParentDelTrigger,
13218 : : ReferencedParentUpdTrigger,
13219 : : &ReferencedDelTriggerOid,
13220 : : &ReferencedUpdTriggerOid);
13221 : :
13222 : : /* Create referencing triggers */
13223 [ + + ]: 68 : if (currcon->confrelid == pkrelid)
13224 : 60 : createForeignKeyCheckTriggers(currcon->conrelid,
13225 : : pkrelid,
13226 : : fkconstraint,
13227 : : conoid,
13228 : : currcon->conindid,
13229 : : ReferencingParentInsTrigger,
13230 : : ReferencingParentUpdTrigger,
13231 : : &ReferencingInsTriggerOid,
13232 : : &ReferencingUpdTriggerOid);
13233 : :
13234 : : /*
13235 : : * Tell Phase 3 to check that the constraint is satisfied by existing
13236 : : * rows. Only applies to leaf partitions, and (for constraints that
13237 : : * reference a partitioned table) only if this is not one of the
13238 : : * pg_constraint rows that exist solely to support action triggers.
13239 : : */
13240 [ + + ]: 68 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
13241 [ + + ]: 56 : currcon->confrelid == pkrelid)
13242 : : {
13243 : : AlteredTableInfo *tab;
13244 : : NewConstraint *newcon;
13245 : :
13246 : 48 : newcon = palloc0_object(NewConstraint);
13247 : 48 : newcon->name = fkconstraint->conname;
13248 : 48 : newcon->contype = CONSTR_FOREIGN;
13249 : 48 : newcon->refrelid = currcon->confrelid;
13250 : 48 : newcon->refindid = currcon->conindid;
13251 : 48 : newcon->conid = currcon->oid;
13252 : 48 : newcon->qual = (Node *) fkconstraint;
13253 : :
13254 : : /* Find or create work queue entry for this table */
13255 : 48 : tab = ATGetQueueEntry(wqueue, rel);
13256 : 48 : tab->constraints = lappend(tab->constraints, newcon);
13257 : : }
13258 : :
13259 : : /*
13260 : : * If the table at either end of the constraint is partitioned, we
13261 : : * need to recurse and create triggers for each constraint that is a
13262 : : * child of this one.
13263 : : */
13264 [ + + + + ]: 124 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13265 : 56 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
13266 : 16 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
13267 : : fkrelid, pkrelid, contuple,
13268 : : lockmode,
13269 : : ReferencedDelTriggerOid,
13270 : : ReferencedUpdTriggerOid,
13271 : : ReferencingInsTriggerOid,
13272 : : ReferencingUpdTriggerOid);
13273 : : }
13274 : :
13275 : 120 : table_close(rel, NoLock);
13276 : :
13277 : 120 : return changed;
13278 : : }
13279 : :
13280 : : /*
13281 : : * Returns true if the CHECK constraint's enforceability is altered.
13282 : : */
13283 : : static bool
13284 : 360 : ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
13285 : : Relation conrel, HeapTuple contuple,
13286 : : bool recurse, bool recursing,
13287 : : List *changing_conids,
13288 : : LOCKMODE lockmode)
13289 : : {
13290 : : Form_pg_constraint currcon;
13291 : : Relation rel;
13292 : 360 : bool changed = false;
13293 : 360 : List *children = NIL;
13294 : 360 : bool target_enforced = cmdcon->is_enforced;
13295 : 360 : Oid enforced_parentoid = InvalidOid;
13296 : :
13297 : : /* Since this function recurses, it could be driven to stack overflow */
13298 : 360 : check_stack_depth();
13299 : :
13300 : : Assert(cmdcon->alterEnforceability);
13301 : :
13302 : 360 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13303 : :
13304 : : Assert(currcon->contype == CONSTRAINT_CHECK);
13305 : :
13306 : : /*
13307 : : * Parent relation already locked by caller, children will be locked by
13308 : : * find_all_inheritors. So NoLock is fine here.
13309 : : */
13310 : 360 : rel = table_open(currcon->conrelid, NoLock);
13311 : :
13312 : : /*
13313 : : * When setting a constraint to NOT ENFORCED, check whether any matching
13314 : : * parent constraint remains ENFORCED and is not part of this ALTER.
13315 : : *
13316 : : * For a direct ALTER of an inherited constraint, reject the command,
13317 : : * because the child cannot be weakened while its parent remains enforced.
13318 : : *
13319 : : * During recursion, another parent outside this ALTER may still enforce
13320 : : * the same constraint in a regular inheritance hierarchy. In that case,
13321 : : * keep the child constraint ENFORCED so that its merged enforceability
13322 : : * still reflects the remaining enforced parent. Partitions do not need
13323 : : * this recursive parent check because a partition can have only one
13324 : : * direct parent.
13325 : : */
13326 [ + + ]: 360 : if (!cmdcon->is_enforced &&
13327 [ + + + + : 304 : (!recursing || !rel->rd_rel->relispartition) &&
+ + ]
13328 : 144 : ATCheckCheckConstrHasEnforcedParent(conrel, rel, contuple,
13329 : : changing_conids,
13330 : : &enforced_parentoid))
13331 : : {
13332 [ + + ]: 32 : if (!recursing)
13333 [ + - ]: 20 : ereport(ERROR,
13334 : : errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
13335 : : errmsg("cannot mark inherited constraint \"%s\" as %s",
13336 : : NameStr(currcon->conname),
13337 : : "NOT ENFORCED"),
13338 : : errdetail("The matching constraint on parent table \"%s\" is %s.",
13339 : : get_rel_name(enforced_parentoid), "ENFORCED"));
13340 : :
13341 : 12 : target_enforced = true;
13342 : : }
13343 : :
13344 : : /*
13345 : : * The constraint is about to be marked validated, so a descendant that is
13346 : : * enforced but not yet valid conflicts with it, as in ALTER TABLE ...
13347 : : * INHERIT.
13348 : : */
13349 [ + + + + ]: 340 : if (recursing && cmdcon->is_enforced &&
13350 [ + + + + ]: 128 : currcon->conenforced && !currcon->convalidated)
13351 [ + - ]: 8 : ereport(ERROR,
13352 : : errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
13353 : : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
13354 : : NameStr(currcon->conname), RelationGetRelationName(rel)),
13355 : : errhint("You may need to use %s on table \"%s\" first.",
13356 : : "ALTER TABLE ... VALIDATE CONSTRAINT",
13357 : : RelationGetRelationName(rel)));
13358 : :
13359 : : /*
13360 : : * Update to the merged enforceability if needed. This may differ from the
13361 : : * requested enforceability when another matching parent constraint
13362 : : * remains enforced.
13363 : : */
13364 [ + + ]: 332 : if (currcon->conenforced != target_enforced)
13365 : : {
13366 : 260 : ATAlterConstraint updatecon = *cmdcon;
13367 : :
13368 : 260 : updatecon.is_enforced = target_enforced;
13369 : 260 : AlterConstrUpdateConstraintEntry(&updatecon, conrel, contuple);
13370 : 260 : changed = true;
13371 : : }
13372 : :
13373 : : /*
13374 : : * Note that we must recurse even when trying to change a check constraint
13375 : : * to not enforced if it is already not enforced, in case descendant
13376 : : * constraints might be enforced and need to be changed to not enforced,
13377 : : * unless they still inherit an enforced constraint from another parent.
13378 : : * Conversely, we should do nothing if a constraint is being set to
13379 : : * enforced and is already enforced, as descendant constraints cannot be
13380 : : * different in that case.
13381 : : */
13382 [ + + + + ]: 332 : if (!cmdcon->is_enforced || changed)
13383 : : {
13384 : : /*
13385 : : * If we're recursing, the parent has already done this, so skip it.
13386 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't
13387 : : * try to look for it in the children.
13388 : : */
13389 [ + + + + ]: 312 : if (!recursing && !currcon->connoinherit)
13390 : : {
13391 : : Assert(changing_conids == NIL);
13392 : :
13393 : 116 : children = find_all_inheritors(RelationGetRelid(rel),
13394 : : lockmode, NULL);
13395 : :
13396 : : /*
13397 : : * When setting NOT ENFORCED, build the set of equivalent CHECK
13398 : : * constraints that this command will attempt to change before
13399 : : * visiting descendants. The root itself has already been checked
13400 : : * above.
13401 : : */
13402 [ + + ]: 116 : if (!cmdcon->is_enforced)
13403 : 48 : changing_conids = list_make1_oid(currcon->oid);
13404 : :
13405 [ + - + + : 560 : foreach_oid(childoid, children)
+ + ]
13406 : : {
13407 [ + + ]: 344 : if (childoid == RelationGetRelid(rel))
13408 : 116 : continue;
13409 : :
13410 : : /*
13411 : : * If we are told not to recurse, there had better not be any
13412 : : * child tables, because we can't change constraint
13413 : : * enforceability on the parent unless we have changed
13414 : : * enforceability for all child.
13415 : : */
13416 [ + + ]: 228 : if (!recurse)
13417 [ + - ]: 8 : ereport(ERROR,
13418 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13419 : : errmsg("constraint must be altered on child tables too"),
13420 : : errhint("Do not specify the ONLY keyword."));
13421 : :
13422 : : /*
13423 : : * It is sufficient to look up the constraint by name here.
13424 : : * Supported DDL ensures that inheritable CHECK constraints
13425 : : * with the same name have equivalent definitions when they
13426 : : * are propagated to children or when inheritance is
13427 : : * established. All descendants returned by
13428 : : * find_all_inheritors must have this constraint: inherited
13429 : : * CHECK constraints propagate to all children at
13430 : : * inheritance-link creation time and cannot be dropped
13431 : : * independently on child tables.
13432 : : */
13433 [ + + ]: 220 : if (!cmdcon->is_enforced)
13434 : : changing_conids =
13435 : 92 : list_append_unique_oid(changing_conids,
13436 : : get_relation_constraint_oid(childoid,
13437 : 92 : cmdcon->conname,
13438 : : false));
13439 : : }
13440 : : }
13441 : :
13442 [ + + + + : 920 : foreach_oid(childoid, children)
+ + ]
13443 : : {
13444 [ + + ]: 328 : if (childoid == RelationGetRelid(rel))
13445 : 108 : continue;
13446 : :
13447 : 220 : AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel,
13448 : : childoid, false, true,
13449 : : changing_conids,
13450 : : lockmode);
13451 : : }
13452 : : }
13453 : :
13454 : : /*
13455 : : * Tell Phase 3 to check that the constraint is satisfied by existing
13456 : : * rows. We only need do this when altering the constraint from NOT
13457 : : * ENFORCED to ENFORCED.
13458 : : */
13459 [ + + ]: 316 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
13460 [ + + + + ]: 268 : !currcon->conenforced &&
13461 : : target_enforced)
13462 : : {
13463 : : AlteredTableInfo *tab;
13464 : : NewConstraint *newcon;
13465 : : Datum val;
13466 : : char *conbin;
13467 : :
13468 : 120 : newcon = palloc0_object(NewConstraint);
13469 : 120 : newcon->name = pstrdup(NameStr(currcon->conname));
13470 : 120 : newcon->contype = CONSTR_CHECK;
13471 : :
13472 : 120 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
13473 : : Anum_pg_constraint_conbin);
13474 : 120 : conbin = TextDatumGetCString(val);
13475 : 120 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
13476 : :
13477 : : /* Find or create work queue entry for this table */
13478 : 120 : tab = ATGetQueueEntry(wqueue, rel);
13479 : 120 : tab->constraints = lappend(tab->constraints, newcon);
13480 : : }
13481 : :
13482 : 316 : table_close(rel, NoLock);
13483 : :
13484 : 316 : return changed;
13485 : : }
13486 : :
13487 : : /*
13488 : : * Invokes ATExecAlterCheckConstrEnforceability for each CHECK constraint that
13489 : : * is a child of the specified constraint.
13490 : : *
13491 : : * We rely on the parent and child tables having identical CHECK constraint
13492 : : * names to retrieve the child's pg_constraint tuple.
13493 : : *
13494 : : * The arguments to this function have the same meaning as the arguments to
13495 : : * ATExecAlterCheckConstrEnforceability.
13496 : : */
13497 : : static void
13498 : 220 : AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13499 : : Relation conrel, Oid conrelid,
13500 : : bool recurse, bool recursing,
13501 : : List *changing_conids,
13502 : : LOCKMODE lockmode)
13503 : : {
13504 : : SysScanDesc pscan;
13505 : : HeapTuple childtup;
13506 : : ScanKeyData skey[3];
13507 : :
13508 : 220 : ScanKeyInit(&skey[0],
13509 : : Anum_pg_constraint_conrelid,
13510 : : BTEqualStrategyNumber, F_OIDEQ,
13511 : : ObjectIdGetDatum(conrelid));
13512 : 220 : ScanKeyInit(&skey[1],
13513 : : Anum_pg_constraint_contypid,
13514 : : BTEqualStrategyNumber, F_OIDEQ,
13515 : : ObjectIdGetDatum(InvalidOid));
13516 : 220 : ScanKeyInit(&skey[2],
13517 : : Anum_pg_constraint_conname,
13518 : : BTEqualStrategyNumber, F_NAMEEQ,
13519 : 220 : CStringGetDatum(cmdcon->conname));
13520 : :
13521 : 220 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
13522 : : NULL, 3, skey);
13523 : :
13524 [ - + ]: 220 : if (!HeapTupleIsValid(childtup = systable_getnext(pscan)))
13525 [ # # ]: 0 : ereport(ERROR,
13526 : : errcode(ERRCODE_UNDEFINED_OBJECT),
13527 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
13528 : : cmdcon->conname, get_rel_name(conrelid)));
13529 : :
13530 : 220 : ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup,
13531 : : recurse, recursing, changing_conids,
13532 : : lockmode);
13533 : :
13534 : 212 : systable_endscan(pscan);
13535 : 212 : }
13536 : :
13537 : : /*
13538 : : * When setting an inherited CHECK constraint to NOT ENFORCED, look for a
13539 : : * matching parent constraint that remains ENFORCED and is not part of the same
13540 : : * ALTER.
13541 : : */
13542 : : static bool
13543 : 268 : ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel,
13544 : : HeapTuple contuple,
13545 : : List *changing_conids,
13546 : : Oid *enforced_parentoid)
13547 : : {
13548 : : Form_pg_constraint currcon;
13549 : : Relation inhrel;
13550 : : SysScanDesc scan;
13551 : : ScanKeyData skey;
13552 : : HeapTuple inheritsTuple;
13553 : :
13554 : : /* Since this function recurses, it could be driven to stack overflow */
13555 : 268 : check_stack_depth();
13556 : :
13557 : 268 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13558 : : Assert(currcon->contype == CONSTRAINT_CHECK);
13559 : :
13560 [ + + ]: 268 : if (currcon->coninhcount <= 0)
13561 : 124 : return false;
13562 : :
13563 : 144 : inhrel = table_open(InheritsRelationId, AccessShareLock);
13564 : :
13565 : 144 : ScanKeyInit(&skey,
13566 : : Anum_pg_inherits_inhrelid,
13567 : : BTEqualStrategyNumber, F_OIDEQ,
13568 : : ObjectIdGetDatum(RelationGetRelid(rel)));
13569 : 144 : scan = systable_beginscan(inhrel, InheritsRelidSeqnoIndexId,
13570 : : true, NULL, 1, &skey);
13571 : :
13572 [ + + ]: 304 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
13573 : : {
13574 : : Oid parentoid;
13575 : 200 : Relation parentrel = NULL;
13576 : : SysScanDesc pscan;
13577 : : ScanKeyData pkey[3];
13578 : : HeapTuple parenttup;
13579 : :
13580 : 200 : parentoid = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
13581 : :
13582 : 200 : ScanKeyInit(&pkey[0],
13583 : : Anum_pg_constraint_conrelid,
13584 : : BTEqualStrategyNumber, F_OIDEQ,
13585 : : ObjectIdGetDatum(parentoid));
13586 : 200 : ScanKeyInit(&pkey[1],
13587 : : Anum_pg_constraint_contypid,
13588 : : BTEqualStrategyNumber, F_OIDEQ,
13589 : : ObjectIdGetDatum(InvalidOid));
13590 : 200 : ScanKeyInit(&pkey[2],
13591 : : Anum_pg_constraint_conname,
13592 : : BTEqualStrategyNumber, F_NAMEEQ,
13593 : 200 : NameGetDatum(&currcon->conname));
13594 : :
13595 : 200 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
13596 : : true, NULL, 3, pkey);
13597 : :
13598 : : /*
13599 : : * ConstraintRelidTypidNameIndexId is unique on (conrelid, contypid,
13600 : : * conname), so this loop body executes at most once per parent.
13601 : : */
13602 [ + + ]: 360 : while (HeapTupleIsValid(parenttup = systable_getnext(pscan)))
13603 : : {
13604 : : Form_pg_constraint parentcon;
13605 : :
13606 : 200 : parentcon = (Form_pg_constraint) GETSTRUCT(parenttup);
13607 : :
13608 [ + - ]: 200 : if (parentcon->contype != CONSTRAINT_CHECK ||
13609 [ + - ]: 200 : parentcon->connoinherit ||
13610 [ + + ]: 200 : !parentcon->conenforced)
13611 : 44 : continue;
13612 : :
13613 [ - + ]: 156 : if (!constraints_equivalent(parenttup, contuple,
13614 : : RelationGetDescr(conrel)))
13615 [ # # ]: 0 : elog(ERROR, "child table \"%s\" has different definition for check constraint \"%s\"",
13616 : : RelationGetRelationName(rel),
13617 : : NameStr(parentcon->conname));
13618 : :
13619 : : /*
13620 : : * A parent listed in changing_conids is being changed by the same
13621 : : * ALTER, but it may not have been updated yet. For regular
13622 : : * inheritance, recurse upward to check whether an equivalent
13623 : : * enforced parent outside the ALTER will make it remain enforced.
13624 : : * Partitions cannot have multiple parents, so they do not need
13625 : : * this check.
13626 : : */
13627 [ + + + + ]: 300 : if (!rel->rd_rel->relispartition &&
13628 : 144 : list_member_oid(changing_conids, parentcon->oid))
13629 : : {
13630 : 124 : Oid parent_enforced_parentoid = InvalidOid;
13631 : :
13632 [ + - ]: 124 : if (parentrel == NULL)
13633 : 124 : parentrel = table_open(parentoid, NoLock);
13634 : :
13635 [ + + ]: 124 : if (!ATCheckCheckConstrHasEnforcedParent(conrel,
13636 : : parentrel,
13637 : : parenttup,
13638 : : changing_conids,
13639 : : &parent_enforced_parentoid))
13640 : 116 : continue;
13641 : : }
13642 : :
13643 : 40 : *enforced_parentoid = parentoid;
13644 [ + + ]: 40 : if (parentrel != NULL)
13645 : 8 : table_close(parentrel, NoLock);
13646 : 40 : systable_endscan(pscan);
13647 : 40 : systable_endscan(scan);
13648 : 40 : table_close(inhrel, AccessShareLock);
13649 : 40 : return true;
13650 : : }
13651 : :
13652 [ + + ]: 160 : if (parentrel != NULL)
13653 : 116 : table_close(parentrel, NoLock);
13654 : 160 : systable_endscan(pscan);
13655 : : }
13656 : :
13657 : 104 : systable_endscan(scan);
13658 : 104 : table_close(inhrel, AccessShareLock);
13659 : :
13660 : 104 : return false;
13661 : : }
13662 : :
13663 : : /*
13664 : : * Returns true if the constraint's deferrability is altered.
13665 : : *
13666 : : * *otherrelids is appended OIDs of relations containing affected triggers.
13667 : : *
13668 : : * Note that we must recurse even when the values are correct, in case
13669 : : * indirect descendants have had their constraints altered locally.
13670 : : * (This could be avoided if we forbade altering constraints in partitions
13671 : : * but existing releases don't do that.)
13672 : : */
13673 : : static bool
13674 : 108 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
13675 : : Relation conrel, Relation tgrel, Relation rel,
13676 : : HeapTuple contuple, bool recurse,
13677 : : List **otherrelids, LOCKMODE lockmode)
13678 : : {
13679 : : Form_pg_constraint currcon;
13680 : : Oid refrelid;
13681 : 108 : bool changed = false;
13682 : :
13683 : : /* since this function recurses, it could be driven to stack overflow */
13684 : 108 : check_stack_depth();
13685 : :
13686 : : Assert(cmdcon->alterDeferrability);
13687 : :
13688 : 108 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13689 : 108 : refrelid = currcon->confrelid;
13690 : :
13691 : : /* Should be foreign key constraint */
13692 : : Assert(currcon->contype == CONSTRAINT_FOREIGN);
13693 : :
13694 : : /*
13695 : : * If called to modify a constraint that's already in the desired state,
13696 : : * silently do nothing.
13697 : : */
13698 [ + + ]: 108 : if (currcon->condeferrable != cmdcon->deferrable ||
13699 [ + - ]: 4 : currcon->condeferred != cmdcon->initdeferred)
13700 : : {
13701 : 108 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13702 : 108 : changed = true;
13703 : :
13704 : : /*
13705 : : * Now we need to update the multiple entries in pg_trigger that
13706 : : * implement the constraint.
13707 : : */
13708 : 108 : AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
13709 : 108 : cmdcon->deferrable,
13710 : 108 : cmdcon->initdeferred, otherrelids);
13711 : : }
13712 : :
13713 : : /*
13714 : : * If the table at either end of the constraint is partitioned, we need to
13715 : : * handle every constraint that is a child of this one.
13716 : : */
13717 [ + - + - ]: 108 : if (recurse && changed &&
13718 [ + + + + ]: 200 : (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13719 : 92 : get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
13720 : 28 : AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
13721 : : contuple, recurse, otherrelids,
13722 : : lockmode);
13723 : :
13724 : 108 : return changed;
13725 : : }
13726 : :
13727 : : /*
13728 : : * Returns true if the constraint's inheritability is altered.
13729 : : */
13730 : : static bool
13731 : 40 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
13732 : : Relation conrel, Relation rel,
13733 : : HeapTuple contuple, LOCKMODE lockmode)
13734 : : {
13735 : : Form_pg_constraint currcon;
13736 : : AttrNumber colNum;
13737 : : char *colName;
13738 : : List *children;
13739 : :
13740 : : Assert(cmdcon->alterInheritability);
13741 : :
13742 : 40 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13743 : :
13744 : : /* The current implementation only works for NOT NULL constraints */
13745 : : Assert(currcon->contype == CONSTRAINT_NOTNULL);
13746 : :
13747 : : /*
13748 : : * If called to modify a constraint that's already in the desired state,
13749 : : * silently do nothing.
13750 : : */
13751 [ - + ]: 40 : if (cmdcon->noinherit == currcon->connoinherit)
13752 : 0 : return false;
13753 : :
13754 : 40 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13755 : 40 : CommandCounterIncrement();
13756 : :
13757 : : /* Fetch the column number and name */
13758 : 40 : colNum = extractNotNullColumn(contuple);
13759 : 40 : colName = get_attname(currcon->conrelid, colNum, false);
13760 : :
13761 : : /*
13762 : : * Propagate the change to children. For this subcommand type we don't
13763 : : * recursively affect children, just the immediate level.
13764 : : */
13765 : 40 : children = find_inheritance_children(RelationGetRelid(rel),
13766 : : lockmode);
13767 [ + + + + : 128 : foreach_oid(childoid, children)
+ + ]
13768 : : {
13769 : : ObjectAddress addr;
13770 : :
13771 [ + + ]: 56 : if (cmdcon->noinherit)
13772 : : {
13773 : : HeapTuple childtup;
13774 : : Form_pg_constraint childcon;
13775 : :
13776 : 20 : childtup = findNotNullConstraint(childoid, colName);
13777 [ - + ]: 20 : if (!childtup)
13778 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
13779 : : colName, childoid);
13780 : 20 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13781 : : Assert(childcon->coninhcount > 0);
13782 : 20 : childcon->coninhcount--;
13783 : 20 : childcon->conislocal = true;
13784 : 20 : CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
13785 : 20 : heap_freetuple(childtup);
13786 : : }
13787 : : else
13788 : : {
13789 : 36 : Relation childrel = table_open(childoid, NoLock);
13790 : :
13791 : 36 : addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
13792 : : colName, true, true, lockmode);
13793 [ + - ]: 32 : if (OidIsValid(addr.objectId))
13794 : 32 : CommandCounterIncrement();
13795 : 32 : table_close(childrel, NoLock);
13796 : : }
13797 : : }
13798 : :
13799 : 36 : return true;
13800 : : }
13801 : :
13802 : : /*
13803 : : * A subroutine of ATExecAlterConstrDeferrability that updated constraint
13804 : : * trigger's deferrability.
13805 : : *
13806 : : * The arguments to this function have the same meaning as the arguments to
13807 : : * ATExecAlterConstrDeferrability.
13808 : : */
13809 : : static void
13810 : 108 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
13811 : : bool deferrable, bool initdeferred,
13812 : : List **otherrelids)
13813 : : {
13814 : : HeapTuple tgtuple;
13815 : : ScanKeyData tgkey;
13816 : : SysScanDesc tgscan;
13817 : :
13818 : 108 : ScanKeyInit(&tgkey,
13819 : : Anum_pg_trigger_tgconstraint,
13820 : : BTEqualStrategyNumber, F_OIDEQ,
13821 : : ObjectIdGetDatum(conoid));
13822 : 108 : tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
13823 : : NULL, 1, &tgkey);
13824 [ + + ]: 420 : while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
13825 : : {
13826 : 312 : Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
13827 : : Form_pg_trigger copy_tg;
13828 : : HeapTuple tgCopyTuple;
13829 : :
13830 : : /*
13831 : : * Remember OIDs of other relation(s) involved in FK constraint.
13832 : : * (Note: it's likely that we could skip forcing a relcache inval for
13833 : : * other rels that don't have a trigger whose properties change, but
13834 : : * let's be conservative.)
13835 : : */
13836 [ + + ]: 312 : if (tgform->tgrelid != RelationGetRelid(rel))
13837 : 152 : *otherrelids = list_append_unique_oid(*otherrelids,
13838 : : tgform->tgrelid);
13839 : :
13840 : : /*
13841 : : * Update enable status and deferrability of RI_FKey_noaction_del,
13842 : : * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
13843 : : * triggers, but not others; see createForeignKeyActionTriggers and
13844 : : * CreateFKCheckTrigger.
13845 : : */
13846 [ + + ]: 312 : if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
13847 [ + + ]: 248 : tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
13848 [ + + ]: 172 : tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
13849 [ + + ]: 92 : tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
13850 : 12 : continue;
13851 : :
13852 : 300 : tgCopyTuple = heap_copytuple(tgtuple);
13853 : 300 : copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
13854 : :
13855 : 300 : copy_tg->tgdeferrable = deferrable;
13856 : 300 : copy_tg->tginitdeferred = initdeferred;
13857 : 300 : CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
13858 : :
13859 [ - + ]: 300 : InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
13860 : :
13861 : 300 : heap_freetuple(tgCopyTuple);
13862 : : }
13863 : :
13864 : 108 : systable_endscan(tgscan);
13865 : 108 : }
13866 : :
13867 : : /*
13868 : : * Invokes ATExecAlterFKConstrEnforceability for each foreign key constraint
13869 : : * that is a child of the specified constraint.
13870 : : *
13871 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13872 : : * list of child relations and recursing; instead it uses the conparentid
13873 : : * relationships. This may need to be reconsidered.
13874 : : *
13875 : : * The arguments to this function have the same meaning as the arguments to
13876 : : * ATExecAlterFKConstrEnforceability.
13877 : : */
13878 : : static void
13879 : 28 : AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13880 : : Relation conrel, Relation tgrel,
13881 : : Oid fkrelid, Oid pkrelid,
13882 : : HeapTuple contuple, LOCKMODE lockmode,
13883 : : Oid ReferencedParentDelTrigger,
13884 : : Oid ReferencedParentUpdTrigger,
13885 : : Oid ReferencingParentInsTrigger,
13886 : : Oid ReferencingParentUpdTrigger)
13887 : : {
13888 : : Form_pg_constraint currcon;
13889 : : Oid conoid;
13890 : : ScanKeyData pkey;
13891 : : SysScanDesc pscan;
13892 : : HeapTuple childtup;
13893 : :
13894 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13895 : 28 : conoid = currcon->oid;
13896 : :
13897 : 28 : ScanKeyInit(&pkey,
13898 : : Anum_pg_constraint_conparentid,
13899 : : BTEqualStrategyNumber, F_OIDEQ,
13900 : : ObjectIdGetDatum(conoid));
13901 : :
13902 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13903 : : true, NULL, 1, &pkey);
13904 : :
13905 [ + + ]: 92 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13906 : 64 : ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
13907 : : pkrelid, childtup, lockmode,
13908 : : ReferencedParentDelTrigger,
13909 : : ReferencedParentUpdTrigger,
13910 : : ReferencingParentInsTrigger,
13911 : : ReferencingParentUpdTrigger);
13912 : :
13913 : 28 : systable_endscan(pscan);
13914 : 28 : }
13915 : :
13916 : : /*
13917 : : * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
13918 : : * the specified constraint.
13919 : : *
13920 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13921 : : * list of child relations and recursing; instead it uses the conparentid
13922 : : * relationships. This may need to be reconsidered.
13923 : : *
13924 : : * The arguments to this function have the same meaning as the arguments to
13925 : : * ATExecAlterConstrDeferrability.
13926 : : */
13927 : : static void
13928 : 28 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13929 : : Relation conrel, Relation tgrel, Relation rel,
13930 : : HeapTuple contuple, bool recurse,
13931 : : List **otherrelids, LOCKMODE lockmode)
13932 : : {
13933 : : Form_pg_constraint currcon;
13934 : : Oid conoid;
13935 : : ScanKeyData pkey;
13936 : : SysScanDesc pscan;
13937 : : HeapTuple childtup;
13938 : :
13939 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13940 : 28 : conoid = currcon->oid;
13941 : :
13942 : 28 : ScanKeyInit(&pkey,
13943 : : Anum_pg_constraint_conparentid,
13944 : : BTEqualStrategyNumber, F_OIDEQ,
13945 : : ObjectIdGetDatum(conoid));
13946 : :
13947 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13948 : : true, NULL, 1, &pkey);
13949 : :
13950 [ + + ]: 72 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13951 : : {
13952 : 44 : Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13953 : : Relation childrel;
13954 : :
13955 : 44 : childrel = table_open(childcon->conrelid, lockmode);
13956 : :
13957 : 44 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
13958 : : childtup, recurse, otherrelids, lockmode);
13959 : 44 : table_close(childrel, NoLock);
13960 : : }
13961 : :
13962 : 28 : systable_endscan(pscan);
13963 : 28 : }
13964 : :
13965 : : /*
13966 : : * Update the constraint entry for the given ATAlterConstraint command, and
13967 : : * invoke the appropriate hooks.
13968 : : */
13969 : : static void
13970 : 524 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
13971 : : HeapTuple contuple)
13972 : : {
13973 : : HeapTuple copyTuple;
13974 : : Form_pg_constraint copy_con;
13975 : :
13976 : : Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
13977 : : cmdcon->alterInheritability);
13978 : :
13979 : 524 : copyTuple = heap_copytuple(contuple);
13980 : 524 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13981 : :
13982 [ + + ]: 524 : if (cmdcon->alterEnforceability)
13983 : : {
13984 : 376 : copy_con->conenforced = cmdcon->is_enforced;
13985 : :
13986 : : /*
13987 : : * NB: The convalidated status is irrelevant when the constraint is
13988 : : * set to NOT ENFORCED, but for consistency, it should still be set
13989 : : * appropriately. Similarly, if the constraint is later changed to
13990 : : * ENFORCED, validation will be performed during phase 3, so it makes
13991 : : * sense to mark it as valid in that case.
13992 : : */
13993 : 376 : copy_con->convalidated = cmdcon->is_enforced;
13994 : : }
13995 [ + + ]: 524 : if (cmdcon->alterDeferrability)
13996 : : {
13997 : 112 : copy_con->condeferrable = cmdcon->deferrable;
13998 : 112 : copy_con->condeferred = cmdcon->initdeferred;
13999 : : }
14000 [ + + ]: 524 : if (cmdcon->alterInheritability)
14001 : 40 : copy_con->connoinherit = cmdcon->noinherit;
14002 : :
14003 : 524 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
14004 [ - + ]: 524 : InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
14005 : :
14006 : : /* Make new constraint flags visible to others */
14007 : 524 : CacheInvalidateRelcacheByRelid(copy_con->conrelid);
14008 : :
14009 : 524 : heap_freetuple(copyTuple);
14010 : 524 : }
14011 : :
14012 : : /*
14013 : : * ALTER TABLE VALIDATE CONSTRAINT
14014 : : *
14015 : : * XXX The reason we handle recursion here rather than at Phase 1 is because
14016 : : * there's no good way to skip recursing when handling foreign keys: there is
14017 : : * no need to lock children in that case, yet we wouldn't be able to avoid
14018 : : * doing so at that level.
14019 : : *
14020 : : * Return value is the address of the validated constraint. If the constraint
14021 : : * was already validated, InvalidObjectAddress is returned.
14022 : : */
14023 : : static ObjectAddress
14024 : 364 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
14025 : : bool recurse, bool recursing, LOCKMODE lockmode)
14026 : : {
14027 : : Relation conrel;
14028 : : SysScanDesc scan;
14029 : : ScanKeyData skey[3];
14030 : : HeapTuple tuple;
14031 : : Form_pg_constraint con;
14032 : : ObjectAddress address;
14033 : :
14034 : 364 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14035 : :
14036 : : /*
14037 : : * Find and check the target constraint
14038 : : */
14039 : 364 : ScanKeyInit(&skey[0],
14040 : : Anum_pg_constraint_conrelid,
14041 : : BTEqualStrategyNumber, F_OIDEQ,
14042 : : ObjectIdGetDatum(RelationGetRelid(rel)));
14043 : 364 : ScanKeyInit(&skey[1],
14044 : : Anum_pg_constraint_contypid,
14045 : : BTEqualStrategyNumber, F_OIDEQ,
14046 : : ObjectIdGetDatum(InvalidOid));
14047 : 364 : ScanKeyInit(&skey[2],
14048 : : Anum_pg_constraint_conname,
14049 : : BTEqualStrategyNumber, F_NAMEEQ,
14050 : : CStringGetDatum(constrName));
14051 : 364 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14052 : : true, NULL, 3, skey);
14053 : :
14054 : : /* There can be at most one matching row */
14055 [ - + ]: 364 : if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
14056 [ # # ]: 0 : ereport(ERROR,
14057 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
14058 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14059 : : constrName, RelationGetRelationName(rel))));
14060 : :
14061 : 364 : con = (Form_pg_constraint) GETSTRUCT(tuple);
14062 [ + + ]: 364 : if (con->contype != CONSTRAINT_FOREIGN &&
14063 [ + + ]: 178 : con->contype != CONSTRAINT_CHECK &&
14064 [ - + ]: 78 : con->contype != CONSTRAINT_NOTNULL)
14065 [ # # ]: 0 : ereport(ERROR,
14066 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
14067 : : errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
14068 : : constrName, RelationGetRelationName(rel)),
14069 : : errdetail("This operation is not supported for this type of constraint."));
14070 : :
14071 [ + + ]: 364 : if (!con->conenforced)
14072 [ + - ]: 4 : ereport(ERROR,
14073 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14074 : : errmsg("cannot validate NOT ENFORCED constraint")));
14075 : :
14076 [ + + ]: 360 : if (!con->convalidated)
14077 : : {
14078 [ + + ]: 348 : if (con->contype == CONSTRAINT_FOREIGN)
14079 : : {
14080 : 182 : QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
14081 : : tuple, lockmode);
14082 : : }
14083 [ + + ]: 166 : else if (con->contype == CONSTRAINT_CHECK)
14084 : : {
14085 : 88 : QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
14086 : : tuple, recurse, recursing, lockmode);
14087 : : }
14088 [ + - ]: 78 : else if (con->contype == CONSTRAINT_NOTNULL)
14089 : : {
14090 : 78 : QueueNNConstraintValidation(wqueue, conrel, rel,
14091 : : tuple, recurse, recursing, lockmode);
14092 : : }
14093 : :
14094 : 348 : ObjectAddressSet(address, ConstraintRelationId, con->oid);
14095 : : }
14096 : : else
14097 : 12 : address = InvalidObjectAddress; /* already validated */
14098 : :
14099 : 360 : systable_endscan(scan);
14100 : :
14101 : 360 : table_close(conrel, RowExclusiveLock);
14102 : :
14103 : 360 : return address;
14104 : : }
14105 : :
14106 : : /*
14107 : : * QueueFKConstraintValidation
14108 : : *
14109 : : * Add an entry to the wqueue to validate the given foreign key constraint in
14110 : : * Phase 3 and update the convalidated field in the pg_constraint catalog
14111 : : * for the specified relation and all its children.
14112 : : */
14113 : : static void
14114 : 230 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
14115 : : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
14116 : : {
14117 : : Form_pg_constraint con;
14118 : : AlteredTableInfo *tab;
14119 : : HeapTuple copyTuple;
14120 : : Form_pg_constraint copy_con;
14121 : :
14122 : : /* since this function recurses, it could be driven to stack overflow */
14123 : 230 : check_stack_depth();
14124 : :
14125 : 230 : con = (Form_pg_constraint) GETSTRUCT(contuple);
14126 : : Assert(con->contype == CONSTRAINT_FOREIGN);
14127 : : Assert(!con->convalidated);
14128 : :
14129 : : /*
14130 : : * Add the validation to phase 3's queue; not needed for partitioned
14131 : : * tables themselves, only for their partitions.
14132 : : *
14133 : : * When the referenced table (pkrelid) is partitioned, the referencing
14134 : : * table (fkrel) has one pg_constraint row pointing to each partition
14135 : : * thereof. These rows are there only to support action triggers and no
14136 : : * table scan is needed, therefore skip this for them as well.
14137 : : */
14138 [ + + ]: 230 : if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
14139 [ + + ]: 198 : con->confrelid == pkrelid)
14140 : : {
14141 : : NewConstraint *newcon;
14142 : : Constraint *fkconstraint;
14143 : :
14144 : : /* Queue validation for phase 3 */
14145 : 190 : fkconstraint = makeNode(Constraint);
14146 : : /* for now this is all we need */
14147 : 190 : fkconstraint->conname = pstrdup(NameStr(con->conname));
14148 : :
14149 : 190 : newcon = palloc0_object(NewConstraint);
14150 : 190 : newcon->name = fkconstraint->conname;
14151 : 190 : newcon->contype = CONSTR_FOREIGN;
14152 : 190 : newcon->refrelid = con->confrelid;
14153 : 190 : newcon->refindid = con->conindid;
14154 : 190 : newcon->conid = con->oid;
14155 : 190 : newcon->qual = (Node *) fkconstraint;
14156 : :
14157 : : /* Find or create work queue entry for this table */
14158 : 190 : tab = ATGetQueueEntry(wqueue, fkrel);
14159 : 190 : tab->constraints = lappend(tab->constraints, newcon);
14160 : : }
14161 : :
14162 : : /*
14163 : : * If the table at either end of the constraint is partitioned, we need to
14164 : : * recurse and handle every unvalidated constraint that is a child of this
14165 : : * constraint.
14166 : : */
14167 [ + + + + ]: 428 : if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
14168 : 198 : get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
14169 : : {
14170 : : ScanKeyData pkey;
14171 : : SysScanDesc pscan;
14172 : : HeapTuple childtup;
14173 : :
14174 : 48 : ScanKeyInit(&pkey,
14175 : : Anum_pg_constraint_conparentid,
14176 : : BTEqualStrategyNumber, F_OIDEQ,
14177 : : ObjectIdGetDatum(con->oid));
14178 : :
14179 : 48 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
14180 : : true, NULL, 1, &pkey);
14181 : :
14182 [ + + ]: 96 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
14183 : : {
14184 : : Form_pg_constraint childcon;
14185 : : Relation childrel;
14186 : :
14187 : 48 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
14188 : :
14189 : : /*
14190 : : * If the child constraint has already been validated, no further
14191 : : * action is required for it or its descendants, as they are all
14192 : : * valid.
14193 : : */
14194 [ + + ]: 48 : if (childcon->convalidated)
14195 : 12 : continue;
14196 : :
14197 : 36 : childrel = table_open(childcon->conrelid, lockmode);
14198 : :
14199 : : /*
14200 : : * NB: Note that pkrelid should be passed as-is during recursion,
14201 : : * as it is required to identify the root referenced table.
14202 : : */
14203 : 36 : QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
14204 : : childtup, lockmode);
14205 : 36 : table_close(childrel, NoLock);
14206 : : }
14207 : :
14208 : 48 : systable_endscan(pscan);
14209 : : }
14210 : :
14211 : : /*
14212 : : * Now mark the pg_constraint row as validated (even if we didn't check,
14213 : : * notably the ones for partitions on the referenced side).
14214 : : *
14215 : : * We rely on transaction abort to roll back this change if phase 3
14216 : : * ultimately finds violating rows. This is a bit ugly.
14217 : : */
14218 : 230 : copyTuple = heap_copytuple(contuple);
14219 : 230 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
14220 : 230 : copy_con->convalidated = true;
14221 : 230 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
14222 : :
14223 [ - + ]: 230 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
14224 : :
14225 : 230 : heap_freetuple(copyTuple);
14226 : 230 : }
14227 : :
14228 : : /*
14229 : : * QueueCheckConstraintValidation
14230 : : *
14231 : : * Add an entry to the wqueue to validate the given check constraint in Phase 3
14232 : : * and update the convalidated field in the pg_constraint catalog for the
14233 : : * specified relation and all its inheriting children.
14234 : : */
14235 : : static void
14236 : 88 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
14237 : : char *constrName, HeapTuple contuple,
14238 : : bool recurse, bool recursing, LOCKMODE lockmode)
14239 : : {
14240 : : Form_pg_constraint con;
14241 : : AlteredTableInfo *tab;
14242 : : HeapTuple copyTuple;
14243 : : Form_pg_constraint copy_con;
14244 : :
14245 : 88 : List *children = NIL;
14246 : : ListCell *child;
14247 : : NewConstraint *newcon;
14248 : : Datum val;
14249 : : char *conbin;
14250 : :
14251 : 88 : con = (Form_pg_constraint) GETSTRUCT(contuple);
14252 : : Assert(con->contype == CONSTRAINT_CHECK);
14253 : :
14254 : : /*
14255 : : * If we're recursing, the parent has already done this, so skip it. Also,
14256 : : * if the constraint is a NO INHERIT constraint, we shouldn't try to look
14257 : : * for it in the children.
14258 : : */
14259 [ + + + + ]: 88 : if (!recursing && !con->connoinherit)
14260 : 52 : children = find_all_inheritors(RelationGetRelid(rel),
14261 : : lockmode, NULL);
14262 : :
14263 : : /*
14264 : : * For CHECK constraints, we must ensure that we only mark the constraint
14265 : : * as validated on the parent if it's already validated on the children.
14266 : : *
14267 : : * We recurse before validating on the parent, to reduce risk of
14268 : : * deadlocks.
14269 : : */
14270 [ + + + + : 172 : foreach(child, children)
+ + ]
14271 : : {
14272 : 84 : Oid childoid = lfirst_oid(child);
14273 : : Relation childrel;
14274 : :
14275 [ + + ]: 84 : if (childoid == RelationGetRelid(rel))
14276 : 52 : continue;
14277 : :
14278 : : /*
14279 : : * If we are told not to recurse, there had better not be any child
14280 : : * tables, because we can't mark the constraint on the parent valid
14281 : : * unless it is valid for all child tables.
14282 : : */
14283 [ - + ]: 32 : if (!recurse)
14284 [ # # ]: 0 : ereport(ERROR,
14285 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14286 : : errmsg("constraint must be validated on child tables too")));
14287 : :
14288 : : /* find_all_inheritors already got lock */
14289 : 32 : childrel = table_open(childoid, NoLock);
14290 : :
14291 : 32 : ATExecValidateConstraint(wqueue, childrel, constrName, false,
14292 : : true, lockmode);
14293 : 32 : table_close(childrel, NoLock);
14294 : : }
14295 : :
14296 : : /* Queue validation for phase 3 */
14297 : 88 : newcon = palloc0_object(NewConstraint);
14298 : 88 : newcon->name = constrName;
14299 : 88 : newcon->contype = CONSTR_CHECK;
14300 : 88 : newcon->refrelid = InvalidOid;
14301 : 88 : newcon->refindid = InvalidOid;
14302 : 88 : newcon->conid = con->oid;
14303 : :
14304 : 88 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
14305 : : Anum_pg_constraint_conbin);
14306 : 88 : conbin = TextDatumGetCString(val);
14307 : 88 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
14308 : :
14309 : : /* Find or create work queue entry for this table */
14310 : 88 : tab = ATGetQueueEntry(wqueue, rel);
14311 : 88 : tab->constraints = lappend(tab->constraints, newcon);
14312 : :
14313 : : /*
14314 : : * Invalidate relcache so that others see the new validated constraint.
14315 : : */
14316 : 88 : CacheInvalidateRelcache(rel);
14317 : :
14318 : : /*
14319 : : * Now update the catalog, while we have the door open.
14320 : : */
14321 : 88 : copyTuple = heap_copytuple(contuple);
14322 : 88 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
14323 : 88 : copy_con->convalidated = true;
14324 : 88 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
14325 : :
14326 [ - + ]: 88 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
14327 : :
14328 : 88 : heap_freetuple(copyTuple);
14329 : 88 : }
14330 : :
14331 : : /*
14332 : : * QueueNNConstraintValidation
14333 : : *
14334 : : * Add an entry to the wqueue to validate the given not-null constraint in
14335 : : * Phase 3 and update the convalidated field in the pg_constraint catalog for
14336 : : * the specified relation and all its inheriting children.
14337 : : */
14338 : : static void
14339 : 78 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
14340 : : HeapTuple contuple, bool recurse, bool recursing,
14341 : : LOCKMODE lockmode)
14342 : : {
14343 : : Form_pg_constraint con;
14344 : : AlteredTableInfo *tab;
14345 : : HeapTuple copyTuple;
14346 : : Form_pg_constraint copy_con;
14347 : 78 : List *children = NIL;
14348 : : AttrNumber attnum;
14349 : : char *colname;
14350 : :
14351 : 78 : con = (Form_pg_constraint) GETSTRUCT(contuple);
14352 : : Assert(con->contype == CONSTRAINT_NOTNULL);
14353 : :
14354 : 78 : attnum = extractNotNullColumn(contuple);
14355 : :
14356 : : /*
14357 : : * If we're recursing, we've already done this for parent, so skip it.
14358 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
14359 : : * look for it in the children.
14360 : : *
14361 : : * We recurse before validating on the parent, to reduce risk of
14362 : : * deadlocks.
14363 : : */
14364 [ + + + - ]: 78 : if (!recursing && !con->connoinherit)
14365 : 54 : children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
14366 : :
14367 : 78 : colname = get_attname(RelationGetRelid(rel), attnum, false);
14368 [ + + + + : 262 : foreach_oid(childoid, children)
+ + ]
14369 : : {
14370 : : Relation childrel;
14371 : : HeapTuple contup;
14372 : : Form_pg_constraint childcon;
14373 : : char *conname;
14374 : :
14375 [ + + ]: 106 : if (childoid == RelationGetRelid(rel))
14376 : 54 : continue;
14377 : :
14378 : : /*
14379 : : * If we are told not to recurse, there had better not be any child
14380 : : * tables, because we can't mark the constraint on the parent valid
14381 : : * unless it is valid for all child tables.
14382 : : */
14383 [ - + ]: 52 : if (!recurse)
14384 [ # # ]: 0 : ereport(ERROR,
14385 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14386 : : errmsg("constraint must be validated on child tables too"));
14387 : :
14388 : : /*
14389 : : * The column on child might have a different attnum, so search by
14390 : : * column name.
14391 : : */
14392 : 52 : contup = findNotNullConstraint(childoid, colname);
14393 [ - + ]: 52 : if (!contup)
14394 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
14395 : : colname, get_rel_name(childoid));
14396 : 52 : childcon = (Form_pg_constraint) GETSTRUCT(contup);
14397 [ + + ]: 52 : if (childcon->convalidated)
14398 : 28 : continue;
14399 : :
14400 : : /* find_all_inheritors already got lock */
14401 : 24 : childrel = table_open(childoid, NoLock);
14402 : 24 : conname = pstrdup(NameStr(childcon->conname));
14403 : :
14404 : : /* XXX improve ATExecValidateConstraint API to avoid double search */
14405 : 24 : ATExecValidateConstraint(wqueue, childrel, conname,
14406 : : false, true, lockmode);
14407 : 24 : table_close(childrel, NoLock);
14408 : : }
14409 : :
14410 : : /* Set attnotnull appropriately without queueing another validation */
14411 : 78 : set_attnotnull(NULL, rel, attnum, false);
14412 : :
14413 : 78 : tab = ATGetQueueEntry(wqueue, rel);
14414 : 78 : tab->verify_new_notnull = true;
14415 : :
14416 : : /*
14417 : : * Invalidate relcache so that others see the new validated constraint.
14418 : : */
14419 : 78 : CacheInvalidateRelcache(rel);
14420 : :
14421 : : /*
14422 : : * Now update the catalogs, while we have the door open.
14423 : : */
14424 : 78 : copyTuple = heap_copytuple(contuple);
14425 : 78 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
14426 : 78 : copy_con->convalidated = true;
14427 : 78 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
14428 : :
14429 [ - + ]: 78 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
14430 : :
14431 : 78 : heap_freetuple(copyTuple);
14432 : 78 : }
14433 : :
14434 : : /*
14435 : : * transformColumnNameList - transform list of column names
14436 : : *
14437 : : * Lookup each name and return its attnum and, optionally, type and collation
14438 : : * OIDs
14439 : : *
14440 : : * Note: the name of this function suggests that it's general-purpose,
14441 : : * but actually it's only used to look up names appearing in foreign-key
14442 : : * clauses. The error messages would need work to use it in other cases,
14443 : : * and perhaps the validity checks as well.
14444 : : */
14445 : : static int
14446 : 4601 : transformColumnNameList(Oid relId, List *colList,
14447 : : int16 *attnums, Oid *atttypids, Oid *attcollids)
14448 : : {
14449 : : ListCell *l;
14450 : : int attnum;
14451 : :
14452 : 4601 : attnum = 0;
14453 [ + + + + : 8381 : foreach(l, colList)
+ + ]
14454 : : {
14455 : 3824 : char *attname = strVal(lfirst(l));
14456 : : HeapTuple atttuple;
14457 : : Form_pg_attribute attform;
14458 : :
14459 : 3824 : atttuple = SearchSysCacheAttName(relId, attname);
14460 [ + + ]: 3824 : if (!HeapTupleIsValid(atttuple))
14461 [ + - ]: 36 : ereport(ERROR,
14462 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
14463 : : errmsg("column \"%s\" referenced in foreign key constraint does not exist",
14464 : : attname)));
14465 : 3788 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
14466 [ + + ]: 3788 : if (attform->attnum < 0)
14467 [ + - ]: 8 : ereport(ERROR,
14468 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14469 : : errmsg("system columns cannot be used in foreign keys")));
14470 [ - + ]: 3780 : if (attnum >= INDEX_MAX_KEYS)
14471 [ # # ]: 0 : ereport(ERROR,
14472 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
14473 : : errmsg("cannot have more than %d keys in a foreign key",
14474 : : INDEX_MAX_KEYS)));
14475 : 3780 : attnums[attnum] = attform->attnum;
14476 [ + + ]: 3780 : if (atttypids != NULL)
14477 : 3756 : atttypids[attnum] = attform->atttypid;
14478 [ + + ]: 3780 : if (attcollids != NULL)
14479 : 3756 : attcollids[attnum] = attform->attcollation;
14480 : 3780 : ReleaseSysCache(atttuple);
14481 : 3780 : attnum++;
14482 : : }
14483 : :
14484 : 4557 : return attnum;
14485 : : }
14486 : :
14487 : : /*
14488 : : * transformFkeyGetPrimaryKey -
14489 : : *
14490 : : * Look up the names, attnums, types, and collations of the primary key attributes
14491 : : * for the pkrel. Also return the index OID and index opclasses of the
14492 : : * index supporting the primary key. Also return whether the index has
14493 : : * WITHOUT OVERLAPS.
14494 : : *
14495 : : * All parameters except pkrel are output parameters. Also, the function
14496 : : * return value is the number of attributes in the primary key.
14497 : : *
14498 : : * Used when the column list in the REFERENCES specification is omitted.
14499 : : */
14500 : : static int
14501 : 908 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
14502 : : List **attnamelist,
14503 : : int16 *attnums, Oid *atttypids, Oid *attcollids,
14504 : : Oid *opclasses, bool *pk_has_without_overlaps)
14505 : : {
14506 : : List *indexoidlist;
14507 : : ListCell *indexoidscan;
14508 : 908 : HeapTuple indexTuple = NULL;
14509 : 908 : Form_pg_index indexStruct = NULL;
14510 : : Datum indclassDatum;
14511 : : oidvector *indclass;
14512 : : int i;
14513 : :
14514 : : /*
14515 : : * Get the list of index OIDs for the table from the relcache, and look up
14516 : : * each one in the pg_index syscache until we find one marked primary key
14517 : : * (hopefully there isn't more than one such). Insist it's valid, too.
14518 : : */
14519 : 908 : *indexOid = InvalidOid;
14520 : :
14521 : 908 : indexoidlist = RelationGetIndexList(pkrel);
14522 : :
14523 [ + - + - : 912 : foreach(indexoidscan, indexoidlist)
+ - ]
14524 : : {
14525 : 912 : Oid indexoid = lfirst_oid(indexoidscan);
14526 : :
14527 : 912 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
14528 [ - + ]: 912 : if (!HeapTupleIsValid(indexTuple))
14529 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
14530 : 912 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
14531 [ + + + - ]: 912 : if (indexStruct->indisprimary && indexStruct->indisvalid)
14532 : : {
14533 : : /*
14534 : : * Refuse to use a deferrable primary key. This is per SQL spec,
14535 : : * and there would be a lot of interesting semantic problems if we
14536 : : * tried to allow it.
14537 : : */
14538 [ - + ]: 908 : if (!indexStruct->indimmediate)
14539 [ # # ]: 0 : ereport(ERROR,
14540 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14541 : : errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
14542 : : RelationGetRelationName(pkrel))));
14543 : :
14544 : 908 : *indexOid = indexoid;
14545 : 908 : break;
14546 : : }
14547 : 4 : ReleaseSysCache(indexTuple);
14548 : : }
14549 : :
14550 : 908 : list_free(indexoidlist);
14551 : :
14552 : : /*
14553 : : * Check that we found it
14554 : : */
14555 [ - + ]: 908 : if (!OidIsValid(*indexOid))
14556 [ # # ]: 0 : ereport(ERROR,
14557 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
14558 : : errmsg("there is no primary key for referenced table \"%s\"",
14559 : : RelationGetRelationName(pkrel))));
14560 : :
14561 : : /* Must get indclass the hard way */
14562 : 908 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
14563 : : Anum_pg_index_indclass);
14564 : 908 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
14565 : :
14566 : : /*
14567 : : * Now build the list of PK attributes from the indkey definition (we
14568 : : * assume a primary key cannot have expressional elements)
14569 : : */
14570 : 908 : *attnamelist = NIL;
14571 [ + + ]: 2132 : for (i = 0; i < indexStruct->indnkeyatts; i++)
14572 : : {
14573 : 1224 : int pkattno = indexStruct->indkey.values[i];
14574 : :
14575 : 1224 : attnums[i] = pkattno;
14576 : 1224 : atttypids[i] = attnumTypeId(pkrel, pkattno);
14577 : 1224 : attcollids[i] = attnumCollationId(pkrel, pkattno);
14578 : 1224 : opclasses[i] = indclass->values[i];
14579 : 1224 : *attnamelist = lappend(*attnamelist,
14580 : 1224 : makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
14581 : : }
14582 : :
14583 : 908 : *pk_has_without_overlaps = indexStruct->indisexclusion;
14584 : :
14585 : 908 : ReleaseSysCache(indexTuple);
14586 : :
14587 : 908 : return i;
14588 : : }
14589 : :
14590 : : /*
14591 : : * transformFkeyCheckAttrs -
14592 : : *
14593 : : * Validate that the 'attnums' columns in the 'pkrel' relation are valid to
14594 : : * reference as part of a foreign key constraint.
14595 : : *
14596 : : * Returns the OID of the unique index supporting the constraint and
14597 : : * populates the caller-provided 'opclasses' array with the opclasses
14598 : : * associated with the index columns. Also sets whether the index
14599 : : * uses WITHOUT OVERLAPS.
14600 : : *
14601 : : * Raises an ERROR on validation failure.
14602 : : */
14603 : : static Oid
14604 : 875 : transformFkeyCheckAttrs(Relation pkrel,
14605 : : int numattrs, int16 *attnums,
14606 : : bool with_period, Oid *opclasses,
14607 : : bool *pk_has_without_overlaps)
14608 : : {
14609 : 875 : Oid indexoid = InvalidOid;
14610 : 875 : bool found = false;
14611 : 875 : bool found_deferrable = false;
14612 : : List *indexoidlist;
14613 : : ListCell *indexoidscan;
14614 : : int i,
14615 : : j;
14616 : :
14617 : : /*
14618 : : * Reject duplicate appearances of columns in the referenced-columns list.
14619 : : * Such a case is forbidden by the SQL standard, and even if we thought it
14620 : : * useful to allow it, there would be ambiguity about how to match the
14621 : : * list to unique indexes (in particular, it'd be unclear which index
14622 : : * opclass goes with which FK column).
14623 : : */
14624 [ + + ]: 2055 : for (i = 0; i < numattrs; i++)
14625 : : {
14626 [ + + ]: 1567 : for (j = i + 1; j < numattrs; j++)
14627 : : {
14628 [ + + ]: 387 : if (attnums[i] == attnums[j])
14629 [ + - ]: 16 : ereport(ERROR,
14630 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
14631 : : errmsg("foreign key referenced-columns list must not contain duplicates")));
14632 : : }
14633 : : }
14634 : :
14635 : : /*
14636 : : * Get the list of index OIDs for the table from the relcache, and look up
14637 : : * each one in the pg_index syscache, and match unique indexes to the list
14638 : : * of attnums we are given.
14639 : : */
14640 : 859 : indexoidlist = RelationGetIndexList(pkrel);
14641 : :
14642 [ + - + + : 978 : foreach(indexoidscan, indexoidlist)
+ + ]
14643 : : {
14644 : : HeapTuple indexTuple;
14645 : : Form_pg_index indexStruct;
14646 : :
14647 : 970 : indexoid = lfirst_oid(indexoidscan);
14648 : 970 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
14649 [ - + ]: 970 : if (!HeapTupleIsValid(indexTuple))
14650 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
14651 : 970 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
14652 : :
14653 : : /*
14654 : : * Must have the right number of columns; must be unique (or if
14655 : : * temporal then exclusion instead) and not a partial index; forget it
14656 : : * if there are any expressions, too. Invalid indexes are out as well.
14657 : : */
14658 [ + + + + : 970 : if (indexStruct->indnkeyatts == numattrs &&
+ + ]
14659 : 889 : (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
14660 [ + - + - ]: 1778 : indexStruct->indisvalid &&
14661 [ + - ]: 1778 : heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
14662 : 889 : heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
14663 : : {
14664 : : Datum indclassDatum;
14665 : : oidvector *indclass;
14666 : :
14667 : : /* Must get indclass the hard way */
14668 : 889 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
14669 : : Anum_pg_index_indclass);
14670 : 889 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
14671 : :
14672 : : /*
14673 : : * The given attnum list may match the index columns in any order.
14674 : : * Check for a match, and extract the appropriate opclasses while
14675 : : * we're at it.
14676 : : *
14677 : : * We know that attnums[] is duplicate-free per the test at the
14678 : : * start of this function, and we checked above that the number of
14679 : : * index columns agrees, so if we find a match for each attnums[]
14680 : : * entry then we must have a one-to-one match in some order.
14681 : : */
14682 [ + + ]: 2061 : for (i = 0; i < numattrs; i++)
14683 : : {
14684 : 1210 : found = false;
14685 [ + + ]: 1619 : for (j = 0; j < numattrs; j++)
14686 : : {
14687 [ + + ]: 1581 : if (attnums[i] == indexStruct->indkey.values[j])
14688 : : {
14689 : 1172 : opclasses[i] = indclass->values[j];
14690 : 1172 : found = true;
14691 : 1172 : break;
14692 : : }
14693 : : }
14694 [ + + ]: 1210 : if (!found)
14695 : 38 : break;
14696 : : }
14697 : : /* The last attribute in the index must be the PERIOD FK part */
14698 [ + + + + ]: 889 : if (found && with_period)
14699 : : {
14700 : 80 : int16 periodattnum = attnums[numattrs - 1];
14701 : :
14702 : 80 : found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
14703 : : }
14704 : :
14705 : : /*
14706 : : * Refuse to use a deferrable unique/primary key. This is per SQL
14707 : : * spec, and there would be a lot of interesting semantic problems
14708 : : * if we tried to allow it.
14709 : : */
14710 [ + + - + ]: 889 : if (found && !indexStruct->indimmediate)
14711 : : {
14712 : : /*
14713 : : * Remember that we found an otherwise matching index, so that
14714 : : * we can generate a more appropriate error message.
14715 : : */
14716 : 0 : found_deferrable = true;
14717 : 0 : found = false;
14718 : : }
14719 : :
14720 : : /* We need to know whether the index has WITHOUT OVERLAPS */
14721 [ + + ]: 889 : if (found)
14722 : 851 : *pk_has_without_overlaps = indexStruct->indisexclusion;
14723 : : }
14724 : 970 : ReleaseSysCache(indexTuple);
14725 [ + + ]: 970 : if (found)
14726 : 851 : break;
14727 : : }
14728 : :
14729 [ + + ]: 859 : if (!found)
14730 : : {
14731 [ - + ]: 8 : if (found_deferrable)
14732 [ # # ]: 0 : ereport(ERROR,
14733 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14734 : : errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
14735 : : RelationGetRelationName(pkrel))));
14736 : : else
14737 [ + - ]: 8 : ereport(ERROR,
14738 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
14739 : : errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
14740 : : RelationGetRelationName(pkrel))));
14741 : : }
14742 : :
14743 : 851 : list_free(indexoidlist);
14744 : :
14745 : 851 : return indexoid;
14746 : : }
14747 : :
14748 : : /*
14749 : : * findFkeyCast -
14750 : : *
14751 : : * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
14752 : : * Caller has equal regard for binary coercibility and for an exact match.
14753 : : */
14754 : : static CoercionPathType
14755 : 8 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
14756 : : {
14757 : : CoercionPathType ret;
14758 : :
14759 [ + - ]: 8 : if (targetTypeId == sourceTypeId)
14760 : : {
14761 : 8 : ret = COERCION_PATH_RELABELTYPE;
14762 : 8 : *funcid = InvalidOid;
14763 : : }
14764 : : else
14765 : : {
14766 : 0 : ret = find_coercion_pathway(targetTypeId, sourceTypeId,
14767 : : COERCION_IMPLICIT, funcid);
14768 [ # # ]: 0 : if (ret == COERCION_PATH_NONE)
14769 : : /* A previously-relied-upon cast is now gone. */
14770 [ # # ]: 0 : elog(ERROR, "could not find cast from %u to %u",
14771 : : sourceTypeId, targetTypeId);
14772 : : }
14773 : :
14774 : 8 : return ret;
14775 : : }
14776 : :
14777 : : /*
14778 : : * Permissions checks on the referenced table for ADD FOREIGN KEY
14779 : : *
14780 : : * Note: we have already checked that the user owns the referencing table,
14781 : : * else we'd have failed much earlier; no additional checks are needed for it.
14782 : : */
14783 : : static void
14784 : 1735 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
14785 : : {
14786 : 1735 : Oid roleid = GetUserId();
14787 : : AclResult aclresult;
14788 : : int i;
14789 : :
14790 : : /* Okay if we have relation-level REFERENCES permission */
14791 : 1735 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
14792 : : ACL_REFERENCES);
14793 [ + - ]: 1735 : if (aclresult == ACLCHECK_OK)
14794 : 1735 : return;
14795 : : /* Else we must have REFERENCES on each column */
14796 [ # # ]: 0 : for (i = 0; i < natts; i++)
14797 : : {
14798 : 0 : aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
14799 : : roleid, ACL_REFERENCES);
14800 [ # # ]: 0 : if (aclresult != ACLCHECK_OK)
14801 : 0 : aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
14802 : 0 : RelationGetRelationName(rel));
14803 : : }
14804 : : }
14805 : :
14806 : : /*
14807 : : * Scan the existing rows in a table to verify they meet a proposed FK
14808 : : * constraint.
14809 : : *
14810 : : * Caller must have opened and locked both relations appropriately.
14811 : : */
14812 : : static void
14813 : 839 : validateForeignKeyConstraint(char *conname,
14814 : : Relation rel,
14815 : : Relation pkrel,
14816 : : Oid pkindOid,
14817 : : Oid constraintOid,
14818 : : bool hasperiod)
14819 : : {
14820 : : TupleTableSlot *slot;
14821 : : TableScanDesc scan;
14822 : 839 : Trigger trig = {0};
14823 : : Snapshot snapshot;
14824 : : MemoryContext oldcxt;
14825 : : MemoryContext perTupCxt;
14826 : :
14827 [ - + ]: 839 : ereport(DEBUG1,
14828 : : (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
14829 : :
14830 : : /*
14831 : : * Build a trigger call structure; we'll need it either way.
14832 : : */
14833 : 839 : trig.tgoid = InvalidOid;
14834 : 839 : trig.tgname = conname;
14835 : 839 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
14836 : 839 : trig.tgisinternal = true;
14837 : 839 : trig.tgconstrrelid = RelationGetRelid(pkrel);
14838 : 839 : trig.tgconstrindid = pkindOid;
14839 : 839 : trig.tgconstraint = constraintOid;
14840 : 839 : trig.tgdeferrable = false;
14841 : 839 : trig.tginitdeferred = false;
14842 : : /* we needn't fill in remaining fields */
14843 : :
14844 : : /*
14845 : : * See if we can do it with a single LEFT JOIN query. A false result
14846 : : * indicates we must proceed with the fire-the-trigger method. We can't do
14847 : : * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
14848 : : * left joins.
14849 : : */
14850 [ + + + + ]: 839 : if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
14851 : 680 : return;
14852 : :
14853 : : /*
14854 : : * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
14855 : : * if that tuple had just been inserted. If any of those fail, it should
14856 : : * ereport(ERROR) and that's that.
14857 : : */
14858 : 112 : snapshot = RegisterSnapshot(GetLatestSnapshot());
14859 : 112 : slot = table_slot_create(rel, NULL);
14860 : 112 : scan = table_beginscan(rel, snapshot, 0, NULL,
14861 : : SO_NONE);
14862 : 112 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
14863 : : "validateForeignKeyConstraint",
14864 : : ALLOCSET_SMALL_SIZES);
14865 : 112 : oldcxt = MemoryContextSwitchTo(perTupCxt);
14866 : :
14867 [ + + ]: 581 : while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
14868 : : {
14869 : 509 : LOCAL_FCINFO(fcinfo, 0);
14870 : 509 : TriggerData trigdata = {0};
14871 : :
14872 [ - + ]: 509 : CHECK_FOR_INTERRUPTS();
14873 : :
14874 : : /*
14875 : : * Make a call to the trigger function
14876 : : *
14877 : : * No parameters are passed, but we do set a context
14878 : : */
14879 [ + - + - : 2545 : MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
+ - + - +
+ ]
14880 : :
14881 : : /*
14882 : : * We assume RI_FKey_check_ins won't look at flinfo...
14883 : : */
14884 : 509 : trigdata.type = T_TriggerData;
14885 : 509 : trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
14886 : 509 : trigdata.tg_relation = rel;
14887 : 509 : trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
14888 : 509 : trigdata.tg_trigslot = slot;
14889 : 509 : trigdata.tg_trigger = &trig;
14890 : :
14891 : 509 : fcinfo->context = (Node *) &trigdata;
14892 : :
14893 : 509 : RI_FKey_check_ins(fcinfo);
14894 : :
14895 : 469 : MemoryContextReset(perTupCxt);
14896 : : }
14897 : :
14898 : 72 : MemoryContextSwitchTo(oldcxt);
14899 : 72 : MemoryContextDelete(perTupCxt);
14900 : 72 : table_endscan(scan);
14901 : 72 : UnregisterSnapshot(snapshot);
14902 : 72 : ExecDropSingleTupleTableSlot(slot);
14903 : : }
14904 : :
14905 : : /*
14906 : : * CreateFKCheckTrigger
14907 : : * Creates the insert (on_insert=true) or update "check" trigger that
14908 : : * implements a given foreign key
14909 : : *
14910 : : * Returns the OID of the so created trigger.
14911 : : */
14912 : : static Oid
14913 : 4100 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14914 : : Oid constraintOid, Oid indexOid, Oid parentTrigOid,
14915 : : bool on_insert)
14916 : : {
14917 : : ObjectAddress trigAddress;
14918 : : CreateTrigStmt *fk_trigger;
14919 : :
14920 : : /*
14921 : : * Note: for a self-referential FK (referencing and referenced tables are
14922 : : * the same), it is important that the ON UPDATE action fires before the
14923 : : * CHECK action, since both triggers will fire on the same row during an
14924 : : * UPDATE event; otherwise the CHECK trigger will be checking a non-final
14925 : : * state of the row. Triggers fire in name order, so we ensure this by
14926 : : * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
14927 : : * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
14928 : : */
14929 : 4100 : fk_trigger = makeNode(CreateTrigStmt);
14930 : 4100 : fk_trigger->replace = false;
14931 : 4100 : fk_trigger->isconstraint = true;
14932 : 4100 : fk_trigger->trigname = "RI_ConstraintTrigger_c";
14933 : 4100 : fk_trigger->relation = NULL;
14934 : :
14935 : : /* Either ON INSERT or ON UPDATE */
14936 [ + + ]: 4100 : if (on_insert)
14937 : : {
14938 : 2050 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
14939 : 2050 : fk_trigger->events = TRIGGER_TYPE_INSERT;
14940 : : }
14941 : : else
14942 : : {
14943 : 2050 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
14944 : 2050 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14945 : : }
14946 : :
14947 : 4100 : fk_trigger->args = NIL;
14948 : 4100 : fk_trigger->row = true;
14949 : 4100 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14950 : 4100 : fk_trigger->columns = NIL;
14951 : 4100 : fk_trigger->whenClause = NULL;
14952 : 4100 : fk_trigger->transitionRels = NIL;
14953 : 4100 : fk_trigger->deferrable = fkconstraint->deferrable;
14954 : 4100 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14955 : 4100 : fk_trigger->constrrel = NULL;
14956 : :
14957 : 4100 : trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
14958 : : constraintOid, indexOid, InvalidOid,
14959 : : parentTrigOid, NULL, true, false);
14960 : :
14961 : : /* Make changes-so-far visible */
14962 : 4100 : CommandCounterIncrement();
14963 : :
14964 : 4100 : return trigAddress.objectId;
14965 : : }
14966 : :
14967 : : /*
14968 : : * createForeignKeyActionTriggers
14969 : : * Create the referenced-side "action" triggers that implement a foreign
14970 : : * key.
14971 : : *
14972 : : * Returns the OIDs of the so created triggers in *deleteTrigOid and
14973 : : * *updateTrigOid.
14974 : : */
14975 : : static void
14976 : 2329 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14977 : : Oid constraintOid, Oid indexOid,
14978 : : Oid parentDelTrigger, Oid parentUpdTrigger,
14979 : : Oid *deleteTrigOid, Oid *updateTrigOid)
14980 : : {
14981 : : CreateTrigStmt *fk_trigger;
14982 : : ObjectAddress trigAddress;
14983 : :
14984 : : /*
14985 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14986 : : * DELETE action on the referenced table.
14987 : : */
14988 : 2329 : fk_trigger = makeNode(CreateTrigStmt);
14989 : 2329 : fk_trigger->replace = false;
14990 : 2329 : fk_trigger->isconstraint = true;
14991 : 2329 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14992 : 2329 : fk_trigger->relation = NULL;
14993 : 2329 : fk_trigger->args = NIL;
14994 : 2329 : fk_trigger->row = true;
14995 : 2329 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14996 : 2329 : fk_trigger->events = TRIGGER_TYPE_DELETE;
14997 : 2329 : fk_trigger->columns = NIL;
14998 : 2329 : fk_trigger->whenClause = NULL;
14999 : 2329 : fk_trigger->transitionRels = NIL;
15000 : 2329 : fk_trigger->constrrel = NULL;
15001 : :
15002 [ + + + + : 2329 : switch (fkconstraint->fk_del_action)
+ - ]
15003 : : {
15004 : 1896 : case FKCONSTR_ACTION_NOACTION:
15005 : 1896 : fk_trigger->deferrable = fkconstraint->deferrable;
15006 : 1896 : fk_trigger->initdeferred = fkconstraint->initdeferred;
15007 : 1896 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
15008 : 1896 : break;
15009 : 20 : case FKCONSTR_ACTION_RESTRICT:
15010 : 20 : fk_trigger->deferrable = false;
15011 : 20 : fk_trigger->initdeferred = false;
15012 : 20 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
15013 : 20 : break;
15014 : 310 : case FKCONSTR_ACTION_CASCADE:
15015 : 310 : fk_trigger->deferrable = false;
15016 : 310 : fk_trigger->initdeferred = false;
15017 : 310 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
15018 : 310 : break;
15019 : 63 : case FKCONSTR_ACTION_SETNULL:
15020 : 63 : fk_trigger->deferrable = false;
15021 : 63 : fk_trigger->initdeferred = false;
15022 : 63 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
15023 : 63 : break;
15024 : 40 : case FKCONSTR_ACTION_SETDEFAULT:
15025 : 40 : fk_trigger->deferrable = false;
15026 : 40 : fk_trigger->initdeferred = false;
15027 : 40 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
15028 : 40 : break;
15029 : 0 : default:
15030 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
15031 : : (int) fkconstraint->fk_del_action);
15032 : : break;
15033 : : }
15034 : :
15035 : 2329 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
15036 : : constraintOid, indexOid, InvalidOid,
15037 : : parentDelTrigger, NULL, true, false);
15038 [ + - ]: 2329 : if (deleteTrigOid)
15039 : 2329 : *deleteTrigOid = trigAddress.objectId;
15040 : :
15041 : : /* Make changes-so-far visible */
15042 : 2329 : CommandCounterIncrement();
15043 : :
15044 : : /*
15045 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
15046 : : * UPDATE action on the referenced table.
15047 : : */
15048 : 2329 : fk_trigger = makeNode(CreateTrigStmt);
15049 : 2329 : fk_trigger->replace = false;
15050 : 2329 : fk_trigger->isconstraint = true;
15051 : 2329 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
15052 : 2329 : fk_trigger->relation = NULL;
15053 : 2329 : fk_trigger->args = NIL;
15054 : 2329 : fk_trigger->row = true;
15055 : 2329 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
15056 : 2329 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
15057 : 2329 : fk_trigger->columns = NIL;
15058 : 2329 : fk_trigger->whenClause = NULL;
15059 : 2329 : fk_trigger->transitionRels = NIL;
15060 : 2329 : fk_trigger->constrrel = NULL;
15061 : :
15062 [ + + + + : 2329 : switch (fkconstraint->fk_upd_action)
+ - ]
15063 : : {
15064 : 2025 : case FKCONSTR_ACTION_NOACTION:
15065 : 2025 : fk_trigger->deferrable = fkconstraint->deferrable;
15066 : 2025 : fk_trigger->initdeferred = fkconstraint->initdeferred;
15067 : 2025 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
15068 : 2025 : break;
15069 : 24 : case FKCONSTR_ACTION_RESTRICT:
15070 : 24 : fk_trigger->deferrable = false;
15071 : 24 : fk_trigger->initdeferred = false;
15072 : 24 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
15073 : 24 : break;
15074 : 211 : case FKCONSTR_ACTION_CASCADE:
15075 : 211 : fk_trigger->deferrable = false;
15076 : 211 : fk_trigger->initdeferred = false;
15077 : 211 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
15078 : 211 : break;
15079 : 41 : case FKCONSTR_ACTION_SETNULL:
15080 : 41 : fk_trigger->deferrable = false;
15081 : 41 : fk_trigger->initdeferred = false;
15082 : 41 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
15083 : 41 : break;
15084 : 28 : case FKCONSTR_ACTION_SETDEFAULT:
15085 : 28 : fk_trigger->deferrable = false;
15086 : 28 : fk_trigger->initdeferred = false;
15087 : 28 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
15088 : 28 : break;
15089 : 0 : default:
15090 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
15091 : : (int) fkconstraint->fk_upd_action);
15092 : : break;
15093 : : }
15094 : :
15095 : 2329 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
15096 : : constraintOid, indexOid, InvalidOid,
15097 : : parentUpdTrigger, NULL, true, false);
15098 [ + - ]: 2329 : if (updateTrigOid)
15099 : 2329 : *updateTrigOid = trigAddress.objectId;
15100 : 2329 : }
15101 : :
15102 : : /*
15103 : : * createForeignKeyCheckTriggers
15104 : : * Create the referencing-side "check" triggers that implement a foreign
15105 : : * key.
15106 : : *
15107 : : * Returns the OIDs of the so created triggers in *insertTrigOid and
15108 : : * *updateTrigOid.
15109 : : */
15110 : : static void
15111 : 2050 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
15112 : : Constraint *fkconstraint, Oid constraintOid,
15113 : : Oid indexOid,
15114 : : Oid parentInsTrigger, Oid parentUpdTrigger,
15115 : : Oid *insertTrigOid, Oid *updateTrigOid)
15116 : : {
15117 : 2050 : *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
15118 : : constraintOid, indexOid,
15119 : : parentInsTrigger, true);
15120 : 2050 : *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
15121 : : constraintOid, indexOid,
15122 : : parentUpdTrigger, false);
15123 : 2050 : }
15124 : :
15125 : : /*
15126 : : * ALTER TABLE DROP CONSTRAINT
15127 : : *
15128 : : * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
15129 : : */
15130 : : static void
15131 : 575 : ATExecDropConstraint(Relation rel, const char *constrName,
15132 : : DropBehavior behavior, bool recurse,
15133 : : bool missing_ok, LOCKMODE lockmode)
15134 : : {
15135 : : Relation conrel;
15136 : : SysScanDesc scan;
15137 : : ScanKeyData skey[3];
15138 : : HeapTuple tuple;
15139 : 575 : bool found = false;
15140 : :
15141 : 575 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
15142 : :
15143 : : /*
15144 : : * Find and drop the target constraint
15145 : : */
15146 : 575 : ScanKeyInit(&skey[0],
15147 : : Anum_pg_constraint_conrelid,
15148 : : BTEqualStrategyNumber, F_OIDEQ,
15149 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15150 : 575 : ScanKeyInit(&skey[1],
15151 : : Anum_pg_constraint_contypid,
15152 : : BTEqualStrategyNumber, F_OIDEQ,
15153 : : ObjectIdGetDatum(InvalidOid));
15154 : 575 : ScanKeyInit(&skey[2],
15155 : : Anum_pg_constraint_conname,
15156 : : BTEqualStrategyNumber, F_NAMEEQ,
15157 : : CStringGetDatum(constrName));
15158 : 575 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
15159 : : true, NULL, 3, skey);
15160 : :
15161 : : /* There can be at most one matching row */
15162 [ + + ]: 575 : if (HeapTupleIsValid(tuple = systable_getnext(scan)))
15163 : : {
15164 : 551 : dropconstraint_internal(rel, tuple, behavior, recurse, false,
15165 : : missing_ok, lockmode);
15166 : 427 : found = true;
15167 : : }
15168 : :
15169 : 451 : systable_endscan(scan);
15170 : :
15171 [ + + ]: 451 : if (!found)
15172 : : {
15173 [ + + ]: 24 : if (!missing_ok)
15174 [ + - ]: 16 : ereport(ERROR,
15175 : : errcode(ERRCODE_UNDEFINED_OBJECT),
15176 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
15177 : : constrName, RelationGetRelationName(rel)));
15178 : : else
15179 [ + - ]: 8 : ereport(NOTICE,
15180 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
15181 : : constrName, RelationGetRelationName(rel)));
15182 : : }
15183 : :
15184 : 435 : table_close(conrel, RowExclusiveLock);
15185 : 435 : }
15186 : :
15187 : : /*
15188 : : * Remove a constraint, using its pg_constraint tuple
15189 : : *
15190 : : * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
15191 : : * DROP NOT NULL.
15192 : : *
15193 : : * Returns the address of the constraint being removed.
15194 : : */
15195 : : static ObjectAddress
15196 : 879 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
15197 : : bool recurse, bool recursing, bool missing_ok,
15198 : : LOCKMODE lockmode)
15199 : : {
15200 : : Relation conrel;
15201 : : Form_pg_constraint con;
15202 : : ObjectAddress conobj;
15203 : : List *children;
15204 : 879 : bool is_no_inherit_constraint = false;
15205 : : char *constrName;
15206 : 879 : char *colname = NULL;
15207 : :
15208 : : /* Guard against stack overflow due to overly deep inheritance tree. */
15209 : 879 : check_stack_depth();
15210 : :
15211 : : /* At top level, permission check was done in ATPrepCmd, else do it */
15212 [ + + ]: 879 : if (recursing)
15213 : 163 : ATSimplePermissions(AT_DropConstraint, rel,
15214 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
15215 : :
15216 : 875 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
15217 : :
15218 : 875 : con = (Form_pg_constraint) GETSTRUCT(constraintTup);
15219 : 875 : constrName = NameStr(con->conname);
15220 : :
15221 : : /* Don't allow drop of inherited constraints */
15222 [ + + + + ]: 875 : if (con->coninhcount > 0 && !recursing)
15223 [ + - ]: 104 : ereport(ERROR,
15224 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15225 : : errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
15226 : : constrName, RelationGetRelationName(rel))));
15227 : :
15228 : : /*
15229 : : * Reset pg_constraint.attnotnull, if this is a not-null constraint.
15230 : : *
15231 : : * While doing that, we're in a good position to disallow dropping a not-
15232 : : * null constraint underneath a primary key, a replica identity index, or
15233 : : * a generated identity column.
15234 : : */
15235 [ + + ]: 771 : if (con->contype == CONSTRAINT_NOTNULL)
15236 : : {
15237 : 235 : Relation attrel = table_open(AttributeRelationId, RowExclusiveLock);
15238 : 235 : AttrNumber attnum = extractNotNullColumn(constraintTup);
15239 : : Bitmapset *pkattrs;
15240 : : Bitmapset *irattrs;
15241 : : HeapTuple atttup;
15242 : : Form_pg_attribute attForm;
15243 : :
15244 : : /* save column name for recursion step */
15245 : 235 : colname = get_attname(RelationGetRelid(rel), attnum, false);
15246 : :
15247 : : /*
15248 : : * Disallow if it's in the primary key. For partitioned tables we
15249 : : * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
15250 : : * return NULL if the primary key is invalid; but we still need to
15251 : : * protect not-null constraints under such a constraint, so check the
15252 : : * slow way.
15253 : : */
15254 : 235 : pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
15255 : :
15256 [ + + ]: 235 : if (pkattrs == NULL &&
15257 [ + + ]: 215 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
15258 : : {
15259 : 16 : Oid pkindex = RelationGetPrimaryKeyIndex(rel, true);
15260 : :
15261 [ - + ]: 16 : if (OidIsValid(pkindex))
15262 : : {
15263 : 0 : Relation pk = relation_open(pkindex, AccessShareLock);
15264 : :
15265 : 0 : pkattrs = NULL;
15266 [ # # ]: 0 : for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
15267 : 0 : pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
15268 : :
15269 : 0 : relation_close(pk, AccessShareLock);
15270 : : }
15271 : : }
15272 : :
15273 [ + + + + ]: 255 : if (pkattrs &&
15274 : 20 : bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
15275 [ + - ]: 16 : ereport(ERROR,
15276 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15277 : : errmsg("column \"%s\" is in a primary key",
15278 : : get_attname(RelationGetRelid(rel), attnum, false)));
15279 : :
15280 : : /* Disallow if it's in the replica identity */
15281 : 219 : irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
15282 [ + + ]: 219 : if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
15283 [ + - ]: 8 : ereport(ERROR,
15284 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15285 : : errmsg("column \"%s\" is in index used as replica identity",
15286 : : get_attname(RelationGetRelid(rel), attnum, false)));
15287 : :
15288 : : /* Disallow if it's a GENERATED AS IDENTITY column */
15289 : 211 : atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
15290 [ - + ]: 211 : if (!HeapTupleIsValid(atttup))
15291 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
15292 : : attnum, RelationGetRelid(rel));
15293 : 211 : attForm = (Form_pg_attribute) GETSTRUCT(atttup);
15294 [ - + ]: 211 : if (attForm->attidentity != '\0')
15295 [ # # ]: 0 : ereport(ERROR,
15296 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
15297 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
15298 : : get_attname(RelationGetRelid(rel), attnum,
15299 : : false),
15300 : : RelationGetRelationName(rel)));
15301 : :
15302 : : /* All good -- reset attnotnull if needed */
15303 [ + - ]: 211 : if (attForm->attnotnull)
15304 : : {
15305 : 211 : attForm->attnotnull = false;
15306 : 211 : CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
15307 : : }
15308 : :
15309 : 211 : table_close(attrel, RowExclusiveLock);
15310 : : }
15311 : :
15312 : 747 : is_no_inherit_constraint = con->connoinherit;
15313 : :
15314 : : /*
15315 : : * If it's a foreign-key constraint, we'd better lock the referenced table
15316 : : * and check that that's not in use, just as we've already done for the
15317 : : * constrained table (else we might, eg, be dropping a trigger that has
15318 : : * unfired events). But we can/must skip that in the self-referential
15319 : : * case.
15320 : : */
15321 [ + + ]: 747 : if (con->contype == CONSTRAINT_FOREIGN &&
15322 [ + - ]: 112 : con->confrelid != RelationGetRelid(rel))
15323 : : {
15324 : : Relation frel;
15325 : :
15326 : : /* Must match lock taken by RemoveTriggerById: */
15327 : 112 : frel = table_open(con->confrelid, AccessExclusiveLock);
15328 : 112 : CheckAlterTableIsSafe(frel);
15329 : 108 : table_close(frel, NoLock);
15330 : : }
15331 : :
15332 : : /*
15333 : : * Perform the actual constraint deletion
15334 : : */
15335 : 743 : ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
15336 : 743 : performDeletion(&conobj, behavior, 0);
15337 : :
15338 : : /*
15339 : : * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
15340 : : * are dropped via the dependency mechanism, so we're done here.
15341 : : */
15342 [ + + ]: 719 : if (con->contype != CONSTRAINT_CHECK &&
15343 [ + + ]: 462 : con->contype != CONSTRAINT_NOTNULL &&
15344 [ + + ]: 251 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
15345 : : {
15346 : 52 : table_close(conrel, RowExclusiveLock);
15347 : 52 : return conobj;
15348 : : }
15349 : :
15350 : : /*
15351 : : * Propagate to children as appropriate. Unlike most other ALTER
15352 : : * routines, we have to do this one level of recursion at a time; we can't
15353 : : * use find_all_inheritors to do it in one pass.
15354 : : */
15355 [ + + ]: 667 : if (!is_no_inherit_constraint)
15356 : 452 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
15357 : : else
15358 : 215 : children = NIL;
15359 : :
15360 [ + + + + : 1613 : foreach_oid(childrelid, children)
+ + ]
15361 : : {
15362 : : Relation childrel;
15363 : : HeapTuple tuple;
15364 : : Form_pg_constraint childcon;
15365 : :
15366 : : /* find_inheritance_children already got lock */
15367 : 287 : childrel = table_open(childrelid, NoLock);
15368 : 287 : CheckAlterTableIsSafe(childrel);
15369 : :
15370 : : /*
15371 : : * We search for not-null constraints by column name, and others by
15372 : : * constraint name.
15373 : : */
15374 [ + + ]: 287 : if (con->contype == CONSTRAINT_NOTNULL)
15375 : : {
15376 : 102 : tuple = findNotNullConstraint(childrelid, colname);
15377 [ - + ]: 102 : if (!HeapTupleIsValid(tuple))
15378 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
15379 : : colname, RelationGetRelid(childrel));
15380 : : }
15381 : : else
15382 : : {
15383 : : SysScanDesc scan;
15384 : : ScanKeyData skey[3];
15385 : :
15386 : 185 : ScanKeyInit(&skey[0],
15387 : : Anum_pg_constraint_conrelid,
15388 : : BTEqualStrategyNumber, F_OIDEQ,
15389 : : ObjectIdGetDatum(childrelid));
15390 : 185 : ScanKeyInit(&skey[1],
15391 : : Anum_pg_constraint_contypid,
15392 : : BTEqualStrategyNumber, F_OIDEQ,
15393 : : ObjectIdGetDatum(InvalidOid));
15394 : 185 : ScanKeyInit(&skey[2],
15395 : : Anum_pg_constraint_conname,
15396 : : BTEqualStrategyNumber, F_NAMEEQ,
15397 : : CStringGetDatum(constrName));
15398 : 185 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
15399 : : true, NULL, 3, skey);
15400 : : /* There can only be one, so no need to loop */
15401 : 185 : tuple = systable_getnext(scan);
15402 [ - + ]: 185 : if (!HeapTupleIsValid(tuple))
15403 [ # # ]: 0 : ereport(ERROR,
15404 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
15405 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
15406 : : constrName,
15407 : : RelationGetRelationName(childrel))));
15408 : 185 : tuple = heap_copytuple(tuple);
15409 : 185 : systable_endscan(scan);
15410 : : }
15411 : :
15412 : 287 : childcon = (Form_pg_constraint) GETSTRUCT(tuple);
15413 : :
15414 : : /* Right now only CHECK and not-null constraints can be inherited */
15415 [ + + ]: 287 : if (childcon->contype != CONSTRAINT_CHECK &&
15416 [ - + ]: 102 : childcon->contype != CONSTRAINT_NOTNULL)
15417 [ # # ]: 0 : elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
15418 : :
15419 [ - + ]: 287 : if (childcon->coninhcount <= 0) /* shouldn't happen */
15420 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
15421 : : childrelid, NameStr(childcon->conname));
15422 : :
15423 [ + + ]: 287 : if (recurse)
15424 : : {
15425 : : /*
15426 : : * If the child constraint has other definition sources, just
15427 : : * decrement its inheritance count; if not, recurse to delete it.
15428 : : */
15429 [ + + + + ]: 219 : if (childcon->coninhcount == 1 && !childcon->conislocal)
15430 : : {
15431 : : /* Time to delete this child constraint, too */
15432 : 163 : dropconstraint_internal(childrel, tuple, behavior,
15433 : : recurse, true, missing_ok,
15434 : : lockmode);
15435 : : }
15436 : : else
15437 : : {
15438 : : /* Child constraint must survive my deletion */
15439 : 56 : childcon->coninhcount--;
15440 : 56 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
15441 : :
15442 : : /* Make update visible */
15443 : 56 : CommandCounterIncrement();
15444 : : }
15445 : : }
15446 : : else
15447 : : {
15448 : : /*
15449 : : * If we were told to drop ONLY in this table (no recursion) and
15450 : : * there are no further parents for this constraint, we need to
15451 : : * mark the inheritors' constraints as locally defined rather than
15452 : : * inherited.
15453 : : */
15454 : 68 : childcon->coninhcount--;
15455 [ + - ]: 68 : if (childcon->coninhcount == 0)
15456 : 68 : childcon->conislocal = true;
15457 : :
15458 : 68 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
15459 : :
15460 : : /* Make update visible */
15461 : 68 : CommandCounterIncrement();
15462 : : }
15463 : :
15464 : 283 : heap_freetuple(tuple);
15465 : :
15466 : 283 : table_close(childrel, NoLock);
15467 : : }
15468 : :
15469 : 663 : table_close(conrel, RowExclusiveLock);
15470 : :
15471 : 663 : return conobj;
15472 : : }
15473 : :
15474 : : /*
15475 : : * ALTER COLUMN TYPE
15476 : : *
15477 : : * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
15478 : : * TYPE during phase 1 --- the AlterTableCmd passed in here is already
15479 : : * transformed (and must be, because we rely on some transformed fields).
15480 : : *
15481 : : * The point of this is that the execution of all ALTER COLUMN TYPEs for a
15482 : : * table will be done "in parallel" during phase 3, so all the USING
15483 : : * expressions should be parsed assuming the original column types. Also,
15484 : : * this allows a USING expression to refer to a field that will be dropped.
15485 : : *
15486 : : * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
15487 : : * the first two execution steps in phase 2; they must not see the effects
15488 : : * of any other subcommand types, since the USING expressions are parsed
15489 : : * against the unmodified table's state.
15490 : : */
15491 : : static void
15492 : 1473 : ATPrepAlterColumnType(List **wqueue,
15493 : : AlteredTableInfo *tab, Relation rel,
15494 : : bool recurse, bool recursing,
15495 : : AlterTableCmd *cmd, LOCKMODE lockmode,
15496 : : AlterTableUtilityContext *context)
15497 : : {
15498 : 1473 : char *colName = cmd->name;
15499 : 1473 : ColumnDef *def = (ColumnDef *) cmd->def;
15500 : 1473 : TypeName *typeName = def->typeName;
15501 : 1473 : Node *transform = def->cooked_default;
15502 : : HeapTuple tuple;
15503 : : Form_pg_attribute attTup;
15504 : : AttrNumber attnum;
15505 : : Oid targettype;
15506 : : int32 targettypmod;
15507 : : Oid targetcollid;
15508 : : NewColumnValue *newval;
15509 : 1473 : ParseState *pstate = make_parsestate(NULL);
15510 : : AclResult aclresult;
15511 : : bool is_expr;
15512 : :
15513 : 1473 : pstate->p_sourcetext = context->queryString;
15514 : :
15515 [ + + + + ]: 1473 : if (rel->rd_rel->reloftype && !recursing)
15516 [ + - ]: 4 : ereport(ERROR,
15517 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15518 : : errmsg("cannot alter column type of typed table"),
15519 : : parser_errposition(pstate, def->location)));
15520 : :
15521 : : /* lookup the attribute so we can check inheritance status */
15522 : 1469 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
15523 [ - + ]: 1469 : if (!HeapTupleIsValid(tuple))
15524 [ # # ]: 0 : ereport(ERROR,
15525 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15526 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15527 : : colName, RelationGetRelationName(rel)),
15528 : : parser_errposition(pstate, def->location)));
15529 : 1469 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
15530 : 1469 : attnum = attTup->attnum;
15531 : :
15532 : : /* Can't alter a system attribute */
15533 [ + + ]: 1469 : if (attnum <= 0)
15534 [ + - ]: 4 : ereport(ERROR,
15535 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15536 : : errmsg("cannot alter system column \"%s\"", colName),
15537 : : parser_errposition(pstate, def->location)));
15538 : :
15539 : : /*
15540 : : * Cannot specify USING when altering type of a generated column, because
15541 : : * that would violate the generation expression.
15542 : : */
15543 [ + + + + ]: 1465 : if (attTup->attgenerated && def->cooked_default)
15544 [ + - ]: 8 : ereport(ERROR,
15545 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
15546 : : errmsg("cannot specify USING when altering type of generated column"),
15547 : : errdetail("Column \"%s\" is a generated column.", colName),
15548 : : parser_errposition(pstate, def->location)));
15549 : :
15550 : : /*
15551 : : * Don't alter inherited columns. At outer level, there had better not be
15552 : : * any inherited definition; when recursing, we assume this was checked at
15553 : : * the parent level (see below).
15554 : : */
15555 [ + + + + ]: 1457 : if (attTup->attinhcount > 0 && !recursing)
15556 [ + - ]: 4 : ereport(ERROR,
15557 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15558 : : errmsg("cannot alter inherited column \"%s\"", colName),
15559 : : parser_errposition(pstate, def->location)));
15560 : :
15561 : : /* Don't alter columns used in the partition key */
15562 [ + + ]: 1453 : if (has_partition_attrs(rel,
15563 : : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
15564 : : &is_expr))
15565 [ + - ]: 12 : ereport(ERROR,
15566 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15567 : : errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
15568 : : colName, RelationGetRelationName(rel)),
15569 : : parser_errposition(pstate, def->location)));
15570 : :
15571 : : /* Look up the target type */
15572 : 1441 : typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
15573 : :
15574 : 1437 : aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
15575 [ + + ]: 1437 : if (aclresult != ACLCHECK_OK)
15576 : 8 : aclcheck_error_type(aclresult, targettype);
15577 : :
15578 : : /* And the collation */
15579 : 1429 : targetcollid = GetColumnDefCollation(pstate, def, targettype);
15580 : :
15581 : : /* make sure datatype is legal for a column */
15582 : 2850 : CheckAttributeType(colName, targettype, targetcollid,
15583 : 1425 : list_make1_oid(rel->rd_rel->reltype),
15584 [ + + ]: 1425 : (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
15585 : :
15586 [ + + ]: 1417 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
15587 : : {
15588 : : /* do nothing */
15589 : : }
15590 [ + + ]: 1381 : else if (tab->relkind == RELKIND_RELATION ||
15591 [ + + ]: 395 : tab->relkind == RELKIND_PARTITIONED_TABLE)
15592 : : {
15593 : : /*
15594 : : * Set up an expression to transform the old data value to the new
15595 : : * type. If a USING option was given, use the expression as
15596 : : * transformed by transformAlterTableStmt, else just take the old
15597 : : * value and try to coerce it. We do this first so that type
15598 : : * incompatibility can be detected before we waste effort, and because
15599 : : * we need the expression to be parsed against the original table row
15600 : : * type.
15601 : : */
15602 [ + + ]: 1050 : if (!transform)
15603 : : {
15604 : 891 : transform = (Node *) makeVar(1, attnum,
15605 : : attTup->atttypid, attTup->atttypmod,
15606 : : attTup->attcollation,
15607 : : 0);
15608 : : }
15609 : :
15610 : 1050 : transform = coerce_to_target_type(pstate,
15611 : : transform, exprType(transform),
15612 : : targettype, targettypmod,
15613 : : COERCION_ASSIGNMENT,
15614 : : COERCE_IMPLICIT_CAST,
15615 : : -1);
15616 [ + + ]: 1050 : if (transform == NULL)
15617 : : {
15618 : : /* error text depends on whether USING was specified or not */
15619 [ + + ]: 15 : if (def->cooked_default != NULL)
15620 [ + - ]: 4 : ereport(ERROR,
15621 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15622 : : errmsg("result of USING clause for column \"%s\""
15623 : : " cannot be cast automatically to type %s",
15624 : : colName, format_type_be(targettype)),
15625 : : errhint("You might need to add an explicit cast.")));
15626 : : else
15627 [ + - + - ]: 11 : ereport(ERROR,
15628 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15629 : : errmsg("column \"%s\" cannot be cast automatically to type %s",
15630 : : colName, format_type_be(targettype)),
15631 : : !attTup->attgenerated ?
15632 : : /* translator: USING is SQL, don't translate it */
15633 : : errhint("You might need to specify \"USING %s::%s\".",
15634 : : quote_identifier(colName),
15635 : : format_type_with_typemod(targettype,
15636 : : targettypmod)) : 0));
15637 : : }
15638 : :
15639 : : /* Fix collations after all else */
15640 : 1035 : assign_expr_collations(pstate, transform);
15641 : :
15642 : : /* Expand virtual generated columns in the expr. */
15643 : 1035 : transform = expand_generated_columns_in_expr(transform, rel, 1);
15644 : :
15645 : : /* Plan the expr now so we can accurately assess the need to rewrite. */
15646 : 1035 : transform = (Node *) expression_planner((Expr *) transform);
15647 : :
15648 : : /*
15649 : : * Add a work queue item to make ATRewriteTable update the column
15650 : : * contents.
15651 : : */
15652 : 1035 : newval = palloc0_object(NewColumnValue);
15653 : 1035 : newval->attnum = attnum;
15654 : 1035 : newval->expr = (Expr *) transform;
15655 : 1035 : newval->is_generated = false;
15656 : :
15657 : 1035 : tab->newvals = lappend(tab->newvals, newval);
15658 [ + + ]: 1917 : if (ATColumnChangeRequiresRewrite(transform, attnum))
15659 : 882 : tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
15660 : : }
15661 [ + + ]: 331 : else if (transform)
15662 [ + - ]: 8 : ereport(ERROR,
15663 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15664 : : errmsg("\"%s\" is not a table",
15665 : : RelationGetRelationName(rel))));
15666 : :
15667 [ + + + - : 1394 : if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ - + - -
+ + + ]
15668 : : {
15669 : : /*
15670 : : * For relations or columns without storage, do this check now.
15671 : : * Regular tables will check it later when the table is being
15672 : : * rewritten.
15673 : : */
15674 : 423 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
15675 : : }
15676 : :
15677 : 1287 : ReleaseSysCache(tuple);
15678 : :
15679 : : /*
15680 : : * Recurse manually by queueing a new command for each child, if
15681 : : * necessary. We cannot apply ATSimpleRecursion here because we need to
15682 : : * remap attribute numbers in the USING expression, if any.
15683 : : *
15684 : : * If we are told not to recurse, there had better not be any child
15685 : : * tables; else the alter would put them out of step.
15686 : : */
15687 [ + + ]: 1287 : if (recurse)
15688 : : {
15689 : 914 : Oid relid = RelationGetRelid(rel);
15690 : : List *child_oids,
15691 : : *child_numparents;
15692 : : ListCell *lo,
15693 : : *li;
15694 : :
15695 : 914 : child_oids = find_all_inheritors(relid, lockmode,
15696 : : &child_numparents);
15697 : :
15698 : : /*
15699 : : * find_all_inheritors does the recursive search of the inheritance
15700 : : * hierarchy, so all we have to do is process all of the relids in the
15701 : : * list that it returns.
15702 : : */
15703 [ + - + + : 1974 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
15704 : : {
15705 : 1076 : Oid childrelid = lfirst_oid(lo);
15706 : 1076 : int numparents = lfirst_int(li);
15707 : : Relation childrel;
15708 : : HeapTuple childtuple;
15709 : : Form_pg_attribute childattTup;
15710 : :
15711 [ + + ]: 1076 : if (childrelid == relid)
15712 : 914 : continue;
15713 : :
15714 : : /* find_all_inheritors already got lock */
15715 : 162 : childrel = relation_open(childrelid, NoLock);
15716 : 162 : CheckAlterTableIsSafe(childrel);
15717 : :
15718 : : /*
15719 : : * Verify that the child doesn't have any inherited definitions of
15720 : : * this column that came from outside this inheritance hierarchy.
15721 : : * (renameatt makes a similar test, though in a different way
15722 : : * because of its different recursion mechanism.)
15723 : : */
15724 : 162 : childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
15725 : : colName);
15726 [ - + ]: 162 : if (!HeapTupleIsValid(childtuple))
15727 [ # # ]: 0 : ereport(ERROR,
15728 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15729 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15730 : : colName, RelationGetRelationName(childrel))));
15731 : 162 : childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
15732 : :
15733 [ + + ]: 162 : if (childattTup->attinhcount > numparents)
15734 [ + - ]: 4 : ereport(ERROR,
15735 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15736 : : errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
15737 : : colName, RelationGetRelationName(childrel))));
15738 : :
15739 : 158 : ReleaseSysCache(childtuple);
15740 : :
15741 : : /*
15742 : : * Remap the attribute numbers. If no USING expression was
15743 : : * specified, there is no need for this step.
15744 : : */
15745 [ + + ]: 158 : if (def->cooked_default)
15746 : : {
15747 : : AttrMap *attmap;
15748 : : bool found_whole_row;
15749 : :
15750 : : /* create a copy to scribble on */
15751 : 52 : cmd = copyObject(cmd);
15752 : :
15753 : 52 : attmap = build_attrmap_by_name(RelationGetDescr(childrel),
15754 : : RelationGetDescr(rel),
15755 : : false);
15756 : 104 : ((ColumnDef *) cmd->def)->cooked_default =
15757 : 52 : map_variable_attnos(def->cooked_default,
15758 : : 1, 0,
15759 : : attmap,
15760 : : InvalidOid, &found_whole_row);
15761 [ + + ]: 52 : if (found_whole_row)
15762 [ + - ]: 4 : ereport(ERROR,
15763 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15764 : : errmsg("cannot convert whole-row table reference"),
15765 : : errdetail("USING expression contains a whole-row table reference.")));
15766 : 48 : pfree(attmap);
15767 : : }
15768 : 154 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
15769 : 146 : relation_close(childrel, NoLock);
15770 : : }
15771 : : }
15772 [ + + - + ]: 600 : else if (!recursing &&
15773 : 227 : find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
15774 [ # # ]: 0 : ereport(ERROR,
15775 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15776 : : errmsg("type of inherited column \"%s\" must be changed in child tables too",
15777 : : colName)));
15778 : :
15779 [ + + ]: 1271 : if (tab->relkind == RELKIND_COMPOSITE_TYPE)
15780 : 227 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
15781 : 1267 : }
15782 : :
15783 : : /*
15784 : : * When the data type of a column is changed, a rewrite might not be required
15785 : : * if the new type is sufficiently identical to the old one, and the USING
15786 : : * clause isn't trying to insert some other value. It's safe to skip the
15787 : : * rewrite in these cases:
15788 : : *
15789 : : * - the old type is binary coercible to the new type
15790 : : * - the new type is an unconstrained domain over the old type
15791 : : * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
15792 : : *
15793 : : * In the case of a constrained domain, we could get by with scanning the
15794 : : * table and checking the constraint rather than actually rewriting it, but we
15795 : : * don't currently try to do that.
15796 : : */
15797 : : static bool
15798 : 1035 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
15799 : : {
15800 : : Assert(expr != NULL);
15801 : :
15802 : : for (;;)
15803 : : {
15804 : : /* only one varno, so no need to check that */
15805 [ + + + - ]: 1123 : if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
15806 : 153 : return false;
15807 [ + + ]: 970 : else if (IsA(expr, RelabelType))
15808 : 80 : expr = (Node *) ((RelabelType *) expr)->arg;
15809 [ + + ]: 890 : else if (IsA(expr, CoerceToDomain))
15810 : : {
15811 : 20 : CoerceToDomain *d = (CoerceToDomain *) expr;
15812 : :
15813 [ + - ]: 20 : if (DomainHasConstraints(d->resulttype, NULL))
15814 : 20 : return true;
15815 : 0 : expr = (Node *) d->arg;
15816 : : }
15817 [ + + ]: 870 : else if (IsA(expr, FuncExpr))
15818 : : {
15819 : 551 : FuncExpr *f = (FuncExpr *) expr;
15820 : :
15821 [ + + ]: 551 : switch (f->funcid)
15822 : : {
15823 : 12 : case F_TIMESTAMPTZ_TIMESTAMP:
15824 : : case F_TIMESTAMP_TIMESTAMPTZ:
15825 [ + + ]: 12 : if (TimestampTimestampTzRequiresRewrite())
15826 : 4 : return true;
15827 : : else
15828 : 8 : expr = linitial(f->args);
15829 : 8 : break;
15830 : 539 : default:
15831 : 539 : return true;
15832 : : }
15833 : : }
15834 : : else
15835 : 319 : return true;
15836 : : }
15837 : : }
15838 : :
15839 : : /*
15840 : : * ALTER COLUMN .. SET DATA TYPE
15841 : : *
15842 : : * Return the address of the modified column.
15843 : : */
15844 : : static ObjectAddress
15845 : 1243 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
15846 : : AlterTableCmd *cmd, LOCKMODE lockmode)
15847 : : {
15848 : 1243 : char *colName = cmd->name;
15849 : 1243 : ColumnDef *def = (ColumnDef *) cmd->def;
15850 : 1243 : TypeName *typeName = def->typeName;
15851 : : HeapTuple heapTup;
15852 : : Form_pg_attribute attTup,
15853 : : attOldTup;
15854 : : AttrNumber attnum;
15855 : : HeapTuple typeTuple;
15856 : : Form_pg_type tform;
15857 : : Oid targettype;
15858 : : int32 targettypmod;
15859 : : Oid targetcollid;
15860 : : Node *defaultexpr;
15861 : : Relation attrelation;
15862 : : Relation depRel;
15863 : : ScanKeyData key[3];
15864 : : SysScanDesc scan;
15865 : : HeapTuple depTup;
15866 : : ObjectAddress address;
15867 : 1243 : XLogRecPtr attversion = InvalidXLogRecPtr;
15868 : :
15869 : : /*
15870 : : * Clear all the missing values if we're rewriting the table, since this
15871 : : * renders them pointless.
15872 : : */
15873 [ + + ]: 1243 : if (tab->rewrite)
15874 : : {
15875 : : Relation newrel;
15876 : :
15877 : 834 : newrel = table_open(RelationGetRelid(rel), NoLock);
15878 : 834 : RelationClearMissing(newrel);
15879 : 834 : relation_close(newrel, NoLock);
15880 : : /* make sure we don't conflict with later attribute modifications */
15881 : 834 : CommandCounterIncrement();
15882 : : }
15883 : :
15884 : 1243 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
15885 : :
15886 : : /* Look up the target column */
15887 : 1243 : heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
15888 [ - + ]: 1243 : if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
15889 [ # # ]: 0 : ereport(ERROR,
15890 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15891 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15892 : : colName, RelationGetRelationName(rel))));
15893 : 1243 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15894 : 1243 : attnum = attTup->attnum;
15895 : 1243 : attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
15896 : :
15897 : : /* Check for multiple ALTER TYPE on same column --- can't cope */
15898 [ + - ]: 1243 : if (attTup->atttypid != attOldTup->atttypid ||
15899 [ - + ]: 1243 : attTup->atttypmod != attOldTup->atttypmod)
15900 [ # # ]: 0 : ereport(ERROR,
15901 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15902 : : errmsg("cannot alter type of column \"%s\" twice",
15903 : : colName)));
15904 : :
15905 : : /* Look up the target type (should not fail, since prep found it) */
15906 : 1243 : typeTuple = typenameType(NULL, typeName, &targettypmod);
15907 : 1243 : tform = (Form_pg_type) GETSTRUCT(typeTuple);
15908 : 1243 : targettype = tform->oid;
15909 : : /* And the collation */
15910 : 1243 : targetcollid = GetColumnDefCollation(NULL, def, targettype);
15911 : :
15912 : : /*
15913 : : * If there is a default expression for the column, get it and ensure we
15914 : : * can coerce it to the new datatype. (We must do this before changing
15915 : : * the column type, because build_column_default itself will try to
15916 : : * coerce, and will not issue the error message we want if it fails.)
15917 : : *
15918 : : * We remove any implicit coercion steps at the top level of the old
15919 : : * default expression; this has been agreed to satisfy the principle of
15920 : : * least surprise. (The conversion to the new column type should act like
15921 : : * it started from what the user sees as the stored expression, and the
15922 : : * implicit coercions aren't going to be shown.)
15923 : : */
15924 [ + + ]: 1243 : if (attTup->atthasdef)
15925 : : {
15926 : 68 : defaultexpr = build_column_default(rel, attnum);
15927 : : Assert(defaultexpr);
15928 : 68 : defaultexpr = strip_implicit_coercions(defaultexpr);
15929 : 68 : defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
15930 : : defaultexpr, exprType(defaultexpr),
15931 : : targettype, targettypmod,
15932 : : COERCION_ASSIGNMENT,
15933 : : COERCE_IMPLICIT_CAST,
15934 : : -1);
15935 [ + + ]: 68 : if (defaultexpr == NULL)
15936 : : {
15937 [ - + ]: 4 : if (attTup->attgenerated)
15938 [ # # ]: 0 : ereport(ERROR,
15939 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15940 : : errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
15941 : : colName, format_type_be(targettype))));
15942 : : else
15943 [ + - ]: 4 : ereport(ERROR,
15944 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15945 : : errmsg("default for column \"%s\" cannot be cast automatically to type %s",
15946 : : colName, format_type_be(targettype))));
15947 : : }
15948 : : }
15949 : : else
15950 : 1175 : defaultexpr = NULL;
15951 : :
15952 : : /*
15953 : : * Find everything that depends on the column (constraints, indexes, etc),
15954 : : * and record enough information to let us recreate the objects.
15955 : : *
15956 : : * The actual recreation does not happen here, but only after we have
15957 : : * performed all the individual ALTER TYPE operations. We have to save
15958 : : * the info before executing ALTER TYPE, though, else the deparser will
15959 : : * get confused.
15960 : : */
15961 : 1239 : RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
15962 : :
15963 : : /*
15964 : : * Now scan for dependencies of this column on other things. The only
15965 : : * things we should find are the dependency on the column datatype and
15966 : : * possibly a collation dependency. Those can be removed.
15967 : : */
15968 : 1203 : depRel = table_open(DependRelationId, RowExclusiveLock);
15969 : :
15970 : 1203 : ScanKeyInit(&key[0],
15971 : : Anum_pg_depend_classid,
15972 : : BTEqualStrategyNumber, F_OIDEQ,
15973 : : ObjectIdGetDatum(RelationRelationId));
15974 : 1203 : ScanKeyInit(&key[1],
15975 : : Anum_pg_depend_objid,
15976 : : BTEqualStrategyNumber, F_OIDEQ,
15977 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15978 : 1203 : ScanKeyInit(&key[2],
15979 : : Anum_pg_depend_objsubid,
15980 : : BTEqualStrategyNumber, F_INT4EQ,
15981 : : Int32GetDatum((int32) attnum));
15982 : :
15983 : 1203 : scan = systable_beginscan(depRel, DependDependerIndexId, true,
15984 : : NULL, 3, key);
15985 : :
15986 [ + + ]: 1205 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15987 : : {
15988 : 2 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15989 : : ObjectAddress foundObject;
15990 : :
15991 : 2 : foundObject.classId = foundDep->refclassid;
15992 : 2 : foundObject.objectId = foundDep->refobjid;
15993 : 2 : foundObject.objectSubId = foundDep->refobjsubid;
15994 : :
15995 [ - + ]: 2 : if (foundDep->deptype != DEPENDENCY_NORMAL)
15996 [ # # ]: 0 : elog(ERROR, "found unexpected dependency type '%c'",
15997 : : foundDep->deptype);
15998 [ + - ]: 2 : if (!(foundDep->refclassid == TypeRelationId &&
15999 [ - + ]: 2 : foundDep->refobjid == attTup->atttypid) &&
16000 [ # # ]: 0 : !(foundDep->refclassid == CollationRelationId &&
16001 [ # # ]: 0 : foundDep->refobjid == attTup->attcollation))
16002 [ # # ]: 0 : elog(ERROR, "found unexpected dependency for column: %s",
16003 : : getObjectDescription(&foundObject, false));
16004 : :
16005 : 2 : CatalogTupleDelete(depRel, &depTup->t_self);
16006 : : }
16007 : :
16008 : 1203 : systable_endscan(scan);
16009 : :
16010 : 1203 : table_close(depRel, RowExclusiveLock);
16011 : :
16012 : : /*
16013 : : * Here we go --- change the recorded column type and collation. (Note
16014 : : * heapTup is a copy of the syscache entry, so okay to scribble on.) First
16015 : : * fix up the missing value if any.
16016 : : */
16017 [ + + ]: 1203 : if (attTup->atthasmissing)
16018 : : {
16019 : : Datum missingval;
16020 : : bool missingNull;
16021 : :
16022 : : /* if rewrite is true the missing value should already be cleared */
16023 : : Assert(tab->rewrite == 0);
16024 : :
16025 : : /* Get the missing value datum */
16026 : 4 : missingval = heap_getattr(heapTup,
16027 : : Anum_pg_attribute_attmissingval,
16028 : : attrelation->rd_att,
16029 : : &missingNull);
16030 : :
16031 : : /* if it's a null array there is nothing to do */
16032 : :
16033 [ + - ]: 4 : if (!missingNull)
16034 : : {
16035 : : /*
16036 : : * Get the datum out of the array and repack it in a new array
16037 : : * built with the new type data. We assume that since the table
16038 : : * doesn't need rewriting, the actual Datum doesn't need to be
16039 : : * changed, only the array metadata.
16040 : : */
16041 : :
16042 : 4 : int one = 1;
16043 : : bool isNull;
16044 : 4 : Datum valuesAtt[Natts_pg_attribute] = {0};
16045 : 4 : bool nullsAtt[Natts_pg_attribute] = {0};
16046 : 4 : bool replacesAtt[Natts_pg_attribute] = {0};
16047 : : HeapTuple newTup;
16048 : :
16049 : 8 : missingval = array_get_element(missingval,
16050 : : 1,
16051 : : &one,
16052 : : 0,
16053 : 4 : attTup->attlen,
16054 : 4 : attTup->attbyval,
16055 : 4 : attTup->attalign,
16056 : : &isNull);
16057 : 4 : missingval = PointerGetDatum(construct_array(&missingval,
16058 : : 1,
16059 : : targettype,
16060 : : tform->typlen,
16061 : : tform->typbyval,
16062 : : tform->typalign));
16063 : :
16064 : 4 : valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
16065 : 4 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
16066 : 4 : nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
16067 : :
16068 : 4 : newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
16069 : : valuesAtt, nullsAtt, replacesAtt);
16070 : 4 : heap_freetuple(heapTup);
16071 : 4 : heapTup = newTup;
16072 : 4 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
16073 : : }
16074 : : }
16075 : :
16076 : 1203 : attTup->atttypid = targettype;
16077 : 1203 : attTup->atttypmod = targettypmod;
16078 : 1203 : attTup->attcollation = targetcollid;
16079 [ - + ]: 1203 : if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
16080 [ # # ]: 0 : ereport(ERROR,
16081 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
16082 : : errmsg("too many array dimensions"));
16083 : 1203 : attTup->attndims = list_length(typeName->arrayBounds);
16084 : 1203 : attTup->attlen = tform->typlen;
16085 : 1203 : attTup->attbyval = tform->typbyval;
16086 : 1203 : attTup->attalign = tform->typalign;
16087 : 1203 : attTup->attstorage = tform->typstorage;
16088 : 1203 : attTup->attcompression = InvalidCompressionMethod;
16089 : :
16090 : : /*
16091 : : * Update the version of this attribute. Together with the update of the
16092 : : * version of following attributes (see SetAttributeVersions() call
16093 : : * below), this prevents old datums containing this, or a following
16094 : : * attribute, from being decoded - that would be unsafe. See
16095 : : * src/backend/catalog/README.attver.md for details.
16096 : : *
16097 : : * This has to be done as part of the same command as the
16098 : : * CatalogTupleUpdate() for the type change, the row is not going to be
16099 : : * visible for a separate update before a CommandCounterIncrement(), and
16100 : : * we don't want to do the CommandCounterIncrement() before having updated
16101 : : * the versions of the subsequent columns, as that would be an
16102 : : * inconsistent view of the catalog. It also would trigger unnecessarily
16103 : : * many cache entry rebuilds.
16104 : : *
16105 : : * NB: We could potentially skip increasing the version in a few cases,
16106 : : * e.g. changes with the same (or a binary coercible) source & target
16107 : : * type. But at the moment we don't allow such changes if there are
16108 : : * existing composite datums in the catalog, so avoiding the version bump
16109 : : * to protect non-catalog datums doesn't really seem worthwhile (note that
16110 : : * we can't rely on ATColumnChangeRequiresRewrite() having run).
16111 : : *
16112 : : * XXX: This would look a lot better if we made surrounding code also use
16113 : : * heap_modify_tuple(), given that we have very similar code above for
16114 : : * atthasmissing.
16115 : : */
16116 : : Assert(HasVersionedAttributes(rel) || allowSystemTableMods);
16117 [ + - ]: 1203 : if (HasVersionedAttributes(rel))
16118 : : {
16119 : : HeapTuple newTup;
16120 : :
16121 : 1203 : attversion = GetNextAttributeVersion();
16122 : :
16123 : 1203 : newTup = SetAttributeVersionInTuple(attrelation,
16124 : : heapTup,
16125 : : attversion);
16126 : 1203 : heap_freetuple(heapTup);
16127 : 1203 : heapTup = newTup;
16128 : 1203 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
16129 : : }
16130 : :
16131 : 1203 : ReleaseSysCache(typeTuple);
16132 : :
16133 : 1203 : CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
16134 : :
16135 : : /*
16136 : : * Update version of all following columns (if any). See comment above
16137 : : * SetAttributeVersionInTuple() call for details.
16138 : : */
16139 [ + - ]: 1203 : if (HasVersionedAttributes(rel) &&
16140 [ + + ]: 1203 : attnum + 1 <= RelationGetNumberOfAttributes(rel))
16141 : 371 : SetAttributeVersions(rel, attnum + 1, attversion);
16142 : :
16143 : 1203 : table_close(attrelation, RowExclusiveLock);
16144 : :
16145 : : /* Install dependencies on new datatype and collation */
16146 : 1203 : add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
16147 : 1203 : add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
16148 : :
16149 : : /*
16150 : : * Drop any pg_statistic entry for the column, since it's now wrong type
16151 : : */
16152 : 1203 : RemoveStatistics(RelationGetRelid(rel), attnum);
16153 : :
16154 [ - + ]: 1203 : InvokeObjectPostAlterHook(RelationRelationId,
16155 : : RelationGetRelid(rel), attnum);
16156 : :
16157 : : /*
16158 : : * Update the default, if present, by brute force --- remove and re-add
16159 : : * the default. Probably unsafe to take shortcuts, since the new version
16160 : : * may well have additional dependencies. (It's okay to do this now,
16161 : : * rather than after other ALTER TYPE commands, since the default won't
16162 : : * depend on other column types.)
16163 : : */
16164 [ + + ]: 1203 : if (defaultexpr)
16165 : : {
16166 : : /*
16167 : : * If it's a GENERATED default, drop its dependency records, in
16168 : : * particular its INTERNAL dependency on the column, which would
16169 : : * otherwise cause dependency.c to refuse to perform the deletion.
16170 : : */
16171 [ + + ]: 64 : if (attTup->attgenerated)
16172 : : {
16173 : 28 : Oid attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
16174 : :
16175 [ - + ]: 28 : if (!OidIsValid(attrdefoid))
16176 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
16177 : : RelationGetRelid(rel), attnum);
16178 : 28 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
16179 : : }
16180 : :
16181 : : /*
16182 : : * Make updates-so-far visible, particularly the new pg_attribute row
16183 : : * which will be updated again.
16184 : : */
16185 : 64 : CommandCounterIncrement();
16186 : :
16187 : : /*
16188 : : * We use RESTRICT here for safety, but at present we do not expect
16189 : : * anything to depend on the default.
16190 : : */
16191 : 64 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
16192 : : true);
16193 : :
16194 : 64 : (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
16195 : : }
16196 : :
16197 : 1203 : ObjectAddressSubSet(address, RelationRelationId,
16198 : : RelationGetRelid(rel), attnum);
16199 : :
16200 : : /* Cleanup */
16201 : 1203 : heap_freetuple(heapTup);
16202 : :
16203 : 1203 : return address;
16204 : : }
16205 : :
16206 : : /*
16207 : : * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
16208 : : * that depends on the column (constraints, indexes, etc), and record enough
16209 : : * information to let us recreate the objects.
16210 : : */
16211 : : static void
16212 : 1428 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
16213 : : Relation rel, AttrNumber attnum, const char *colName)
16214 : : {
16215 : : Relation depRel;
16216 : : ScanKeyData key[3];
16217 : : SysScanDesc scan;
16218 : : HeapTuple depTup;
16219 : :
16220 : : Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
16221 : :
16222 : 1428 : depRel = table_open(DependRelationId, RowExclusiveLock);
16223 : :
16224 : 1428 : ScanKeyInit(&key[0],
16225 : : Anum_pg_depend_refclassid,
16226 : : BTEqualStrategyNumber, F_OIDEQ,
16227 : : ObjectIdGetDatum(RelationRelationId));
16228 : 1428 : ScanKeyInit(&key[1],
16229 : : Anum_pg_depend_refobjid,
16230 : : BTEqualStrategyNumber, F_OIDEQ,
16231 : : ObjectIdGetDatum(RelationGetRelid(rel)));
16232 : 1428 : ScanKeyInit(&key[2],
16233 : : Anum_pg_depend_refobjsubid,
16234 : : BTEqualStrategyNumber, F_INT4EQ,
16235 : : Int32GetDatum((int32) attnum));
16236 : :
16237 : 1428 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
16238 : : NULL, 3, key);
16239 : :
16240 [ + + ]: 2465 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
16241 : : {
16242 : 1081 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
16243 : : ObjectAddress foundObject;
16244 : :
16245 : 1081 : foundObject.classId = foundDep->classid;
16246 : 1081 : foundObject.objectId = foundDep->objid;
16247 : 1081 : foundObject.objectSubId = foundDep->objsubid;
16248 : :
16249 [ + + + + : 1081 : switch (foundObject.classId)
- - + + -
- ]
16250 : : {
16251 : 212 : case RelationRelationId:
16252 : : {
16253 : 212 : char relKind = get_rel_relkind(foundObject.objectId);
16254 : :
16255 [ + + + + ]: 212 : if (relKind == RELKIND_INDEX ||
16256 : : relKind == RELKIND_PARTITIONED_INDEX)
16257 : : {
16258 : : Assert(foundObject.objectSubId == 0);
16259 : 175 : RememberIndexForRebuilding(foundObject.objectId, tab);
16260 : : }
16261 [ + + ]: 37 : else if (relKind == RELKIND_SEQUENCE)
16262 : : {
16263 : : /*
16264 : : * This must be a SERIAL column's sequence. We need
16265 : : * not do anything to it.
16266 : : */
16267 : : Assert(foundObject.objectSubId == 0);
16268 : : }
16269 : : else
16270 : : {
16271 : : /* Not expecting any other direct dependencies... */
16272 [ + - ]: 12 : elog(ERROR, "unexpected object depending on column: %s",
16273 : : getObjectDescription(&foundObject, false));
16274 : : }
16275 : 200 : break;
16276 : : }
16277 : :
16278 : 528 : case ConstraintRelationId:
16279 : : Assert(foundObject.objectSubId == 0);
16280 : 528 : RememberConstraintForRebuilding(foundObject.objectId, tab);
16281 : 528 : break;
16282 : :
16283 : 4 : case ProcedureRelationId:
16284 : :
16285 : : /*
16286 : : * A new-style SQL function can depend on a column, if that
16287 : : * column is referenced in the parsed function body. Ideally
16288 : : * we'd automatically update the function by deparsing and
16289 : : * reparsing it, but that's risky and might well fail anyhow.
16290 : : * FIXME someday.
16291 : : *
16292 : : * This is only a problem for AT_AlterColumnType, not
16293 : : * AT_SetExpression.
16294 : : */
16295 [ + - ]: 4 : if (subtype == AT_AlterColumnType)
16296 [ + - ]: 4 : ereport(ERROR,
16297 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16298 : : errmsg("cannot alter type of a column used by a function or procedure"),
16299 : : errdetail("%s depends on column \"%s\".",
16300 : : getObjectDescription(&foundObject, false),
16301 : : colName)));
16302 : 0 : break;
16303 : :
16304 : 12 : case RewriteRelationId:
16305 : :
16306 : : /*
16307 : : * View/rule bodies have pretty much the same issues as
16308 : : * function bodies. FIXME someday.
16309 : : */
16310 [ + - ]: 12 : if (subtype == AT_AlterColumnType)
16311 [ + - ]: 12 : ereport(ERROR,
16312 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16313 : : errmsg("cannot alter type of a column used by a view or rule"),
16314 : : errdetail("%s depends on column \"%s\".",
16315 : : getObjectDescription(&foundObject, false),
16316 : : colName)));
16317 : 0 : break;
16318 : :
16319 : 0 : case TriggerRelationId:
16320 : :
16321 : : /*
16322 : : * A trigger can depend on a column because the column is
16323 : : * specified as an update target, or because the column is
16324 : : * used in the trigger's WHEN condition. The first case would
16325 : : * not require any extra work, but the second case would
16326 : : * require updating the WHEN expression, which has the same
16327 : : * issues as above. Since we can't easily tell which case
16328 : : * applies, we punt for both. FIXME someday.
16329 : : */
16330 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
16331 [ # # ]: 0 : ereport(ERROR,
16332 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16333 : : errmsg("cannot alter type of a column used in a trigger definition"),
16334 : : errdetail("%s depends on column \"%s\".",
16335 : : getObjectDescription(&foundObject, false),
16336 : : colName)));
16337 : 0 : break;
16338 : :
16339 : 0 : case PolicyRelationId:
16340 : :
16341 : : /*
16342 : : * A policy can depend on a column because the column is
16343 : : * specified in the policy's USING or WITH CHECK qual
16344 : : * expressions. It might be possible to rewrite and recheck
16345 : : * the policy expression, but punt for now. It's certainly
16346 : : * easy enough to remove and recreate the policy; still, FIXME
16347 : : * someday.
16348 : : */
16349 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
16350 [ # # ]: 0 : ereport(ERROR,
16351 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16352 : : errmsg("cannot alter type of a column used in a policy definition"),
16353 : : errdetail("%s depends on column \"%s\".",
16354 : : getObjectDescription(&foundObject, false),
16355 : : colName)));
16356 : 0 : break;
16357 : :
16358 : 268 : case AttrDefaultRelationId:
16359 : : {
16360 : 268 : ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
16361 : :
16362 [ + - ]: 520 : if (col.objectId == RelationGetRelid(rel) &&
16363 [ + + ]: 268 : col.objectSubId == attnum)
16364 : : {
16365 : : /*
16366 : : * Ignore the column's own default expression. The
16367 : : * caller deals with it.
16368 : : */
16369 : : }
16370 : : else
16371 : : {
16372 : : /*
16373 : : * This must be a reference from the expression of a
16374 : : * generated column elsewhere in the same table.
16375 : : * Changing the type/generated expression of a column
16376 : : * that is used by a generated column is not allowed
16377 : : * by SQL standard, so just punt for now. It might be
16378 : : * doable with some thinking and effort.
16379 : : */
16380 [ + - ]: 16 : if (subtype == AT_AlterColumnType)
16381 [ + - ]: 16 : ereport(ERROR,
16382 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16383 : : errmsg("cannot alter type of a column used by a generated column"),
16384 : : errdetail("Column \"%s\" is used by generated column \"%s\".",
16385 : : colName,
16386 : : get_attname(col.objectId,
16387 : : col.objectSubId,
16388 : : false))));
16389 : : }
16390 : 252 : break;
16391 : : }
16392 : :
16393 : 57 : case StatisticExtRelationId:
16394 : :
16395 : : /*
16396 : : * Give the extended-stats machinery a chance to fix anything
16397 : : * that this column type change would break.
16398 : : */
16399 : 57 : RememberStatisticsForRebuilding(foundObject.objectId, tab);
16400 : 57 : break;
16401 : :
16402 : 0 : case PublicationRelRelationId:
16403 : :
16404 : : /*
16405 : : * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
16406 : : * clause. Same issues as above. FIXME someday.
16407 : : */
16408 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
16409 [ # # ]: 0 : ereport(ERROR,
16410 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16411 : : errmsg("cannot alter type of a column used by a publication WHERE clause"),
16412 : : errdetail("%s depends on column \"%s\".",
16413 : : getObjectDescription(&foundObject, false),
16414 : : colName)));
16415 : 0 : break;
16416 : :
16417 : 0 : default:
16418 : :
16419 : : /*
16420 : : * We don't expect any other sorts of objects to depend on a
16421 : : * column.
16422 : : */
16423 [ # # ]: 0 : elog(ERROR, "unexpected object depending on column: %s",
16424 : : getObjectDescription(&foundObject, false));
16425 : : break;
16426 : : }
16427 : : }
16428 : :
16429 : 1384 : systable_endscan(scan);
16430 : 1384 : table_close(depRel, NoLock);
16431 : 1384 : }
16432 : :
16433 : : /*
16434 : : * Record information about dependencies between objects with whole-row Var
16435 : : * references (indexes, check constraints, etc.) and the relation.
16436 : : *
16437 : : * See also RememberAllDependentForRebuilding, which handles non-whole-row Var
16438 : : * references.
16439 : : *
16440 : : * This function currently applies only to ALTER COLUMN SET EXPRESSION.
16441 : : */
16442 : : static void
16443 : 181 : RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, Relation rel)
16444 : : {
16445 : : ScanKeyData skey;
16446 : : Relation pg_constraint;
16447 : : Relation pg_index;
16448 : : SysScanDesc conscan;
16449 : : SysScanDesc indscan;
16450 : : HeapTuple constrTuple;
16451 : : HeapTuple indexTuple;
16452 : : bool isnull;
16453 : :
16454 : : Assert(subtype == AT_SetExpression);
16455 : :
16456 : : /*
16457 : : * Check CHECK constraints with whole-row references first.
16458 : : */
16459 [ + - ]: 181 : if (RelationGetDescr(rel)->constr &&
16460 [ + + ]: 181 : RelationGetDescr(rel)->constr->num_check > 0)
16461 : : {
16462 : 28 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
16463 : :
16464 : 28 : ScanKeyInit(&skey,
16465 : : Anum_pg_constraint_conrelid,
16466 : : BTEqualStrategyNumber, F_OIDEQ,
16467 : : ObjectIdGetDatum(RelationGetRelid(rel)));
16468 : :
16469 : 28 : conscan = systable_beginscan(pg_constraint,
16470 : : ConstraintRelidTypidNameIndexId,
16471 : : true,
16472 : : NULL,
16473 : : 1,
16474 : : &skey);
16475 : :
16476 [ + + ]: 96 : while (HeapTupleIsValid(constrTuple = systable_getnext(conscan)))
16477 : : {
16478 : 68 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(constrTuple);
16479 : : Datum exprDatum;
16480 : :
16481 [ + + ]: 68 : if (conform->contype != CONSTRAINT_CHECK)
16482 : 40 : continue;
16483 : :
16484 : 28 : exprDatum = heap_getattr(constrTuple,
16485 : : Anum_pg_constraint_conbin,
16486 : : RelationGetDescr(pg_constraint),
16487 : : &isnull);
16488 [ - + ]: 28 : if (isnull)
16489 [ # # ]: 0 : elog(ERROR, "null conbin for relation \"%s\"",
16490 : : RelationGetRelationName(rel));
16491 : : else
16492 : : {
16493 : : char *exprString;
16494 : : Node *expr;
16495 : 28 : Bitmapset *expr_attrs = NULL;
16496 : :
16497 : 28 : exprString = TextDatumGetCString(exprDatum);
16498 : 28 : expr = stringToNode(exprString);
16499 : 28 : pfree(exprString);
16500 : :
16501 : : /* Find all attributes referenced */
16502 : 28 : pull_varattnos(expr, 1, &expr_attrs);
16503 : :
16504 : : /*
16505 : : * If the CHECK constraint contains whole-row reference then
16506 : : * remember it.
16507 : : */
16508 [ + + ]: 28 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
16509 : : {
16510 : 8 : RememberConstraintForRebuilding(conform->oid, tab);
16511 : : }
16512 : : }
16513 : : }
16514 : 28 : systable_endscan(conscan);
16515 : 28 : table_close(pg_constraint, AccessShareLock);
16516 : : }
16517 : :
16518 : : /*
16519 : : * Now check indexes with whole-row references. Prepare to scan pg_index
16520 : : * for entries having indrelid matching this relation.
16521 : : */
16522 : 181 : ScanKeyInit(&skey,
16523 : : Anum_pg_index_indrelid,
16524 : : BTEqualStrategyNumber, F_OIDEQ,
16525 : : ObjectIdGetDatum(RelationGetRelid(rel)));
16526 : :
16527 : 181 : pg_index = table_open(IndexRelationId, AccessShareLock);
16528 : :
16529 : 181 : indscan = systable_beginscan(pg_index,
16530 : : IndexIndrelidIndexId,
16531 : : true,
16532 : : NULL,
16533 : : 1,
16534 : : &skey);
16535 : :
16536 [ + + ]: 261 : while (HeapTupleIsValid(indexTuple = systable_getnext(indscan)))
16537 : : {
16538 : 80 : Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
16539 : : Datum exprDatum;
16540 : :
16541 : 80 : exprDatum = heap_getattr(indexTuple,
16542 : : Anum_pg_index_indexprs,
16543 : : RelationGetDescr(pg_index),
16544 : : &isnull);
16545 [ + + ]: 80 : if (!isnull)
16546 : : {
16547 : : char *exprString;
16548 : : Node *expr;
16549 : 12 : Bitmapset *expr_attrs = NULL;
16550 : :
16551 : 12 : exprString = TextDatumGetCString(exprDatum);
16552 : 12 : expr = stringToNode(exprString);
16553 : 12 : pfree(exprString);
16554 : :
16555 : : /* Find all attributes referenced */
16556 : 12 : pull_varattnos(expr, 1, &expr_attrs);
16557 : :
16558 : : /*
16559 : : * If the index expression contains a whole-row reference then
16560 : : * remember it.
16561 : : */
16562 [ + + ]: 12 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
16563 : : {
16564 : 8 : RememberIndexForRebuilding(index->indexrelid, tab);
16565 : 8 : continue;
16566 : : }
16567 : : }
16568 : :
16569 : 72 : exprDatum = heap_getattr(indexTuple,
16570 : : Anum_pg_index_indpred,
16571 : : RelationGetDescr(pg_index),
16572 : : &isnull);
16573 [ + + ]: 72 : if (!isnull)
16574 : : {
16575 : : char *exprString;
16576 : : Node *expr;
16577 : 20 : Bitmapset *expr_attrs = NULL;
16578 : :
16579 : 20 : exprString = TextDatumGetCString(exprDatum);
16580 : 20 : expr = stringToNode(exprString);
16581 : 20 : pfree(exprString);
16582 : :
16583 : : /* Find all attributes referenced */
16584 : 20 : pull_varattnos(expr, 1, &expr_attrs);
16585 : :
16586 : : /*
16587 : : * If the index predicate expression contains a whole-row
16588 : : * reference then remember it.
16589 : : */
16590 [ + + ]: 20 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
16591 : : {
16592 : 16 : RememberIndexForRebuilding(index->indexrelid, tab);
16593 : : }
16594 : : }
16595 : : }
16596 : :
16597 : 181 : systable_endscan(indscan);
16598 : 181 : table_close(pg_index, AccessShareLock);
16599 : 181 : }
16600 : :
16601 : : /*
16602 : : * Subroutine for ATExecAlterColumnType: remember that a replica identity
16603 : : * needs to be reset.
16604 : : */
16605 : : static void
16606 : 338 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
16607 : : {
16608 [ + + ]: 338 : if (!get_index_isreplident(indoid))
16609 : 326 : return;
16610 : :
16611 [ - + ]: 12 : if (tab->replicaIdentityIndex)
16612 [ # # ]: 0 : elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
16613 : :
16614 : 12 : tab->replicaIdentityIndex = get_rel_name(indoid);
16615 : : }
16616 : :
16617 : : /*
16618 : : * Subroutine for ATExecAlterColumnType: remember any clustered index.
16619 : : */
16620 : : static void
16621 : 338 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
16622 : : {
16623 [ + + ]: 338 : if (!get_index_isclustered(indoid))
16624 : 326 : return;
16625 : :
16626 [ - + ]: 12 : if (tab->clusterOnIndex)
16627 [ # # ]: 0 : elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
16628 : :
16629 : 12 : tab->clusterOnIndex = get_rel_name(indoid);
16630 : : }
16631 : :
16632 : : /*
16633 : : * Subroutine for ATExecAlterColumnType: remember that a constraint needs
16634 : : * to be rebuilt (which we might already know).
16635 : : */
16636 : : static void
16637 : 544 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
16638 : : {
16639 : : /*
16640 : : * This de-duplication check is critical for two independent reasons: we
16641 : : * mustn't try to recreate the same constraint twice, and if a constraint
16642 : : * depends on more than one column whose type is to be altered, we must
16643 : : * capture its definition string before applying any of the column type
16644 : : * changes. ruleutils.c will get confused if we ask again later.
16645 : : */
16646 [ + + ]: 544 : if (!list_member_oid(tab->changedConstraintOids, conoid))
16647 : : {
16648 : : /* OK, capture the constraint's existing definition string */
16649 : 468 : char *defstring = pg_get_constraintdef_command(conoid);
16650 : : Oid indoid;
16651 : :
16652 : : /*
16653 : : * It is critical to create not-null constraints ahead of primary key
16654 : : * indexes; otherwise, the not-null constraint would be created by the
16655 : : * primary key, and the constraint name would be wrong.
16656 : : */
16657 [ + + ]: 468 : if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
16658 : : {
16659 : 163 : tab->changedConstraintOids = lcons_oid(conoid,
16660 : : tab->changedConstraintOids);
16661 : 163 : tab->changedConstraintDefs = lcons(defstring,
16662 : : tab->changedConstraintDefs);
16663 : : }
16664 : : else
16665 : : {
16666 : :
16667 : 305 : tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
16668 : : conoid);
16669 : 305 : tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
16670 : : defstring);
16671 : : }
16672 : :
16673 : : /*
16674 : : * For the index of a constraint, if any, remember if it is used for
16675 : : * the table's replica identity or if it is a clustered index, so that
16676 : : * ATPostAlterTypeCleanup() can queue up commands necessary to restore
16677 : : * those properties.
16678 : : */
16679 : 468 : indoid = get_constraint_index(conoid);
16680 [ + + ]: 468 : if (OidIsValid(indoid))
16681 : : {
16682 : 152 : RememberReplicaIdentityForRebuilding(indoid, tab);
16683 : 152 : RememberClusterOnForRebuilding(indoid, tab);
16684 : : }
16685 : : }
16686 : 544 : }
16687 : :
16688 : : /*
16689 : : * Subroutine for ATExecAlterColumnType: remember that an index needs
16690 : : * to be rebuilt (which we might already know).
16691 : : */
16692 : : static void
16693 : 199 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
16694 : : {
16695 : : /*
16696 : : * This de-duplication check is critical for two independent reasons: we
16697 : : * mustn't try to recreate the same index twice, and if an index depends
16698 : : * on more than one column whose type is to be altered, we must capture
16699 : : * its definition string before applying any of the column type changes.
16700 : : * ruleutils.c will get confused if we ask again later.
16701 : : */
16702 [ + + ]: 199 : if (!list_member_oid(tab->changedIndexOids, indoid))
16703 : : {
16704 : : /*
16705 : : * Before adding it as an index-to-rebuild, we'd better see if it
16706 : : * belongs to a constraint, and if so rebuild the constraint instead.
16707 : : * Typically this check fails, because constraint indexes normally
16708 : : * have only dependencies on their constraint. But it's possible for
16709 : : * such an index to also have direct dependencies on table columns,
16710 : : * for example with a partial exclusion constraint.
16711 : : */
16712 : 194 : Oid conoid = get_index_constraint(indoid);
16713 : :
16714 [ + + ]: 194 : if (OidIsValid(conoid))
16715 : : {
16716 : 8 : RememberConstraintForRebuilding(conoid, tab);
16717 : : }
16718 : : else
16719 : : {
16720 : : /* OK, capture the index's existing definition string */
16721 : 186 : char *defstring = pg_get_indexdef_string(indoid);
16722 : :
16723 : 186 : tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
16724 : : indoid);
16725 : 186 : tab->changedIndexDefs = lappend(tab->changedIndexDefs,
16726 : : defstring);
16727 : :
16728 : : /*
16729 : : * Remember if this index is used for the table's replica identity
16730 : : * or if it is a clustered index, so that ATPostAlterTypeCleanup()
16731 : : * can queue up commands necessary to restore those properties.
16732 : : */
16733 : 186 : RememberReplicaIdentityForRebuilding(indoid, tab);
16734 : 186 : RememberClusterOnForRebuilding(indoid, tab);
16735 : : }
16736 : : }
16737 : 199 : }
16738 : :
16739 : : /*
16740 : : * Subroutine for ATExecAlterColumnType: remember that a statistics object
16741 : : * needs to be rebuilt (which we might already know).
16742 : : */
16743 : : static void
16744 : 57 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
16745 : : {
16746 : : /*
16747 : : * This de-duplication check is critical for two independent reasons: we
16748 : : * mustn't try to recreate the same statistics object twice, and if the
16749 : : * statistics object depends on more than one column whose type is to be
16750 : : * altered, we must capture its definition string before applying any of
16751 : : * the type changes. ruleutils.c will get confused if we ask again later.
16752 : : */
16753 [ + - ]: 57 : if (!list_member_oid(tab->changedStatisticsOids, stxoid))
16754 : : {
16755 : : /* OK, capture the statistics object's existing definition string */
16756 : 57 : char *defstring = pg_get_statisticsobjdef_string(stxoid);
16757 : : HeapTuple tup;
16758 : : Form_pg_statistic_ext statext;
16759 : :
16760 : 57 : tup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
16761 : :
16762 [ - + ]: 57 : if (!HeapTupleIsValid(tup)) /* should not happen */
16763 [ # # ]: 0 : elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
16764 : :
16765 : 57 : statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
16766 : :
16767 : 57 : tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
16768 : : stxoid);
16769 : 57 : tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
16770 : : defstring);
16771 : :
16772 : 57 : tab->changedStatisticsOwners = lappend_oid(tab->changedStatisticsOwners,
16773 : : statext->stxowner);
16774 : :
16775 : 57 : ReleaseSysCache(tup);
16776 : : }
16777 : 57 : }
16778 : :
16779 : : /*
16780 : : * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
16781 : : * operations for a particular relation. We have to drop and recreate all the
16782 : : * indexes and constraints that depend on the altered columns. We do the
16783 : : * actual dropping here, but re-creation is managed by adding work queue
16784 : : * entries to do those steps later.
16785 : : */
16786 : : static void
16787 : 1352 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
16788 : : {
16789 : : ObjectAddress obj;
16790 : : ObjectAddresses *objects;
16791 : : ListCell *def_item;
16792 : : ListCell *oid_item;
16793 : : ListCell *owner_item;
16794 : :
16795 : : /*
16796 : : * Collect all the constraints and indexes to drop so we can process them
16797 : : * in a single call. That way we don't have to worry about dependencies
16798 : : * among them.
16799 : : */
16800 : 1352 : objects = new_object_addresses();
16801 : :
16802 : : /*
16803 : : * Re-parse the index and constraint definitions, and attach them to the
16804 : : * appropriate work queue entries. We do this before dropping because in
16805 : : * the case of a constraint on another table, we might not yet have
16806 : : * exclusive lock on the table the constraint is attached to, and we need
16807 : : * to get that before reparsing/dropping. (That's possible at least for
16808 : : * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
16809 : : * requires a dependency on the target table's composite type in the other
16810 : : * table's constraint expressions.)
16811 : : *
16812 : : * We can't rely on the output of deparsing to tell us which relation to
16813 : : * operate on, because concurrent activity might have made the name
16814 : : * resolve differently. Instead, we've got to use the OID of the
16815 : : * constraint or index we're processing to figure out which relation to
16816 : : * operate on.
16817 : : */
16818 [ + + + + : 1820 : forboth(oid_item, tab->changedConstraintOids,
+ + + + +
+ + - +
+ ]
16819 : : def_item, tab->changedConstraintDefs)
16820 : : {
16821 : 468 : Oid oldId = lfirst_oid(oid_item);
16822 : : HeapTuple tup;
16823 : : Form_pg_constraint con;
16824 : : Oid relid;
16825 : : Oid confrelid;
16826 : : bool conislocal;
16827 : :
16828 : 468 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16829 [ - + ]: 468 : if (!HeapTupleIsValid(tup)) /* should not happen */
16830 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16831 : 468 : con = (Form_pg_constraint) GETSTRUCT(tup);
16832 [ + + ]: 468 : if (OidIsValid(con->conrelid))
16833 : 455 : relid = con->conrelid;
16834 : : else
16835 : : {
16836 : : /* must be a domain constraint */
16837 : 13 : relid = get_typ_typrelid(getBaseType(con->contypid));
16838 [ - + ]: 13 : if (!OidIsValid(relid))
16839 [ # # ]: 0 : elog(ERROR, "could not identify relation associated with constraint %u", oldId);
16840 : : }
16841 : 468 : confrelid = con->confrelid;
16842 : 468 : conislocal = con->conislocal;
16843 : 468 : ReleaseSysCache(tup);
16844 : :
16845 : 468 : ObjectAddressSet(obj, ConstraintRelationId, oldId);
16846 : 468 : add_exact_object_address(&obj, objects);
16847 : :
16848 : : /*
16849 : : * If the constraint is inherited (only), we don't want to inject a
16850 : : * new definition here; it'll get recreated when
16851 : : * ATAddCheckNNConstraint recurses from adding the parent table's
16852 : : * constraint. But we had to carry the info this far so that we can
16853 : : * drop the constraint below.
16854 : : */
16855 [ + + ]: 468 : if (!conislocal)
16856 : 34 : continue;
16857 : :
16858 : : /*
16859 : : * When rebuilding another table's constraint that references the
16860 : : * table we're modifying, we might not yet have any lock on the other
16861 : : * table, so get one now. We'll need AccessExclusiveLock for the DROP
16862 : : * CONSTRAINT step, so there's no value in asking for anything weaker.
16863 : : */
16864 [ + + ]: 434 : if (relid != tab->relid)
16865 : 36 : LockRelationOid(relid, AccessExclusiveLock);
16866 : :
16867 : 434 : ATPostAlterTypeParse(oldId, relid, confrelid, InvalidOid,
16868 : 434 : (char *) lfirst(def_item),
16869 : 434 : wqueue, lockmode, tab->rewrite);
16870 : : }
16871 [ + + + + : 1538 : forboth(oid_item, tab->changedIndexOids,
+ + + + +
+ + - +
+ ]
16872 : : def_item, tab->changedIndexDefs)
16873 : : {
16874 : 186 : Oid oldId = lfirst_oid(oid_item);
16875 : : Oid relid;
16876 : :
16877 : 186 : relid = IndexGetRelation(oldId, false);
16878 : :
16879 : : /*
16880 : : * As above, make sure we have lock on the index's table if it's not
16881 : : * the same table.
16882 : : */
16883 [ + + ]: 186 : if (relid != tab->relid)
16884 : 20 : LockRelationOid(relid, AccessExclusiveLock);
16885 : :
16886 : 186 : ATPostAlterTypeParse(oldId, relid, InvalidOid, InvalidOid,
16887 : 186 : (char *) lfirst(def_item),
16888 : 186 : wqueue, lockmode, tab->rewrite);
16889 : :
16890 : 186 : ObjectAddressSet(obj, RelationRelationId, oldId);
16891 : 186 : add_exact_object_address(&obj, objects);
16892 : : }
16893 : :
16894 : : /* add dependencies for new statistics */
16895 [ + + + + : 1409 : forthree(oid_item, tab->changedStatisticsOids,
+ + + + +
+ + + + +
+ - + - +
+ ]
16896 : : def_item, tab->changedStatisticsDefs,
16897 : : owner_item, tab->changedStatisticsOwners)
16898 : : {
16899 : 57 : Oid oldId = lfirst_oid(oid_item);
16900 : : Oid relid;
16901 : :
16902 : 57 : relid = StatisticsGetRelation(oldId, false);
16903 : :
16904 : : /*
16905 : : * As above, make sure we have lock on the statistics object's table
16906 : : * if it's not the same table. However, we take
16907 : : * ShareUpdateExclusiveLock here, aligning with the lock level used in
16908 : : * CreateStatistics and RemoveStatisticsById.
16909 : : *
16910 : : * CAUTION: this should be done after all cases that grab
16911 : : * AccessExclusiveLock, else we risk causing deadlock due to needing
16912 : : * to promote our table lock.
16913 : : */
16914 [ + + ]: 57 : if (relid != tab->relid)
16915 : 12 : LockRelationOid(relid, ShareUpdateExclusiveLock);
16916 : :
16917 : 57 : ATPostAlterTypeParse(oldId, relid, InvalidOid, lfirst_oid(owner_item),
16918 : 57 : (char *) lfirst(def_item),
16919 : 57 : wqueue, lockmode, tab->rewrite);
16920 : :
16921 : 57 : ObjectAddressSet(obj, StatisticExtRelationId, oldId);
16922 : 57 : add_exact_object_address(&obj, objects);
16923 : : }
16924 : :
16925 : : /*
16926 : : * Queue up command to restore replica identity index marking
16927 : : */
16928 [ + + ]: 1352 : if (tab->replicaIdentityIndex)
16929 : : {
16930 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16931 : 12 : ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
16932 : :
16933 : 12 : subcmd->identity_type = REPLICA_IDENTITY_INDEX;
16934 : 12 : subcmd->name = tab->replicaIdentityIndex;
16935 : 12 : cmd->subtype = AT_ReplicaIdentity;
16936 : 12 : cmd->def = (Node *) subcmd;
16937 : :
16938 : : /* do it after indexes and constraints */
16939 : 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16940 : 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16941 : : }
16942 : :
16943 : : /*
16944 : : * Queue up command to restore marking of index used for cluster.
16945 : : */
16946 [ + + ]: 1352 : if (tab->clusterOnIndex)
16947 : : {
16948 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16949 : :
16950 : 12 : cmd->subtype = AT_ClusterOn;
16951 : 12 : cmd->name = tab->clusterOnIndex;
16952 : :
16953 : : /* do it after indexes and constraints */
16954 : 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16955 : 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16956 : : }
16957 : :
16958 : : /*
16959 : : * It should be okay to use DROP_RESTRICT here, since nothing else should
16960 : : * be depending on these objects.
16961 : : */
16962 : 1352 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
16963 : :
16964 : 1352 : free_object_addresses(objects);
16965 : :
16966 : : /*
16967 : : * The objects will get recreated during subsequent passes over the work
16968 : : * queue.
16969 : : */
16970 : 1352 : }
16971 : :
16972 : : /*
16973 : : * Parse the previously-saved definition string for a constraint, index or
16974 : : * statistics object against the newly-established column data type(s), and
16975 : : * queue up the resulting command parsetrees for execution.
16976 : : *
16977 : : * This might fail if, for example, you have a WHERE clause that uses an
16978 : : * operator that's not available for the new column type.
16979 : : */
16980 : : static void
16981 : 677 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
16982 : : const char *cmdstring, List **wqueue, LOCKMODE lockmode,
16983 : : bool rewrite)
16984 : : {
16985 : : List *raw_parsetree_list;
16986 : : List *querytree_list;
16987 : : ListCell *list_item;
16988 : : Relation rel;
16989 : :
16990 : : /*
16991 : : * We expect that we will get only ALTER TABLE and CREATE INDEX
16992 : : * statements. Hence, there is no need to pass them through
16993 : : * parse_analyze_*() or the rewriter, but instead we need to pass them
16994 : : * through parse_utilcmd.c to make them ready for execution.
16995 : : */
16996 : 677 : raw_parsetree_list = raw_parser(cmdstring, RAW_PARSE_DEFAULT);
16997 : 677 : querytree_list = NIL;
16998 [ + - + + : 1354 : foreach(list_item, raw_parsetree_list)
+ + ]
16999 : : {
17000 : 677 : RawStmt *rs = lfirst_node(RawStmt, list_item);
17001 : 677 : Node *stmt = rs->stmt;
17002 : :
17003 [ + + ]: 677 : if (IsA(stmt, IndexStmt))
17004 : 186 : querytree_list = lappend(querytree_list,
17005 : 186 : transformIndexStmt(oldRelId,
17006 : : (IndexStmt *) stmt,
17007 : : cmdstring));
17008 [ + + ]: 491 : else if (IsA(stmt, AlterTableStmt))
17009 : : {
17010 : : List *beforeStmts;
17011 : : List *afterStmts;
17012 : :
17013 : 421 : stmt = (Node *) transformAlterTableStmt(oldRelId,
17014 : : (AlterTableStmt *) stmt,
17015 : : cmdstring,
17016 : : &beforeStmts,
17017 : : &afterStmts);
17018 : 421 : querytree_list = list_concat(querytree_list, beforeStmts);
17019 : 421 : querytree_list = lappend(querytree_list, stmt);
17020 : 421 : querytree_list = list_concat(querytree_list, afterStmts);
17021 : : }
17022 [ + + ]: 70 : else if (IsA(stmt, CreateStatsStmt))
17023 : : {
17024 : : CreateStatsStmt *csstmt;
17025 : :
17026 : 57 : csstmt = transformStatsStmt(oldRelId, (CreateStatsStmt *) stmt, cmdstring);
17027 : 57 : csstmt->owner = ownerId;
17028 : :
17029 : 57 : querytree_list = lappend(querytree_list, csstmt);
17030 : : }
17031 : : else
17032 : 13 : querytree_list = lappend(querytree_list, stmt);
17033 : : }
17034 : :
17035 : : /* Caller should already have acquired whatever lock we need. */
17036 : 677 : rel = relation_open(oldRelId, NoLock);
17037 : :
17038 : : /*
17039 : : * Attach each generated command to the proper place in the work queue.
17040 : : * Note this could result in creation of entirely new work-queue entries.
17041 : : *
17042 : : * Also note that we have to tweak the command subtypes, because it turns
17043 : : * out that re-creation of indexes and constraints has to act a bit
17044 : : * differently from initial creation.
17045 : : */
17046 [ + - + + : 1354 : foreach(list_item, querytree_list)
+ + ]
17047 : : {
17048 : 677 : Node *stm = (Node *) lfirst(list_item);
17049 : : AlteredTableInfo *tab;
17050 : :
17051 : 677 : tab = ATGetQueueEntry(wqueue, rel);
17052 : :
17053 [ + + ]: 677 : if (IsA(stm, IndexStmt))
17054 : : {
17055 : 186 : IndexStmt *stmt = (IndexStmt *) stm;
17056 : : AlterTableCmd *newcmd;
17057 : :
17058 [ + + ]: 186 : if (!rewrite)
17059 : 53 : TryReuseIndex(oldId, stmt);
17060 : 186 : stmt->reset_default_tblspc = true;
17061 : : /* keep the index's comment */
17062 : 186 : stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
17063 : :
17064 : 186 : newcmd = makeNode(AlterTableCmd);
17065 : 186 : newcmd->subtype = AT_ReAddIndex;
17066 : 186 : newcmd->def = (Node *) stmt;
17067 : 186 : tab->subcmds[AT_PASS_OLD_INDEX] =
17068 : 186 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
17069 : : }
17070 [ + + ]: 491 : else if (IsA(stm, AlterTableStmt))
17071 : : {
17072 : 421 : AlterTableStmt *stmt = (AlterTableStmt *) stm;
17073 : : ListCell *lcmd;
17074 : :
17075 [ + - + + : 842 : foreach(lcmd, stmt->cmds)
+ + ]
17076 : : {
17077 : 421 : AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
17078 : :
17079 [ + + ]: 421 : if (cmd->subtype == AT_AddIndex)
17080 : : {
17081 : : IndexStmt *indstmt;
17082 : : Oid indoid;
17083 : :
17084 : 152 : indstmt = castNode(IndexStmt, cmd->def);
17085 : 152 : indoid = get_constraint_index(oldId);
17086 : :
17087 [ + + ]: 152 : if (!rewrite)
17088 : 32 : TryReuseIndex(indoid, indstmt);
17089 : : /* keep any comment on the index */
17090 : 152 : indstmt->idxcomment = GetComment(indoid,
17091 : : RelationRelationId, 0);
17092 : 152 : indstmt->reset_default_tblspc = true;
17093 : :
17094 : 152 : cmd->subtype = AT_ReAddIndex;
17095 : 152 : tab->subcmds[AT_PASS_OLD_INDEX] =
17096 : 152 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
17097 : :
17098 : : /* recreate any comment on the constraint */
17099 : 152 : RebuildConstraintComment(tab,
17100 : : AT_PASS_OLD_INDEX,
17101 : : oldId,
17102 : : rel,
17103 : : NIL,
17104 : 152 : indstmt->idxname);
17105 : : }
17106 [ + - ]: 269 : else if (cmd->subtype == AT_AddConstraint)
17107 : : {
17108 : 269 : Constraint *con = castNode(Constraint, cmd->def);
17109 : :
17110 : 269 : con->old_pktable_oid = refRelId;
17111 : : /* rewriting neither side of a FK */
17112 [ + + ]: 269 : if (con->contype == CONSTR_FOREIGN &&
17113 [ + + + - ]: 48 : !rewrite && tab->rewrite == 0)
17114 : 4 : TryReuseForeignKey(oldId, con);
17115 : 269 : con->reset_default_tblspc = true;
17116 : 269 : cmd->subtype = AT_ReAddConstraint;
17117 : 269 : tab->subcmds[AT_PASS_OLD_CONSTR] =
17118 : 269 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
17119 : :
17120 : : /*
17121 : : * Recreate any comment on the constraint. If we have
17122 : : * recreated a primary key, then transformTableConstraint
17123 : : * has added an unnamed not-null constraint here; skip
17124 : : * this in that case.
17125 : : */
17126 [ + - ]: 269 : if (con->conname)
17127 : 269 : RebuildConstraintComment(tab,
17128 : : AT_PASS_OLD_CONSTR,
17129 : : oldId,
17130 : : rel,
17131 : : NIL,
17132 : 269 : con->conname);
17133 : : else
17134 : : Assert(con->contype == CONSTR_NOTNULL);
17135 : : }
17136 : : else
17137 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
17138 : : (int) cmd->subtype);
17139 : : }
17140 : : }
17141 [ + + ]: 70 : else if (IsA(stm, AlterDomainStmt))
17142 : : {
17143 : 13 : AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
17144 : :
17145 [ + - ]: 13 : if (stmt->subtype == AD_AddConstraint)
17146 : : {
17147 : 13 : Constraint *con = castNode(Constraint, stmt->def);
17148 : 13 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
17149 : :
17150 : 13 : cmd->subtype = AT_ReAddDomainConstraint;
17151 : 13 : cmd->def = (Node *) stmt;
17152 : 13 : tab->subcmds[AT_PASS_OLD_CONSTR] =
17153 : 13 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
17154 : :
17155 : : /* recreate any comment on the constraint */
17156 : 13 : RebuildConstraintComment(tab,
17157 : : AT_PASS_OLD_CONSTR,
17158 : : oldId,
17159 : : NULL,
17160 : : stmt->typeName,
17161 : 13 : con->conname);
17162 : : }
17163 : : else
17164 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
17165 : : (int) stmt->subtype);
17166 : : }
17167 [ + - ]: 57 : else if (IsA(stm, CreateStatsStmt))
17168 : : {
17169 : 57 : CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
17170 : : AlterTableCmd *newcmd;
17171 : :
17172 : : /* keep the statistics object's comment */
17173 : 57 : stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
17174 : :
17175 : 57 : newcmd = makeNode(AlterTableCmd);
17176 : 57 : newcmd->subtype = AT_ReAddStatistics;
17177 : 57 : newcmd->def = (Node *) stmt;
17178 : 57 : tab->subcmds[AT_PASS_MISC] =
17179 : 57 : lappend(tab->subcmds[AT_PASS_MISC], newcmd);
17180 : : }
17181 : : else
17182 [ # # ]: 0 : elog(ERROR, "unexpected statement type: %d",
17183 : : (int) nodeTag(stm));
17184 : : }
17185 : :
17186 : 677 : relation_close(rel, NoLock);
17187 : 677 : }
17188 : :
17189 : : /*
17190 : : * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
17191 : : * for a table or domain constraint that is being rebuilt.
17192 : : *
17193 : : * objid is the OID of the constraint.
17194 : : * Pass "rel" for a table constraint, or "domname" (domain's qualified name
17195 : : * as a string list) for a domain constraint.
17196 : : * (We could dig that info, as well as the conname, out of the pg_constraint
17197 : : * entry; but callers already have them so might as well pass them.)
17198 : : */
17199 : : static void
17200 : 434 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
17201 : : Relation rel, List *domname,
17202 : : const char *conname)
17203 : : {
17204 : : CommentStmt *cmd;
17205 : : char *comment_str;
17206 : : AlterTableCmd *newcmd;
17207 : :
17208 : : /* Look for comment for object wanted, and leave if none */
17209 : 434 : comment_str = GetComment(objid, ConstraintRelationId, 0);
17210 [ + + ]: 434 : if (comment_str == NULL)
17211 : 374 : return;
17212 : :
17213 : : /* Build CommentStmt node, copying all input data for safety */
17214 : 60 : cmd = makeNode(CommentStmt);
17215 [ + + ]: 60 : if (rel)
17216 : : {
17217 : 52 : cmd->objtype = OBJECT_TABCONSTRAINT;
17218 : 52 : cmd->object = (Node *)
17219 : 52 : list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
17220 : : makeString(pstrdup(RelationGetRelationName(rel))),
17221 : : makeString(pstrdup(conname)));
17222 : : }
17223 : : else
17224 : : {
17225 : 8 : cmd->objtype = OBJECT_DOMCONSTRAINT;
17226 : 8 : cmd->object = (Node *)
17227 : 8 : list_make2(makeTypeNameFromNameList(copyObject(domname)),
17228 : : makeString(pstrdup(conname)));
17229 : : }
17230 : 60 : cmd->comment = comment_str;
17231 : :
17232 : : /* Append it to list of commands */
17233 : 60 : newcmd = makeNode(AlterTableCmd);
17234 : 60 : newcmd->subtype = AT_ReAddComment;
17235 : 60 : newcmd->def = (Node *) cmd;
17236 : 60 : tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
17237 : : }
17238 : :
17239 : : /*
17240 : : * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
17241 : : * for the real analysis, then mutates the IndexStmt based on that verdict.
17242 : : */
17243 : : static void
17244 : 85 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
17245 : : {
17246 [ + + ]: 85 : if (CheckIndexCompatible(oldId,
17247 : 85 : stmt->accessMethod,
17248 : 85 : stmt->indexParams,
17249 : 85 : stmt->excludeOpNames,
17250 : 85 : stmt->iswithoutoverlaps))
17251 : : {
17252 : 69 : Relation irel = index_open(oldId, NoLock);
17253 : :
17254 : : /* If it's a partitioned index, there is no storage to share. */
17255 [ + + ]: 69 : if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
17256 : : {
17257 : 49 : stmt->oldNumber = irel->rd_locator.relNumber;
17258 : 49 : stmt->oldCreateSubid = irel->rd_createSubid;
17259 : 49 : stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
17260 : : }
17261 : 69 : index_close(irel, NoLock);
17262 : : }
17263 : 85 : }
17264 : :
17265 : : /*
17266 : : * Subroutine for ATPostAlterTypeParse().
17267 : : *
17268 : : * Stash the old P-F equality operator into the Constraint node, for possible
17269 : : * use by ATAddForeignKeyConstraint() in determining whether revalidation of
17270 : : * this constraint can be skipped.
17271 : : */
17272 : : static void
17273 : 4 : TryReuseForeignKey(Oid oldId, Constraint *con)
17274 : : {
17275 : : HeapTuple tup;
17276 : : Datum adatum;
17277 : : ArrayType *arr;
17278 : : Oid *rawarr;
17279 : : int numkeys;
17280 : : int i;
17281 : :
17282 : : Assert(con->contype == CONSTR_FOREIGN);
17283 : : Assert(con->old_conpfeqop == NIL); /* already prepared this node */
17284 : :
17285 : 4 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
17286 [ - + ]: 4 : if (!HeapTupleIsValid(tup)) /* should not happen */
17287 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
17288 : :
17289 : 4 : adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
17290 : : Anum_pg_constraint_conpfeqop);
17291 : 4 : arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
17292 : 4 : numkeys = ARR_DIMS(arr)[0];
17293 : : /* test follows the one in ri_FetchConstraintInfo() */
17294 [ + - ]: 4 : if (ARR_NDIM(arr) != 1 ||
17295 [ + - ]: 4 : ARR_HASNULL(arr) ||
17296 [ - + ]: 4 : ARR_ELEMTYPE(arr) != OIDOID)
17297 [ # # ]: 0 : elog(ERROR, "conpfeqop is not a 1-D Oid array");
17298 [ - + ]: 4 : rawarr = (Oid *) ARR_DATA_PTR(arr);
17299 : :
17300 : : /* stash a List of the operator Oids in our Constraint node */
17301 [ + + ]: 8 : for (i = 0; i < numkeys; i++)
17302 : 4 : con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
17303 : :
17304 : 4 : ReleaseSysCache(tup);
17305 : 4 : }
17306 : :
17307 : : /*
17308 : : * ALTER COLUMN .. OPTIONS ( ... )
17309 : : *
17310 : : * Returns the address of the modified column
17311 : : */
17312 : : static ObjectAddress
17313 : 94 : ATExecAlterColumnGenericOptions(Relation rel,
17314 : : const char *colName,
17315 : : List *options,
17316 : : LOCKMODE lockmode)
17317 : : {
17318 : : Relation ftrel;
17319 : : Relation attrel;
17320 : : ForeignServer *server;
17321 : : ForeignDataWrapper *fdw;
17322 : : HeapTuple tuple;
17323 : : HeapTuple newtuple;
17324 : : bool isnull;
17325 : : Datum repl_val[Natts_pg_attribute];
17326 : : bool repl_null[Natts_pg_attribute];
17327 : : bool repl_repl[Natts_pg_attribute];
17328 : : Datum datum;
17329 : : Form_pg_foreign_table fttableform;
17330 : : Form_pg_attribute atttableform;
17331 : : AttrNumber attnum;
17332 : : ObjectAddress address;
17333 : :
17334 [ - + ]: 94 : if (options == NIL)
17335 : 0 : return InvalidObjectAddress;
17336 : :
17337 : : /* First, determine FDW validator associated to the foreign table. */
17338 : 94 : ftrel = table_open(ForeignTableRelationId, AccessShareLock);
17339 : 94 : tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
17340 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
17341 [ # # ]: 0 : ereport(ERROR,
17342 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
17343 : : errmsg("foreign table \"%s\" does not exist",
17344 : : RelationGetRelationName(rel))));
17345 : 94 : fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
17346 : 94 : server = GetForeignServer(fttableform->ftserver);
17347 : 94 : fdw = GetForeignDataWrapper(server->fdwid);
17348 : :
17349 : 94 : table_close(ftrel, AccessShareLock);
17350 : 94 : ReleaseSysCache(tuple);
17351 : :
17352 : 94 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
17353 : 94 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
17354 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
17355 [ # # ]: 0 : ereport(ERROR,
17356 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
17357 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
17358 : : colName, RelationGetRelationName(rel))));
17359 : :
17360 : : /* Prevent them from altering a system attribute */
17361 : 94 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
17362 : 94 : attnum = atttableform->attnum;
17363 [ + + ]: 94 : if (attnum <= 0)
17364 [ + - ]: 4 : ereport(ERROR,
17365 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17366 : : errmsg("cannot alter system column \"%s\"", colName)));
17367 : :
17368 : :
17369 : : /* Initialize buffers for new tuple values */
17370 : 90 : memset(repl_val, 0, sizeof(repl_val));
17371 : 90 : memset(repl_null, false, sizeof(repl_null));
17372 : 90 : memset(repl_repl, false, sizeof(repl_repl));
17373 : :
17374 : : /* Extract the current options */
17375 : 90 : datum = SysCacheGetAttr(ATTNAME,
17376 : : tuple,
17377 : : Anum_pg_attribute_attfdwoptions,
17378 : : &isnull);
17379 [ + + ]: 90 : if (isnull)
17380 : 84 : datum = PointerGetDatum(NULL);
17381 : :
17382 : : /* Transform the options */
17383 : 90 : datum = transformGenericOptions(AttributeRelationId,
17384 : : datum,
17385 : : options,
17386 : : fdw->fdwvalidator);
17387 : :
17388 [ + - ]: 90 : if (DatumGetPointer(datum) != NULL)
17389 : 90 : repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
17390 : : else
17391 : 0 : repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
17392 : :
17393 : 90 : repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
17394 : :
17395 : : /* Everything looks good - update the tuple */
17396 : :
17397 : 90 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
17398 : : repl_val, repl_null, repl_repl);
17399 : :
17400 : 90 : CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
17401 : :
17402 [ - + ]: 90 : InvokeObjectPostAlterHook(RelationRelationId,
17403 : : RelationGetRelid(rel),
17404 : : atttableform->attnum);
17405 : 90 : ObjectAddressSubSet(address, RelationRelationId,
17406 : : RelationGetRelid(rel), attnum);
17407 : :
17408 : 90 : ReleaseSysCache(tuple);
17409 : :
17410 : 90 : table_close(attrel, RowExclusiveLock);
17411 : :
17412 : 90 : heap_freetuple(newtuple);
17413 : :
17414 : 90 : return address;
17415 : : }
17416 : :
17417 : : /*
17418 : : * ALTER TABLE OWNER
17419 : : *
17420 : : * recursing is true if we are recursing from a table to its indexes,
17421 : : * sequences, or toast table. We don't allow the ownership of those things to
17422 : : * be changed separately from the parent table. Also, we can skip permission
17423 : : * checks (this is necessary not just an optimization, else we'd fail to
17424 : : * handle toast tables properly).
17425 : : *
17426 : : * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
17427 : : * free-standing composite type.
17428 : : */
17429 : : void
17430 : 1490 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
17431 : : {
17432 : : Relation target_rel;
17433 : : Relation class_rel;
17434 : : HeapTuple tuple;
17435 : : Form_pg_class tuple_class;
17436 : :
17437 : : /*
17438 : : * Get exclusive lock till end of transaction on the target table. Use
17439 : : * relation_open so that we can work on indexes and sequences.
17440 : : */
17441 : 1490 : target_rel = relation_open(relationOid, lockmode);
17442 : :
17443 : : /* Get its pg_class tuple, too */
17444 : 1490 : class_rel = table_open(RelationRelationId, RowExclusiveLock);
17445 : :
17446 : 1490 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
17447 [ - + ]: 1490 : if (!HeapTupleIsValid(tuple))
17448 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationOid);
17449 : 1490 : tuple_class = (Form_pg_class) GETSTRUCT(tuple);
17450 : :
17451 : : /* Can we change the ownership of this tuple? */
17452 [ + + + + : 1490 : switch (tuple_class->relkind)
+ + - ]
17453 : : {
17454 : 1228 : case RELKIND_RELATION:
17455 : : case RELKIND_VIEW:
17456 : : case RELKIND_MATVIEW:
17457 : : case RELKIND_FOREIGN_TABLE:
17458 : : case RELKIND_PARTITIONED_TABLE:
17459 : : /* ok to change owner */
17460 : 1228 : break;
17461 : 111 : case RELKIND_INDEX:
17462 [ - + ]: 111 : if (!recursing)
17463 : : {
17464 : : /*
17465 : : * Because ALTER INDEX OWNER used to be allowed, and in fact
17466 : : * is generated by old versions of pg_dump, we give a warning
17467 : : * and do nothing rather than erroring out. Also, to avoid
17468 : : * unnecessary chatter while restoring those old dumps, say
17469 : : * nothing at all if the command would be a no-op anyway.
17470 : : */
17471 [ # # ]: 0 : if (tuple_class->relowner != newOwnerId)
17472 [ # # ]: 0 : ereport(WARNING,
17473 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17474 : : errmsg("cannot change owner of index \"%s\"",
17475 : : NameStr(tuple_class->relname)),
17476 : : errhint("Change the ownership of the index's table instead.")));
17477 : : /* quick hack to exit via the no-op path */
17478 : 0 : newOwnerId = tuple_class->relowner;
17479 : : }
17480 : 111 : break;
17481 : 26 : case RELKIND_PARTITIONED_INDEX:
17482 [ + - ]: 26 : if (recursing)
17483 : 26 : break;
17484 [ # # ]: 0 : ereport(ERROR,
17485 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17486 : : errmsg("cannot change owner of index \"%s\"",
17487 : : NameStr(tuple_class->relname)),
17488 : : errhint("Change the ownership of the index's table instead.")));
17489 : : break;
17490 : 69 : case RELKIND_SEQUENCE:
17491 [ + + ]: 69 : if (!recursing &&
17492 [ + + ]: 39 : tuple_class->relowner != newOwnerId)
17493 : : {
17494 : : /* if it's an owned sequence, disallow changing it by itself */
17495 : : Oid tableId;
17496 : : int32 colId;
17497 : :
17498 [ + - - + ]: 8 : if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
17499 : 4 : sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
17500 [ # # ]: 0 : ereport(ERROR,
17501 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17502 : : errmsg("cannot change owner of sequence \"%s\"",
17503 : : NameStr(tuple_class->relname)),
17504 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
17505 : : NameStr(tuple_class->relname),
17506 : : get_rel_name(tableId))));
17507 : : }
17508 : 69 : break;
17509 : 5 : case RELKIND_COMPOSITE_TYPE:
17510 [ + - ]: 5 : if (recursing)
17511 : 5 : break;
17512 [ # # ]: 0 : ereport(ERROR,
17513 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17514 : : errmsg("\"%s\" is a composite type",
17515 : : NameStr(tuple_class->relname)),
17516 : : /* translator: %s is an SQL ALTER command */
17517 : : errhint("Use %s instead.",
17518 : : "ALTER TYPE")));
17519 : : break;
17520 : 51 : case RELKIND_TOASTVALUE:
17521 [ + - ]: 51 : if (recursing)
17522 : 51 : break;
17523 : : pg_fallthrough;
17524 : : default:
17525 [ # # ]: 0 : ereport(ERROR,
17526 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17527 : : errmsg("cannot change owner of relation \"%s\"",
17528 : : NameStr(tuple_class->relname)),
17529 : : errdetail_relkind_not_supported(tuple_class->relkind)));
17530 : : }
17531 : :
17532 : : /*
17533 : : * If the new owner is the same as the existing owner, consider the
17534 : : * command to have succeeded. This is for dump restoration purposes.
17535 : : */
17536 [ + + ]: 1490 : if (tuple_class->relowner != newOwnerId)
17537 : : {
17538 : : Datum repl_val[Natts_pg_class];
17539 : : bool repl_null[Natts_pg_class];
17540 : : bool repl_repl[Natts_pg_class];
17541 : : Acl *newAcl;
17542 : : Datum aclDatum;
17543 : : bool isNull;
17544 : : HeapTuple newtuple;
17545 : :
17546 : : /* skip permission checks when recursing to index or toast table */
17547 [ + + ]: 481 : if (!recursing)
17548 : : {
17549 : : /* Superusers can always do it */
17550 [ + + ]: 248 : if (!superuser())
17551 : : {
17552 : 28 : Oid namespaceOid = tuple_class->relnamespace;
17553 : : AclResult aclresult;
17554 : :
17555 : : /* Otherwise, must be owner of the existing object */
17556 [ - + ]: 28 : if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
17557 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
17558 : 0 : RelationGetRelationName(target_rel));
17559 : :
17560 : : /* Must be able to become new owner */
17561 : 28 : check_can_set_role(GetUserId(), newOwnerId);
17562 : :
17563 : : /* New owner must have CREATE privilege on namespace */
17564 : 20 : aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
17565 : : ACL_CREATE);
17566 [ - + ]: 20 : if (aclresult != ACLCHECK_OK)
17567 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
17568 : 0 : get_namespace_name(namespaceOid));
17569 : : }
17570 : : }
17571 : :
17572 : 473 : memset(repl_null, false, sizeof(repl_null));
17573 : 473 : memset(repl_repl, false, sizeof(repl_repl));
17574 : :
17575 : 473 : repl_repl[Anum_pg_class_relowner - 1] = true;
17576 : 473 : repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
17577 : :
17578 : : /*
17579 : : * Determine the modified ACL for the new owner. This is only
17580 : : * necessary when the ACL is non-null.
17581 : : */
17582 : 473 : aclDatum = SysCacheGetAttr(RELOID, tuple,
17583 : : Anum_pg_class_relacl,
17584 : : &isNull);
17585 [ + + ]: 473 : if (!isNull)
17586 : : {
17587 : 36 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
17588 : : tuple_class->relowner, newOwnerId);
17589 : 36 : repl_repl[Anum_pg_class_relacl - 1] = true;
17590 : 36 : repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
17591 : : }
17592 : :
17593 : 473 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
17594 : :
17595 : 473 : CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
17596 : :
17597 : 473 : heap_freetuple(newtuple);
17598 : :
17599 : : /*
17600 : : * We must similarly update any per-column ACLs to reflect the new
17601 : : * owner; for neatness reasons that's split out as a subroutine.
17602 : : */
17603 : 473 : change_owner_fix_column_acls(relationOid,
17604 : : tuple_class->relowner,
17605 : : newOwnerId);
17606 : :
17607 : : /*
17608 : : * Update owner dependency reference, if any. A composite type has
17609 : : * none, because it's tracked for the pg_type entry instead of here;
17610 : : * indexes and TOAST tables don't have their own entries either.
17611 : : */
17612 [ + + ]: 473 : if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
17613 [ + + ]: 468 : tuple_class->relkind != RELKIND_INDEX &&
17614 [ + + ]: 357 : tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
17615 [ + + ]: 331 : tuple_class->relkind != RELKIND_TOASTVALUE)
17616 : 280 : changeDependencyOnOwner(RelationRelationId, relationOid,
17617 : : newOwnerId);
17618 : :
17619 : : /*
17620 : : * Also change the ownership of the table's row type, if it has one
17621 : : */
17622 [ + + ]: 473 : if (OidIsValid(tuple_class->reltype))
17623 : 260 : AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
17624 : :
17625 : : /*
17626 : : * If we are operating on a table or materialized view, also change
17627 : : * the ownership of any indexes and sequences that belong to the
17628 : : * relation, as well as its toast table (if it has one).
17629 : : */
17630 [ + + ]: 473 : if (tuple_class->relkind == RELKIND_RELATION ||
17631 [ + + ]: 269 : tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
17632 [ + - ]: 232 : tuple_class->relkind == RELKIND_MATVIEW ||
17633 [ + + ]: 232 : tuple_class->relkind == RELKIND_TOASTVALUE)
17634 : : {
17635 : : List *index_oid_list;
17636 : : ListCell *i;
17637 : :
17638 : : /* Find all the indexes belonging to this relation */
17639 : 292 : index_oid_list = RelationGetIndexList(target_rel);
17640 : :
17641 : : /* For each index, recursively change its ownership */
17642 [ + + + + : 429 : foreach(i, index_oid_list)
+ + ]
17643 : 137 : ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
17644 : :
17645 : 292 : list_free(index_oid_list);
17646 : : }
17647 : :
17648 : : /* If it has a toast table, recurse to change its ownership */
17649 [ + + ]: 473 : if (tuple_class->reltoastrelid != InvalidOid)
17650 : 51 : ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
17651 : : true, lockmode);
17652 : :
17653 : : /* If it has dependent sequences, recurse to change them too */
17654 : 473 : change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
17655 : : }
17656 : :
17657 [ - + ]: 1482 : InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
17658 : :
17659 : 1482 : ReleaseSysCache(tuple);
17660 : 1482 : table_close(class_rel, RowExclusiveLock);
17661 : 1482 : relation_close(target_rel, NoLock);
17662 : 1482 : }
17663 : :
17664 : : /*
17665 : : * change_owner_fix_column_acls
17666 : : *
17667 : : * Helper function for ATExecChangeOwner. Scan the columns of the table
17668 : : * and fix any non-null column ACLs to reflect the new owner.
17669 : : */
17670 : : static void
17671 : 473 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
17672 : : {
17673 : : Relation attRelation;
17674 : : SysScanDesc scan;
17675 : : ScanKeyData key[1];
17676 : : HeapTuple attributeTuple;
17677 : :
17678 : 473 : attRelation = table_open(AttributeRelationId, RowExclusiveLock);
17679 : 473 : ScanKeyInit(&key[0],
17680 : : Anum_pg_attribute_attrelid,
17681 : : BTEqualStrategyNumber, F_OIDEQ,
17682 : : ObjectIdGetDatum(relationOid));
17683 : 473 : scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
17684 : : true, NULL, 1, key);
17685 [ + + ]: 3297 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
17686 : : {
17687 : 2824 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
17688 : : Datum repl_val[Natts_pg_attribute];
17689 : : bool repl_null[Natts_pg_attribute];
17690 : : bool repl_repl[Natts_pg_attribute];
17691 : : Acl *newAcl;
17692 : : Datum aclDatum;
17693 : : bool isNull;
17694 : : HeapTuple newtuple;
17695 : :
17696 : : /* Ignore dropped columns */
17697 [ - + ]: 2824 : if (att->attisdropped)
17698 : 2823 : continue;
17699 : :
17700 : 2824 : aclDatum = heap_getattr(attributeTuple,
17701 : : Anum_pg_attribute_attacl,
17702 : : RelationGetDescr(attRelation),
17703 : : &isNull);
17704 : : /* Null ACLs do not require changes */
17705 [ + + ]: 2824 : if (isNull)
17706 : 2823 : continue;
17707 : :
17708 : 1 : memset(repl_null, false, sizeof(repl_null));
17709 : 1 : memset(repl_repl, false, sizeof(repl_repl));
17710 : :
17711 : 1 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
17712 : : oldOwnerId, newOwnerId);
17713 : 1 : repl_repl[Anum_pg_attribute_attacl - 1] = true;
17714 : 1 : repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
17715 : :
17716 : 1 : newtuple = heap_modify_tuple(attributeTuple,
17717 : : RelationGetDescr(attRelation),
17718 : : repl_val, repl_null, repl_repl);
17719 : :
17720 : 1 : CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
17721 : :
17722 : 1 : heap_freetuple(newtuple);
17723 : : }
17724 : 473 : systable_endscan(scan);
17725 : 473 : table_close(attRelation, RowExclusiveLock);
17726 : 473 : }
17727 : :
17728 : : /*
17729 : : * change_owner_recurse_to_sequences
17730 : : *
17731 : : * Helper function for ATExecChangeOwner. Examines pg_depend searching
17732 : : * for sequences that are dependent on serial columns, and changes their
17733 : : * ownership.
17734 : : */
17735 : : static void
17736 : 473 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
17737 : : {
17738 : : Relation depRel;
17739 : : SysScanDesc scan;
17740 : : ScanKeyData key[2];
17741 : : HeapTuple tup;
17742 : :
17743 : : /*
17744 : : * SERIAL sequences are those having an auto dependency on one of the
17745 : : * table's columns (we don't care *which* column, exactly).
17746 : : */
17747 : 473 : depRel = table_open(DependRelationId, AccessShareLock);
17748 : :
17749 : 473 : ScanKeyInit(&key[0],
17750 : : Anum_pg_depend_refclassid,
17751 : : BTEqualStrategyNumber, F_OIDEQ,
17752 : : ObjectIdGetDatum(RelationRelationId));
17753 : 473 : ScanKeyInit(&key[1],
17754 : : Anum_pg_depend_refobjid,
17755 : : BTEqualStrategyNumber, F_OIDEQ,
17756 : : ObjectIdGetDatum(relationOid));
17757 : : /* we leave refobjsubid unspecified */
17758 : :
17759 : 473 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
17760 : : NULL, 2, key);
17761 : :
17762 [ + + ]: 1359 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
17763 : : {
17764 : 886 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
17765 : : Relation seqRel;
17766 : :
17767 : : /* skip dependencies other than auto dependencies on columns */
17768 [ + + ]: 886 : if (depForm->refobjsubid == 0 ||
17769 [ + + ]: 388 : depForm->classid != RelationRelationId ||
17770 [ + - ]: 155 : depForm->objsubid != 0 ||
17771 [ + + - + ]: 155 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
17772 : 731 : continue;
17773 : :
17774 : : /* Use relation_open just in case it's an index */
17775 : 155 : seqRel = relation_open(depForm->objid, lockmode);
17776 : :
17777 : : /* skip non-sequence relations */
17778 [ + + ]: 155 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
17779 : : {
17780 : : /* No need to keep the lock */
17781 : 138 : relation_close(seqRel, lockmode);
17782 : 138 : continue;
17783 : : }
17784 : :
17785 : : /* We don't need to close the sequence while we alter it. */
17786 : 17 : ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
17787 : :
17788 : : /* Now we can close it. Keep the lock till end of transaction. */
17789 : 17 : relation_close(seqRel, NoLock);
17790 : : }
17791 : :
17792 : 473 : systable_endscan(scan);
17793 : :
17794 : 473 : relation_close(depRel, AccessShareLock);
17795 : 473 : }
17796 : :
17797 : : /*
17798 : : * ALTER TABLE CLUSTER ON
17799 : : *
17800 : : * The only thing we have to do is to change the indisclustered bits.
17801 : : *
17802 : : * Return the address of the new clustering index.
17803 : : */
17804 : : static ObjectAddress
17805 : 39 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
17806 : : {
17807 : : Oid indexOid;
17808 : : ObjectAddress address;
17809 : :
17810 : 39 : indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
17811 : :
17812 [ - + ]: 39 : if (!OidIsValid(indexOid))
17813 [ # # ]: 0 : ereport(ERROR,
17814 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
17815 : : errmsg("index \"%s\" for table \"%s\" does not exist",
17816 : : indexName, RelationGetRelationName(rel))));
17817 : :
17818 : : /* Check index is valid to cluster on */
17819 : 39 : check_index_is_clusterable(rel, indexOid, lockmode);
17820 : :
17821 : : /* And do the work */
17822 : 39 : mark_index_clustered(rel, indexOid, false);
17823 : :
17824 : 39 : ObjectAddressSet(address,
17825 : : RelationRelationId, indexOid);
17826 : :
17827 : 39 : return address;
17828 : : }
17829 : :
17830 : : /*
17831 : : * ALTER TABLE SET WITHOUT CLUSTER
17832 : : *
17833 : : * We have to find any indexes on the table that have indisclustered bit
17834 : : * set and turn it off.
17835 : : */
17836 : : static void
17837 : 8 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
17838 : : {
17839 : 8 : mark_index_clustered(rel, InvalidOid, false);
17840 : 8 : }
17841 : :
17842 : : /*
17843 : : * Preparation phase for SET ACCESS METHOD
17844 : : *
17845 : : * Check that the access method exists and determine whether a change is
17846 : : * actually needed.
17847 : : */
17848 : : static void
17849 : 73 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
17850 : : {
17851 : : Oid amoid;
17852 : :
17853 : : /*
17854 : : * Look up the access method name and check that it differs from the
17855 : : * table's current AM. If DEFAULT was specified for a partitioned table
17856 : : * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
17857 : : */
17858 [ + + ]: 73 : if (amname != NULL)
17859 : 49 : amoid = get_table_am_oid(amname, false);
17860 [ + + ]: 24 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17861 : 12 : amoid = InvalidOid;
17862 : : else
17863 : 12 : amoid = get_table_am_oid(default_table_access_method, false);
17864 : :
17865 : : /* if it's a match, phase 3 doesn't need to do anything */
17866 [ + + ]: 73 : if (rel->rd_rel->relam == amoid)
17867 : 8 : return;
17868 : :
17869 : : /* Save info for Phase 3 to do the real work */
17870 : 65 : tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
17871 : 65 : tab->newAccessMethod = amoid;
17872 : 65 : tab->chgAccessMethod = true;
17873 : : }
17874 : :
17875 : : /*
17876 : : * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
17877 : : * storage that have an interest in preserving AM.
17878 : : *
17879 : : * Since these have no storage, setting the access method is a catalog only
17880 : : * operation.
17881 : : */
17882 : : static void
17883 : 29 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
17884 : : {
17885 : : Relation pg_class;
17886 : : Oid oldAccessMethodId;
17887 : : HeapTuple tuple;
17888 : : Form_pg_class rd_rel;
17889 : 29 : Oid reloid = RelationGetRelid(rel);
17890 : :
17891 : : /*
17892 : : * Shouldn't be called on relations having storage; these are processed in
17893 : : * phase 3.
17894 : : */
17895 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17896 : :
17897 : : /* Get a modifiable copy of the relation's pg_class row. */
17898 : 29 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
17899 : :
17900 : 29 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
17901 [ - + ]: 29 : if (!HeapTupleIsValid(tuple))
17902 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
17903 : 29 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
17904 : :
17905 : : /* Update the pg_class row. */
17906 : 29 : oldAccessMethodId = rd_rel->relam;
17907 : 29 : rd_rel->relam = newAccessMethodId;
17908 : :
17909 : : /* Leave if no update required */
17910 [ - + ]: 29 : if (rd_rel->relam == oldAccessMethodId)
17911 : : {
17912 : 0 : heap_freetuple(tuple);
17913 : 0 : table_close(pg_class, RowExclusiveLock);
17914 : 0 : return;
17915 : : }
17916 : :
17917 : 29 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
17918 : :
17919 : : /*
17920 : : * Update the dependency on the new access method. No dependency is added
17921 : : * if the new access method is InvalidOid (default case). Be very careful
17922 : : * that this has to compare the previous value stored in pg_class with the
17923 : : * new one.
17924 : : */
17925 [ + + + - ]: 29 : if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
17926 : 13 : {
17927 : : ObjectAddress relobj,
17928 : : referenced;
17929 : :
17930 : : /*
17931 : : * New access method is defined and there was no dependency
17932 : : * previously, so record a new one.
17933 : : */
17934 : 13 : ObjectAddressSet(relobj, RelationRelationId, reloid);
17935 : 13 : ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
17936 : 13 : recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
17937 : : }
17938 [ + - ]: 16 : else if (OidIsValid(oldAccessMethodId) &&
17939 [ + + ]: 16 : !OidIsValid(rd_rel->relam))
17940 : : {
17941 : : /*
17942 : : * There was an access method defined, and no new one, so just remove
17943 : : * the existing dependency.
17944 : : */
17945 : 8 : deleteDependencyRecordsForClass(RelationRelationId, reloid,
17946 : : AccessMethodRelationId,
17947 : : DEPENDENCY_NORMAL);
17948 : : }
17949 : : else
17950 : : {
17951 : : Assert(OidIsValid(oldAccessMethodId) &&
17952 : : OidIsValid(rd_rel->relam));
17953 : :
17954 : : /* Both are valid, so update the dependency */
17955 : 8 : changeDependencyFor(RelationRelationId, reloid,
17956 : : AccessMethodRelationId,
17957 : : oldAccessMethodId, rd_rel->relam);
17958 : : }
17959 : :
17960 : : /* make the relam and dependency changes visible */
17961 : 29 : CommandCounterIncrement();
17962 : :
17963 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17964 : :
17965 : 29 : heap_freetuple(tuple);
17966 : 29 : table_close(pg_class, RowExclusiveLock);
17967 : : }
17968 : :
17969 : : /*
17970 : : * ALTER TABLE SET TABLESPACE
17971 : : */
17972 : : static void
17973 : 107 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
17974 : : {
17975 : : Oid tablespaceId;
17976 : :
17977 : : /* Check that the tablespace exists */
17978 : 107 : tablespaceId = get_tablespace_oid(tablespacename, false);
17979 : :
17980 : : /* Check permissions except when moving to database's default */
17981 [ + - + + ]: 107 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
17982 : : {
17983 : : AclResult aclresult;
17984 : :
17985 : 49 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
17986 [ - + ]: 49 : if (aclresult != ACLCHECK_OK)
17987 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
17988 : : }
17989 : :
17990 : : /* Save info for Phase 3 to do the real work */
17991 [ - + ]: 107 : if (OidIsValid(tab->newTableSpace))
17992 [ # # ]: 0 : ereport(ERROR,
17993 : : (errcode(ERRCODE_SYNTAX_ERROR),
17994 : : errmsg("cannot have multiple SET TABLESPACE subcommands")));
17995 : :
17996 : 107 : tab->newTableSpace = tablespaceId;
17997 : 107 : }
17998 : :
17999 : : /*
18000 : : * Set, reset, or replace reloptions.
18001 : : */
18002 : : static void
18003 : 707 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
18004 : : LOCKMODE lockmode)
18005 : : {
18006 : : Oid relid;
18007 : : Relation pgclass;
18008 : : HeapTuple tuple;
18009 : : HeapTuple newtuple;
18010 : : Datum datum;
18011 : : Datum newOptions;
18012 : : Datum repl_val[Natts_pg_class];
18013 : : bool repl_null[Natts_pg_class];
18014 : : bool repl_repl[Natts_pg_class];
18015 : 707 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
18016 : :
18017 [ + + - + ]: 707 : if (defList == NIL && operation != AT_ReplaceRelOptions)
18018 : 0 : return; /* nothing to do */
18019 : :
18020 : 707 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
18021 : :
18022 : : /* Fetch heap tuple */
18023 : 707 : relid = RelationGetRelid(rel);
18024 : 707 : tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
18025 [ - + ]: 707 : if (!HeapTupleIsValid(tuple))
18026 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18027 : :
18028 [ + + ]: 707 : if (operation == AT_ReplaceRelOptions)
18029 : : {
18030 : : /*
18031 : : * If we're supposed to replace the reloptions list, we just pretend
18032 : : * there were none before.
18033 : : */
18034 : 169 : datum = (Datum) 0;
18035 : : }
18036 : : else
18037 : : {
18038 : : bool isnull;
18039 : :
18040 : : /* Get the old reloptions */
18041 : 538 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
18042 : : &isnull);
18043 [ + + ]: 538 : if (isnull)
18044 : 302 : datum = (Datum) 0;
18045 : : }
18046 : :
18047 : : /* Generate new proposed reloptions (text array) */
18048 : 707 : newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
18049 : : operation == AT_ResetRelOptions);
18050 : :
18051 : : /* Validate */
18052 [ + + + + : 703 : switch (rel->rd_rel->relkind)
- ]
18053 : : {
18054 : 391 : case RELKIND_RELATION:
18055 : : case RELKIND_MATVIEW:
18056 : 391 : (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
18057 : 391 : break;
18058 : 4 : case RELKIND_PARTITIONED_TABLE:
18059 : 4 : (void) partitioned_table_reloptions(newOptions, true);
18060 : 0 : break;
18061 : 237 : case RELKIND_VIEW:
18062 : 237 : (void) view_reloptions(newOptions, true);
18063 : 225 : break;
18064 : 71 : case RELKIND_INDEX:
18065 : : case RELKIND_PARTITIONED_INDEX:
18066 : 71 : (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
18067 : 57 : break;
18068 : 0 : case RELKIND_TOASTVALUE:
18069 : : /* fall through to error -- shouldn't ever get here */
18070 : : default:
18071 [ # # ]: 0 : ereport(ERROR,
18072 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18073 : : errmsg("cannot set options for relation \"%s\"",
18074 : : RelationGetRelationName(rel)),
18075 : : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
18076 : : break;
18077 : : }
18078 : :
18079 : : /* Special-case validation of view options */
18080 [ + + ]: 673 : if (rel->rd_rel->relkind == RELKIND_VIEW)
18081 : : {
18082 : 225 : Query *view_query = get_view_query(rel);
18083 : 225 : List *view_options = untransformRelOptions(newOptions);
18084 : : ListCell *cell;
18085 : 225 : bool check_option = false;
18086 : :
18087 [ + + + + : 293 : foreach(cell, view_options)
+ + ]
18088 : : {
18089 : 68 : DefElem *defel = (DefElem *) lfirst(cell);
18090 : :
18091 [ + + ]: 68 : if (strcmp(defel->defname, "check_option") == 0)
18092 : 16 : check_option = true;
18093 : : }
18094 : :
18095 : : /*
18096 : : * If the check option is specified, look to see if the view is
18097 : : * actually auto-updatable or not.
18098 : : */
18099 [ + + ]: 225 : if (check_option)
18100 : : {
18101 : : const char *view_updatable_error =
18102 : 16 : view_query_is_auto_updatable(view_query, true);
18103 : :
18104 [ - + ]: 16 : if (view_updatable_error)
18105 [ # # ]: 0 : ereport(ERROR,
18106 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18107 : : errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
18108 : : errhint("%s", _(view_updatable_error))));
18109 : : }
18110 : : }
18111 : :
18112 : : /*
18113 : : * All we need do here is update the pg_class row; the new options will be
18114 : : * propagated into relcaches during post-commit cache inval.
18115 : : */
18116 : 673 : memset(repl_val, 0, sizeof(repl_val));
18117 : 673 : memset(repl_null, false, sizeof(repl_null));
18118 : 673 : memset(repl_repl, false, sizeof(repl_repl));
18119 : :
18120 [ + + ]: 673 : if (newOptions != (Datum) 0)
18121 : 427 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
18122 : : else
18123 : 246 : repl_null[Anum_pg_class_reloptions - 1] = true;
18124 : :
18125 : 673 : repl_repl[Anum_pg_class_reloptions - 1] = true;
18126 : :
18127 : 673 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
18128 : : repl_val, repl_null, repl_repl);
18129 : :
18130 : 673 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
18131 : 673 : UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
18132 : :
18133 [ - + ]: 673 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
18134 : :
18135 : 673 : heap_freetuple(newtuple);
18136 : :
18137 : 673 : ReleaseSysCache(tuple);
18138 : :
18139 : : /* repeat the whole exercise for the toast table, if there's one */
18140 [ + + ]: 673 : if (OidIsValid(rel->rd_rel->reltoastrelid))
18141 : : {
18142 : : Relation toastrel;
18143 : 222 : Oid toastid = rel->rd_rel->reltoastrelid;
18144 : :
18145 : 222 : toastrel = table_open(toastid, lockmode);
18146 : :
18147 : : /* Fetch heap tuple */
18148 : 222 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
18149 [ - + ]: 222 : if (!HeapTupleIsValid(tuple))
18150 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", toastid);
18151 : :
18152 [ - + ]: 222 : if (operation == AT_ReplaceRelOptions)
18153 : : {
18154 : : /*
18155 : : * If we're supposed to replace the reloptions list, we just
18156 : : * pretend there were none before.
18157 : : */
18158 : 0 : datum = (Datum) 0;
18159 : : }
18160 : : else
18161 : : {
18162 : : bool isnull;
18163 : :
18164 : : /* Get the old reloptions */
18165 : 222 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
18166 : : &isnull);
18167 [ + + ]: 222 : if (isnull)
18168 : 198 : datum = (Datum) 0;
18169 : : }
18170 : :
18171 : 222 : newOptions = transformRelOptions(datum, defList, "toast", validnsps,
18172 : : false, operation == AT_ResetRelOptions);
18173 : :
18174 : 222 : (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
18175 : :
18176 : 222 : memset(repl_val, 0, sizeof(repl_val));
18177 : 222 : memset(repl_null, false, sizeof(repl_null));
18178 : 222 : memset(repl_repl, false, sizeof(repl_repl));
18179 : :
18180 [ + + ]: 222 : if (newOptions != (Datum) 0)
18181 : 28 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
18182 : : else
18183 : 194 : repl_null[Anum_pg_class_reloptions - 1] = true;
18184 : :
18185 : 222 : repl_repl[Anum_pg_class_reloptions - 1] = true;
18186 : :
18187 : 222 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
18188 : : repl_val, repl_null, repl_repl);
18189 : :
18190 : 222 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
18191 : :
18192 [ - + ]: 222 : InvokeObjectPostAlterHookArg(RelationRelationId,
18193 : : RelationGetRelid(toastrel), 0,
18194 : : InvalidOid, true);
18195 : :
18196 : 222 : heap_freetuple(newtuple);
18197 : :
18198 : 222 : ReleaseSysCache(tuple);
18199 : :
18200 : 222 : table_close(toastrel, NoLock);
18201 : : }
18202 : :
18203 : 673 : table_close(pgclass, RowExclusiveLock);
18204 : : }
18205 : :
18206 : : /*
18207 : : * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
18208 : : * rewriting to be done, so we just want to copy the data as fast as possible.
18209 : : */
18210 : : static void
18211 : 117 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
18212 : : {
18213 : : Relation rel;
18214 : : Oid reltoastrelid;
18215 : : RelFileNumber newrelfilenumber;
18216 : : RelFileLocator newrlocator;
18217 : 117 : List *reltoastidxids = NIL;
18218 : : ListCell *lc;
18219 : :
18220 : : /*
18221 : : * Need lock here in case we are recursing to toast table or index
18222 : : */
18223 : 117 : rel = relation_open(tableOid, lockmode);
18224 : :
18225 : : /* Check first if relation can be moved to new tablespace */
18226 [ + + ]: 117 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
18227 : : {
18228 [ - + ]: 5 : InvokeObjectPostAlterHook(RelationRelationId,
18229 : : RelationGetRelid(rel), 0);
18230 : 5 : relation_close(rel, NoLock);
18231 : 5 : return;
18232 : : }
18233 : :
18234 : 112 : reltoastrelid = rel->rd_rel->reltoastrelid;
18235 : : /* Fetch the list of indexes on toast relation if necessary */
18236 [ + + ]: 112 : if (OidIsValid(reltoastrelid))
18237 : : {
18238 : 17 : Relation toastRel = relation_open(reltoastrelid, lockmode);
18239 : :
18240 : 17 : reltoastidxids = RelationGetIndexList(toastRel);
18241 : 17 : relation_close(toastRel, lockmode);
18242 : : }
18243 : :
18244 : : /*
18245 : : * Relfilenumbers are not unique in databases across tablespaces, so we
18246 : : * need to allocate a new one in the new tablespace.
18247 : : */
18248 : 112 : newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
18249 : 112 : rel->rd_rel->relpersistence);
18250 : :
18251 : : /* Open old and new relation */
18252 : 112 : newrlocator = rel->rd_locator;
18253 : 112 : newrlocator.relNumber = newrelfilenumber;
18254 : 112 : newrlocator.spcOid = newTableSpace;
18255 : :
18256 : : /* hand off to AM to actually create new rel storage and copy the data */
18257 [ + + ]: 112 : if (rel->rd_rel->relkind == RELKIND_INDEX)
18258 : : {
18259 : 40 : index_copy_data(rel, newrlocator);
18260 : : }
18261 : : else
18262 : : {
18263 : : Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
18264 : 72 : table_relation_copy_data(rel, &newrlocator);
18265 : : }
18266 : :
18267 : : /*
18268 : : * Update the pg_class row.
18269 : : *
18270 : : * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
18271 : : * executed on pg_class or its indexes (the above copy wouldn't contain
18272 : : * the updated pg_class entry), but that's forbidden with
18273 : : * CheckRelationTableSpaceMove().
18274 : : */
18275 : 112 : SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
18276 : :
18277 [ - + ]: 112 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
18278 : :
18279 : 112 : RelationAssumeNewRelfilelocator(rel);
18280 : :
18281 : 112 : relation_close(rel, NoLock);
18282 : :
18283 : : /* Make sure the reltablespace change is visible */
18284 : 112 : CommandCounterIncrement();
18285 : :
18286 : : /* Move associated toast relation and/or indexes, too */
18287 [ + + ]: 112 : if (OidIsValid(reltoastrelid))
18288 : 17 : ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
18289 [ + + + + : 129 : foreach(lc, reltoastidxids)
+ + ]
18290 : 17 : ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
18291 : :
18292 : : /* Clean up */
18293 : 112 : list_free(reltoastidxids);
18294 : : }
18295 : :
18296 : : /*
18297 : : * Special handling of ALTER TABLE SET TABLESPACE for relations with no
18298 : : * storage that have an interest in preserving tablespace.
18299 : : *
18300 : : * Since these have no storage the tablespace can be updated with a simple
18301 : : * metadata only operation to update the tablespace.
18302 : : */
18303 : : static void
18304 : 24 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
18305 : : {
18306 : : /*
18307 : : * Shouldn't be called on relations having storage; these are processed in
18308 : : * phase 3.
18309 : : */
18310 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
18311 : :
18312 : : /* check if relation can be moved to its new tablespace */
18313 [ - + ]: 24 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
18314 : : {
18315 [ # # ]: 0 : InvokeObjectPostAlterHook(RelationRelationId,
18316 : : RelationGetRelid(rel),
18317 : : 0);
18318 : 0 : return;
18319 : : }
18320 : :
18321 : : /* Update can be done, so change reltablespace */
18322 : 20 : SetRelationTableSpace(rel, newTableSpace, InvalidOid);
18323 : :
18324 [ - + ]: 20 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
18325 : :
18326 : : /* Make sure the reltablespace change is visible */
18327 : 20 : CommandCounterIncrement();
18328 : : }
18329 : :
18330 : : /*
18331 : : * Alter Table ALL ... SET TABLESPACE
18332 : : *
18333 : : * Allows a user to move all objects of some type in a given tablespace in the
18334 : : * current database to another tablespace. Objects can be chosen based on the
18335 : : * owner of the object also, to allow users to move only their objects.
18336 : : * The user must have CREATE rights on the new tablespace, as usual. The main
18337 : : * permissions handling is done by the lower-level table move function.
18338 : : *
18339 : : * All to-be-moved objects are locked first. If NOWAIT is specified and the
18340 : : * lock can't be acquired then we ereport(ERROR).
18341 : : */
18342 : : Oid
18343 : 16 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
18344 : : {
18345 : 16 : List *relations = NIL;
18346 : : ListCell *l;
18347 : : ScanKeyData key[1];
18348 : : Relation rel;
18349 : : TableScanDesc scan;
18350 : : HeapTuple tuple;
18351 : : Oid orig_tablespaceoid;
18352 : : Oid new_tablespaceoid;
18353 : 16 : List *role_oids = roleSpecsToIds(stmt->roles);
18354 : :
18355 : : /* Ensure we were not asked to move something we can't */
18356 [ + + + + ]: 16 : if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
18357 [ - + ]: 6 : stmt->objtype != OBJECT_MATVIEW)
18358 [ # # ]: 0 : ereport(ERROR,
18359 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
18360 : : errmsg("only tables, indexes, and materialized views exist in tablespaces")));
18361 : :
18362 : : /* Get the orig and new tablespace OIDs */
18363 : 16 : orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
18364 : 16 : new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
18365 : :
18366 : : /* Can't move shared relations in to or out of pg_global */
18367 : : /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
18368 [ + - - + ]: 16 : if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
18369 : : new_tablespaceoid == GLOBALTABLESPACE_OID)
18370 [ # # ]: 0 : ereport(ERROR,
18371 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
18372 : : errmsg("cannot move relations in to or out of pg_global tablespace")));
18373 : :
18374 : : /*
18375 : : * Must have CREATE rights on the new tablespace, unless it is the
18376 : : * database default tablespace (which all users implicitly have CREATE
18377 : : * rights on).
18378 : : */
18379 [ + - + + ]: 16 : if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
18380 : : {
18381 : : AclResult aclresult;
18382 : :
18383 : 1 : aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
18384 : : ACL_CREATE);
18385 [ - + ]: 1 : if (aclresult != ACLCHECK_OK)
18386 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
18387 : 0 : get_tablespace_name(new_tablespaceoid));
18388 : : }
18389 : :
18390 : : /*
18391 : : * Now that the checks are done, check if we should set either to
18392 : : * InvalidOid because it is our database's default tablespace.
18393 : : */
18394 [ + + ]: 16 : if (orig_tablespaceoid == MyDatabaseTableSpace)
18395 : 1 : orig_tablespaceoid = InvalidOid;
18396 : :
18397 [ + + ]: 16 : if (new_tablespaceoid == MyDatabaseTableSpace)
18398 : 15 : new_tablespaceoid = InvalidOid;
18399 : :
18400 : : /* no-op */
18401 [ - + ]: 16 : if (orig_tablespaceoid == new_tablespaceoid)
18402 : 0 : return new_tablespaceoid;
18403 : :
18404 : : /*
18405 : : * Walk the list of objects in the tablespace and move them. This will
18406 : : * only find objects in our database, of course.
18407 : : */
18408 : 16 : ScanKeyInit(&key[0],
18409 : : Anum_pg_class_reltablespace,
18410 : : BTEqualStrategyNumber, F_OIDEQ,
18411 : : ObjectIdGetDatum(orig_tablespaceoid));
18412 : :
18413 : 16 : rel = table_open(RelationRelationId, AccessShareLock);
18414 : 16 : scan = table_beginscan_catalog(rel, 1, key);
18415 [ + + ]: 449 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
18416 : : {
18417 : 433 : Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
18418 : 433 : Oid relOid = relForm->oid;
18419 : :
18420 : : /*
18421 : : * Do not move objects in pg_catalog as part of this, if an admin
18422 : : * really wishes to do so, they can issue the individual ALTER
18423 : : * commands directly.
18424 : : *
18425 : : * Also, explicitly avoid any shared tables, temp tables, TOAST (TOAST
18426 : : * will be moved with the main table).
18427 : : *
18428 : : * Conflict log tables are system-managed for logical replication and
18429 : : * cannot be altered directly, so skip them as well; otherwise a
18430 : : * single such table in the source tablespace would abort the whole
18431 : : * bulk move.
18432 : : */
18433 [ + + ]: 433 : if (IsCatalogNamespace(relForm->relnamespace) ||
18434 [ + - + - ]: 376 : relForm->relisshared ||
18435 [ + + ]: 376 : isAnyTempNamespace(relForm->relnamespace) ||
18436 [ + + ]: 310 : IsToastNamespace(relForm->relnamespace) ||
18437 : 122 : IsConflictLogTableNamespace(relForm->relnamespace))
18438 : 312 : continue;
18439 : :
18440 : : /* Only move the object type requested */
18441 [ + + ]: 121 : if ((stmt->objtype == OBJECT_TABLE &&
18442 [ + + ]: 100 : relForm->relkind != RELKIND_RELATION &&
18443 [ - + ]: 83 : relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
18444 [ + + ]: 38 : (stmt->objtype == OBJECT_INDEX &&
18445 [ + + ]: 18 : relForm->relkind != RELKIND_INDEX &&
18446 [ - + ]: 3 : relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
18447 [ + + ]: 35 : (stmt->objtype == OBJECT_MATVIEW &&
18448 [ - + ]: 3 : relForm->relkind != RELKIND_MATVIEW))
18449 : 86 : continue;
18450 : :
18451 : : /* Check if we are only moving objects owned by certain roles */
18452 [ - + - - ]: 35 : if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
18453 : 0 : continue;
18454 : :
18455 : : /*
18456 : : * Handle permissions-checking here since we are locking the tables
18457 : : * and also to avoid doing a bunch of work only to fail part-way. Note
18458 : : * that permissions will also be checked by AlterTableInternal().
18459 : : *
18460 : : * Caller must be considered an owner on the table to move it.
18461 : : */
18462 [ - + ]: 35 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
18463 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
18464 : 0 : NameStr(relForm->relname));
18465 : :
18466 [ - + ]: 35 : if (stmt->nowait &&
18467 [ # # ]: 0 : !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
18468 [ # # ]: 0 : ereport(ERROR,
18469 : : (errcode(ERRCODE_OBJECT_IN_USE),
18470 : : errmsg("aborting because lock on relation \"%s.%s\" is not available",
18471 : : get_namespace_name(relForm->relnamespace),
18472 : : NameStr(relForm->relname))));
18473 : : else
18474 : 35 : LockRelationOid(relOid, AccessExclusiveLock);
18475 : :
18476 : : /* Add to our list of objects to move */
18477 : 35 : relations = lappend_oid(relations, relOid);
18478 : : }
18479 : :
18480 : 16 : table_endscan(scan);
18481 : 16 : table_close(rel, AccessShareLock);
18482 : :
18483 [ + + ]: 16 : if (relations == NIL)
18484 [ + - + - ]: 6 : ereport(NOTICE,
18485 : : (errcode(ERRCODE_NO_DATA_FOUND),
18486 : : errmsg("no matching relations in tablespace \"%s\" found",
18487 : : orig_tablespaceoid == InvalidOid ? "(database default)" :
18488 : : get_tablespace_name(orig_tablespaceoid))));
18489 : :
18490 : : /* Everything is locked, loop through and move all of the relations. */
18491 [ + + + + : 51 : foreach(l, relations)
+ + ]
18492 : : {
18493 : 35 : List *cmds = NIL;
18494 : 35 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
18495 : :
18496 : 35 : cmd->subtype = AT_SetTableSpace;
18497 : 35 : cmd->name = stmt->new_tablespacename;
18498 : :
18499 : 35 : cmds = lappend(cmds, cmd);
18500 : :
18501 : 35 : EventTriggerAlterTableStart((Node *) stmt);
18502 : : /* OID is set by AlterTableInternal */
18503 : 35 : AlterTableInternal(lfirst_oid(l), cmds, false);
18504 : 35 : EventTriggerAlterTableEnd();
18505 : : }
18506 : :
18507 : 16 : return new_tablespaceoid;
18508 : : }
18509 : :
18510 : : static void
18511 : 40 : index_copy_data(Relation rel, RelFileLocator newrlocator)
18512 : : {
18513 : : SMgrRelation dstrel;
18514 : :
18515 : : /*
18516 : : * Since we copy the file directly without looking at the shared buffers,
18517 : : * we'd better first flush out any pages of the source relation that are
18518 : : * in shared buffers. We assume no new changes will be made while we are
18519 : : * holding exclusive lock on the rel.
18520 : : */
18521 : 40 : FlushRelationBuffers(rel);
18522 : :
18523 : : /*
18524 : : * Create and copy all forks of the relation, and schedule unlinking of
18525 : : * old physical files.
18526 : : *
18527 : : * NOTE: any conflict in relfilenumber value will be caught in
18528 : : * RelationCreateStorage().
18529 : : */
18530 : 40 : dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
18531 : :
18532 : : /*
18533 : : * Assume standard main-fork pages only for B-tree. Other index AMs may
18534 : : * use standard pages today but still have nonstandard pages from older
18535 : : * versions (e.g. GIN).
18536 : : */
18537 : 40 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
18538 : 40 : rel->rd_rel->relpersistence,
18539 : 40 : rel->rd_rel->relam == BTREE_AM_OID);
18540 : :
18541 : : /* copy those extra forks that exist */
18542 : 40 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
18543 [ + + ]: 160 : forkNum <= MAX_FORKNUM; forkNum++)
18544 : : {
18545 [ - + ]: 120 : if (smgrexists(RelationGetSmgr(rel), forkNum))
18546 : : {
18547 : 0 : smgrcreate(dstrel, forkNum, false);
18548 : :
18549 : : /*
18550 : : * WAL log creation if the relation is persistent, or this is the
18551 : : * init fork of an unlogged relation.
18552 : : */
18553 [ # # ]: 0 : if (RelationIsPermanent(rel) ||
18554 [ # # # # ]: 0 : (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
18555 : : forkNum == INIT_FORKNUM))
18556 : 0 : log_smgrcreate(&newrlocator, forkNum);
18557 : 0 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
18558 : 0 : rel->rd_rel->relpersistence, false);
18559 : : }
18560 : : }
18561 : :
18562 : : /* drop old relation, and close new one */
18563 : 40 : RelationDropStorage(rel);
18564 : 40 : smgrclose(dstrel);
18565 : 40 : }
18566 : :
18567 : : /*
18568 : : * ALTER TABLE ENABLE/DISABLE TRIGGER
18569 : : *
18570 : : * We just pass this off to trigger.c.
18571 : : */
18572 : : static void
18573 : 191 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
18574 : : char fires_when, bool skip_system, bool recurse,
18575 : : LOCKMODE lockmode)
18576 : : {
18577 : 191 : EnableDisableTrigger(rel, trigname, InvalidOid,
18578 : : fires_when, skip_system, recurse,
18579 : : lockmode);
18580 : :
18581 [ + + ]: 191 : InvokeObjectPostAlterHook(RelationRelationId,
18582 : : RelationGetRelid(rel), 0);
18583 : 191 : }
18584 : :
18585 : : /*
18586 : : * ALTER TABLE ENABLE/DISABLE RULE
18587 : : *
18588 : : * We just pass this off to rewriteDefine.c.
18589 : : */
18590 : : static void
18591 : 29 : ATExecEnableDisableRule(Relation rel, const char *rulename,
18592 : : char fires_when, LOCKMODE lockmode)
18593 : : {
18594 : 29 : EnableDisableRule(rel, rulename, fires_when);
18595 : :
18596 [ + + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
18597 : : RelationGetRelid(rel), 0);
18598 : 29 : }
18599 : :
18600 : : /*
18601 : : * Preparation phase of [NO] INHERIT
18602 : : *
18603 : : * Check the relation defined as a child.
18604 : : */
18605 : : static void
18606 : 371 : ATPrepChangeInherit(Relation child_rel)
18607 : : {
18608 [ + + ]: 371 : if (child_rel->rd_rel->reloftype)
18609 [ + - ]: 8 : ereport(ERROR,
18610 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18611 : : errmsg("cannot change inheritance of typed table")));
18612 : :
18613 [ + + ]: 363 : if (child_rel->rd_rel->relispartition)
18614 [ + - ]: 12 : ereport(ERROR,
18615 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18616 : : errmsg("cannot change inheritance of a partition")));
18617 : 351 : }
18618 : :
18619 : : /*
18620 : : * ALTER TABLE INHERIT
18621 : : *
18622 : : * Return the address of the new parent relation.
18623 : : */
18624 : : static ObjectAddress
18625 : 290 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
18626 : : {
18627 : : Relation parent_rel;
18628 : : List *children;
18629 : : ObjectAddress address;
18630 : : const char *trigger_name;
18631 : :
18632 : : /*
18633 : : * A self-exclusive lock is needed here. See the similar case in
18634 : : * MergeAttributes() for a full explanation.
18635 : : */
18636 : 290 : parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
18637 : :
18638 : : /*
18639 : : * Must be owner of both parent and child -- child was checked by
18640 : : * ATSimplePermissions call in ATPrepCmd
18641 : : */
18642 : 290 : ATSimplePermissions(AT_AddInherit, parent_rel,
18643 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
18644 : :
18645 : : /* Permanent rels cannot inherit from temporary ones */
18646 [ + + ]: 290 : if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
18647 [ - + ]: 4 : child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
18648 [ # # ]: 0 : ereport(ERROR,
18649 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18650 : : errmsg("cannot inherit from temporary relation \"%s\"",
18651 : : RelationGetRelationName(parent_rel))));
18652 : :
18653 : : /* If parent rel is temp, it must belong to this session */
18654 [ + + - + ]: 290 : if (RELATION_IS_OTHER_TEMP(parent_rel))
18655 [ # # ]: 0 : ereport(ERROR,
18656 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18657 : : errmsg("cannot inherit from temporary relation of another session")));
18658 : :
18659 : : /* Ditto for the child */
18660 [ + + - + ]: 290 : if (RELATION_IS_OTHER_TEMP(child_rel))
18661 [ # # ]: 0 : ereport(ERROR,
18662 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18663 : : errmsg("cannot inherit to temporary relation of another session")));
18664 : :
18665 : : /* Prevent partitioned tables from becoming inheritance parents */
18666 [ + + ]: 290 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18667 [ + - ]: 4 : ereport(ERROR,
18668 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18669 : : errmsg("cannot inherit from partitioned table \"%s\"",
18670 : : parent->relname)));
18671 : :
18672 : : /* Likewise for partitions */
18673 [ + + ]: 286 : if (parent_rel->rd_rel->relispartition)
18674 [ + - ]: 4 : ereport(ERROR,
18675 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18676 : : errmsg("cannot inherit from a partition")));
18677 : :
18678 : : /*
18679 : : * Prevent circularity by seeing if proposed parent inherits from child.
18680 : : * (In particular, this disallows making a rel inherit from itself.)
18681 : : *
18682 : : * This is not completely bulletproof because of race conditions: in
18683 : : * multi-level inheritance trees, someone else could concurrently be
18684 : : * making another inheritance link that closes the loop but does not join
18685 : : * either of the rels we have locked. Preventing that seems to require
18686 : : * exclusive locks on the entire inheritance tree, which is a cure worse
18687 : : * than the disease. find_all_inheritors() will cope with circularity
18688 : : * anyway, so don't sweat it too much.
18689 : : *
18690 : : * We use weakest lock we can on child's children, namely AccessShareLock.
18691 : : */
18692 : 282 : children = find_all_inheritors(RelationGetRelid(child_rel),
18693 : : AccessShareLock, NULL);
18694 : :
18695 [ + + ]: 282 : if (list_member_oid(children, RelationGetRelid(parent_rel)))
18696 [ + - ]: 8 : ereport(ERROR,
18697 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18698 : : errmsg("circular inheritance not allowed"),
18699 : : errdetail("\"%s\" is already a child of \"%s\".",
18700 : : parent->relname,
18701 : : RelationGetRelationName(child_rel))));
18702 : :
18703 : : /*
18704 : : * If child_rel has row-level triggers with transition tables, we
18705 : : * currently don't allow it to become an inheritance child. See also
18706 : : * prohibitions in ATExecAttachPartition() and CreateTrigger().
18707 : : */
18708 : 274 : trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
18709 [ + + ]: 274 : if (trigger_name != NULL)
18710 [ + - ]: 4 : ereport(ERROR,
18711 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18712 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
18713 : : trigger_name, RelationGetRelationName(child_rel)),
18714 : : errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
18715 : :
18716 : : /* OK to create inheritance */
18717 : 270 : CreateInheritance(child_rel, parent_rel, false);
18718 : :
18719 : 210 : ObjectAddressSet(address, RelationRelationId,
18720 : : RelationGetRelid(parent_rel));
18721 : :
18722 : : /* keep our lock on the parent relation until commit */
18723 : 210 : table_close(parent_rel, NoLock);
18724 : :
18725 : 210 : return address;
18726 : : }
18727 : :
18728 : : /*
18729 : : * CreateInheritance
18730 : : * Catalog manipulation portion of creating inheritance between a child
18731 : : * table and a parent table.
18732 : : *
18733 : : * This verifies that all the columns and check constraints of the parent
18734 : : * appear in the child and that they have the same data types and expressions.
18735 : : *
18736 : : * Common to ATExecAddInherit() and ATExecAttachPartition().
18737 : : */
18738 : : static void
18739 : 1728 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
18740 : : {
18741 : : Relation catalogRelation;
18742 : : SysScanDesc scan;
18743 : : ScanKeyData key;
18744 : : HeapTuple inheritsTuple;
18745 : : int32 inhseqno;
18746 : :
18747 : : /* Note: get RowExclusiveLock because we will write pg_inherits below. */
18748 : 1728 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18749 : :
18750 : : /*
18751 : : * Check for duplicates in the list of parents, and determine the highest
18752 : : * inhseqno already present; we'll use the next one for the new parent.
18753 : : * Also, if proposed child is a partition, it cannot already be
18754 : : * inheriting.
18755 : : *
18756 : : * Note: we do not reject the case where the child already inherits from
18757 : : * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
18758 : : */
18759 : 1728 : ScanKeyInit(&key,
18760 : : Anum_pg_inherits_inhrelid,
18761 : : BTEqualStrategyNumber, F_OIDEQ,
18762 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18763 : 1728 : scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
18764 : : true, NULL, 1, &key);
18765 : :
18766 : : /* inhseqno sequences start at 1 */
18767 : 1728 : inhseqno = 0;
18768 [ + + ]: 1779 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18769 : : {
18770 : 55 : Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18771 : :
18772 [ + + ]: 55 : if (inh->inhparent == RelationGetRelid(parent_rel))
18773 [ + - ]: 4 : ereport(ERROR,
18774 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18775 : : errmsg("relation \"%s\" would be inherited from more than once",
18776 : : RelationGetRelationName(parent_rel))));
18777 : :
18778 [ + - ]: 51 : if (inh->inhseqno > inhseqno)
18779 : 51 : inhseqno = inh->inhseqno;
18780 : : }
18781 : 1724 : systable_endscan(scan);
18782 : :
18783 : : /* Match up the columns and bump attinhcount as needed */
18784 : 1724 : MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
18785 : :
18786 : : /* Match up the constraints and bump coninhcount as needed */
18787 : 1636 : MergeConstraintsIntoExisting(child_rel, parent_rel);
18788 : :
18789 : : /*
18790 : : * OK, it looks valid. Make the catalog entries that show inheritance.
18791 : : */
18792 : 1596 : StoreCatalogInheritance1(RelationGetRelid(child_rel),
18793 : : RelationGetRelid(parent_rel),
18794 : : inhseqno + 1,
18795 : : catalogRelation,
18796 : 1596 : parent_rel->rd_rel->relkind ==
18797 : : RELKIND_PARTITIONED_TABLE);
18798 : :
18799 : : /* Now we're done with pg_inherits */
18800 : 1596 : table_close(catalogRelation, RowExclusiveLock);
18801 : 1596 : }
18802 : :
18803 : : /*
18804 : : * Obtain the source-text form of the constraint expression for a check
18805 : : * constraint, given its pg_constraint tuple
18806 : : */
18807 : : static char *
18808 : 480 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
18809 : : {
18810 : : Form_pg_constraint con;
18811 : : bool isnull;
18812 : : Datum attr;
18813 : : Datum expr;
18814 : :
18815 : 480 : con = (Form_pg_constraint) GETSTRUCT(contup);
18816 : 480 : attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
18817 [ - + ]: 480 : if (isnull)
18818 [ # # ]: 0 : elog(ERROR, "null conbin for constraint %u", con->oid);
18819 : :
18820 : 480 : expr = DirectFunctionCall2(pg_get_expr, attr,
18821 : : ObjectIdGetDatum(con->conrelid));
18822 : 480 : return TextDatumGetCString(expr);
18823 : : }
18824 : :
18825 : : /*
18826 : : * Determine whether two check constraints are functionally equivalent
18827 : : *
18828 : : * The test we apply is to see whether they reverse-compile to the same
18829 : : * source string. This insulates us from issues like whether attributes
18830 : : * have the same physical column numbers in parent and child relations.
18831 : : *
18832 : : * Note that we ignore enforceability as there are cases where constraints
18833 : : * with differing enforceability are allowed.
18834 : : */
18835 : : static bool
18836 : 240 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
18837 : : {
18838 : 240 : Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
18839 : 240 : Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
18840 : :
18841 [ + - ]: 240 : if (acon->condeferrable != bcon->condeferrable ||
18842 [ + - ]: 240 : acon->condeferred != bcon->condeferred ||
18843 [ + + ]: 240 : strcmp(decompile_conbin(a, tupleDesc),
18844 : 240 : decompile_conbin(b, tupleDesc)) != 0)
18845 : 4 : return false;
18846 : : else
18847 : 236 : return true;
18848 : : }
18849 : :
18850 : : /*
18851 : : * Check columns in child table match up with columns in parent, and increment
18852 : : * their attinhcount.
18853 : : *
18854 : : * Called by CreateInheritance
18855 : : *
18856 : : * Currently all parent columns must be found in child. Missing columns are an
18857 : : * error. One day we might consider creating new columns like CREATE TABLE
18858 : : * does. However, that is widely unpopular --- in the common use case of
18859 : : * partitioned tables it's a foot-gun.
18860 : : *
18861 : : * The data type must match exactly. If the parent column is NOT NULL then
18862 : : * the child must be as well. Defaults are not compared, however.
18863 : : */
18864 : : static void
18865 : 1724 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
18866 : : {
18867 : : Relation attrrel;
18868 : : TupleDesc parent_desc;
18869 : :
18870 : 1724 : attrrel = table_open(AttributeRelationId, RowExclusiveLock);
18871 : 1724 : parent_desc = RelationGetDescr(parent_rel);
18872 : :
18873 [ + + ]: 5450 : for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
18874 : : {
18875 : 3814 : Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
18876 : 3814 : char *parent_attname = NameStr(parent_att->attname);
18877 : : HeapTuple tuple;
18878 : :
18879 : : /* Ignore dropped columns in the parent. */
18880 [ + + ]: 3814 : if (parent_att->attisdropped)
18881 : 180 : continue;
18882 : :
18883 : : /* Find same column in child (matching on column name). */
18884 : 3634 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
18885 [ + + ]: 3634 : if (HeapTupleIsValid(tuple))
18886 : : {
18887 : 3626 : Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
18888 : :
18889 [ + + ]: 3626 : if (parent_att->atttypid != child_att->atttypid ||
18890 [ + + ]: 3622 : parent_att->atttypmod != child_att->atttypmod)
18891 [ + - ]: 8 : ereport(ERROR,
18892 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18893 : : errmsg("child table \"%s\" has different type for column \"%s\"",
18894 : : RelationGetRelationName(child_rel), parent_attname)));
18895 : :
18896 [ + + ]: 3618 : if (parent_att->attcollation != child_att->attcollation)
18897 [ + - ]: 4 : ereport(ERROR,
18898 : : (errcode(ERRCODE_COLLATION_MISMATCH),
18899 : : errmsg("child table \"%s\" has different collation for column \"%s\"",
18900 : : RelationGetRelationName(child_rel), parent_attname)));
18901 : :
18902 : : /*
18903 : : * If the parent has a not-null constraint that's not NO INHERIT,
18904 : : * make sure the child has one too.
18905 : : *
18906 : : * Other constraints are checked elsewhere.
18907 : : */
18908 [ + + + + ]: 3614 : if (parent_att->attnotnull && !child_att->attnotnull)
18909 : : {
18910 : : HeapTuple contup;
18911 : :
18912 : 32 : contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
18913 : 32 : parent_att->attnum);
18914 [ + - ]: 32 : if (HeapTupleIsValid(contup) &&
18915 [ + + ]: 32 : !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
18916 [ + - ]: 20 : ereport(ERROR,
18917 : : errcode(ERRCODE_DATATYPE_MISMATCH),
18918 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18919 : : parent_attname, RelationGetRelationName(child_rel)));
18920 : : }
18921 : :
18922 : : /*
18923 : : * Child column must be generated if and only if parent column is.
18924 : : */
18925 [ + + + + ]: 3594 : if (parent_att->attgenerated && !child_att->attgenerated)
18926 [ + - ]: 24 : ereport(ERROR,
18927 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18928 : : errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
18929 [ + + + + ]: 3570 : if (child_att->attgenerated && !parent_att->attgenerated)
18930 [ + - ]: 16 : ereport(ERROR,
18931 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18932 : : errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
18933 : :
18934 [ + + + - : 3554 : if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
+ + ]
18935 [ + - + + : 8 : ereport(ERROR,
+ + ]
18936 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18937 : : errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
18938 : : errdetail("Parent column is %s, child column is %s.",
18939 : : parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
18940 : : child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
18941 : :
18942 : : /*
18943 : : * Regular inheritance children are independent enough not to
18944 : : * inherit identity columns. But partitions are integral part of
18945 : : * a partitioned table and inherit identity column.
18946 : : */
18947 [ + + ]: 3546 : if (ispartition)
18948 : 3091 : child_att->attidentity = parent_att->attidentity;
18949 : :
18950 : : /*
18951 : : * OK, bump the child column's inheritance count. (If we fail
18952 : : * later on, this change will just roll back.)
18953 : : */
18954 [ - + ]: 3546 : if (pg_add_s16_overflow(child_att->attinhcount, 1,
18955 : : &child_att->attinhcount))
18956 [ # # ]: 0 : ereport(ERROR,
18957 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18958 : : errmsg("too many inheritance parents"));
18959 : :
18960 : : /*
18961 : : * In case of partitions, we must enforce that value of attislocal
18962 : : * is same in all partitions. (Note: there are only inherited
18963 : : * attributes in partitions)
18964 : : */
18965 [ + + ]: 3546 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18966 : : {
18967 : : Assert(child_att->attinhcount == 1);
18968 : 3091 : child_att->attislocal = false;
18969 : : }
18970 : :
18971 : 3546 : CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
18972 : 3546 : heap_freetuple(tuple);
18973 : : }
18974 : : else
18975 : : {
18976 [ + - ]: 8 : ereport(ERROR,
18977 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18978 : : errmsg("child table is missing column \"%s\"", parent_attname)));
18979 : : }
18980 : : }
18981 : :
18982 : 1636 : table_close(attrrel, RowExclusiveLock);
18983 : 1636 : }
18984 : :
18985 : : /*
18986 : : * Check constraints in child table match up with constraints in parent,
18987 : : * and increment their coninhcount.
18988 : : *
18989 : : * Constraints that are marked ONLY in the parent are ignored.
18990 : : *
18991 : : * Called by CreateInheritance
18992 : : *
18993 : : * Currently all constraints in parent must be present in the child. One day we
18994 : : * may consider adding new constraints like CREATE TABLE does.
18995 : : *
18996 : : * XXX This is O(N^2) which may be an issue with tables with hundreds of
18997 : : * constraints. As long as tables have more like 10 constraints it shouldn't be
18998 : : * a problem though. Even 100 constraints ought not be the end of the world.
18999 : : *
19000 : : * XXX See MergeWithExistingConstraint too if you change this code.
19001 : : */
19002 : : static void
19003 : 1636 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
19004 : : {
19005 : : Relation constraintrel;
19006 : : SysScanDesc parent_scan;
19007 : : ScanKeyData parent_key;
19008 : : HeapTuple parent_tuple;
19009 : 1636 : Oid parent_relid = RelationGetRelid(parent_rel);
19010 : : AttrMap *attmap;
19011 : :
19012 : 1636 : constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
19013 : :
19014 : : /* Outer loop scans through the parent's constraint definitions */
19015 : 1636 : ScanKeyInit(&parent_key,
19016 : : Anum_pg_constraint_conrelid,
19017 : : BTEqualStrategyNumber, F_OIDEQ,
19018 : : ObjectIdGetDatum(parent_relid));
19019 : 1636 : parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
19020 : : true, NULL, 1, &parent_key);
19021 : :
19022 : 1636 : attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
19023 : : RelationGetDescr(child_rel),
19024 : : true);
19025 : :
19026 [ + + ]: 2927 : while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
19027 : : {
19028 : 1331 : Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
19029 : : SysScanDesc child_scan;
19030 : : ScanKeyData child_key;
19031 : : HeapTuple child_tuple;
19032 : : AttrNumber parent_attno;
19033 : 1331 : bool found = false;
19034 : :
19035 [ + + ]: 1331 : if (parent_con->contype != CONSTRAINT_CHECK &&
19036 [ + + ]: 1215 : parent_con->contype != CONSTRAINT_NOTNULL)
19037 : 654 : continue;
19038 : :
19039 : : /* if the parent's constraint is marked NO INHERIT, it's not inherited */
19040 [ + + ]: 709 : if (parent_con->connoinherit)
19041 : 32 : continue;
19042 : :
19043 [ + + ]: 677 : if (parent_con->contype == CONSTRAINT_NOTNULL)
19044 : 577 : parent_attno = extractNotNullColumn(parent_tuple);
19045 : : else
19046 : 100 : parent_attno = InvalidAttrNumber;
19047 : :
19048 : : /* Search for a child constraint matching this one */
19049 : 677 : ScanKeyInit(&child_key,
19050 : : Anum_pg_constraint_conrelid,
19051 : : BTEqualStrategyNumber, F_OIDEQ,
19052 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
19053 : 677 : child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
19054 : : true, NULL, 1, &child_key);
19055 : :
19056 [ + + ]: 1064 : while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
19057 : : {
19058 : 1048 : Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
19059 : : HeapTuple child_copy;
19060 : :
19061 [ + + ]: 1048 : if (child_con->contype != parent_con->contype)
19062 : 186 : continue;
19063 : :
19064 : : /*
19065 : : * CHECK constraint are matched by constraint name, NOT NULL ones
19066 : : * by attribute number.
19067 : : */
19068 [ + + ]: 862 : if (child_con->contype == CONSTRAINT_CHECK)
19069 : : {
19070 : 130 : if (strcmp(NameStr(parent_con->conname),
19071 [ + + ]: 107 : NameStr(child_con->conname)) != 0)
19072 : 23 : continue;
19073 : : }
19074 [ + - ]: 755 : else if (child_con->contype == CONSTRAINT_NOTNULL)
19075 : : {
19076 : : Form_pg_attribute parent_attr;
19077 : : Form_pg_attribute child_attr;
19078 : : AttrNumber child_attno;
19079 : :
19080 : 755 : parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
19081 : 755 : child_attno = extractNotNullColumn(child_tuple);
19082 [ + + ]: 755 : if (parent_attno != attmap->attnums[child_attno - 1])
19083 : 178 : continue;
19084 : :
19085 : 577 : child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
19086 : : /* there shouldn't be constraints on dropped columns */
19087 [ + - - + ]: 577 : if (parent_attr->attisdropped || child_attr->attisdropped)
19088 [ # # ]: 0 : elog(ERROR, "found not-null constraint on dropped columns");
19089 : : }
19090 : :
19091 [ + + ]: 661 : if (child_con->contype == CONSTRAINT_CHECK &&
19092 [ + + ]: 84 : !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
19093 [ + - ]: 4 : ereport(ERROR,
19094 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
19095 : : errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
19096 : : RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
19097 : :
19098 : : /*
19099 : : * If the child constraint is "no inherit" then cannot merge
19100 : : */
19101 [ + + ]: 657 : if (child_con->connoinherit)
19102 [ + - ]: 8 : ereport(ERROR,
19103 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19104 : : errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
19105 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
19106 : :
19107 : : /*
19108 : : * If the child constraint is "not valid" then cannot merge with a
19109 : : * valid parent constraint
19110 : : */
19111 [ + + + + ]: 649 : if (parent_con->convalidated && child_con->conenforced &&
19112 [ + + ]: 597 : !child_con->convalidated)
19113 [ + - ]: 8 : ereport(ERROR,
19114 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19115 : : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
19116 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
19117 : :
19118 : : /*
19119 : : * A NOT ENFORCED child constraint cannot be merged with an
19120 : : * ENFORCED parent constraint. However, the reverse is allowed,
19121 : : * where the child constraint is ENFORCED.
19122 : : */
19123 [ + + + + ]: 641 : if (parent_con->conenforced && !child_con->conenforced)
19124 [ + - ]: 4 : ereport(ERROR,
19125 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19126 : : errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
19127 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
19128 : :
19129 : : /*
19130 : : * OK, bump the child constraint's inheritance count. (If we fail
19131 : : * later on, this change will just roll back.)
19132 : : */
19133 : 637 : child_copy = heap_copytuple(child_tuple);
19134 : 637 : child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
19135 : :
19136 [ - + ]: 637 : if (pg_add_s16_overflow(child_con->coninhcount, 1,
19137 : : &child_con->coninhcount))
19138 [ # # ]: 0 : ereport(ERROR,
19139 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
19140 : : errmsg("too many inheritance parents"));
19141 : :
19142 : : /*
19143 : : * In case of partitions, an inherited constraint must be
19144 : : * inherited only once since it cannot have multiple parents and
19145 : : * it is never considered local.
19146 : : */
19147 [ + + ]: 637 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
19148 : : {
19149 : : Assert(child_con->coninhcount == 1);
19150 : 534 : child_con->conislocal = false;
19151 : : }
19152 : :
19153 : 637 : CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
19154 : 637 : heap_freetuple(child_copy);
19155 : :
19156 : 637 : found = true;
19157 : 637 : break;
19158 : : }
19159 : :
19160 : 653 : systable_endscan(child_scan);
19161 : :
19162 [ + + ]: 653 : if (!found)
19163 : : {
19164 [ - + ]: 16 : if (parent_con->contype == CONSTRAINT_NOTNULL)
19165 [ # # ]: 0 : ereport(ERROR,
19166 : : errcode(ERRCODE_DATATYPE_MISMATCH),
19167 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
19168 : : get_attname(parent_relid,
19169 : : extractNotNullColumn(parent_tuple),
19170 : : false),
19171 : : RelationGetRelationName(child_rel)));
19172 : :
19173 [ + - ]: 16 : ereport(ERROR,
19174 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
19175 : : errmsg("child table is missing constraint \"%s\"",
19176 : : NameStr(parent_con->conname))));
19177 : : }
19178 : : }
19179 : :
19180 : 1596 : systable_endscan(parent_scan);
19181 : 1596 : table_close(constraintrel, RowExclusiveLock);
19182 : 1596 : }
19183 : :
19184 : : /*
19185 : : * ALTER TABLE NO INHERIT
19186 : : *
19187 : : * Return value is the address of the relation that is no longer parent.
19188 : : */
19189 : : static ObjectAddress
19190 : 61 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
19191 : : {
19192 : : ObjectAddress address;
19193 : : Relation parent_rel;
19194 : :
19195 : : /*
19196 : : * AccessShareLock on the parent is probably enough, seeing that DROP
19197 : : * TABLE doesn't lock parent tables at all. We need some lock since we'll
19198 : : * be inspecting the parent's schema.
19199 : : */
19200 : 61 : parent_rel = table_openrv(parent, AccessShareLock);
19201 : :
19202 : : /*
19203 : : * We don't bother to check ownership of the parent table --- ownership of
19204 : : * the child is presumed enough rights.
19205 : : */
19206 : :
19207 : : /* Off to RemoveInheritance() where most of the work happens */
19208 : 61 : RemoveInheritance(rel, parent_rel, false);
19209 : :
19210 : 57 : ObjectAddressSet(address, RelationRelationId,
19211 : : RelationGetRelid(parent_rel));
19212 : :
19213 : : /* keep our lock on the parent relation until commit */
19214 : 57 : table_close(parent_rel, NoLock);
19215 : :
19216 : 57 : return address;
19217 : : }
19218 : :
19219 : : /*
19220 : : * MarkInheritDetached
19221 : : *
19222 : : * Set inhdetachpending for a partition, for ATExecDetachPartition
19223 : : * in concurrent mode. While at it, verify that no other partition is
19224 : : * already pending detach.
19225 : : */
19226 : : static void
19227 : 77 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
19228 : : {
19229 : : Relation catalogRelation;
19230 : : SysScanDesc scan;
19231 : : ScanKeyData key;
19232 : : HeapTuple inheritsTuple;
19233 : 77 : bool found = false;
19234 : :
19235 : : Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
19236 : :
19237 : : /*
19238 : : * Find pg_inherits entries by inhparent. (We need to scan them all in
19239 : : * order to verify that no other partition is pending detach.)
19240 : : */
19241 : 77 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
19242 : 77 : ScanKeyInit(&key,
19243 : : Anum_pg_inherits_inhparent,
19244 : : BTEqualStrategyNumber, F_OIDEQ,
19245 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
19246 : 77 : scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
19247 : : true, NULL, 1, &key);
19248 : :
19249 [ + + ]: 301 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
19250 : : {
19251 : : Form_pg_inherits inhForm;
19252 : :
19253 : 148 : inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
19254 [ + + ]: 148 : if (inhForm->inhdetachpending)
19255 [ + - ]: 1 : ereport(ERROR,
19256 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19257 : : errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
19258 : : get_rel_name(inhForm->inhrelid),
19259 : : get_namespace_name(parent_rel->rd_rel->relnamespace),
19260 : : RelationGetRelationName(parent_rel)),
19261 : : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
19262 : :
19263 [ + + ]: 147 : if (inhForm->inhrelid == RelationGetRelid(child_rel))
19264 : : {
19265 : : HeapTuple newtup;
19266 : :
19267 : 76 : newtup = heap_copytuple(inheritsTuple);
19268 : 76 : ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
19269 : :
19270 : 76 : CatalogTupleUpdate(catalogRelation,
19271 : 76 : &inheritsTuple->t_self,
19272 : : newtup);
19273 : 76 : found = true;
19274 : 76 : heap_freetuple(newtup);
19275 : : /* keep looking, to ensure we catch others pending detach */
19276 : : }
19277 : : }
19278 : :
19279 : : /* Done */
19280 : 76 : systable_endscan(scan);
19281 : 76 : table_close(catalogRelation, RowExclusiveLock);
19282 : :
19283 [ - + ]: 76 : if (!found)
19284 [ # # ]: 0 : ereport(ERROR,
19285 : : (errcode(ERRCODE_UNDEFINED_TABLE),
19286 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
19287 : : RelationGetRelationName(child_rel),
19288 : : RelationGetRelationName(parent_rel))));
19289 : 76 : }
19290 : :
19291 : : /*
19292 : : * RemoveInheritance
19293 : : *
19294 : : * Drop a parent from the child's parents. This just adjusts the attinhcount
19295 : : * and attislocal of the columns and removes the pg_inherit and pg_depend
19296 : : * entries. expect_detached is passed down to DeleteInheritsTuple, q.v..
19297 : : *
19298 : : * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
19299 : : * up attislocal stays true, which means if a child is ever removed from a
19300 : : * parent then its columns will never be automatically dropped which may
19301 : : * surprise. But at least we'll never surprise by dropping columns someone
19302 : : * isn't expecting to be dropped which would actually mean data loss.
19303 : : *
19304 : : * coninhcount and conislocal for inherited constraints are adjusted in
19305 : : * exactly the same way.
19306 : : *
19307 : : * Common to ATExecDropInherit() and ATExecDetachPartition().
19308 : : */
19309 : : static void
19310 : 385 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
19311 : : {
19312 : : Relation catalogRelation;
19313 : : SysScanDesc scan;
19314 : : ScanKeyData key[3];
19315 : : HeapTuple attributeTuple,
19316 : : constraintTuple;
19317 : : AttrMap *attmap;
19318 : : List *connames;
19319 : : List *nncolumns;
19320 : : bool found;
19321 : : bool is_partitioning;
19322 : :
19323 : 385 : is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
19324 : :
19325 : 385 : found = DeleteInheritsTuple(RelationGetRelid(child_rel),
19326 : : RelationGetRelid(parent_rel),
19327 : : expect_detached,
19328 : 385 : RelationGetRelationName(child_rel));
19329 [ + + ]: 385 : if (!found)
19330 : : {
19331 [ + + ]: 16 : if (is_partitioning)
19332 [ + - ]: 12 : ereport(ERROR,
19333 : : (errcode(ERRCODE_UNDEFINED_TABLE),
19334 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
19335 : : RelationGetRelationName(child_rel),
19336 : : RelationGetRelationName(parent_rel))));
19337 : : else
19338 [ + - ]: 4 : ereport(ERROR,
19339 : : (errcode(ERRCODE_UNDEFINED_TABLE),
19340 : : errmsg("relation \"%s\" is not a parent of relation \"%s\"",
19341 : : RelationGetRelationName(parent_rel),
19342 : : RelationGetRelationName(child_rel))));
19343 : : }
19344 : :
19345 : : /*
19346 : : * Search through child columns looking for ones matching parent rel
19347 : : */
19348 : 369 : catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
19349 : 369 : ScanKeyInit(&key[0],
19350 : : Anum_pg_attribute_attrelid,
19351 : : BTEqualStrategyNumber, F_OIDEQ,
19352 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
19353 : 369 : scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
19354 : : true, NULL, 1, key);
19355 [ + + ]: 3308 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
19356 : : {
19357 : 2939 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
19358 : :
19359 : : /* Ignore if dropped or not inherited */
19360 [ + + ]: 2939 : if (att->attisdropped)
19361 : 4 : continue;
19362 [ + + ]: 2935 : if (att->attinhcount <= 0)
19363 : 2234 : continue;
19364 : :
19365 [ + + ]: 701 : if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
19366 : 701 : NameStr(att->attname)))
19367 : : {
19368 : : /* Decrement inhcount and possibly set islocal to true */
19369 : 665 : HeapTuple copyTuple = heap_copytuple(attributeTuple);
19370 : 665 : Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
19371 : :
19372 : 665 : copy_att->attinhcount--;
19373 [ + + ]: 665 : if (copy_att->attinhcount == 0)
19374 : 645 : copy_att->attislocal = true;
19375 : :
19376 : 665 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
19377 : 665 : heap_freetuple(copyTuple);
19378 : : }
19379 : : }
19380 : 369 : systable_endscan(scan);
19381 : 369 : table_close(catalogRelation, RowExclusiveLock);
19382 : :
19383 : : /*
19384 : : * Likewise, find inherited check and not-null constraints and disinherit
19385 : : * them. To do this, we first need a list of the names of the parent's
19386 : : * check constraints. (We cheat a bit by only checking for name matches,
19387 : : * assuming that the expressions will match.)
19388 : : *
19389 : : * For NOT NULL columns, we store column numbers to match, mapping them in
19390 : : * to the child rel's attribute numbers.
19391 : : */
19392 : 369 : attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
19393 : : RelationGetDescr(parent_rel),
19394 : : false);
19395 : :
19396 : 369 : catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
19397 : 369 : ScanKeyInit(&key[0],
19398 : : Anum_pg_constraint_conrelid,
19399 : : BTEqualStrategyNumber, F_OIDEQ,
19400 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
19401 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
19402 : : true, NULL, 1, key);
19403 : :
19404 : 369 : connames = NIL;
19405 : 369 : nncolumns = NIL;
19406 : :
19407 [ + + ]: 794 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
19408 : : {
19409 : 425 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
19410 : :
19411 [ + + ]: 425 : if (con->connoinherit)
19412 : 68 : continue;
19413 : :
19414 [ + + ]: 357 : if (con->contype == CONSTRAINT_CHECK)
19415 : 8 : connames = lappend(connames, pstrdup(NameStr(con->conname)));
19416 [ + + ]: 357 : if (con->contype == CONSTRAINT_NOTNULL)
19417 : : {
19418 : 133 : AttrNumber parent_attno = extractNotNullColumn(constraintTuple);
19419 : :
19420 : 133 : nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
19421 : : }
19422 : : }
19423 : :
19424 : 369 : systable_endscan(scan);
19425 : :
19426 : : /* Now scan the child's constraints to find matches */
19427 : 369 : ScanKeyInit(&key[0],
19428 : : Anum_pg_constraint_conrelid,
19429 : : BTEqualStrategyNumber, F_OIDEQ,
19430 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
19431 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
19432 : : true, NULL, 1, key);
19433 : :
19434 [ + + ]: 790 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
19435 : : {
19436 : 421 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
19437 : 421 : bool match = false;
19438 : :
19439 : : /*
19440 : : * Match CHECK constraints by name, not-null constraints by column
19441 : : * number, and ignore all others.
19442 : : */
19443 [ + + ]: 421 : if (con->contype == CONSTRAINT_CHECK)
19444 : : {
19445 [ + + + + : 92 : foreach_ptr(char, chkname, connames)
+ + ]
19446 : : {
19447 [ + - ]: 12 : if (con->contype == CONSTRAINT_CHECK &&
19448 [ + + ]: 12 : strcmp(NameStr(con->conname), chkname) == 0)
19449 : : {
19450 : 8 : match = true;
19451 : 8 : connames = foreach_delete_current(connames, chkname);
19452 : 8 : break;
19453 : : }
19454 : : }
19455 : : }
19456 [ + + ]: 377 : else if (con->contype == CONSTRAINT_NOTNULL)
19457 : : {
19458 : 173 : AttrNumber child_attno = extractNotNullColumn(constraintTuple);
19459 : :
19460 [ + + + + : 350 : foreach_int(prevattno, nncolumns)
+ + ]
19461 : : {
19462 [ + + ]: 137 : if (prevattno == child_attno)
19463 : : {
19464 : 133 : match = true;
19465 : 133 : nncolumns = foreach_delete_current(nncolumns, prevattno);
19466 : 133 : break;
19467 : : }
19468 : : }
19469 : : }
19470 : : else
19471 : 204 : continue;
19472 : :
19473 [ + + ]: 217 : if (match)
19474 : : {
19475 : : /* Decrement inhcount and possibly set islocal to true */
19476 : 141 : HeapTuple copyTuple = heap_copytuple(constraintTuple);
19477 : 141 : Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
19478 : :
19479 [ - + ]: 141 : if (copy_con->coninhcount <= 0) /* shouldn't happen */
19480 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
19481 : : RelationGetRelid(child_rel), NameStr(copy_con->conname));
19482 : :
19483 : 141 : copy_con->coninhcount--;
19484 [ + + ]: 141 : if (copy_con->coninhcount == 0)
19485 : 129 : copy_con->conislocal = true;
19486 : :
19487 : 141 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
19488 : 141 : heap_freetuple(copyTuple);
19489 : : }
19490 : : }
19491 : :
19492 : : /* We should have matched all constraints */
19493 [ + - - + ]: 369 : if (connames != NIL || nncolumns != NIL)
19494 [ # # ]: 0 : elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
19495 : : list_length(connames) + list_length(nncolumns),
19496 : : RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
19497 : :
19498 : 369 : systable_endscan(scan);
19499 : 369 : table_close(catalogRelation, RowExclusiveLock);
19500 : :
19501 [ + + ]: 369 : drop_parent_dependency(RelationGetRelid(child_rel),
19502 : : RelationRelationId,
19503 : : RelationGetRelid(parent_rel),
19504 : : child_dependency_type(is_partitioning));
19505 : :
19506 : : /*
19507 : : * Post alter hook of this inherits. Since object_access_hook doesn't take
19508 : : * multiple object identifiers, we relay oid of parent relation using
19509 : : * auxiliary_id argument.
19510 : : */
19511 [ - + ]: 369 : InvokeObjectPostAlterHookArg(InheritsRelationId,
19512 : : RelationGetRelid(child_rel), 0,
19513 : : RelationGetRelid(parent_rel), false);
19514 : 369 : }
19515 : :
19516 : : /*
19517 : : * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
19518 : : * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
19519 : : * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
19520 : : * be TypeRelationId). There's no convenient way to do this, so go trawling
19521 : : * through pg_depend.
19522 : : */
19523 : : static void
19524 : 377 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
19525 : : DependencyType deptype)
19526 : : {
19527 : : Relation catalogRelation;
19528 : : SysScanDesc scan;
19529 : : ScanKeyData key[3];
19530 : : HeapTuple depTuple;
19531 : :
19532 : 377 : catalogRelation = table_open(DependRelationId, RowExclusiveLock);
19533 : :
19534 : 377 : ScanKeyInit(&key[0],
19535 : : Anum_pg_depend_classid,
19536 : : BTEqualStrategyNumber, F_OIDEQ,
19537 : : ObjectIdGetDatum(RelationRelationId));
19538 : 377 : ScanKeyInit(&key[1],
19539 : : Anum_pg_depend_objid,
19540 : : BTEqualStrategyNumber, F_OIDEQ,
19541 : : ObjectIdGetDatum(relid));
19542 : 377 : ScanKeyInit(&key[2],
19543 : : Anum_pg_depend_objsubid,
19544 : : BTEqualStrategyNumber, F_INT4EQ,
19545 : : Int32GetDatum(0));
19546 : :
19547 : 377 : scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
19548 : : NULL, 3, key);
19549 : :
19550 [ + + ]: 1172 : while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
19551 : : {
19552 : 795 : Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
19553 : :
19554 [ + + ]: 795 : if (dep->refclassid == refclassid &&
19555 [ + + ]: 405 : dep->refobjid == refobjid &&
19556 [ + - ]: 377 : dep->refobjsubid == 0 &&
19557 [ + - ]: 377 : dep->deptype == deptype)
19558 : 377 : CatalogTupleDelete(catalogRelation, &depTuple->t_self);
19559 : : }
19560 : :
19561 : 377 : systable_endscan(scan);
19562 : 377 : table_close(catalogRelation, RowExclusiveLock);
19563 : 377 : }
19564 : :
19565 : : /*
19566 : : * ALTER TABLE OF
19567 : : *
19568 : : * Attach a table to a composite type, as though it had been created with CREATE
19569 : : * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
19570 : : * subject table must not have inheritance parents. These restrictions ensure
19571 : : * that you cannot create a configuration impossible with CREATE TABLE OF alone.
19572 : : *
19573 : : * The address of the type is returned.
19574 : : */
19575 : : static ObjectAddress
19576 : 51 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
19577 : : {
19578 : 51 : Oid relid = RelationGetRelid(rel);
19579 : : Type typetuple;
19580 : : Form_pg_type typeform;
19581 : : Oid typeid;
19582 : : Relation inheritsRelation,
19583 : : relationRelation;
19584 : : SysScanDesc scan;
19585 : : ScanKeyData key;
19586 : : AttrNumber table_attno,
19587 : : type_attno;
19588 : : TupleDesc typeTupleDesc,
19589 : : tableTupleDesc;
19590 : : ObjectAddress tableobj,
19591 : : typeobj;
19592 : : HeapTuple classtuple;
19593 : : AclResult aclresult;
19594 : :
19595 : : /* Validate the type. */
19596 : 51 : typetuple = typenameType(NULL, ofTypename, NULL);
19597 : 51 : check_of_type(typetuple);
19598 : 51 : typeform = (Form_pg_type) GETSTRUCT(typetuple);
19599 : 51 : typeid = typeform->oid;
19600 : :
19601 : 51 : aclresult = object_aclcheck(TypeRelationId, typeid, GetUserId(), ACL_USAGE);
19602 [ + + ]: 51 : if (aclresult != ACLCHECK_OK)
19603 : 4 : aclcheck_error_type(aclresult, typeid);
19604 : :
19605 : : /* Fail if the table has any inheritance parents. */
19606 : 47 : inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
19607 : 47 : ScanKeyInit(&key,
19608 : : Anum_pg_inherits_inhrelid,
19609 : : BTEqualStrategyNumber, F_OIDEQ,
19610 : : ObjectIdGetDatum(relid));
19611 : 47 : scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
19612 : : true, NULL, 1, &key);
19613 [ + + ]: 47 : if (HeapTupleIsValid(systable_getnext(scan)))
19614 [ + - ]: 4 : ereport(ERROR,
19615 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19616 : : errmsg("typed tables cannot inherit")));
19617 : 43 : systable_endscan(scan);
19618 : 43 : table_close(inheritsRelation, AccessShareLock);
19619 : :
19620 : : /*
19621 : : * Check the tuple descriptors for compatibility. Unlike inheritance, we
19622 : : * require that the order also match. However, attnotnull need not match.
19623 : : */
19624 : 43 : typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
19625 : 43 : tableTupleDesc = RelationGetDescr(rel);
19626 : 43 : table_attno = 1;
19627 [ + + ]: 137 : for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
19628 : : {
19629 : : Form_pg_attribute type_attr,
19630 : : table_attr;
19631 : : const char *type_attname,
19632 : : *table_attname;
19633 : :
19634 : : /* Get the next non-dropped type attribute. */
19635 : 110 : type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
19636 [ + + ]: 110 : if (type_attr->attisdropped)
19637 : 29 : continue;
19638 : 81 : type_attname = NameStr(type_attr->attname);
19639 : :
19640 : : /* Get the next non-dropped table attribute. */
19641 : : do
19642 : : {
19643 [ + + ]: 89 : if (table_attno > tableTupleDesc->natts)
19644 [ + - ]: 4 : ereport(ERROR,
19645 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
19646 : : errmsg("table is missing column \"%s\"",
19647 : : type_attname)));
19648 : 85 : table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
19649 : 85 : table_attno++;
19650 [ + + ]: 85 : } while (table_attr->attisdropped);
19651 : 77 : table_attname = NameStr(table_attr->attname);
19652 : :
19653 : : /* Compare name. */
19654 [ + + ]: 77 : if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
19655 [ + - ]: 4 : ereport(ERROR,
19656 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
19657 : : errmsg("table has column \"%s\" where type requires \"%s\"",
19658 : : table_attname, type_attname)));
19659 : :
19660 : : /* Compare type. */
19661 [ + + ]: 73 : if (table_attr->atttypid != type_attr->atttypid ||
19662 [ + + ]: 69 : table_attr->atttypmod != type_attr->atttypmod ||
19663 [ - + ]: 65 : table_attr->attcollation != type_attr->attcollation)
19664 [ + - ]: 8 : ereport(ERROR,
19665 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
19666 : : errmsg("table \"%s\" has different type for column \"%s\"",
19667 : : RelationGetRelationName(rel), type_attname)));
19668 : : }
19669 [ + - ]: 27 : ReleaseTupleDesc(typeTupleDesc);
19670 : :
19671 : : /* Any remaining columns at the end of the table had better be dropped. */
19672 [ + + ]: 27 : for (; table_attno <= tableTupleDesc->natts; table_attno++)
19673 : : {
19674 : 4 : Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
19675 : : table_attno - 1);
19676 : :
19677 [ + - ]: 4 : if (!table_attr->attisdropped)
19678 [ + - ]: 4 : ereport(ERROR,
19679 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
19680 : : errmsg("table has extra column \"%s\"",
19681 : : NameStr(table_attr->attname))));
19682 : : }
19683 : :
19684 : : /* If the table was already typed, drop the existing dependency. */
19685 [ + + ]: 23 : if (rel->rd_rel->reloftype)
19686 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
19687 : : DEPENDENCY_NORMAL);
19688 : :
19689 : : /* Record a dependency on the new type. */
19690 : 23 : tableobj.classId = RelationRelationId;
19691 : 23 : tableobj.objectId = relid;
19692 : 23 : tableobj.objectSubId = 0;
19693 : 23 : typeobj.classId = TypeRelationId;
19694 : 23 : typeobj.objectId = typeid;
19695 : 23 : typeobj.objectSubId = 0;
19696 : 23 : recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
19697 : :
19698 : : /* Update pg_class.reloftype */
19699 : 23 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19700 : 23 : classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19701 [ - + ]: 23 : if (!HeapTupleIsValid(classtuple))
19702 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19703 : 23 : ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
19704 : 23 : CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
19705 : :
19706 [ - + ]: 23 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19707 : :
19708 : 23 : heap_freetuple(classtuple);
19709 : 23 : table_close(relationRelation, RowExclusiveLock);
19710 : :
19711 : 23 : ReleaseSysCache(typetuple);
19712 : :
19713 : 23 : return typeobj;
19714 : : }
19715 : :
19716 : : /*
19717 : : * ALTER TABLE NOT OF
19718 : : *
19719 : : * Detach a typed table from its originating type. Just clear reloftype and
19720 : : * remove the dependency.
19721 : : */
19722 : : static void
19723 : 4 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
19724 : : {
19725 : 4 : Oid relid = RelationGetRelid(rel);
19726 : : Relation relationRelation;
19727 : : HeapTuple tuple;
19728 : :
19729 [ - + ]: 4 : if (!OidIsValid(rel->rd_rel->reloftype))
19730 [ # # ]: 0 : ereport(ERROR,
19731 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19732 : : errmsg("\"%s\" is not a typed table",
19733 : : RelationGetRelationName(rel))));
19734 : :
19735 : : /*
19736 : : * We don't bother to check ownership of the type --- ownership of the
19737 : : * table is presumed enough rights. No lock required on the type, either.
19738 : : */
19739 : :
19740 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
19741 : : DEPENDENCY_NORMAL);
19742 : :
19743 : : /* Clear pg_class.reloftype */
19744 : 4 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19745 : 4 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19746 [ - + ]: 4 : if (!HeapTupleIsValid(tuple))
19747 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19748 : 4 : ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
19749 : 4 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
19750 : :
19751 [ - + ]: 4 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19752 : :
19753 : 4 : heap_freetuple(tuple);
19754 : 4 : table_close(relationRelation, RowExclusiveLock);
19755 : 4 : }
19756 : :
19757 : : /*
19758 : : * relation_mark_replica_identity: Update a table's replica identity
19759 : : *
19760 : : * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
19761 : : * index. Otherwise, it must be InvalidOid.
19762 : : *
19763 : : * Caller had better hold an exclusive lock on the relation, as the results
19764 : : * of running two of these concurrently wouldn't be pretty.
19765 : : */
19766 : : static void
19767 : 298 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
19768 : : bool is_internal)
19769 : : {
19770 : : Relation pg_index;
19771 : : Relation pg_class;
19772 : : HeapTuple pg_class_tuple;
19773 : : HeapTuple pg_index_tuple;
19774 : : Form_pg_class pg_class_form;
19775 : : Form_pg_index pg_index_form;
19776 : : ListCell *index;
19777 : :
19778 : : /*
19779 : : * Check whether relreplident has changed, and update it if so.
19780 : : */
19781 : 298 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19782 : 298 : pg_class_tuple = SearchSysCacheCopy1(RELOID,
19783 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19784 [ - + ]: 298 : if (!HeapTupleIsValid(pg_class_tuple))
19785 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation \"%s\"",
19786 : : RelationGetRelationName(rel));
19787 : 298 : pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
19788 [ + + ]: 298 : if (pg_class_form->relreplident != ri_type)
19789 : : {
19790 : 264 : pg_class_form->relreplident = ri_type;
19791 : 264 : CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
19792 : : }
19793 : 298 : table_close(pg_class, RowExclusiveLock);
19794 : 298 : heap_freetuple(pg_class_tuple);
19795 : :
19796 : : /*
19797 : : * Update the per-index indisreplident flags correctly.
19798 : : */
19799 : 298 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
19800 [ + + + + : 780 : foreach(index, RelationGetIndexList(rel))
+ + ]
19801 : : {
19802 : 482 : Oid thisIndexOid = lfirst_oid(index);
19803 : 482 : bool dirty = false;
19804 : :
19805 : 482 : pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
19806 : : ObjectIdGetDatum(thisIndexOid));
19807 [ - + ]: 482 : if (!HeapTupleIsValid(pg_index_tuple))
19808 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
19809 : 482 : pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
19810 : :
19811 [ + + ]: 482 : if (thisIndexOid == indexOid)
19812 : : {
19813 : : /* Set the bit if not already set. */
19814 [ + + ]: 162 : if (!pg_index_form->indisreplident)
19815 : : {
19816 : 150 : dirty = true;
19817 : 150 : pg_index_form->indisreplident = true;
19818 : : }
19819 : : }
19820 : : else
19821 : : {
19822 : : /* Unset the bit if set. */
19823 [ + + ]: 320 : if (pg_index_form->indisreplident)
19824 : : {
19825 : 34 : dirty = true;
19826 : 34 : pg_index_form->indisreplident = false;
19827 : : }
19828 : : }
19829 : :
19830 [ + + ]: 482 : if (dirty)
19831 : : {
19832 : 184 : CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
19833 [ - + ]: 184 : InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
19834 : : InvalidOid, is_internal);
19835 : :
19836 : : /*
19837 : : * Invalidate the relcache for the table, so that after we commit
19838 : : * all sessions will refresh the table's replica identity index
19839 : : * before attempting any UPDATE or DELETE on the table. (If we
19840 : : * changed the table's pg_class row above, then a relcache inval
19841 : : * is already queued due to that; but we might not have.)
19842 : : */
19843 : 184 : CacheInvalidateRelcache(rel);
19844 : : }
19845 : 482 : heap_freetuple(pg_index_tuple);
19846 : : }
19847 : :
19848 : 298 : table_close(pg_index, RowExclusiveLock);
19849 : 298 : }
19850 : :
19851 : : /*
19852 : : * ALTER TABLE <name> REPLICA IDENTITY ...
19853 : : */
19854 : : static void
19855 : 334 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
19856 : : {
19857 : : Oid indexOid;
19858 : : Relation indexRel;
19859 : : int key;
19860 : :
19861 [ + + ]: 334 : if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
19862 : : {
19863 : 5 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19864 : 5 : return;
19865 : : }
19866 [ + + ]: 329 : else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
19867 : : {
19868 : 101 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19869 : 101 : return;
19870 : : }
19871 [ + + ]: 228 : else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
19872 : : {
19873 : 30 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19874 : 30 : return;
19875 : : }
19876 [ - + ]: 198 : else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
19877 : : {
19878 : : /* fallthrough */ ;
19879 : : }
19880 : : else
19881 [ # # ]: 0 : elog(ERROR, "unexpected identity type %u", stmt->identity_type);
19882 : :
19883 : : /* Check that the index exists */
19884 : 198 : indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
19885 [ - + ]: 198 : if (!OidIsValid(indexOid))
19886 [ # # ]: 0 : ereport(ERROR,
19887 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
19888 : : errmsg("index \"%s\" for table \"%s\" does not exist",
19889 : : stmt->name, RelationGetRelationName(rel))));
19890 : :
19891 : 198 : indexRel = index_open(indexOid, ShareLock);
19892 : :
19893 : : /* Check that the index is on the relation we're altering. */
19894 [ + - ]: 198 : if (indexRel->rd_index == NULL ||
19895 [ + + ]: 198 : indexRel->rd_index->indrelid != RelationGetRelid(rel))
19896 [ + - ]: 4 : ereport(ERROR,
19897 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19898 : : errmsg("\"%s\" is not an index for table \"%s\"",
19899 : : RelationGetRelationName(indexRel),
19900 : : RelationGetRelationName(rel))));
19901 : :
19902 : : /*
19903 : : * The AM must support uniqueness, and the index must in fact be unique.
19904 : : * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
19905 : : * exclusion), we can use that too.
19906 : : */
19907 [ + + ]: 194 : if ((!indexRel->rd_indam->amcanunique ||
19908 [ + + ]: 180 : !indexRel->rd_index->indisunique) &&
19909 [ + + - + ]: 18 : !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
19910 [ + - ]: 8 : ereport(ERROR,
19911 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19912 : : errmsg("cannot use non-unique index \"%s\" as replica identity",
19913 : : RelationGetRelationName(indexRel))));
19914 : : /* Deferred indexes are not guaranteed to be always unique. */
19915 [ + + ]: 186 : if (!indexRel->rd_index->indimmediate)
19916 [ + - ]: 8 : ereport(ERROR,
19917 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19918 : : errmsg("cannot use non-immediate index \"%s\" as replica identity",
19919 : : RelationGetRelationName(indexRel))));
19920 : : /* Expression indexes aren't supported. */
19921 [ + + ]: 178 : if (RelationGetIndexExpressions(indexRel) != NIL)
19922 [ + - ]: 4 : ereport(ERROR,
19923 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19924 : : errmsg("cannot use expression index \"%s\" as replica identity",
19925 : : RelationGetRelationName(indexRel))));
19926 : : /* Predicate indexes aren't supported. */
19927 [ + + ]: 174 : if (RelationGetIndexPredicate(indexRel) != NIL)
19928 [ + - ]: 4 : ereport(ERROR,
19929 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19930 : : errmsg("cannot use partial index \"%s\" as replica identity",
19931 : : RelationGetRelationName(indexRel))));
19932 : :
19933 : : /* Check index for nullable columns. */
19934 [ + + ]: 377 : for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
19935 : : {
19936 : 215 : int16 attno = indexRel->rd_index->indkey.values[key];
19937 : : Form_pg_attribute attr;
19938 : : HeapTuple contup;
19939 : : Form_pg_constraint conForm;
19940 : :
19941 : : /*
19942 : : * Reject any other system columns. (Going forward, we'll disallow
19943 : : * indexes containing such columns in the first place, but they might
19944 : : * exist in older branches.)
19945 : : */
19946 [ - + ]: 215 : if (attno <= 0)
19947 [ # # ]: 0 : ereport(ERROR,
19948 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
19949 : : errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
19950 : : RelationGetRelationName(indexRel), attno)));
19951 : :
19952 : 215 : attr = TupleDescAttr(rel->rd_att, attno - 1);
19953 [ + + ]: 215 : if (!attr->attnotnull)
19954 [ + - ]: 4 : ereport(ERROR,
19955 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19956 : : errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
19957 : : RelationGetRelationName(indexRel),
19958 : : NameStr(attr->attname))));
19959 : :
19960 : : /*
19961 : : * Verify that the not-null constraint for the column is valid.
19962 : : */
19963 : 211 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel), attno);
19964 [ - + ]: 211 : if (!HeapTupleIsValid(contup))
19965 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
19966 : : NameStr(attr->attname), RelationGetRelationName(rel));
19967 : 211 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
19968 [ + + ]: 211 : if (!conForm->convalidated)
19969 [ + - ]: 4 : ereport(ERROR,
19970 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19971 : : errmsg("cannot use index \"%s\" as replica identity",
19972 : : RelationGetRelationName(indexRel)),
19973 : : /*- translator: third %s is a constraint characteristic such as NOT VALID */
19974 : : errdetail("The constraint \"%s\" on column \"%s\" is marked %s.",
19975 : : NameStr(conForm->conname), NameStr(attr->attname), "NOT VALID"),
19976 : : errhint("You might need to validate it using %s.",
19977 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
19978 : 207 : heap_freetuple(contup);
19979 : : }
19980 : :
19981 : : /* This index is suitable for use as a replica identity. Mark it. */
19982 : 162 : relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
19983 : :
19984 : 162 : index_close(indexRel, NoLock);
19985 : : }
19986 : :
19987 : : /*
19988 : : * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
19989 : : */
19990 : : static void
19991 : 260 : ATExecSetRowSecurity(Relation rel, bool rls)
19992 : : {
19993 : : Relation pg_class;
19994 : : Oid relid;
19995 : : HeapTuple tuple;
19996 : :
19997 : 260 : relid = RelationGetRelid(rel);
19998 : :
19999 : : /* Pull the record for this relation and update it */
20000 : 260 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
20001 : :
20002 : 260 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
20003 : :
20004 [ - + ]: 260 : if (!HeapTupleIsValid(tuple))
20005 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
20006 : :
20007 : 260 : ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
20008 : 260 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
20009 : :
20010 [ + + ]: 260 : InvokeObjectPostAlterHook(RelationRelationId,
20011 : : RelationGetRelid(rel), 0);
20012 : :
20013 : 260 : table_close(pg_class, RowExclusiveLock);
20014 : 260 : heap_freetuple(tuple);
20015 : 260 : }
20016 : :
20017 : : /*
20018 : : * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
20019 : : */
20020 : : static void
20021 : 85 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
20022 : : {
20023 : : Relation pg_class;
20024 : : Oid relid;
20025 : : HeapTuple tuple;
20026 : :
20027 : 85 : relid = RelationGetRelid(rel);
20028 : :
20029 : 85 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
20030 : :
20031 : 85 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
20032 : :
20033 [ - + ]: 85 : if (!HeapTupleIsValid(tuple))
20034 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
20035 : :
20036 : 85 : ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
20037 : 85 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
20038 : :
20039 [ + + ]: 85 : InvokeObjectPostAlterHook(RelationRelationId,
20040 : : RelationGetRelid(rel), 0);
20041 : :
20042 : 85 : table_close(pg_class, RowExclusiveLock);
20043 : 85 : heap_freetuple(tuple);
20044 : 85 : }
20045 : :
20046 : : /*
20047 : : * ALTER FOREIGN TABLE <name> OPTIONS (...)
20048 : : */
20049 : : static void
20050 : 34 : ATExecGenericOptions(Relation rel, List *options)
20051 : : {
20052 : : Relation ftrel;
20053 : : ForeignServer *server;
20054 : : ForeignDataWrapper *fdw;
20055 : : HeapTuple tuple;
20056 : : bool isnull;
20057 : : Datum repl_val[Natts_pg_foreign_table];
20058 : : bool repl_null[Natts_pg_foreign_table];
20059 : : bool repl_repl[Natts_pg_foreign_table];
20060 : : Datum datum;
20061 : : Form_pg_foreign_table tableform;
20062 : :
20063 [ - + ]: 34 : if (options == NIL)
20064 : 0 : return;
20065 : :
20066 : 34 : ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
20067 : :
20068 : 34 : tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
20069 : : ObjectIdGetDatum(rel->rd_id));
20070 [ - + ]: 34 : if (!HeapTupleIsValid(tuple))
20071 [ # # ]: 0 : ereport(ERROR,
20072 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
20073 : : errmsg("foreign table \"%s\" does not exist",
20074 : : RelationGetRelationName(rel))));
20075 : 34 : tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
20076 : 34 : server = GetForeignServer(tableform->ftserver);
20077 : 34 : fdw = GetForeignDataWrapper(server->fdwid);
20078 : :
20079 : 34 : memset(repl_val, 0, sizeof(repl_val));
20080 : 34 : memset(repl_null, false, sizeof(repl_null));
20081 : 34 : memset(repl_repl, false, sizeof(repl_repl));
20082 : :
20083 : : /* Extract the current options */
20084 : 34 : datum = SysCacheGetAttr(FOREIGNTABLEREL,
20085 : : tuple,
20086 : : Anum_pg_foreign_table_ftoptions,
20087 : : &isnull);
20088 [ + + ]: 34 : if (isnull)
20089 : 2 : datum = PointerGetDatum(NULL);
20090 : :
20091 : : /* Transform the options */
20092 : 34 : datum = transformGenericOptions(ForeignTableRelationId,
20093 : : datum,
20094 : : options,
20095 : : fdw->fdwvalidator);
20096 : :
20097 [ + - ]: 33 : if (DatumGetPointer(datum) != NULL)
20098 : 33 : repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
20099 : : else
20100 : 0 : repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
20101 : :
20102 : 33 : repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
20103 : :
20104 : : /* Everything looks good - update the tuple */
20105 : :
20106 : 33 : tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
20107 : : repl_val, repl_null, repl_repl);
20108 : :
20109 : 33 : CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
20110 : :
20111 : : /*
20112 : : * Invalidate relcache so that all sessions will refresh any cached plans
20113 : : * that might depend on the old options.
20114 : : */
20115 : 33 : CacheInvalidateRelcache(rel);
20116 : :
20117 [ - + ]: 33 : InvokeObjectPostAlterHook(ForeignTableRelationId,
20118 : : RelationGetRelid(rel), 0);
20119 : :
20120 : 33 : table_close(ftrel, RowExclusiveLock);
20121 : :
20122 : 33 : heap_freetuple(tuple);
20123 : : }
20124 : :
20125 : : /*
20126 : : * ALTER TABLE ALTER COLUMN SET COMPRESSION
20127 : : *
20128 : : * Return value is the address of the modified column
20129 : : */
20130 : : static ObjectAddress
20131 : 49 : ATExecSetCompression(Relation rel,
20132 : : const char *column,
20133 : : Node *newValue,
20134 : : LOCKMODE lockmode)
20135 : : {
20136 : : Relation attrel;
20137 : : HeapTuple tuple;
20138 : : Form_pg_attribute atttableform;
20139 : : AttrNumber attnum;
20140 : : char *compression;
20141 : : char cmethod;
20142 : : ObjectAddress address;
20143 : :
20144 : 49 : compression = strVal(newValue);
20145 : :
20146 : 49 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
20147 : :
20148 : : /* copy the cache entry so we can scribble on it below */
20149 : 49 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
20150 [ - + ]: 49 : if (!HeapTupleIsValid(tuple))
20151 [ # # ]: 0 : ereport(ERROR,
20152 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
20153 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
20154 : : column, RelationGetRelationName(rel))));
20155 : :
20156 : : /* prevent them from altering a system attribute */
20157 : 49 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
20158 : 49 : attnum = atttableform->attnum;
20159 [ - + ]: 49 : if (attnum <= 0)
20160 [ # # ]: 0 : ereport(ERROR,
20161 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
20162 : : errmsg("cannot alter system column \"%s\"", column)));
20163 : :
20164 : : /*
20165 : : * Check that column type is compressible, then get the attribute
20166 : : * compression method code
20167 : : */
20168 : 49 : cmethod = GetAttributeCompression(atttableform->atttypid, compression);
20169 : :
20170 : : /* update pg_attribute entry */
20171 : 45 : atttableform->attcompression = cmethod;
20172 : 45 : CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
20173 : :
20174 [ - + ]: 45 : InvokeObjectPostAlterHook(RelationRelationId,
20175 : : RelationGetRelid(rel),
20176 : : attnum);
20177 : :
20178 : : /*
20179 : : * Apply the change to indexes as well (only for simple index columns,
20180 : : * matching behavior of index.c ConstructTupleDescriptor()).
20181 : : */
20182 : 45 : SetIndexStorageProperties(rel, attrel, attnum,
20183 : : false, 0,
20184 : : true, cmethod,
20185 : : lockmode);
20186 : :
20187 : 45 : heap_freetuple(tuple);
20188 : :
20189 : 45 : table_close(attrel, RowExclusiveLock);
20190 : :
20191 : : /* make changes visible */
20192 : 45 : CommandCounterIncrement();
20193 : :
20194 : 45 : ObjectAddressSubSet(address, RelationRelationId,
20195 : : RelationGetRelid(rel), attnum);
20196 : 45 : return address;
20197 : : }
20198 : :
20199 : :
20200 : : /*
20201 : : * Preparation phase for SET LOGGED/UNLOGGED
20202 : : *
20203 : : * This verifies that we're not trying to change a temp table. Also,
20204 : : * existing foreign key constraints are checked to avoid ending up with
20205 : : * permanent tables referencing unlogged tables.
20206 : : */
20207 : : static void
20208 : 75 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
20209 : : {
20210 : : Relation pg_constraint;
20211 : : HeapTuple tuple;
20212 : : SysScanDesc scan;
20213 : : ScanKeyData skey[1];
20214 : :
20215 : : /*
20216 : : * Disallow changing status for a temp table. Also verify whether we can
20217 : : * get away with doing nothing; in such cases we don't need to run the
20218 : : * checks below, either.
20219 : : */
20220 [ - + + - ]: 75 : switch (rel->rd_rel->relpersistence)
20221 : : {
20222 : 0 : case RELPERSISTENCE_TEMP:
20223 [ # # ]: 0 : ereport(ERROR,
20224 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
20225 : : errmsg("cannot change logged status of table \"%s\" because it is temporary",
20226 : : RelationGetRelationName(rel)),
20227 : : errtable(rel)));
20228 : : break;
20229 : 45 : case RELPERSISTENCE_PERMANENT:
20230 [ + + ]: 45 : if (toLogged)
20231 : : /* nothing to do */
20232 : 8 : return;
20233 : 41 : break;
20234 : 30 : case RELPERSISTENCE_UNLOGGED:
20235 [ + + ]: 30 : if (!toLogged)
20236 : : /* nothing to do */
20237 : 4 : return;
20238 : 26 : break;
20239 : : }
20240 : :
20241 : : /*
20242 : : * UNLOGGED tables can neither be published nor be named in a
20243 : : * publication's EXCEPT clause, so reject the change if the table is
20244 : : * referenced by any publication.
20245 : : */
20246 [ + + + + ]: 67 : if (!toLogged && RelationHasPublication(RelationGetRelid(rel)))
20247 [ + - ]: 4 : ereport(ERROR,
20248 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20249 : : errmsg("cannot change table \"%s\" to unlogged because it is referenced by a publication",
20250 : : RelationGetRelationName(rel)),
20251 : : errdetail("Unlogged relations cannot be published or excluded via an EXCEPT clause."),
20252 : : errhint("Drop the table from the publication, or remove it from the publication's EXCEPT clause, first.")));
20253 : :
20254 : : /*
20255 : : * Check existing foreign key constraints to preserve the invariant that
20256 : : * permanent tables cannot reference unlogged ones. Self-referencing
20257 : : * foreign keys can safely be ignored.
20258 : : */
20259 : 63 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
20260 : :
20261 : : /*
20262 : : * Scan conrelid if changing to permanent, else confrelid; this also
20263 : : * determines which index to use.
20264 : : */
20265 [ + + ]: 63 : ScanKeyInit(&skey[0],
20266 : : toLogged ? Anum_pg_constraint_conrelid :
20267 : : Anum_pg_constraint_confrelid,
20268 : : BTEqualStrategyNumber, F_OIDEQ,
20269 : : ObjectIdGetDatum(RelationGetRelid(rel)));
20270 [ + + ]: 63 : scan = systable_beginscan(pg_constraint,
20271 : : toLogged ? ConstraintRelidTypidNameIndexId :
20272 : : ConstraintForeignRelIndexId,
20273 : : true, NULL, 1, skey);
20274 : :
20275 [ + + ]: 99 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
20276 : : {
20277 : 44 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
20278 : :
20279 [ + + ]: 44 : if (con->contype == CONSTRAINT_FOREIGN)
20280 : : {
20281 : : Oid foreignrelid;
20282 : : Relation foreignrel;
20283 : :
20284 : : /* the opposite end of what we used as scankey */
20285 [ + + ]: 20 : foreignrelid = toLogged ? con->confrelid : con->conrelid;
20286 : :
20287 : : /* ignore if self-referencing */
20288 [ + + ]: 20 : if (RelationGetRelid(rel) == foreignrelid)
20289 : 8 : continue;
20290 : :
20291 : 12 : foreignrel = relation_open(foreignrelid, AccessShareLock);
20292 : :
20293 [ + + ]: 12 : if (toLogged)
20294 : : {
20295 [ + - ]: 4 : if (!RelationIsPermanent(foreignrel))
20296 [ + - ]: 4 : ereport(ERROR,
20297 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
20298 : : errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
20299 : : RelationGetRelationName(rel),
20300 : : RelationGetRelationName(foreignrel)),
20301 : : errtableconstraint(rel, NameStr(con->conname))));
20302 : : }
20303 : : else
20304 : : {
20305 [ + + ]: 8 : if (RelationIsPermanent(foreignrel))
20306 [ + - ]: 4 : ereport(ERROR,
20307 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
20308 : : errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
20309 : : RelationGetRelationName(rel),
20310 : : RelationGetRelationName(foreignrel)),
20311 : : errtableconstraint(rel, NameStr(con->conname))));
20312 : : }
20313 : :
20314 : 4 : relation_close(foreignrel, AccessShareLock);
20315 : : }
20316 : : }
20317 : :
20318 : 55 : systable_endscan(scan);
20319 : :
20320 : 55 : table_close(pg_constraint, AccessShareLock);
20321 : :
20322 : : /* force rewrite if necessary; see comment in ATRewriteTables */
20323 : 55 : tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
20324 [ + + ]: 55 : if (toLogged)
20325 : 22 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
20326 : : else
20327 : 33 : tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
20328 : 55 : tab->chgPersistence = true;
20329 : : }
20330 : :
20331 : : /*
20332 : : * Execute ALTER TABLE SET SCHEMA
20333 : : */
20334 : : ObjectAddress
20335 : 76 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
20336 : : {
20337 : : Relation rel;
20338 : : Oid relid;
20339 : : Oid oldNspOid;
20340 : : Oid nspOid;
20341 : : RangeVar *newrv;
20342 : : ObjectAddresses *objsMoved;
20343 : : ObjectAddress myself;
20344 : :
20345 : 76 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
20346 : 76 : stmt->missing_ok ? RVR_MISSING_OK : 0,
20347 : : RangeVarCallbackForAlterRelation,
20348 : : stmt);
20349 : :
20350 [ + + ]: 71 : if (!OidIsValid(relid))
20351 : : {
20352 [ + - ]: 8 : ereport(NOTICE,
20353 : : (errmsg("relation \"%s\" does not exist, skipping",
20354 : : stmt->relation->relname)));
20355 : 8 : return InvalidObjectAddress;
20356 : : }
20357 : :
20358 : 63 : rel = relation_open(relid, NoLock);
20359 : :
20360 : 63 : oldNspOid = RelationGetNamespace(rel);
20361 : :
20362 : : /* If it's an owned sequence, disallow moving it by itself. */
20363 [ + + ]: 63 : if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
20364 : : {
20365 : : Oid tableId;
20366 : : int32 colId;
20367 : :
20368 [ + + - + ]: 6 : if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
20369 : 1 : sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
20370 [ + - ]: 4 : ereport(ERROR,
20371 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
20372 : : errmsg("cannot move an owned sequence into another schema"),
20373 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
20374 : : RelationGetRelationName(rel),
20375 : : get_rel_name(tableId))));
20376 : : }
20377 : :
20378 : : /* Get and lock schema OID and check its permissions. */
20379 : 59 : newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
20380 : 59 : nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
20381 : :
20382 : : /* common checks on switching namespaces */
20383 : 55 : CheckSetNamespace(oldNspOid, nspOid);
20384 : :
20385 : 55 : objsMoved = new_object_addresses();
20386 : 55 : AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
20387 : 55 : free_object_addresses(objsMoved);
20388 : :
20389 : 55 : ObjectAddressSet(myself, RelationRelationId, relid);
20390 : :
20391 [ + - ]: 55 : if (oldschema)
20392 : 55 : *oldschema = oldNspOid;
20393 : :
20394 : : /* close rel, but keep lock until commit */
20395 : 55 : relation_close(rel, NoLock);
20396 : :
20397 : 55 : return myself;
20398 : : }
20399 : :
20400 : : /*
20401 : : * The guts of relocating a table or materialized view to another namespace:
20402 : : * besides moving the relation itself, its dependent objects are relocated to
20403 : : * the new schema.
20404 : : */
20405 : : void
20406 : 56 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
20407 : : ObjectAddresses *objsMoved)
20408 : : {
20409 : : Relation classRel;
20410 : :
20411 : : Assert(objsMoved != NULL);
20412 : :
20413 : : /* OK, modify the pg_class row and pg_depend entry */
20414 : 56 : classRel = table_open(RelationRelationId, RowExclusiveLock);
20415 : :
20416 : 56 : AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
20417 : : nspOid, true, objsMoved);
20418 : :
20419 : : /* Fix the table's row type too, if it has one */
20420 [ + + ]: 56 : if (OidIsValid(rel->rd_rel->reltype))
20421 : 55 : AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
20422 : : false, /* isImplicitArray */
20423 : : false, /* ignoreDependent */
20424 : : false, /* errorOnTableType */
20425 : : objsMoved);
20426 : :
20427 : : /* Fix other dependent stuff */
20428 : 56 : AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
20429 : 56 : AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
20430 : : objsMoved, AccessExclusiveLock);
20431 : 56 : AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
20432 : : false, objsMoved);
20433 : :
20434 : 56 : table_close(classRel, RowExclusiveLock);
20435 : 56 : }
20436 : :
20437 : : /*
20438 : : * The guts of relocating a relation to another namespace: fix the pg_class
20439 : : * entry, and the pg_depend entry if any. Caller must already have
20440 : : * opened and write-locked pg_class.
20441 : : */
20442 : : void
20443 : 123 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
20444 : : Oid oldNspOid, Oid newNspOid,
20445 : : bool hasDependEntry,
20446 : : ObjectAddresses *objsMoved)
20447 : : {
20448 : : HeapTuple classTup;
20449 : : Form_pg_class classForm;
20450 : : ObjectAddress thisobj;
20451 : 123 : bool already_done = false;
20452 : :
20453 : : /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
20454 : 123 : classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
20455 [ - + ]: 123 : if (!HeapTupleIsValid(classTup))
20456 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
20457 : 123 : classForm = (Form_pg_class) GETSTRUCT(classTup);
20458 : :
20459 : : Assert(classForm->relnamespace == oldNspOid);
20460 : :
20461 : 123 : thisobj.classId = RelationRelationId;
20462 : 123 : thisobj.objectId = relOid;
20463 : 123 : thisobj.objectSubId = 0;
20464 : :
20465 : : /*
20466 : : * If the object has already been moved, don't move it again. If it's
20467 : : * already in the right place, don't move it, but still fire the object
20468 : : * access hook.
20469 : : */
20470 : 123 : already_done = object_address_present(&thisobj, objsMoved);
20471 [ + - + + ]: 123 : if (!already_done && oldNspOid != newNspOid)
20472 : 95 : {
20473 : 95 : ItemPointerData otid = classTup->t_self;
20474 : :
20475 : : /* check for duplicate name (more friendly than unique-index failure) */
20476 [ - + ]: 95 : if (get_relname_relid(NameStr(classForm->relname),
20477 : : newNspOid) != InvalidOid)
20478 [ # # ]: 0 : ereport(ERROR,
20479 : : (errcode(ERRCODE_DUPLICATE_TABLE),
20480 : : errmsg("relation \"%s\" already exists in schema \"%s\"",
20481 : : NameStr(classForm->relname),
20482 : : get_namespace_name(newNspOid))));
20483 : :
20484 : : /* classTup is a copy, so OK to scribble on */
20485 : 95 : classForm->relnamespace = newNspOid;
20486 : :
20487 : 95 : CatalogTupleUpdate(classRel, &otid, classTup);
20488 : 95 : UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
20489 : :
20490 : :
20491 : : /* Update dependency on schema if caller said so */
20492 [ + + - + ]: 163 : if (hasDependEntry &&
20493 : 68 : changeDependencyFor(RelationRelationId,
20494 : : relOid,
20495 : : NamespaceRelationId,
20496 : : oldNspOid,
20497 : : newNspOid) != 1)
20498 [ # # ]: 0 : elog(ERROR, "could not change schema dependency for relation \"%s\"",
20499 : : NameStr(classForm->relname));
20500 : : }
20501 : : else
20502 : 28 : UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
20503 [ + - ]: 123 : if (!already_done)
20504 : : {
20505 : 123 : add_exact_object_address(&thisobj, objsMoved);
20506 : :
20507 [ - + ]: 123 : InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
20508 : : }
20509 : :
20510 : 123 : heap_freetuple(classTup);
20511 : 123 : }
20512 : :
20513 : : /*
20514 : : * Move all indexes for the specified relation to another namespace.
20515 : : *
20516 : : * Note: we assume adequate permission checking was done by the caller,
20517 : : * and that the caller has a suitable lock on the owning relation.
20518 : : */
20519 : : static void
20520 : 56 : AlterIndexNamespaces(Relation classRel, Relation rel,
20521 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
20522 : : {
20523 : : List *indexList;
20524 : : ListCell *l;
20525 : :
20526 : 56 : indexList = RelationGetIndexList(rel);
20527 : :
20528 [ + + + + : 86 : foreach(l, indexList)
+ + ]
20529 : : {
20530 : 30 : Oid indexOid = lfirst_oid(l);
20531 : : ObjectAddress thisobj;
20532 : :
20533 : 30 : thisobj.classId = RelationRelationId;
20534 : 30 : thisobj.objectId = indexOid;
20535 : 30 : thisobj.objectSubId = 0;
20536 : :
20537 : : /*
20538 : : * Note: currently, the index will not have its own dependency on the
20539 : : * namespace, so we don't need to do changeDependencyFor(). There's no
20540 : : * row type in pg_type, either.
20541 : : *
20542 : : * XXX this objsMoved test may be pointless -- surely we have a single
20543 : : * dependency link from a relation to each index?
20544 : : */
20545 [ + - ]: 30 : if (!object_address_present(&thisobj, objsMoved))
20546 : : {
20547 : 30 : AlterRelationNamespaceInternal(classRel, indexOid,
20548 : : oldNspOid, newNspOid,
20549 : : false, objsMoved);
20550 : 30 : add_exact_object_address(&thisobj, objsMoved);
20551 : : }
20552 : : }
20553 : :
20554 : 56 : list_free(indexList);
20555 : 56 : }
20556 : :
20557 : : /*
20558 : : * Move all identity and SERIAL-column sequences of the specified relation to another
20559 : : * namespace.
20560 : : *
20561 : : * Note: we assume adequate permission checking was done by the caller,
20562 : : * and that the caller has a suitable lock on the owning relation.
20563 : : */
20564 : : static void
20565 : 56 : AlterSeqNamespaces(Relation classRel, Relation rel,
20566 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
20567 : : LOCKMODE lockmode)
20568 : : {
20569 : : Relation depRel;
20570 : : SysScanDesc scan;
20571 : : ScanKeyData key[2];
20572 : : HeapTuple tup;
20573 : :
20574 : : /*
20575 : : * SERIAL sequences are those having an auto dependency on one of the
20576 : : * table's columns (we don't care *which* column, exactly).
20577 : : */
20578 : 56 : depRel = table_open(DependRelationId, AccessShareLock);
20579 : :
20580 : 56 : ScanKeyInit(&key[0],
20581 : : Anum_pg_depend_refclassid,
20582 : : BTEqualStrategyNumber, F_OIDEQ,
20583 : : ObjectIdGetDatum(RelationRelationId));
20584 : 56 : ScanKeyInit(&key[1],
20585 : : Anum_pg_depend_refobjid,
20586 : : BTEqualStrategyNumber, F_OIDEQ,
20587 : : ObjectIdGetDatum(RelationGetRelid(rel)));
20588 : : /* we leave refobjsubid unspecified */
20589 : :
20590 : 56 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
20591 : : NULL, 2, key);
20592 : :
20593 [ + + ]: 405 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
20594 : : {
20595 : 349 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
20596 : : Relation seqRel;
20597 : :
20598 : : /* skip dependencies other than auto dependencies on columns */
20599 [ + + ]: 349 : if (depForm->refobjsubid == 0 ||
20600 [ + + ]: 252 : depForm->classid != RelationRelationId ||
20601 [ + - ]: 28 : depForm->objsubid != 0 ||
20602 [ - + - - ]: 28 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
20603 : 321 : continue;
20604 : :
20605 : : /* Use relation_open just in case it's an index */
20606 : 28 : seqRel = relation_open(depForm->objid, lockmode);
20607 : :
20608 : : /* skip non-sequence relations */
20609 [ - + ]: 28 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
20610 : : {
20611 : : /* No need to keep the lock */
20612 : 0 : relation_close(seqRel, lockmode);
20613 : 0 : continue;
20614 : : }
20615 : :
20616 : : /* Fix the pg_class and pg_depend entries */
20617 : 28 : AlterRelationNamespaceInternal(classRel, depForm->objid,
20618 : : oldNspOid, newNspOid,
20619 : : true, objsMoved);
20620 : :
20621 : : /*
20622 : : * Sequences used to have entries in pg_type, but no longer do. If we
20623 : : * ever re-instate that, we'll need to move the pg_type entry to the
20624 : : * new namespace, too (using AlterTypeNamespaceInternal).
20625 : : */
20626 : : Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
20627 : :
20628 : : /* Now we can close it. Keep the lock till end of transaction. */
20629 : 28 : relation_close(seqRel, NoLock);
20630 : : }
20631 : :
20632 : 56 : systable_endscan(scan);
20633 : :
20634 : 56 : relation_close(depRel, AccessShareLock);
20635 : 56 : }
20636 : :
20637 : :
20638 : : /*
20639 : : * This code supports
20640 : : * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
20641 : : *
20642 : : * Because we only support this for TEMP tables, it's sufficient to remember
20643 : : * the state in a backend-local data structure.
20644 : : */
20645 : :
20646 : : /*
20647 : : * Register a newly-created relation's ON COMMIT action.
20648 : : */
20649 : : void
20650 : 116 : register_on_commit_action(Oid relid, OnCommitAction action)
20651 : : {
20652 : : OnCommitItem *oc;
20653 : : MemoryContext oldcxt;
20654 : :
20655 : : /*
20656 : : * We needn't bother registering the relation unless there is an ON COMMIT
20657 : : * action we need to take.
20658 : : */
20659 [ + - + + ]: 116 : if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
20660 : 16 : return;
20661 : :
20662 : 100 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
20663 : :
20664 : 100 : oc = palloc_object(OnCommitItem);
20665 : 100 : oc->relid = relid;
20666 : 100 : oc->oncommit = action;
20667 : 100 : oc->creating_subid = GetCurrentSubTransactionId();
20668 : 100 : oc->deleting_subid = InvalidSubTransactionId;
20669 : :
20670 : : /*
20671 : : * We use lcons() here so that ON COMMIT actions are processed in reverse
20672 : : * order of registration. That might not be essential but it seems
20673 : : * reasonable.
20674 : : */
20675 : 100 : on_commits = lcons(oc, on_commits);
20676 : :
20677 : 100 : MemoryContextSwitchTo(oldcxt);
20678 : : }
20679 : :
20680 : : /*
20681 : : * Unregister any ON COMMIT action when a relation is deleted.
20682 : : *
20683 : : * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
20684 : : */
20685 : : void
20686 : 34784 : remove_on_commit_action(Oid relid)
20687 : : {
20688 : : ListCell *l;
20689 : :
20690 [ + + + + : 34881 : foreach(l, on_commits)
+ + ]
20691 : : {
20692 : 189 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20693 : :
20694 [ + + ]: 189 : if (oc->relid == relid)
20695 : : {
20696 : 92 : oc->deleting_subid = GetCurrentSubTransactionId();
20697 : 92 : break;
20698 : : }
20699 : : }
20700 : 34784 : }
20701 : :
20702 : : /*
20703 : : * Perform ON COMMIT actions.
20704 : : *
20705 : : * This is invoked just before actually committing, since it's possible
20706 : : * to encounter errors.
20707 : : */
20708 : : void
20709 : 610455 : PreCommit_on_commit_actions(void)
20710 : : {
20711 : : ListCell *l;
20712 : 610455 : List *oids_to_truncate = NIL;
20713 : 610455 : List *oids_to_drop = NIL;
20714 : :
20715 [ + + + + : 611001 : foreach(l, on_commits)
+ + ]
20716 : : {
20717 : 546 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20718 : :
20719 : : /* Ignore entry if already dropped in this xact */
20720 [ + + ]: 546 : if (oc->deleting_subid != InvalidSubTransactionId)
20721 : 49 : continue;
20722 : :
20723 [ - + + - ]: 497 : switch (oc->oncommit)
20724 : : {
20725 : 0 : case ONCOMMIT_NOOP:
20726 : : case ONCOMMIT_PRESERVE_ROWS:
20727 : : /* Do nothing (there shouldn't be such entries, actually) */
20728 : 0 : break;
20729 : 462 : case ONCOMMIT_DELETE_ROWS:
20730 : :
20731 : : /*
20732 : : * If this transaction hasn't accessed any temporary
20733 : : * relations, we can skip truncating ON COMMIT DELETE ROWS
20734 : : * tables, as they must still be empty.
20735 : : */
20736 [ + + ]: 462 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
20737 : 298 : oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
20738 : 462 : break;
20739 : 35 : case ONCOMMIT_DROP:
20740 : 35 : oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
20741 : 35 : break;
20742 : : }
20743 : : }
20744 : :
20745 : : /*
20746 : : * Truncate relations before dropping so that all dependencies between
20747 : : * relations are removed after they are worked on. Doing it like this
20748 : : * might be a waste as it is possible that a relation being truncated will
20749 : : * be dropped anyway due to its parent being dropped, but this makes the
20750 : : * code more robust because of not having to re-check that the relation
20751 : : * exists at truncation time.
20752 : : */
20753 [ + + ]: 610455 : if (oids_to_truncate != NIL)
20754 : 254 : heap_truncate(oids_to_truncate);
20755 : :
20756 [ + + ]: 610451 : if (oids_to_drop != NIL)
20757 : : {
20758 : 31 : ObjectAddresses *targetObjects = new_object_addresses();
20759 : :
20760 [ + - + + : 66 : foreach(l, oids_to_drop)
+ + ]
20761 : : {
20762 : : ObjectAddress object;
20763 : :
20764 : 35 : object.classId = RelationRelationId;
20765 : 35 : object.objectId = lfirst_oid(l);
20766 : 35 : object.objectSubId = 0;
20767 : :
20768 : : Assert(!object_address_present(&object, targetObjects));
20769 : :
20770 : 35 : add_exact_object_address(&object, targetObjects);
20771 : : }
20772 : :
20773 : : /*
20774 : : * Object deletion might involve toast table access (to clean up
20775 : : * toasted catalog entries), so ensure we have a valid snapshot.
20776 : : */
20777 : 31 : PushActiveSnapshot(GetTransactionSnapshot());
20778 : :
20779 : : /*
20780 : : * Since this is an automatic drop, rather than one directly initiated
20781 : : * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
20782 : : */
20783 : 31 : performMultipleDeletions(targetObjects, DROP_CASCADE,
20784 : : PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
20785 : :
20786 : 31 : PopActiveSnapshot();
20787 : :
20788 : : #ifdef USE_ASSERT_CHECKING
20789 : :
20790 : : /*
20791 : : * Note that table deletion will call remove_on_commit_action, so the
20792 : : * entry should get marked as deleted.
20793 : : */
20794 : : foreach(l, on_commits)
20795 : : {
20796 : : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20797 : :
20798 : : if (oc->oncommit != ONCOMMIT_DROP)
20799 : : continue;
20800 : :
20801 : : Assert(oc->deleting_subid != InvalidSubTransactionId);
20802 : : }
20803 : : #endif
20804 : : }
20805 : 610451 : }
20806 : :
20807 : : /*
20808 : : * Post-commit or post-abort cleanup for ON COMMIT management.
20809 : : *
20810 : : * All we do here is remove no-longer-needed OnCommitItem entries.
20811 : : *
20812 : : * During commit, remove entries that were deleted during this transaction;
20813 : : * during abort, remove those created during this transaction.
20814 : : */
20815 : : void
20816 : 647928 : AtEOXact_on_commit_actions(bool isCommit)
20817 : : {
20818 : : ListCell *cur_item;
20819 : :
20820 [ + + + + : 648494 : foreach(cur_item, on_commits)
+ + ]
20821 : : {
20822 : 566 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20823 : :
20824 [ + + + + ]: 634 : if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
20825 : 68 : oc->creating_subid != InvalidSubTransactionId)
20826 : : {
20827 : : /* cur_item must be removed */
20828 : 100 : on_commits = foreach_delete_current(on_commits, cur_item);
20829 : 100 : pfree(oc);
20830 : : }
20831 : : else
20832 : : {
20833 : : /* cur_item must be preserved */
20834 : 466 : oc->creating_subid = InvalidSubTransactionId;
20835 : 466 : oc->deleting_subid = InvalidSubTransactionId;
20836 : : }
20837 : : }
20838 : 647928 : }
20839 : :
20840 : : /*
20841 : : * Post-subcommit or post-subabort cleanup for ON COMMIT management.
20842 : : *
20843 : : * During subabort, we can immediately remove entries created during this
20844 : : * subtransaction. During subcommit, just relabel entries marked during
20845 : : * this subtransaction as being the parent's responsibility.
20846 : : */
20847 : : void
20848 : 23157 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
20849 : : SubTransactionId parentSubid)
20850 : : {
20851 : : ListCell *cur_item;
20852 : :
20853 [ - + - - : 23157 : foreach(cur_item, on_commits)
- + ]
20854 : : {
20855 : 0 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20856 : :
20857 [ # # # # ]: 0 : if (!isCommit && oc->creating_subid == mySubid)
20858 : : {
20859 : : /* cur_item must be removed */
20860 : 0 : on_commits = foreach_delete_current(on_commits, cur_item);
20861 : 0 : pfree(oc);
20862 : : }
20863 : : else
20864 : : {
20865 : : /* cur_item must be preserved */
20866 [ # # ]: 0 : if (oc->creating_subid == mySubid)
20867 : 0 : oc->creating_subid = parentSubid;
20868 [ # # ]: 0 : if (oc->deleting_subid == mySubid)
20869 [ # # ]: 0 : oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
20870 : : }
20871 : : }
20872 : 23157 : }
20873 : :
20874 : : /*
20875 : : * This is intended as a callback for RangeVarGetRelidExtended(). It allows
20876 : : * the relation to be locked only if (1) it's a plain or partitioned table,
20877 : : * materialized view, or TOAST table and (2) the current user is the owner (or
20878 : : * the superuser) or has been granted MAINTAIN. This meets the
20879 : : * permission-checking needs of CLUSTER, REPACK, REINDEX TABLE, and REFRESH
20880 : : * MATERIALIZED VIEW; we expose it here so that it can be used by all.
20881 : : */
20882 : : void
20883 : 820 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
20884 : : Oid relId, Oid oldRelId, void *arg)
20885 : : {
20886 : : char relkind;
20887 : : AclResult aclresult;
20888 : :
20889 : : /* Nothing to do if the relation was not found. */
20890 [ + + ]: 820 : if (!OidIsValid(relId))
20891 : 3 : return;
20892 : :
20893 : : /*
20894 : : * If the relation does exist, check whether it's an index. But note that
20895 : : * the relation might have been dropped between the time we did the name
20896 : : * lookup and now. In that case, there's nothing to do.
20897 : : */
20898 : 817 : relkind = get_rel_relkind(relId);
20899 [ - + ]: 817 : if (!relkind)
20900 : 0 : return;
20901 [ + + + + : 817 : if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
+ + ]
20902 [ + + ]: 127 : relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
20903 [ + - ]: 22 : ereport(ERROR,
20904 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20905 : : errmsg("\"%s\" is not a table or materialized view", relation->relname)));
20906 : :
20907 : : /* Check permissions */
20908 : 795 : aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
20909 [ + + ]: 795 : if (aclresult != ACLCHECK_OK)
20910 : 20 : aclcheck_error(aclresult,
20911 : 20 : get_relkind_objtype(get_rel_relkind(relId)),
20912 : 20 : relation->relname);
20913 : : }
20914 : :
20915 : : /*
20916 : : * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
20917 : : */
20918 : : static void
20919 : 1462 : RangeVarCallbackForTruncate(const RangeVar *relation,
20920 : : Oid relId, Oid oldRelId, void *arg)
20921 : : {
20922 : : HeapTuple tuple;
20923 : :
20924 : : /* Nothing to do if the relation was not found. */
20925 [ - + ]: 1462 : if (!OidIsValid(relId))
20926 : 0 : return;
20927 : :
20928 : 1462 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20929 [ - + ]: 1462 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20930 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20931 : :
20932 : 1462 : truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
20933 : 1459 : truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
20934 : :
20935 : 1439 : ReleaseSysCache(tuple);
20936 : : }
20937 : :
20938 : : /*
20939 : : * Callback for RangeVarGetRelidExtended(). Checks that the current user is
20940 : : * the owner of the relation, or superuser.
20941 : : */
20942 : : void
20943 : 10524 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
20944 : : Oid relId, Oid oldRelId, void *arg)
20945 : : {
20946 : : HeapTuple tuple;
20947 : :
20948 : : /* Nothing to do if the relation was not found. */
20949 [ + + ]: 10524 : if (!OidIsValid(relId))
20950 : 5 : return;
20951 : :
20952 : 10519 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20953 [ - + ]: 10519 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20954 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20955 : :
20956 [ + + ]: 10519 : if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
20957 : 4 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
20958 : 4 : relation->relname);
20959 : :
20960 : : /*
20961 : : * Conflict log tables are used internally for logical replication
20962 : : * conflict logging and should not be modified directly, as it could
20963 : : * disrupt conflict logging.
20964 : : */
20965 [ + + ]: 10515 : if (IsConflictLogTableClass((Form_pg_class) GETSTRUCT(tuple)))
20966 [ + - ]: 4 : ereport(ERROR,
20967 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20968 : : errmsg("cannot change conflict log table \"%s\"",
20969 : : relation->relname),
20970 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
20971 : :
20972 [ + + + + ]: 20962 : if (!allowSystemTableMods &&
20973 : 10451 : IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
20974 [ + - ]: 1 : ereport(ERROR,
20975 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
20976 : : errmsg("permission denied: \"%s\" is a system catalog",
20977 : : relation->relname)));
20978 : :
20979 : 10510 : ReleaseSysCache(tuple);
20980 : : }
20981 : :
20982 : : /*
20983 : : * Common RangeVarGetRelid callback for rename, set schema, and alter table
20984 : : * processing.
20985 : : */
20986 : : static void
20987 : 25559 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
20988 : : void *arg)
20989 : : {
20990 : 25559 : Node *stmt = (Node *) arg;
20991 : : ObjectType reltype;
20992 : : HeapTuple tuple;
20993 : : Form_pg_class classform;
20994 : : AclResult aclresult;
20995 : : char relkind;
20996 : :
20997 : 25559 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
20998 [ + + ]: 25559 : if (!HeapTupleIsValid(tuple))
20999 : 167 : return; /* concurrently dropped */
21000 : 25392 : classform = (Form_pg_class) GETSTRUCT(tuple);
21001 : 25392 : relkind = classform->relkind;
21002 : :
21003 : : /* Must own relation. */
21004 [ + + ]: 25392 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
21005 : 40 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
21006 : :
21007 : : /*
21008 : : * Conflict log tables are used internally for logical replication
21009 : : * conflict logging and should not be altered directly, as it could
21010 : : * disrupt conflict logging.
21011 : : */
21012 [ + + ]: 25352 : if (IsConflictLogTableClass(classform))
21013 [ + - ]: 13 : ereport(ERROR,
21014 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21015 : : errmsg("cannot alter conflict log table \"%s\"",
21016 : : rv->relname),
21017 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
21018 : :
21019 : : /* No system table modifications unless explicitly allowed. */
21020 [ + + + + ]: 25339 : if (!allowSystemTableMods && IsSystemClass(relid, classform))
21021 [ + - ]: 18 : ereport(ERROR,
21022 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
21023 : : errmsg("permission denied: \"%s\" is a system catalog",
21024 : : rv->relname)));
21025 : :
21026 : : /*
21027 : : * Extract the specified relation type from the statement parse tree.
21028 : : *
21029 : : * Also, for ALTER .. RENAME, check permissions: the user must (still)
21030 : : * have CREATE rights on the containing namespace.
21031 : : */
21032 [ + + ]: 25321 : if (IsA(stmt, RenameStmt))
21033 : : {
21034 : 287 : aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
21035 : : GetUserId(), ACL_CREATE);
21036 [ - + ]: 287 : if (aclresult != ACLCHECK_OK)
21037 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
21038 : 0 : get_namespace_name(classform->relnamespace));
21039 : 287 : reltype = ((RenameStmt *) stmt)->renameType;
21040 : : }
21041 [ + + ]: 25034 : else if (IsA(stmt, AlterObjectSchemaStmt))
21042 : 64 : reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
21043 : :
21044 [ + - ]: 24970 : else if (IsA(stmt, AlterTableStmt))
21045 : 24970 : reltype = ((AlterTableStmt *) stmt)->objtype;
21046 : : else
21047 : : {
21048 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
21049 : : reltype = OBJECT_TABLE; /* placate compiler */
21050 : : }
21051 : :
21052 : : /*
21053 : : * For compatibility with prior releases, we allow ALTER TABLE to be used
21054 : : * with most other types of relations (but not composite types). We allow
21055 : : * similar flexibility for ALTER INDEX in the case of RENAME, but not
21056 : : * otherwise. Otherwise, the user must select the correct form of the
21057 : : * command for the relation at issue.
21058 : : */
21059 [ + + - + ]: 25321 : if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
21060 [ # # ]: 0 : ereport(ERROR,
21061 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21062 : : errmsg("\"%s\" is not a sequence", rv->relname)));
21063 : :
21064 [ + + - + ]: 25321 : if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
21065 [ # # ]: 0 : ereport(ERROR,
21066 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21067 : : errmsg("\"%s\" is not a view", rv->relname)));
21068 : :
21069 [ + + - + ]: 25321 : if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
21070 [ # # ]: 0 : ereport(ERROR,
21071 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21072 : : errmsg("\"%s\" is not a materialized view", rv->relname)));
21073 : :
21074 [ + + - + ]: 25321 : if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
21075 [ # # ]: 0 : ereport(ERROR,
21076 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21077 : : errmsg("\"%s\" is not a foreign table", rv->relname)));
21078 : :
21079 [ + + - + ]: 25321 : if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
21080 [ # # ]: 0 : ereport(ERROR,
21081 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21082 : : errmsg("\"%s\" is not a composite type", rv->relname)));
21083 : :
21084 [ + + + + : 25321 : if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
+ + ]
21085 : : relkind != RELKIND_PARTITIONED_INDEX
21086 [ + + ]: 24 : && !IsA(stmt, RenameStmt))
21087 [ + - ]: 4 : ereport(ERROR,
21088 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21089 : : errmsg("\"%s\" is not an index", rv->relname)));
21090 : :
21091 : : /*
21092 : : * Don't allow ALTER TABLE on composite types. We want people to use ALTER
21093 : : * TYPE for that.
21094 : : */
21095 [ + + - + ]: 25317 : if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
21096 [ # # ]: 0 : ereport(ERROR,
21097 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21098 : : errmsg("\"%s\" is a composite type", rv->relname),
21099 : : /* translator: %s is an SQL ALTER command */
21100 : : errhint("Use %s instead.",
21101 : : "ALTER TYPE")));
21102 : :
21103 : : /*
21104 : : * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
21105 : : * to a different schema, such as indexes and TOAST tables.
21106 : : */
21107 [ + + ]: 25317 : if (IsA(stmt, AlterObjectSchemaStmt))
21108 : : {
21109 [ + - - + ]: 64 : if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
21110 [ # # ]: 0 : ereport(ERROR,
21111 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21112 : : errmsg("cannot change schema of index \"%s\"",
21113 : : rv->relname),
21114 : : errhint("Change the schema of the table instead.")));
21115 [ - + ]: 64 : else if (relkind == RELKIND_COMPOSITE_TYPE)
21116 [ # # ]: 0 : ereport(ERROR,
21117 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21118 : : errmsg("cannot change schema of composite type \"%s\"",
21119 : : rv->relname),
21120 : : /* translator: %s is an SQL ALTER command */
21121 : : errhint("Use %s instead.",
21122 : : "ALTER TYPE")));
21123 [ - + ]: 64 : else if (relkind == RELKIND_TOASTVALUE)
21124 [ # # ]: 0 : ereport(ERROR,
21125 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21126 : : errmsg("cannot change schema of TOAST table \"%s\"",
21127 : : rv->relname),
21128 : : errhint("Change the schema of the table instead.")));
21129 : : }
21130 : :
21131 : 25317 : ReleaseSysCache(tuple);
21132 : : }
21133 : :
21134 : : /*
21135 : : * Transform any expressions present in the partition key
21136 : : *
21137 : : * Returns a transformed PartitionSpec.
21138 : : */
21139 : : static PartitionSpec *
21140 : 3549 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
21141 : : {
21142 : : PartitionSpec *newspec;
21143 : : ParseState *pstate;
21144 : : ParseNamespaceItem *nsitem;
21145 : : ListCell *l;
21146 : :
21147 : 3549 : newspec = makeNode(PartitionSpec);
21148 : :
21149 : 3549 : newspec->strategy = partspec->strategy;
21150 : 3549 : newspec->partParams = NIL;
21151 : 3549 : newspec->location = partspec->location;
21152 : :
21153 : : /* Check valid number of columns for strategy */
21154 [ + + + + ]: 5235 : if (partspec->strategy == PARTITION_STRATEGY_LIST &&
21155 : 1686 : list_length(partspec->partParams) != 1)
21156 [ + - ]: 4 : ereport(ERROR,
21157 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21158 : : errmsg("cannot use \"list\" partition strategy with more than one column")));
21159 : :
21160 : : /*
21161 : : * Create a dummy ParseState and insert the target relation as its sole
21162 : : * rangetable entry. We need a ParseState for transformExpr.
21163 : : */
21164 : 3545 : pstate = make_parsestate(NULL);
21165 : 3545 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
21166 : : NULL, false, true);
21167 : 3545 : addNSItemToQuery(pstate, nsitem, true, true, true);
21168 : :
21169 : : /* take care of any partition expressions */
21170 [ + - + + : 7392 : foreach(l, partspec->partParams)
+ + ]
21171 : : {
21172 : 3863 : PartitionElem *pelem = lfirst_node(PartitionElem, l);
21173 : :
21174 [ + + ]: 3863 : if (pelem->expr)
21175 : : {
21176 : : /* Copy, to avoid scribbling on the input */
21177 : 262 : pelem = copyObject(pelem);
21178 : :
21179 : : /* Now do parse transformation of the expression */
21180 : 262 : pelem->expr = transformExpr(pstate, pelem->expr,
21181 : : EXPR_KIND_PARTITION_EXPRESSION);
21182 : :
21183 : : /* we have to fix its collations too */
21184 : 246 : assign_expr_collations(pstate, pelem->expr);
21185 : : }
21186 : :
21187 : 3847 : newspec->partParams = lappend(newspec->partParams, pelem);
21188 : : }
21189 : :
21190 : 3529 : return newspec;
21191 : : }
21192 : :
21193 : : /*
21194 : : * Compute per-partition-column information from a list of PartitionElems.
21195 : : * Expressions in the PartitionElems must be parse-analyzed already.
21196 : : */
21197 : : static void
21198 : 3529 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
21199 : : List **partexprs, Oid *partopclass, Oid *partcollation,
21200 : : PartitionStrategy strategy)
21201 : : {
21202 : : int attn;
21203 : : ListCell *lc;
21204 : : Oid am_oid;
21205 : :
21206 : 3529 : attn = 0;
21207 [ + - + + : 7288 : foreach(lc, partParams)
+ + ]
21208 : : {
21209 : 3847 : PartitionElem *pelem = lfirst_node(PartitionElem, lc);
21210 : : Oid atttype;
21211 : : Oid attcollation;
21212 : :
21213 [ + + ]: 3847 : if (pelem->name != NULL)
21214 : : {
21215 : : /* Simple attribute reference */
21216 : : HeapTuple atttuple;
21217 : : Form_pg_attribute attform;
21218 : :
21219 : 3601 : atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
21220 : 3601 : pelem->name);
21221 [ + + ]: 3601 : if (!HeapTupleIsValid(atttuple))
21222 [ + - ]: 8 : ereport(ERROR,
21223 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
21224 : : errmsg("column \"%s\" named in partition key does not exist",
21225 : : pelem->name),
21226 : : parser_errposition(pstate, pelem->location)));
21227 : 3593 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
21228 : :
21229 [ + + ]: 3593 : if (attform->attnum <= 0)
21230 [ + - ]: 4 : ereport(ERROR,
21231 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21232 : : errmsg("cannot use system column \"%s\" in partition key",
21233 : : pelem->name),
21234 : : parser_errposition(pstate, pelem->location)));
21235 : :
21236 : : /*
21237 : : * Stored generated columns cannot work: They are computed after
21238 : : * BEFORE triggers, but partition routing is done before all
21239 : : * triggers. Maybe virtual generated columns could be made to
21240 : : * work, but then they would need to be handled as an expression
21241 : : * below.
21242 : : */
21243 [ + + ]: 3589 : if (attform->attgenerated)
21244 [ + - ]: 8 : ereport(ERROR,
21245 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21246 : : errmsg("cannot use generated column in partition key"),
21247 : : errdetail("Column \"%s\" is a generated column.",
21248 : : pelem->name),
21249 : : parser_errposition(pstate, pelem->location)));
21250 : :
21251 : 3581 : partattrs[attn] = attform->attnum;
21252 : 3581 : atttype = attform->atttypid;
21253 : 3581 : attcollation = attform->attcollation;
21254 : 3581 : ReleaseSysCache(atttuple);
21255 : : }
21256 : : else
21257 : : {
21258 : : /* Expression */
21259 : 246 : Node *expr = pelem->expr;
21260 : : char partattname[16];
21261 : 246 : Bitmapset *expr_attrs = NULL;
21262 : : int i;
21263 : :
21264 : : Assert(expr != NULL);
21265 : 246 : atttype = exprType(expr);
21266 : 246 : attcollation = exprCollation(expr);
21267 : :
21268 : : /*
21269 : : * The expression must be of a storable type (e.g., not RECORD).
21270 : : * The test is the same as for whether a table column is of a safe
21271 : : * type (which is why we needn't check for the non-expression
21272 : : * case).
21273 : : */
21274 : 246 : snprintf(partattname, sizeof(partattname), "%d", attn + 1);
21275 : 246 : CheckAttributeType(partattname,
21276 : : atttype, attcollation,
21277 : : NIL, CHKATYPE_IS_PARTKEY);
21278 : :
21279 : : /*
21280 : : * Strip any top-level COLLATE clause. This ensures that we treat
21281 : : * "x COLLATE y" and "(x COLLATE y)" alike.
21282 : : */
21283 [ - + ]: 238 : while (IsA(expr, CollateExpr))
21284 : 0 : expr = (Node *) ((CollateExpr *) expr)->arg;
21285 : :
21286 : : /*
21287 : : * Examine all the columns in the partition key expression. When
21288 : : * the whole-row reference is present, examine all the columns of
21289 : : * the partitioned table.
21290 : : */
21291 : 238 : pull_varattnos(expr, 1, &expr_attrs);
21292 [ + + ]: 238 : if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, expr_attrs))
21293 : : {
21294 : 48 : expr_attrs = bms_add_range(expr_attrs,
21295 : : 1 - FirstLowInvalidHeapAttributeNumber,
21296 : 24 : RelationGetNumberOfAttributes(rel) - FirstLowInvalidHeapAttributeNumber);
21297 : 24 : expr_attrs = bms_del_member(expr_attrs, 0 - FirstLowInvalidHeapAttributeNumber);
21298 : : }
21299 : :
21300 : 238 : i = -1;
21301 [ + + ]: 525 : while ((i = bms_next_member(expr_attrs, i)) >= 0)
21302 : : {
21303 : 319 : AttrNumber attno = i + FirstLowInvalidHeapAttributeNumber;
21304 : :
21305 : : Assert(attno != 0);
21306 : :
21307 : : /*
21308 : : * Cannot allow system column references, since that would
21309 : : * make partition routing impossible: their values won't be
21310 : : * known yet when we need to do that.
21311 : : */
21312 [ - + ]: 319 : if (attno < 0)
21313 [ # # ]: 0 : ereport(ERROR,
21314 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21315 : : errmsg("partition key expressions cannot contain system column references")));
21316 : :
21317 : : /*
21318 : : * Stored generated columns cannot work: They are computed
21319 : : * after BEFORE triggers, but partition routing is done before
21320 : : * all triggers. Virtual generated columns could probably
21321 : : * work, but it would require more work elsewhere (for example
21322 : : * SET EXPRESSION would need to check whether the column is
21323 : : * used in partition keys). Seems safer to prohibit for now.
21324 : : */
21325 [ + + ]: 319 : if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
21326 [ + - ]: 32 : ereport(ERROR,
21327 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21328 : : errmsg("cannot use generated column in partition key"),
21329 : : errdetail("Column \"%s\" is a generated column.",
21330 : : get_attname(RelationGetRelid(rel), attno, false)),
21331 : : parser_errposition(pstate, pelem->location)));
21332 : : }
21333 : :
21334 [ + + ]: 206 : if (IsA(expr, Var) &&
21335 [ + + ]: 12 : ((Var *) expr)->varattno > 0)
21336 : : {
21337 : :
21338 : : /*
21339 : : * User wrote "(column)" or "(column COLLATE something)".
21340 : : * Treat it like simple attribute anyway.
21341 : : */
21342 : 4 : partattrs[attn] = ((Var *) expr)->varattno;
21343 : : }
21344 : : else
21345 : : {
21346 : 202 : partattrs[attn] = 0; /* marks the column as expression */
21347 : 202 : *partexprs = lappend(*partexprs, expr);
21348 : :
21349 : : /*
21350 : : * transformPartitionSpec() should have already rejected
21351 : : * subqueries, aggregates, window functions, and SRFs, based
21352 : : * on the EXPR_KIND_ for partition expressions.
21353 : : */
21354 : :
21355 : : /*
21356 : : * Preprocess the expression before checking for mutability.
21357 : : * This is essential for the reasons described in
21358 : : * contain_mutable_functions_after_planning. However, we call
21359 : : * expression_planner for ourselves rather than using that
21360 : : * function, because if constant-folding reduces the
21361 : : * expression to a constant, we'd like to know that so we can
21362 : : * complain below.
21363 : : *
21364 : : * Like contain_mutable_functions_after_planning, assume that
21365 : : * expression_planner won't scribble on its input, so this
21366 : : * won't affect the partexprs entry we saved above.
21367 : : */
21368 : 202 : expr = (Node *) expression_planner((Expr *) expr);
21369 : :
21370 : : /*
21371 : : * Partition expressions cannot contain mutable functions,
21372 : : * because a given row must always map to the same partition
21373 : : * as long as there is no change in the partition boundary
21374 : : * structure.
21375 : : */
21376 [ + + ]: 202 : if (contain_mutable_functions(expr))
21377 [ + - ]: 4 : ereport(ERROR,
21378 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21379 : : errmsg("functions in partition key expression must be marked IMMUTABLE")));
21380 : :
21381 : : /*
21382 : : * While it is not exactly *wrong* for a partition expression
21383 : : * to be a constant, it seems better to reject such keys.
21384 : : */
21385 [ + + ]: 198 : if (IsA(expr, Const))
21386 [ + - ]: 8 : ereport(ERROR,
21387 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21388 : : errmsg("cannot use constant expression as partition key")));
21389 : : }
21390 : : }
21391 : :
21392 : : /*
21393 : : * Apply collation override if any
21394 : : */
21395 [ + + ]: 3775 : if (pelem->collation)
21396 : 36 : attcollation = get_collation_oid(pelem->collation, false);
21397 : :
21398 : : /*
21399 : : * Check we have a collation iff it's a collatable type. The only
21400 : : * expected failures here are (1) COLLATE applied to a noncollatable
21401 : : * type, or (2) partition expression had an unresolved collation. But
21402 : : * we might as well code this to be a complete consistency check.
21403 : : */
21404 [ + + ]: 3775 : if (type_is_collatable(atttype))
21405 : : {
21406 [ - + ]: 397 : if (!OidIsValid(attcollation))
21407 [ # # ]: 0 : ereport(ERROR,
21408 : : (errcode(ERRCODE_INDETERMINATE_COLLATION),
21409 : : errmsg("could not determine which collation to use for partition expression"),
21410 : : errhint("Use the COLLATE clause to set the collation explicitly.")));
21411 : : }
21412 : : else
21413 : : {
21414 [ - + ]: 3378 : if (OidIsValid(attcollation))
21415 [ # # ]: 0 : ereport(ERROR,
21416 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
21417 : : errmsg("collations are not supported by type %s",
21418 : : format_type_be(atttype))));
21419 : : }
21420 : :
21421 : 3775 : partcollation[attn] = attcollation;
21422 : :
21423 : : /*
21424 : : * Identify the appropriate operator class. For list and range
21425 : : * partitioning, we use a btree operator class; hash partitioning uses
21426 : : * a hash operator class.
21427 : : */
21428 [ + + ]: 3775 : if (strategy == PARTITION_STRATEGY_HASH)
21429 : 225 : am_oid = HASH_AM_OID;
21430 : : else
21431 : 3550 : am_oid = BTREE_AM_OID;
21432 : :
21433 [ + + ]: 3775 : if (!pelem->opclass)
21434 : : {
21435 : 3675 : partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
21436 : :
21437 [ + + ]: 3675 : if (!OidIsValid(partopclass[attn]))
21438 : : {
21439 [ - + ]: 8 : if (strategy == PARTITION_STRATEGY_HASH)
21440 [ # # ]: 0 : ereport(ERROR,
21441 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
21442 : : errmsg("data type %s has no default operator class for access method \"%s\"",
21443 : : format_type_be(atttype), "hash"),
21444 : : errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
21445 : : else
21446 [ + - ]: 8 : ereport(ERROR,
21447 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
21448 : : errmsg("data type %s has no default operator class for access method \"%s\"",
21449 : : format_type_be(atttype), "btree"),
21450 : : errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
21451 : : }
21452 : : }
21453 : : else
21454 [ + + ]: 100 : partopclass[attn] = ResolveOpClass(pelem->opclass,
21455 : : atttype,
21456 : : am_oid == HASH_AM_OID ? "hash" : "btree",
21457 : : am_oid);
21458 : :
21459 : 3759 : attn++;
21460 : : }
21461 : 3441 : }
21462 : :
21463 : : /*
21464 : : * PartConstraintImpliedByRelConstraint
21465 : : * Do scanrel's existing constraints imply the partition constraint?
21466 : : *
21467 : : * "Existing constraints" include its check constraints and column-level
21468 : : * not-null constraints. partConstraint describes the partition constraint,
21469 : : * in implicit-AND form.
21470 : : */
21471 : : bool
21472 : 2020 : PartConstraintImpliedByRelConstraint(Relation scanrel,
21473 : : List *partConstraint)
21474 : : {
21475 : 2020 : List *existConstraint = NIL;
21476 : 2020 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
21477 : : int i;
21478 : :
21479 [ + + + + ]: 2020 : if (constr && constr->has_not_null)
21480 : : {
21481 : 504 : int natts = scanrel->rd_att->natts;
21482 : :
21483 [ + + ]: 1678 : for (i = 1; i <= natts; i++)
21484 : : {
21485 : 1174 : CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
21486 : :
21487 : : /* invalid not-null constraint must be ignored here */
21488 [ + + + - ]: 1174 : if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
21489 : : {
21490 : 699 : Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
21491 : 699 : NullTest *ntest = makeNode(NullTest);
21492 : :
21493 : 699 : ntest->arg = (Expr *) makeVar(1,
21494 : : i,
21495 : : wholeatt->atttypid,
21496 : : wholeatt->atttypmod,
21497 : : wholeatt->attcollation,
21498 : : 0);
21499 : 699 : ntest->nulltesttype = IS_NOT_NULL;
21500 : :
21501 : : /*
21502 : : * argisrow=false is correct even for a composite column,
21503 : : * because attnotnull does not represent a SQL-spec IS NOT
21504 : : * NULL test in such a case, just IS DISTINCT FROM NULL.
21505 : : */
21506 : 699 : ntest->argisrow = false;
21507 : 699 : ntest->location = -1;
21508 : 699 : existConstraint = lappend(existConstraint, ntest);
21509 : : }
21510 : : }
21511 : : }
21512 : :
21513 : 2020 : return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
21514 : : }
21515 : :
21516 : : /*
21517 : : * ConstraintImpliedByRelConstraint
21518 : : * Do scanrel's existing constraints imply the given constraint?
21519 : : *
21520 : : * testConstraint is the constraint to validate. provenConstraint is a
21521 : : * caller-provided list of conditions which this function may assume
21522 : : * to be true. Both provenConstraint and testConstraint must be in
21523 : : * implicit-AND form, must only contain immutable clauses, and must
21524 : : * contain only Vars with varno = 1.
21525 : : */
21526 : : bool
21527 : 2868 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
21528 : : {
21529 : 2868 : List *existConstraint = list_copy(provenConstraint);
21530 : 2868 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
21531 : : int num_check,
21532 : : i;
21533 : :
21534 [ + + ]: 2868 : num_check = (constr != NULL) ? constr->num_check : 0;
21535 [ + + ]: 3208 : for (i = 0; i < num_check; i++)
21536 : : {
21537 : : Node *cexpr;
21538 : :
21539 : : /*
21540 : : * If this constraint hasn't been fully validated yet, we must ignore
21541 : : * it here.
21542 : : */
21543 [ + + ]: 340 : if (!constr->check[i].ccvalid)
21544 : 16 : continue;
21545 : :
21546 : : /*
21547 : : * NOT ENFORCED constraints are always marked as invalid, which should
21548 : : * have been ignored.
21549 : : */
21550 : : Assert(constr->check[i].ccenforced);
21551 : :
21552 : 324 : cexpr = stringToNode(constr->check[i].ccbin);
21553 : :
21554 : : /*
21555 : : * Run each expression through const-simplification and
21556 : : * canonicalization. It is necessary, because we will be comparing it
21557 : : * to similarly-processed partition constraint expressions, and may
21558 : : * fail to detect valid matches without this.
21559 : : */
21560 : 324 : cexpr = eval_const_expressions(NULL, cexpr);
21561 : 324 : cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
21562 : :
21563 : 324 : existConstraint = list_concat(existConstraint,
21564 : 324 : make_ands_implicit((Expr *) cexpr));
21565 : : }
21566 : :
21567 : : /*
21568 : : * Try to make the proof. Since we are comparing CHECK constraints, we
21569 : : * need to use weak implication, i.e., we assume existConstraint is
21570 : : * not-false and try to prove the same for testConstraint.
21571 : : *
21572 : : * Note that predicate_implied_by assumes its first argument is known
21573 : : * immutable. That should always be true for both NOT NULL and partition
21574 : : * constraints, so we don't test it here.
21575 : : */
21576 : 2868 : return predicate_implied_by(testConstraint, existConstraint, true);
21577 : : }
21578 : :
21579 : : /*
21580 : : * QueuePartitionConstraintValidation
21581 : : *
21582 : : * Add an entry to wqueue to have the given partition constraint validated by
21583 : : * Phase 3, for the given relation, and all its children.
21584 : : *
21585 : : * We first verify whether the given constraint is implied by pre-existing
21586 : : * relation constraints; if it is, there's no need to scan the table to
21587 : : * validate, so don't queue in that case.
21588 : : */
21589 : : static void
21590 : 1671 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
21591 : : List *partConstraint,
21592 : : bool validate_default)
21593 : : {
21594 : : /*
21595 : : * Based on the table's existing constraints, determine whether or not we
21596 : : * may skip scanning the table.
21597 : : */
21598 [ + + ]: 1671 : if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
21599 : : {
21600 [ + + ]: 55 : if (!validate_default)
21601 [ + + ]: 41 : ereport(DEBUG1,
21602 : : (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
21603 : : RelationGetRelationName(scanrel))));
21604 : : else
21605 [ + + ]: 14 : ereport(DEBUG1,
21606 : : (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
21607 : : RelationGetRelationName(scanrel))));
21608 : 55 : return;
21609 : : }
21610 : :
21611 : : /*
21612 : : * Constraints proved insufficient. For plain relations, queue a
21613 : : * validation item now; for partitioned tables, recurse to process each
21614 : : * partition.
21615 : : */
21616 [ + + ]: 1616 : if (scanrel->rd_rel->relkind == RELKIND_RELATION)
21617 : : {
21618 : : AlteredTableInfo *tab;
21619 : :
21620 : : /* Grab a work queue entry. */
21621 : 1353 : tab = ATGetQueueEntry(wqueue, scanrel);
21622 : : Assert(tab->partition_constraint == NULL);
21623 : 1353 : tab->partition_constraint = (Expr *) linitial(partConstraint);
21624 : 1353 : tab->validate_default = validate_default;
21625 : : }
21626 [ + + ]: 263 : else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21627 : : {
21628 : 232 : PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
21629 : : int i;
21630 : :
21631 [ + + ]: 488 : for (i = 0; i < partdesc->nparts; i++)
21632 : : {
21633 : : Relation part_rel;
21634 : : List *thisPartConstraint;
21635 : :
21636 : : /*
21637 : : * This is the minimum lock we need to prevent deadlocks.
21638 : : */
21639 : 256 : part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
21640 : :
21641 : : /*
21642 : : * Adjust the constraint for scanrel so that it matches this
21643 : : * partition's attribute numbers.
21644 : : */
21645 : : thisPartConstraint =
21646 : 256 : map_partition_varattnos(partConstraint, 1,
21647 : : part_rel, scanrel);
21648 : :
21649 : 256 : QueuePartitionConstraintValidation(wqueue, part_rel,
21650 : : thisPartConstraint,
21651 : : validate_default);
21652 : 256 : table_close(part_rel, NoLock); /* keep lock till commit */
21653 : : }
21654 : : }
21655 : : }
21656 : :
21657 : : /*
21658 : : * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
21659 : : *
21660 : : * Return the address of the newly attached partition.
21661 : : */
21662 : : static ObjectAddress
21663 : 1566 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
21664 : : AlterTableUtilityContext *context)
21665 : : {
21666 : : Relation attachrel,
21667 : : catalog;
21668 : : List *attachrel_children;
21669 : : List *partConstraint;
21670 : : SysScanDesc scan;
21671 : : ScanKeyData skey;
21672 : : AttrNumber attno;
21673 : : int natts;
21674 : : TupleDesc tupleDesc;
21675 : : ObjectAddress address;
21676 : : const char *trigger_name;
21677 : : Oid defaultPartOid;
21678 : : List *partBoundConstraint;
21679 : 1566 : List *exceptpuboids = NIL;
21680 : 1566 : ParseState *pstate = make_parsestate(NULL);
21681 : :
21682 : 1566 : pstate->p_sourcetext = context->queryString;
21683 : :
21684 : : /*
21685 : : * We must lock the default partition if one exists, because attaching a
21686 : : * new partition will change its partition constraint.
21687 : : */
21688 : : defaultPartOid =
21689 : 1566 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
21690 [ + + ]: 1566 : if (OidIsValid(defaultPartOid))
21691 : 117 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
21692 : :
21693 : 1566 : attachrel = table_openrv(cmd->name, AccessExclusiveLock);
21694 : :
21695 : : /*
21696 : : * XXX I think it'd be a good idea to grab locks on all tables referenced
21697 : : * by FKs at this point also.
21698 : : */
21699 : :
21700 : : /*
21701 : : * Must be owner of both parent and source table -- parent was checked by
21702 : : * ATSimplePermissions call in ATPrepCmd
21703 : : */
21704 : 1562 : ATSimplePermissions(AT_AttachPartition, attachrel,
21705 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
21706 : :
21707 : : /* A partition can only have one parent */
21708 [ + + ]: 1558 : if (attachrel->rd_rel->relispartition)
21709 [ + - ]: 4 : ereport(ERROR,
21710 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21711 : : errmsg("\"%s\" is already a partition",
21712 : : RelationGetRelationName(attachrel))));
21713 : :
21714 [ + + ]: 1554 : if (OidIsValid(attachrel->rd_rel->reloftype))
21715 [ + - ]: 4 : ereport(ERROR,
21716 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21717 : : errmsg("cannot attach a typed table as partition")));
21718 : :
21719 : : /*
21720 : : * Disallow attaching a partition if the table is referenced in a
21721 : : * publication EXCEPT clause. Changing the partition hierarchy could alter
21722 : : * the effective publication membership.
21723 : : */
21724 : 1550 : exceptpuboids = GetRelationExcludedPublications(RelationGetRelid(attachrel));
21725 [ + + ]: 1550 : if (exceptpuboids != NIL)
21726 : : {
21727 : 4 : bool first = true;
21728 : : StringInfoData pubnames;
21729 : :
21730 : 4 : initStringInfo(&pubnames);
21731 : :
21732 [ + - + + : 12 : foreach_oid(pubid, exceptpuboids)
+ + ]
21733 : : {
21734 : 4 : char *pubname = get_publication_name(pubid, false);
21735 : :
21736 [ + - ]: 4 : if (first)
21737 : 4 : appendStringInfo(&pubnames, _("\"%s\""), pubname);
21738 : : else
21739 : 0 : appendStringInfo(&pubnames, _(", \"%s\""), pubname);
21740 : 4 : first = false;
21741 : : }
21742 : :
21743 [ + - ]: 4 : ereport(ERROR,
21744 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21745 : : errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause",
21746 : : "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause",
21747 : : list_length(exceptpuboids),
21748 : : RelationGetRelationName(attachrel),
21749 : : pubnames.data),
21750 : : errdetail("The publication EXCEPT clause cannot contain tables that are partitions."),
21751 : : errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES."));
21752 : : }
21753 : :
21754 : 1546 : list_free(exceptpuboids);
21755 : :
21756 : : /*
21757 : : * Table being attached should not already be part of inheritance; either
21758 : : * as a child table...
21759 : : */
21760 : 1546 : catalog = table_open(InheritsRelationId, AccessShareLock);
21761 : 1546 : ScanKeyInit(&skey,
21762 : : Anum_pg_inherits_inhrelid,
21763 : : BTEqualStrategyNumber, F_OIDEQ,
21764 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21765 : 1546 : scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
21766 : : NULL, 1, &skey);
21767 [ + + ]: 1546 : if (HeapTupleIsValid(systable_getnext(scan)))
21768 [ + - ]: 4 : ereport(ERROR,
21769 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21770 : : errmsg("cannot attach inheritance child as partition")));
21771 : 1542 : systable_endscan(scan);
21772 : :
21773 : : /* ...or as a parent table (except the case when it is partitioned) */
21774 : 1542 : ScanKeyInit(&skey,
21775 : : Anum_pg_inherits_inhparent,
21776 : : BTEqualStrategyNumber, F_OIDEQ,
21777 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21778 : 1542 : scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
21779 : : 1, &skey);
21780 [ + + ]: 1542 : if (HeapTupleIsValid(systable_getnext(scan)) &&
21781 [ + + ]: 172 : attachrel->rd_rel->relkind == RELKIND_RELATION)
21782 [ + - ]: 4 : ereport(ERROR,
21783 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21784 : : errmsg("cannot attach inheritance parent as partition")));
21785 : 1538 : systable_endscan(scan);
21786 : 1538 : table_close(catalog, AccessShareLock);
21787 : :
21788 : : /*
21789 : : * Prevent circularity by seeing if rel is a partition of attachrel. (In
21790 : : * particular, this disallows making a rel a partition of itself.)
21791 : : *
21792 : : * We do that by checking if rel is a member of the list of attachrel's
21793 : : * partitions provided the latter is partitioned at all. We want to avoid
21794 : : * having to construct this list again, so we request the strongest lock
21795 : : * on all partitions. We need the strongest lock, because we may decide
21796 : : * to scan them if we find out that the table being attached (or its leaf
21797 : : * partitions) may contain rows that violate the partition constraint. If
21798 : : * the table has a constraint that would prevent such rows, which by
21799 : : * definition is present in all the partitions, we need not scan the
21800 : : * table, nor its partitions. But we cannot risk a deadlock by taking a
21801 : : * weaker lock now and the stronger one only when needed.
21802 : : */
21803 : 1538 : attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
21804 : : AccessExclusiveLock, NULL);
21805 [ + + ]: 1538 : if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
21806 [ + - ]: 8 : ereport(ERROR,
21807 : : (errcode(ERRCODE_DUPLICATE_TABLE),
21808 : : errmsg("circular inheritance not allowed"),
21809 : : errdetail("\"%s\" is already a child of \"%s\".",
21810 : : RelationGetRelationName(rel),
21811 : : RelationGetRelationName(attachrel))));
21812 : :
21813 : : /* If the parent is permanent, so must be all of its partitions. */
21814 [ + + ]: 1530 : if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
21815 [ + + ]: 1502 : attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
21816 [ + - ]: 4 : ereport(ERROR,
21817 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21818 : : errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
21819 : : RelationGetRelationName(rel))));
21820 : :
21821 : : /* Temp parent cannot have a partition that is itself not a temp */
21822 [ + + ]: 1526 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
21823 [ + + ]: 28 : attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
21824 [ + - ]: 12 : ereport(ERROR,
21825 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21826 : : errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
21827 : : RelationGetRelationName(rel))));
21828 : :
21829 : : /* If the parent is temp, it must belong to this session */
21830 [ + + - + ]: 1514 : if (RELATION_IS_OTHER_TEMP(rel))
21831 [ # # ]: 0 : ereport(ERROR,
21832 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21833 : : errmsg("cannot attach as partition of temporary relation of another session")));
21834 : :
21835 : : /* Ditto for the partition */
21836 [ + + - + ]: 1514 : if (RELATION_IS_OTHER_TEMP(attachrel))
21837 [ # # ]: 0 : ereport(ERROR,
21838 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21839 : : errmsg("cannot attach temporary relation of another session as partition")));
21840 : :
21841 : : /*
21842 : : * Check if attachrel has any identity columns or any columns that aren't
21843 : : * in the parent.
21844 : : */
21845 : 1514 : tupleDesc = RelationGetDescr(attachrel);
21846 : 1514 : natts = tupleDesc->natts;
21847 [ + + ]: 5137 : for (attno = 1; attno <= natts; attno++)
21848 : : {
21849 : 3651 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
21850 : 3651 : char *attributeName = NameStr(attribute->attname);
21851 : :
21852 : : /* Ignore dropped */
21853 [ + + ]: 3651 : if (attribute->attisdropped)
21854 : 368 : continue;
21855 : :
21856 [ + + ]: 3283 : if (attribute->attidentity)
21857 [ + - ]: 16 : ereport(ERROR,
21858 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21859 : : errmsg("table \"%s\" being attached contains an identity column \"%s\"",
21860 : : RelationGetRelationName(attachrel), attributeName),
21861 : : errdetail("The new partition may not contain an identity column."));
21862 : :
21863 : : /* Try to find the column in parent (matching on column name) */
21864 [ + + ]: 3267 : if (!SearchSysCacheExists2(ATTNAME,
21865 : : ObjectIdGetDatum(RelationGetRelid(rel)),
21866 : : CStringGetDatum(attributeName)))
21867 [ + - ]: 12 : ereport(ERROR,
21868 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
21869 : : errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
21870 : : RelationGetRelationName(attachrel), attributeName,
21871 : : RelationGetRelationName(rel)),
21872 : : errdetail("The new partition may contain only the columns present in parent.")));
21873 : : }
21874 : :
21875 : : /*
21876 : : * If child_rel has row-level triggers with transition tables, we
21877 : : * currently don't allow it to become a partition. See also prohibitions
21878 : : * in ATExecAddInherit() and CreateTrigger().
21879 : : */
21880 : 1486 : trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
21881 [ + + ]: 1486 : if (trigger_name != NULL)
21882 [ + - ]: 4 : ereport(ERROR,
21883 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
21884 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
21885 : : trigger_name, RelationGetRelationName(attachrel)),
21886 : : errdetail("ROW triggers with transition tables are not supported on partitions.")));
21887 : :
21888 : : /*
21889 : : * Check that the new partition's bound is valid and does not overlap any
21890 : : * of existing partitions of the parent - note that it does not return on
21891 : : * error.
21892 : : */
21893 : 1482 : check_new_partition_bound(RelationGetRelationName(attachrel), rel,
21894 : : cmd->bound, pstate);
21895 : :
21896 : : /* OK to create inheritance. Rest of the checks performed there */
21897 : 1458 : CreateInheritance(attachrel, rel, true);
21898 : :
21899 : : /* Update the pg_class entry. */
21900 : 1386 : StorePartitionBound(attachrel, rel, cmd->bound);
21901 : :
21902 : : /* Ensure there exists a correct set of indexes in the partition. */
21903 : 1386 : AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
21904 : :
21905 : : /* and triggers */
21906 : 1366 : CloneRowTriggersToPartition(rel, attachrel);
21907 : :
21908 : : /*
21909 : : * Clone foreign key constraints. Callee is responsible for setting up
21910 : : * for phase 3 constraint verification.
21911 : : */
21912 : 1362 : CloneForeignKeyConstraints(wqueue, rel, attachrel);
21913 : :
21914 : : /*
21915 : : * Generate partition constraint from the partition bound specification.
21916 : : * If the parent itself is a partition, make sure to include its
21917 : : * constraint as well.
21918 : : */
21919 : 1350 : partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
21920 : :
21921 : : /*
21922 : : * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
21923 : : * since it's needed later to construct the constraint expression for
21924 : : * validating against the default partition, if any.
21925 : : */
21926 : 1350 : partConstraint = list_concat_copy(partBoundConstraint,
21927 : 1350 : RelationGetPartitionQual(rel));
21928 : :
21929 : : /* Skip validation if there are no constraints to validate. */
21930 [ + + ]: 1350 : if (partConstraint)
21931 : : {
21932 : : /*
21933 : : * Run the partition quals through const-simplification similar to
21934 : : * check constraints. We skip canonicalize_qual, though, because
21935 : : * partition quals should be in canonical form already.
21936 : : */
21937 : : partConstraint =
21938 : 1322 : (List *) eval_const_expressions(NULL,
21939 : : (Node *) partConstraint);
21940 : :
21941 : : /* XXX this sure looks wrong */
21942 : 1322 : partConstraint = list_make1(make_ands_explicit(partConstraint));
21943 : :
21944 : : /*
21945 : : * Adjust the generated constraint to match this partition's attribute
21946 : : * numbers.
21947 : : */
21948 : 1322 : partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
21949 : : rel);
21950 : :
21951 : : /* Validate partition constraints against the table being attached. */
21952 : 1322 : QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
21953 : : false);
21954 : : }
21955 : :
21956 : : /*
21957 : : * If we're attaching a partition other than the default partition and a
21958 : : * default one exists, then that partition's partition constraint changes,
21959 : : * so add an entry to the work queue to validate it, too. (We must not do
21960 : : * this when the partition being attached is the default one; we already
21961 : : * did it above!)
21962 : : */
21963 [ + + ]: 1350 : if (OidIsValid(defaultPartOid))
21964 : : {
21965 : : Relation defaultrel;
21966 : : List *defPartConstraint;
21967 : :
21968 : : Assert(!cmd->bound->is_default);
21969 : :
21970 : : /* we already hold a lock on the default partition */
21971 : 93 : defaultrel = table_open(defaultPartOid, NoLock);
21972 : : defPartConstraint =
21973 : 93 : get_proposed_default_constraint(partBoundConstraint);
21974 : :
21975 : : /*
21976 : : * Map the Vars in the constraint expression from rel's attnos to
21977 : : * defaultrel's.
21978 : : */
21979 : : defPartConstraint =
21980 : 93 : map_partition_varattnos(defPartConstraint,
21981 : : 1, defaultrel, rel);
21982 : 93 : QueuePartitionConstraintValidation(wqueue, defaultrel,
21983 : : defPartConstraint, true);
21984 : :
21985 : : /* keep our lock until commit. */
21986 : 93 : table_close(defaultrel, NoLock);
21987 : : }
21988 : :
21989 : 1350 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
21990 : :
21991 : : /*
21992 : : * If the partition we just attached is partitioned itself, invalidate
21993 : : * relcache for all descendent partitions too to ensure that their
21994 : : * rd_partcheck expression trees are rebuilt; partitions already locked at
21995 : : * the beginning of this function.
21996 : : */
21997 [ + + ]: 1350 : if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21998 : : {
21999 : : ListCell *l;
22000 : :
22001 [ + - + + : 663 : foreach(l, attachrel_children)
+ + ]
22002 : : {
22003 : 446 : CacheInvalidateRelcacheByRelid(lfirst_oid(l));
22004 : : }
22005 : : }
22006 : :
22007 : : /* keep our lock until commit */
22008 : 1350 : table_close(attachrel, NoLock);
22009 : :
22010 : 1350 : return address;
22011 : : }
22012 : :
22013 : : /*
22014 : : * AttachPartitionEnsureIndexes
22015 : : * subroutine for ATExecAttachPartition to create/match indexes
22016 : : *
22017 : : * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
22018 : : * PARTITION: every partition must have an index attached to each index on the
22019 : : * partitioned table.
22020 : : */
22021 : : static void
22022 : 1386 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
22023 : : {
22024 : : List *idxes;
22025 : : List *attachRelIdxs;
22026 : : Relation *attachrelIdxRels;
22027 : : IndexInfo **attachInfos;
22028 : : ListCell *cell;
22029 : : MemoryContext cxt;
22030 : : MemoryContext oldcxt;
22031 : :
22032 : 1386 : cxt = AllocSetContextCreate(CurrentMemoryContext,
22033 : : "AttachPartitionEnsureIndexes",
22034 : : ALLOCSET_DEFAULT_SIZES);
22035 : 1386 : oldcxt = MemoryContextSwitchTo(cxt);
22036 : :
22037 : 1386 : idxes = RelationGetIndexList(rel);
22038 : 1386 : attachRelIdxs = RelationGetIndexList(attachrel);
22039 : 1386 : attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
22040 : 1386 : attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
22041 : :
22042 : : /* Build arrays of all existing indexes and their IndexInfos */
22043 [ + + + + : 3025 : foreach_oid(cldIdxId, attachRelIdxs)
+ + ]
22044 : : {
22045 : 253 : int i = foreach_current_index(cldIdxId);
22046 : :
22047 : 253 : attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
22048 : 253 : attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
22049 : : }
22050 : :
22051 : : /*
22052 : : * If we're attaching a foreign table, we must fail if any of the indexes
22053 : : * is a constraint index; otherwise, there's nothing to do here. Do this
22054 : : * before starting work, to avoid wasting the effort of building a few
22055 : : * non-unique indexes before coming across a unique one.
22056 : : */
22057 [ + + ]: 1386 : if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
22058 : : {
22059 [ + + + + : 55 : foreach(cell, idxes)
+ + ]
22060 : : {
22061 : 24 : Oid idx = lfirst_oid(cell);
22062 : 24 : Relation idxRel = index_open(idx, AccessShareLock);
22063 : :
22064 [ + + ]: 24 : if (idxRel->rd_index->indisunique ||
22065 [ - + ]: 16 : idxRel->rd_index->indisprimary)
22066 [ + - ]: 8 : ereport(ERROR,
22067 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
22068 : : errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
22069 : : RelationGetRelationName(attachrel),
22070 : : RelationGetRelationName(rel)),
22071 : : errdetail("Partitioned table \"%s\" contains unique indexes.",
22072 : : RelationGetRelationName(rel))));
22073 : 16 : index_close(idxRel, AccessShareLock);
22074 : : }
22075 : :
22076 : 31 : goto out;
22077 : : }
22078 : :
22079 : : /*
22080 : : * For each index on the partitioned table, find a matching one in the
22081 : : * partition-to-be; if one is not found, create one.
22082 : : */
22083 [ + + + + : 1632 : foreach(cell, idxes)
+ + ]
22084 : : {
22085 : 297 : Oid idx = lfirst_oid(cell);
22086 : 297 : Relation idxRel = index_open(idx, AccessShareLock);
22087 : : IndexInfo *info;
22088 : : AttrMap *attmap;
22089 : 297 : bool found = false;
22090 : : Oid constraintOid;
22091 : :
22092 : : /*
22093 : : * Ignore indexes in the partitioned table other than partitioned
22094 : : * indexes.
22095 : : */
22096 [ - + ]: 297 : if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
22097 : : {
22098 : 0 : index_close(idxRel, AccessShareLock);
22099 : 0 : continue;
22100 : : }
22101 : :
22102 : : /* construct an indexinfo to compare existing indexes against */
22103 : 297 : info = BuildIndexInfo(idxRel);
22104 : 297 : attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
22105 : : RelationGetDescr(rel),
22106 : : false);
22107 : 297 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
22108 : :
22109 : : /*
22110 : : * Scan the list of existing indexes in the partition-to-be, and mark
22111 : : * the first matching, valid, unattached one we find, if any, as
22112 : : * partition of the parent index. If we find one, we're done.
22113 : : */
22114 [ + + ]: 337 : for (int i = 0; i < list_length(attachRelIdxs); i++)
22115 : : {
22116 : 181 : Oid cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
22117 : 181 : Oid cldConstrOid = InvalidOid;
22118 : :
22119 : : /* does this index have a parent? if so, can't use it */
22120 [ + + ]: 181 : if (attachrelIdxRels[i]->rd_rel->relispartition)
22121 : 8 : continue;
22122 : :
22123 : : /* If this index is invalid, can't use it */
22124 [ + + ]: 173 : if (!attachrelIdxRels[i]->rd_index->indisvalid)
22125 : 4 : continue;
22126 : :
22127 [ + + ]: 169 : if (CompareIndexInfo(attachInfos[i], info,
22128 : 169 : attachrelIdxRels[i]->rd_indcollation,
22129 : 169 : idxRel->rd_indcollation,
22130 : 169 : attachrelIdxRels[i]->rd_opfamily,
22131 : 169 : idxRel->rd_opfamily,
22132 : : attmap))
22133 : : {
22134 : : /*
22135 : : * If this index is being created in the parent because of a
22136 : : * constraint, then the child needs to have a constraint also,
22137 : : * so look for one. If there is no such constraint, this
22138 : : * index is no good, so keep looking.
22139 : : */
22140 [ + + ]: 145 : if (OidIsValid(constraintOid))
22141 : : {
22142 : : cldConstrOid =
22143 : 80 : get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
22144 : : cldIdxId);
22145 : : /* no dice */
22146 [ + + ]: 80 : if (!OidIsValid(cldConstrOid))
22147 : 4 : continue;
22148 : :
22149 : : /* Ensure they're both the same type of constraint */
22150 [ - + ]: 152 : if (get_constraint_type(constraintOid) !=
22151 : 76 : get_constraint_type(cldConstrOid))
22152 : 0 : continue;
22153 : : }
22154 : :
22155 : : /* bingo. */
22156 : 141 : IndexSetParentIndex(attachrelIdxRels[i], idx);
22157 [ + + ]: 141 : if (OidIsValid(constraintOid))
22158 : 76 : ConstraintSetParentConstraint(cldConstrOid, constraintOid,
22159 : : RelationGetRelid(attachrel));
22160 : 141 : found = true;
22161 : :
22162 : 141 : CommandCounterIncrement();
22163 : 141 : break;
22164 : : }
22165 : : }
22166 : :
22167 : : /*
22168 : : * If no suitable index was found in the partition-to-be, create one
22169 : : * now. Note that if this is a PK, not-null constraints must already
22170 : : * exist.
22171 : : */
22172 [ + + ]: 297 : if (!found)
22173 : : {
22174 : : IndexStmt *stmt;
22175 : : Oid conOid;
22176 : :
22177 : 156 : stmt = generateClonedIndexStmt(NULL,
22178 : : idxRel, attmap,
22179 : : &conOid);
22180 : 156 : DefineIndex(NULL,
22181 : : RelationGetRelid(attachrel), stmt, InvalidOid,
22182 : : RelationGetRelid(idxRel),
22183 : : conOid,
22184 : : -1,
22185 : : true, false, false, false, false);
22186 : : }
22187 : :
22188 : 285 : index_close(idxRel, AccessShareLock);
22189 : : }
22190 : :
22191 : 1366 : out:
22192 : : /* Clean up. */
22193 [ + + ]: 1611 : for (int i = 0; i < list_length(attachRelIdxs); i++)
22194 : 245 : index_close(attachrelIdxRels[i], AccessShareLock);
22195 : 1366 : MemoryContextSwitchTo(oldcxt);
22196 : 1366 : MemoryContextDelete(cxt);
22197 : 1366 : }
22198 : :
22199 : : /*
22200 : : * CloneRowTriggersToPartition
22201 : : * subroutine for ATExecAttachPartition/DefineRelation to create row
22202 : : * triggers on partitions
22203 : : */
22204 : : static void
22205 : 1598 : CloneRowTriggersToPartition(Relation parent, Relation partition)
22206 : : {
22207 : : Relation pg_trigger;
22208 : : ScanKeyData key;
22209 : : SysScanDesc scan;
22210 : : HeapTuple tuple;
22211 : : MemoryContext perTupCxt;
22212 : :
22213 : 1598 : ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
22214 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
22215 : 1598 : pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
22216 : 1598 : scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
22217 : : true, NULL, 1, &key);
22218 : :
22219 : 1598 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
22220 : : "clone trig", ALLOCSET_SMALL_SIZES);
22221 : :
22222 [ + + ]: 2655 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
22223 : : {
22224 : 1061 : Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
22225 : : CreateTrigStmt *trigStmt;
22226 : 1061 : Node *qual = NULL;
22227 : : Datum value;
22228 : : bool isnull;
22229 : 1061 : List *cols = NIL;
22230 : 1061 : List *trigargs = NIL;
22231 : : MemoryContext oldcxt;
22232 : :
22233 : : /*
22234 : : * Ignore statement-level triggers; those are not cloned.
22235 : : */
22236 [ + + ]: 1061 : if (!TRIGGER_FOR_ROW(trigForm->tgtype))
22237 : 958 : continue;
22238 : :
22239 : : /*
22240 : : * Don't clone internal triggers, because the constraint cloning code
22241 : : * will.
22242 : : */
22243 [ + + ]: 1049 : if (trigForm->tgisinternal)
22244 : 946 : continue;
22245 : :
22246 : : /*
22247 : : * Complain if we find an unexpected trigger type.
22248 : : */
22249 [ + + ]: 103 : if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
22250 [ - + ]: 91 : !TRIGGER_FOR_AFTER(trigForm->tgtype))
22251 [ # # ]: 0 : elog(ERROR, "unexpected trigger \"%s\" found",
22252 : : NameStr(trigForm->tgname));
22253 : :
22254 : : /* Use short-lived context for CREATE TRIGGER */
22255 : 103 : oldcxt = MemoryContextSwitchTo(perTupCxt);
22256 : :
22257 : : /*
22258 : : * If there is a WHEN clause, generate a 'cooked' version of it that's
22259 : : * appropriate for the partition.
22260 : : */
22261 : 103 : value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
22262 : : RelationGetDescr(pg_trigger), &isnull);
22263 [ + + ]: 103 : if (!isnull)
22264 : : {
22265 : 4 : qual = stringToNode(TextDatumGetCString(value));
22266 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
22267 : : partition, parent);
22268 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
22269 : : partition, parent);
22270 : : }
22271 : :
22272 : : /*
22273 : : * If there is a column list, transform it to a list of column names.
22274 : : * Note we don't need to map this list in any way ...
22275 : : */
22276 [ + + ]: 103 : if (trigForm->tgattr.dim1 > 0)
22277 : : {
22278 : : int i;
22279 : :
22280 [ + + ]: 8 : for (i = 0; i < trigForm->tgattr.dim1; i++)
22281 : : {
22282 : : Form_pg_attribute col;
22283 : :
22284 : 4 : col = TupleDescAttr(parent->rd_att,
22285 : 4 : trigForm->tgattr.values[i] - 1);
22286 : 4 : cols = lappend(cols,
22287 : 4 : makeString(pstrdup(NameStr(col->attname))));
22288 : : }
22289 : : }
22290 : :
22291 : : /* Reconstruct trigger arguments list. */
22292 [ + + ]: 103 : if (trigForm->tgnargs > 0)
22293 : : {
22294 : : char *p;
22295 : :
22296 : 8 : value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
22297 : : RelationGetDescr(pg_trigger), &isnull);
22298 [ - + ]: 8 : if (isnull)
22299 [ # # ]: 0 : elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
22300 : : NameStr(trigForm->tgname), RelationGetRelationName(partition));
22301 : :
22302 : 8 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
22303 : :
22304 [ + + ]: 24 : for (int i = 0; i < trigForm->tgnargs; i++)
22305 : : {
22306 : 16 : trigargs = lappend(trigargs, makeString(pstrdup(p)));
22307 : 16 : p += strlen(p) + 1;
22308 : : }
22309 : : }
22310 : :
22311 : 103 : trigStmt = makeNode(CreateTrigStmt);
22312 : 103 : trigStmt->replace = false;
22313 : 103 : trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
22314 : 103 : trigStmt->trigname = NameStr(trigForm->tgname);
22315 : 103 : trigStmt->relation = NULL;
22316 : 103 : trigStmt->funcname = NULL; /* passed separately */
22317 : 103 : trigStmt->args = trigargs;
22318 : 103 : trigStmt->row = true;
22319 : 103 : trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
22320 : 103 : trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
22321 : 103 : trigStmt->columns = cols;
22322 : 103 : trigStmt->whenClause = NULL; /* passed separately */
22323 : 103 : trigStmt->transitionRels = NIL; /* not supported at present */
22324 : 103 : trigStmt->deferrable = trigForm->tgdeferrable;
22325 : 103 : trigStmt->initdeferred = trigForm->tginitdeferred;
22326 : 103 : trigStmt->constrrel = NULL; /* passed separately */
22327 : :
22328 : 103 : CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
22329 : : trigForm->tgconstrrelid, InvalidOid, InvalidOid,
22330 : : trigForm->tgfoid, trigForm->oid, qual,
22331 : 103 : false, true, trigForm->tgenabled);
22332 : :
22333 : 99 : MemoryContextSwitchTo(oldcxt);
22334 : 99 : MemoryContextReset(perTupCxt);
22335 : : }
22336 : :
22337 : 1594 : MemoryContextDelete(perTupCxt);
22338 : :
22339 : 1594 : systable_endscan(scan);
22340 : 1594 : table_close(pg_trigger, RowExclusiveLock);
22341 : 1594 : }
22342 : :
22343 : : /*
22344 : : * ALTER TABLE DETACH PARTITION
22345 : : *
22346 : : * Return the address of the relation that is no longer a partition of rel.
22347 : : *
22348 : : * If concurrent mode is requested, we run in two transactions. A side-
22349 : : * effect is that this command cannot run in a multi-part ALTER TABLE.
22350 : : * Currently, that's enforced by the grammar.
22351 : : *
22352 : : * The strategy for concurrency is to first modify the partition's
22353 : : * pg_inherit catalog row to make it visible to everyone that the
22354 : : * partition is detached, lock the partition against writes, and commit
22355 : : * the transaction; anyone who requests the partition descriptor from
22356 : : * that point onwards has to ignore such a partition. In a second
22357 : : * transaction, we wait until all transactions that could have seen the
22358 : : * partition as attached are gone, then we remove the rest of partition
22359 : : * metadata (pg_inherits and pg_class.relpartbounds).
22360 : : */
22361 : : static ObjectAddress
22362 : 363 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
22363 : : RangeVar *name, bool concurrent)
22364 : : {
22365 : : Relation partRel;
22366 : : ObjectAddress address;
22367 : : Oid defaultPartOid;
22368 : :
22369 : : /*
22370 : : * We must lock the default partition, because detaching this partition
22371 : : * will change its partition constraint.
22372 : : */
22373 : : defaultPartOid =
22374 : 363 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
22375 [ + + ]: 363 : if (OidIsValid(defaultPartOid))
22376 : : {
22377 : : /*
22378 : : * Concurrent detaching when a default partition exists is not
22379 : : * supported. The main problem is that the default partition
22380 : : * constraint would change. And there's a definitional problem: what
22381 : : * should happen to the tuples that are being inserted that belong to
22382 : : * the partition being detached? Putting them on the partition being
22383 : : * detached would be wrong, since they'd become "lost" after the
22384 : : * detaching completes but we cannot put them in the default partition
22385 : : * either until we alter its partition constraint.
22386 : : *
22387 : : * I think we could solve this problem if we effected the constraint
22388 : : * change before committing the first transaction. But the lock would
22389 : : * have to remain AEL and it would cause concurrent query planning to
22390 : : * be blocked, so changing it that way would be even worse.
22391 : : */
22392 [ + + ]: 70 : if (concurrent)
22393 [ + - ]: 8 : ereport(ERROR,
22394 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22395 : : errmsg("cannot detach partitions concurrently when a default partition exists")));
22396 : 62 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
22397 : : }
22398 : :
22399 : : /*
22400 : : * In concurrent mode, the partition is locked with share-update-exclusive
22401 : : * in the first transaction. This allows concurrent transactions to be
22402 : : * doing DML to the partition.
22403 : : */
22404 [ + + ]: 355 : partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
22405 : : AccessExclusiveLock);
22406 : :
22407 : : /*
22408 : : * Check inheritance conditions and either delete the pg_inherits row (in
22409 : : * non-concurrent mode) or just set the inhdetachpending flag.
22410 : : */
22411 [ + + ]: 347 : if (!concurrent)
22412 : 270 : RemoveInheritance(partRel, rel, false);
22413 : : else
22414 : 77 : MarkInheritDetached(partRel, rel);
22415 : :
22416 : : /*
22417 : : * Ensure that foreign keys still hold after this detach. This keeps
22418 : : * locks on the referencing tables, which prevents concurrent transactions
22419 : : * from adding rows that we wouldn't see. For this to work in concurrent
22420 : : * mode, it is critical that the partition appears as no longer attached
22421 : : * for the RI queries as soon as the first transaction commits.
22422 : : */
22423 : 334 : ATDetachCheckNoForeignKeyRefs(partRel);
22424 : :
22425 : : /*
22426 : : * Concurrent mode has to work harder; first we add a new constraint to
22427 : : * the partition that matches the partition constraint. Then we close our
22428 : : * existing transaction, and in a new one wait for all processes to catch
22429 : : * up on the catalog updates we've done so far; at that point we can
22430 : : * complete the operation.
22431 : : */
22432 [ + + ]: 312 : if (concurrent)
22433 : : {
22434 : : Oid partrelid,
22435 : : parentrelid;
22436 : : LOCKTAG tag;
22437 : : char *parentrelname;
22438 : : char *partrelname;
22439 : :
22440 : : /*
22441 : : * We're almost done now; the only traces that remain are the
22442 : : * pg_inherits tuple and the partition's relpartbounds. Before we can
22443 : : * remove those, we need to wait until all transactions that know that
22444 : : * this is a partition are gone.
22445 : : */
22446 : :
22447 : : /*
22448 : : * Remember relation OIDs to re-acquire them later; and relation names
22449 : : * too, for error messages if something is dropped in between.
22450 : : */
22451 : 74 : partrelid = RelationGetRelid(partRel);
22452 : 74 : parentrelid = RelationGetRelid(rel);
22453 : 74 : parentrelname = MemoryContextStrdup(PortalContext,
22454 : 74 : RelationGetRelationName(rel));
22455 : 74 : partrelname = MemoryContextStrdup(PortalContext,
22456 : 74 : RelationGetRelationName(partRel));
22457 : :
22458 : : /* Invalidate relcache entries for the parent -- must be before close */
22459 : 74 : CacheInvalidateRelcache(rel);
22460 : :
22461 : 74 : table_close(partRel, NoLock);
22462 : 74 : table_close(rel, NoLock);
22463 : 74 : tab->rel = NULL;
22464 : :
22465 : : /* Make updated catalog entry visible */
22466 : 74 : PopActiveSnapshot();
22467 : 74 : CommitTransactionCommand();
22468 : :
22469 : 74 : StartTransactionCommand();
22470 : :
22471 : : /*
22472 : : * Now wait. This ensures that all queries that were planned
22473 : : * including the partition are finished before we remove the rest of
22474 : : * catalog entries. We don't need or indeed want to acquire this
22475 : : * lock, though -- that would block later queries.
22476 : : *
22477 : : * We don't need to concern ourselves with waiting for a lock on the
22478 : : * partition itself, since we will acquire AccessExclusiveLock below.
22479 : : */
22480 : 74 : SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
22481 : 74 : WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
22482 : :
22483 : : /*
22484 : : * Now acquire locks in both relations again. Note they may have been
22485 : : * removed in the meantime, so care is required.
22486 : : */
22487 : 47 : rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
22488 : 47 : partRel = try_relation_open(partrelid, AccessExclusiveLock);
22489 : :
22490 : : /* If the relations aren't there, something bad happened; bail out */
22491 [ - + ]: 47 : if (rel == NULL)
22492 : : {
22493 [ # # ]: 0 : if (partRel != NULL) /* shouldn't happen */
22494 [ # # ]: 0 : elog(WARNING, "dangling partition \"%s\" remains, can't fix",
22495 : : partrelname);
22496 [ # # ]: 0 : ereport(ERROR,
22497 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22498 : : errmsg("partitioned table \"%s\" was removed concurrently",
22499 : : parentrelname)));
22500 : : }
22501 [ - + ]: 47 : if (partRel == NULL)
22502 [ # # ]: 0 : ereport(ERROR,
22503 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22504 : : errmsg("partition \"%s\" was removed concurrently", partrelname)));
22505 : :
22506 : 47 : tab->rel = rel;
22507 : : }
22508 : :
22509 : : /*
22510 : : * Detaching the partition might involve TOAST table access, so ensure we
22511 : : * have a valid snapshot.
22512 : : */
22513 : 285 : PushActiveSnapshot(GetTransactionSnapshot());
22514 : :
22515 : : /* Do the final part of detaching */
22516 : 285 : DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
22517 : :
22518 : 284 : PopActiveSnapshot();
22519 : :
22520 : 284 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
22521 : :
22522 : : /* keep our lock until commit */
22523 : 284 : table_close(partRel, NoLock);
22524 : :
22525 : 284 : return address;
22526 : : }
22527 : :
22528 : : /*
22529 : : * Second part of ALTER TABLE .. DETACH.
22530 : : *
22531 : : * This is separate so that it can be run independently when the second
22532 : : * transaction of the concurrent algorithm fails (crash or abort).
22533 : : */
22534 : : static void
22535 : 292 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
22536 : : Oid defaultPartOid)
22537 : : {
22538 : : Relation classRel;
22539 : : List *fks;
22540 : : ListCell *cell;
22541 : : List *indexes;
22542 : : Datum new_val[Natts_pg_class];
22543 : : bool new_null[Natts_pg_class],
22544 : : new_repl[Natts_pg_class];
22545 : : HeapTuple tuple,
22546 : : newtuple;
22547 : 292 : Relation trigrel = NULL;
22548 : 292 : List *fkoids = NIL;
22549 : :
22550 [ + + ]: 292 : if (concurrent)
22551 : : {
22552 : : /*
22553 : : * We can remove the pg_inherits row now. (In the non-concurrent case,
22554 : : * this was already done).
22555 : : */
22556 : 54 : RemoveInheritance(partRel, rel, true);
22557 : : }
22558 : :
22559 : : /* Drop any triggers that were cloned on creation/attach. */
22560 : 292 : DropClonedTriggersFromPartition(RelationGetRelid(partRel));
22561 : :
22562 : : /*
22563 : : * Detach any foreign keys that are inherited. This includes creating
22564 : : * additional action triggers.
22565 : : */
22566 : 292 : fks = copyObject(RelationGetFKeyList(partRel));
22567 [ + + ]: 292 : if (fks != NIL)
22568 : 56 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
22569 : :
22570 : : /*
22571 : : * It's possible that the partition being detached has a foreign key that
22572 : : * references a partitioned table. When that happens, there are multiple
22573 : : * pg_constraint rows for the partition: one points to the partitioned
22574 : : * table itself, while the others point to each of its partitions. Only
22575 : : * the topmost one is to be considered here; the child constraints must be
22576 : : * left alone, because conceptually those aren't coming from our parent
22577 : : * partitioned table, but from this partition itself.
22578 : : *
22579 : : * We implement this by collecting all the constraint OIDs in a first scan
22580 : : * of the FK array, and skipping in the loop below those constraints whose
22581 : : * parents are listed here.
22582 : : */
22583 [ + + + + : 696 : foreach_node(ForeignKeyCacheInfo, fk, fks)
+ + ]
22584 : 112 : fkoids = lappend_oid(fkoids, fk->conoid);
22585 : :
22586 [ + + + + : 404 : foreach(cell, fks)
+ + ]
22587 : : {
22588 : 112 : ForeignKeyCacheInfo *fk = lfirst(cell);
22589 : : HeapTuple contup;
22590 : : Form_pg_constraint conform;
22591 : :
22592 : 112 : contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
22593 [ - + ]: 112 : if (!HeapTupleIsValid(contup))
22594 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
22595 : 112 : conform = (Form_pg_constraint) GETSTRUCT(contup);
22596 : :
22597 : : /*
22598 : : * Consider only inherited foreign keys, and only if their parents
22599 : : * aren't in the list.
22600 : : */
22601 [ + - ]: 112 : if (conform->contype != CONSTRAINT_FOREIGN ||
22602 [ + + + + ]: 208 : !OidIsValid(conform->conparentid) ||
22603 : 96 : list_member_oid(fkoids, conform->conparentid))
22604 : : {
22605 : 44 : ReleaseSysCache(contup);
22606 : 44 : continue;
22607 : : }
22608 : :
22609 : : /*
22610 : : * The constraint on this table must be marked no longer a child of
22611 : : * the parent's constraint, as do its check triggers.
22612 : : */
22613 : 68 : ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
22614 : :
22615 : : /*
22616 : : * Also, look up the partition's "check" triggers corresponding to the
22617 : : * ENFORCED constraint being detached and detach them from the parent
22618 : : * triggers. NOT ENFORCED constraints do not have these triggers;
22619 : : * therefore, this step is not needed.
22620 : : */
22621 [ + - ]: 68 : if (fk->conenforced)
22622 : : {
22623 : : Oid insertTriggerOid,
22624 : : updateTriggerOid;
22625 : :
22626 : 68 : GetForeignKeyCheckTriggers(trigrel,
22627 : : fk->conoid, fk->confrelid, fk->conrelid,
22628 : : &insertTriggerOid, &updateTriggerOid);
22629 : : Assert(OidIsValid(insertTriggerOid));
22630 : 68 : TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
22631 : : RelationGetRelid(partRel));
22632 : : Assert(OidIsValid(updateTriggerOid));
22633 : 68 : TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
22634 : : RelationGetRelid(partRel));
22635 : : }
22636 : :
22637 : : /*
22638 : : * Lastly, create the action triggers on the referenced table, using
22639 : : * addFkRecurseReferenced, which requires some elaborate setup (so put
22640 : : * it in a separate block). While at it, if the table is partitioned,
22641 : : * that function will recurse to create the pg_constraint rows and
22642 : : * action triggers for each partition.
22643 : : *
22644 : : * Note there's no need to do addFkConstraint() here, because the
22645 : : * pg_constraint row already exists.
22646 : : */
22647 : : {
22648 : : Constraint *fkconstraint;
22649 : : int numfks;
22650 : : AttrNumber conkey[INDEX_MAX_KEYS];
22651 : : AttrNumber confkey[INDEX_MAX_KEYS];
22652 : : Oid conpfeqop[INDEX_MAX_KEYS];
22653 : : Oid conppeqop[INDEX_MAX_KEYS];
22654 : : Oid conffeqop[INDEX_MAX_KEYS];
22655 : : int numfkdelsetcols;
22656 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
22657 : : Relation refdRel;
22658 : :
22659 : 68 : DeconstructFkConstraintRow(contup,
22660 : : &numfks,
22661 : : conkey,
22662 : : confkey,
22663 : : conpfeqop,
22664 : : conppeqop,
22665 : : conffeqop,
22666 : : &numfkdelsetcols,
22667 : : confdelsetcols);
22668 : :
22669 : : /* Create a synthetic node we'll use throughout */
22670 : 68 : fkconstraint = makeNode(Constraint);
22671 : 68 : fkconstraint->contype = CONSTRAINT_FOREIGN;
22672 : 68 : fkconstraint->conname = pstrdup(NameStr(conform->conname));
22673 : 68 : fkconstraint->deferrable = conform->condeferrable;
22674 : 68 : fkconstraint->initdeferred = conform->condeferred;
22675 : 68 : fkconstraint->is_enforced = conform->conenforced;
22676 : 68 : fkconstraint->skip_validation = true;
22677 : 68 : fkconstraint->initially_valid = conform->convalidated;
22678 : : /* a few irrelevant fields omitted here */
22679 : 68 : fkconstraint->pktable = NULL;
22680 : 68 : fkconstraint->fk_attrs = NIL;
22681 : 68 : fkconstraint->pk_attrs = NIL;
22682 : 68 : fkconstraint->fk_matchtype = conform->confmatchtype;
22683 : 68 : fkconstraint->fk_upd_action = conform->confupdtype;
22684 : 68 : fkconstraint->fk_del_action = conform->confdeltype;
22685 : 68 : fkconstraint->fk_del_set_cols = NIL;
22686 : 68 : fkconstraint->old_conpfeqop = NIL;
22687 : 68 : fkconstraint->old_pktable_oid = InvalidOid;
22688 : 68 : fkconstraint->location = -1;
22689 : :
22690 : : /* set up colnames, used to generate the constraint name */
22691 [ + + ]: 168 : for (int i = 0; i < numfks; i++)
22692 : : {
22693 : : Form_pg_attribute att;
22694 : :
22695 : 100 : att = TupleDescAttr(RelationGetDescr(partRel),
22696 : 100 : conkey[i] - 1);
22697 : :
22698 : 100 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
22699 : 100 : makeString(NameStr(att->attname)));
22700 : : }
22701 : :
22702 : 68 : refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
22703 : :
22704 : 68 : addFkRecurseReferenced(fkconstraint, partRel,
22705 : : refdRel,
22706 : : conform->conindid,
22707 : : fk->conoid,
22708 : : numfks,
22709 : : confkey,
22710 : : conkey,
22711 : : conpfeqop,
22712 : : conppeqop,
22713 : : conffeqop,
22714 : : numfkdelsetcols,
22715 : : confdelsetcols,
22716 : : true,
22717 : : InvalidOid, InvalidOid,
22718 : 68 : conform->conperiod);
22719 : 68 : table_close(refdRel, NoLock); /* keep lock till end of xact */
22720 : : }
22721 : :
22722 : 68 : ReleaseSysCache(contup);
22723 : : }
22724 : 292 : list_free_deep(fks);
22725 [ + + ]: 292 : if (trigrel)
22726 : 56 : table_close(trigrel, RowExclusiveLock);
22727 : :
22728 : : /*
22729 : : * Any sub-constraints that are in the referenced-side of a larger
22730 : : * constraint have to be removed. This partition is no longer part of the
22731 : : * key space of the constraint.
22732 : : */
22733 [ + + + + : 327 : foreach(cell, GetParentedForeignKeyRefs(partRel))
+ + ]
22734 : : {
22735 : 36 : Oid constrOid = lfirst_oid(cell);
22736 : : ObjectAddress constraint;
22737 : :
22738 : 36 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22739 : 36 : deleteDependencyRecordsForClass(ConstraintRelationId,
22740 : : constrOid,
22741 : : ConstraintRelationId,
22742 : : DEPENDENCY_INTERNAL);
22743 : 36 : CommandCounterIncrement();
22744 : :
22745 : 36 : ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
22746 : 36 : performDeletion(&constraint, DROP_RESTRICT, 0);
22747 : : }
22748 : :
22749 : : /* Now we can detach indexes */
22750 : 291 : indexes = RelationGetIndexList(partRel);
22751 [ + + + + : 415 : foreach(cell, indexes)
+ + ]
22752 : : {
22753 : 124 : Oid idxid = lfirst_oid(cell);
22754 : : Oid parentidx;
22755 : : Relation idx;
22756 : : Oid constrOid;
22757 : : Oid parentConstrOid;
22758 : :
22759 [ + + ]: 124 : if (!has_superclass(idxid))
22760 : 8 : continue;
22761 : :
22762 : 116 : parentidx = get_partition_parent(idxid, false);
22763 : : Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
22764 : :
22765 : 116 : idx = index_open(idxid, AccessExclusiveLock);
22766 : 116 : IndexSetParentIndex(idx, InvalidOid);
22767 : :
22768 : : /*
22769 : : * If there's a constraint associated with the index, detach it too.
22770 : : * Careful: it is possible for a constraint index in a partition to be
22771 : : * the child of a non-constraint index, so verify whether the parent
22772 : : * index does actually have a constraint.
22773 : : */
22774 : 116 : constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
22775 : : idxid);
22776 : 116 : parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
22777 : : parentidx);
22778 [ + + + - ]: 116 : if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
22779 : 51 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22780 : :
22781 : 116 : index_close(idx, NoLock);
22782 : : }
22783 : :
22784 : : /* Update pg_class tuple */
22785 : 291 : classRel = table_open(RelationRelationId, RowExclusiveLock);
22786 : 291 : tuple = SearchSysCacheCopy1(RELOID,
22787 : : ObjectIdGetDatum(RelationGetRelid(partRel)));
22788 [ - + ]: 291 : if (!HeapTupleIsValid(tuple))
22789 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u",
22790 : : RelationGetRelid(partRel));
22791 : : Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
22792 : :
22793 : : /* Clear relpartbound and reset relispartition */
22794 : 291 : memset(new_val, 0, sizeof(new_val));
22795 : 291 : memset(new_null, false, sizeof(new_null));
22796 : 291 : memset(new_repl, false, sizeof(new_repl));
22797 : 291 : new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
22798 : 291 : new_null[Anum_pg_class_relpartbound - 1] = true;
22799 : 291 : new_repl[Anum_pg_class_relpartbound - 1] = true;
22800 : 291 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
22801 : : new_val, new_null, new_repl);
22802 : :
22803 : 291 : ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
22804 : 291 : CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
22805 : 291 : heap_freetuple(newtuple);
22806 : 291 : table_close(classRel, RowExclusiveLock);
22807 : :
22808 : : /*
22809 : : * Drop identity property from all identity columns of partition.
22810 : : */
22811 [ + + ]: 840 : for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
22812 : : {
22813 : 549 : Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
22814 : :
22815 [ + + + + ]: 549 : if (!attr->attisdropped && attr->attidentity)
22816 : 4 : ATExecDropIdentity(partRel, NameStr(attr->attname), false,
22817 : : AccessExclusiveLock, true, true);
22818 : : }
22819 : :
22820 [ + + ]: 291 : if (OidIsValid(defaultPartOid))
22821 : : {
22822 : : /*
22823 : : * If the relation being detached is the default partition itself,
22824 : : * remove it from the parent's pg_partitioned_table entry.
22825 : : *
22826 : : * If not, we must invalidate default partition's relcache entry, as
22827 : : * in StorePartitionBound: its partition constraint depends on every
22828 : : * other partition's partition constraint.
22829 : : */
22830 [ + + ]: 30 : if (RelationGetRelid(partRel) == defaultPartOid)
22831 : 1 : update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
22832 : : else
22833 : 29 : CacheInvalidateRelcacheByRelid(defaultPartOid);
22834 : : }
22835 : :
22836 : : /*
22837 : : * Invalidate the parent's relcache so that the partition is no longer
22838 : : * included in its partition descriptor.
22839 : : */
22840 : 291 : CacheInvalidateRelcache(rel);
22841 : :
22842 : : /*
22843 : : * If the partition we just detached is partitioned itself, invalidate
22844 : : * relcache for all descendent partitions too to ensure that their
22845 : : * rd_partcheck expression trees are rebuilt; must lock partitions before
22846 : : * doing so, using the same lockmode as what partRel has been locked with
22847 : : * by the caller.
22848 : : */
22849 [ + + ]: 291 : if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
22850 : : {
22851 : : List *children;
22852 : :
22853 : 41 : children = find_all_inheritors(RelationGetRelid(partRel),
22854 : : AccessExclusiveLock, NULL);
22855 [ + - + + : 135 : foreach(cell, children)
+ + ]
22856 : : {
22857 : 94 : CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
22858 : : }
22859 : : }
22860 : 291 : }
22861 : :
22862 : : /*
22863 : : * ALTER TABLE ... DETACH PARTITION ... FINALIZE
22864 : : *
22865 : : * To use when a DETACH PARTITION command previously did not run to
22866 : : * completion; this completes the detaching process.
22867 : : */
22868 : : static ObjectAddress
22869 : 7 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
22870 : : {
22871 : : Relation partRel;
22872 : : ObjectAddress address;
22873 : 7 : Snapshot snap = GetActiveSnapshot();
22874 : :
22875 : 7 : partRel = table_openrv(name, AccessExclusiveLock);
22876 : :
22877 : : /*
22878 : : * Wait until existing snapshots are gone. This is important if the
22879 : : * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
22880 : : * user could immediately run DETACH FINALIZE without actually waiting for
22881 : : * existing transactions. We must not complete the detach action until
22882 : : * all such queries are complete (otherwise we would present them with an
22883 : : * inconsistent view of catalogs).
22884 : : */
22885 : 7 : WaitForOlderSnapshots(snap->xmin, false);
22886 : :
22887 : 7 : DetachPartitionFinalize(rel, partRel, true, InvalidOid);
22888 : :
22889 : 7 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
22890 : :
22891 : 7 : table_close(partRel, NoLock);
22892 : :
22893 : 7 : return address;
22894 : : }
22895 : :
22896 : : /*
22897 : : * DropClonedTriggersFromPartition
22898 : : * subroutine for ATExecDetachPartition to remove any triggers that were
22899 : : * cloned to the partition when it was created-as-partition or attached.
22900 : : * This undoes what CloneRowTriggersToPartition did.
22901 : : */
22902 : : static void
22903 : 292 : DropClonedTriggersFromPartition(Oid partitionId)
22904 : : {
22905 : : ScanKeyData skey;
22906 : : SysScanDesc scan;
22907 : : HeapTuple trigtup;
22908 : : Relation tgrel;
22909 : : ObjectAddresses *objects;
22910 : :
22911 : 292 : objects = new_object_addresses();
22912 : :
22913 : : /*
22914 : : * Scan pg_trigger to search for all triggers on this rel.
22915 : : */
22916 : 292 : ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
22917 : : F_OIDEQ, ObjectIdGetDatum(partitionId));
22918 : 292 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
22919 : 292 : scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
22920 : : true, NULL, 1, &skey);
22921 [ + + ]: 556 : while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
22922 : : {
22923 : 264 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
22924 : : ObjectAddress trig;
22925 : :
22926 : : /* Ignore triggers that weren't cloned */
22927 [ + + ]: 264 : if (!OidIsValid(pg_trigger->tgparentid))
22928 : 252 : continue;
22929 : :
22930 : : /*
22931 : : * Ignore internal triggers that are implementation objects of foreign
22932 : : * keys, because these will be detached when the foreign keys
22933 : : * themselves are.
22934 : : */
22935 [ + + ]: 220 : if (OidIsValid(pg_trigger->tgconstrrelid))
22936 : 208 : continue;
22937 : :
22938 : : /*
22939 : : * This is ugly, but necessary: remove the dependency markings on the
22940 : : * trigger so that it can be removed.
22941 : : */
22942 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22943 : : TriggerRelationId,
22944 : : DEPENDENCY_PARTITION_PRI);
22945 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22946 : : RelationRelationId,
22947 : : DEPENDENCY_PARTITION_SEC);
22948 : :
22949 : : /* remember this trigger to remove it below */
22950 : 12 : ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
22951 : 12 : add_exact_object_address(&trig, objects);
22952 : : }
22953 : :
22954 : : /* make the dependency removal visible to the deletion below */
22955 : 292 : CommandCounterIncrement();
22956 : 292 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
22957 : :
22958 : : /* done */
22959 : 292 : free_object_addresses(objects);
22960 : 292 : systable_endscan(scan);
22961 : 292 : table_close(tgrel, RowExclusiveLock);
22962 : 292 : }
22963 : :
22964 : : /*
22965 : : * Before acquiring lock on an index, acquire the same lock on the owning
22966 : : * table.
22967 : : */
22968 : : struct AttachIndexCallbackState
22969 : : {
22970 : : Oid partitionOid;
22971 : : Oid parentTblOid;
22972 : : bool lockedParentTbl;
22973 : : };
22974 : :
22975 : : static void
22976 : 293 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
22977 : : void *arg)
22978 : : {
22979 : : struct AttachIndexCallbackState *state;
22980 : : Form_pg_class classform;
22981 : : HeapTuple tuple;
22982 : :
22983 : 293 : state = (struct AttachIndexCallbackState *) arg;
22984 : :
22985 [ + + ]: 293 : if (!state->lockedParentTbl)
22986 : : {
22987 : 286 : LockRelationOid(state->parentTblOid, AccessShareLock);
22988 : 286 : state->lockedParentTbl = true;
22989 : : }
22990 : :
22991 : : /*
22992 : : * If we previously locked some other heap, and the name we're looking up
22993 : : * no longer refers to an index on that relation, release the now-useless
22994 : : * lock. XXX maybe we should do *after* we verify whether the index does
22995 : : * not actually belong to the same relation ...
22996 : : */
22997 [ + + - + ]: 293 : if (relOid != oldRelOid && OidIsValid(state->partitionOid))
22998 : : {
22999 : 0 : UnlockRelationOid(state->partitionOid, AccessShareLock);
23000 : 0 : state->partitionOid = InvalidOid;
23001 : : }
23002 : :
23003 : : /* Didn't find a relation, so no need for locking or permission checks. */
23004 [ + + ]: 293 : if (!OidIsValid(relOid))
23005 : 4 : return;
23006 : :
23007 : 289 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
23008 [ - + ]: 289 : if (!HeapTupleIsValid(tuple))
23009 : 0 : return; /* concurrently dropped, so nothing to do */
23010 : 289 : classform = (Form_pg_class) GETSTRUCT(tuple);
23011 [ + + ]: 289 : if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
23012 [ + + ]: 224 : classform->relkind != RELKIND_INDEX)
23013 [ + - ]: 4 : ereport(ERROR,
23014 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
23015 : : errmsg("\"%s\" is not an index", rv->relname)));
23016 : 285 : ReleaseSysCache(tuple);
23017 : :
23018 : : /*
23019 : : * Since we need only examine the heap's tupledesc, an access share lock
23020 : : * on it (preventing any DDL) is sufficient.
23021 : : */
23022 : 285 : state->partitionOid = IndexGetRelation(relOid, false);
23023 : 285 : LockRelationOid(state->partitionOid, AccessShareLock);
23024 : : }
23025 : :
23026 : : /*
23027 : : * ALTER INDEX i1 ATTACH PARTITION i2
23028 : : */
23029 : : static ObjectAddress
23030 : 286 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
23031 : : {
23032 : : Relation partIdx;
23033 : : Relation partTbl;
23034 : : Relation parentTbl;
23035 : : ObjectAddress address;
23036 : : Oid partIdxId;
23037 : : Oid currParent;
23038 : : struct AttachIndexCallbackState state;
23039 : :
23040 : : /*
23041 : : * We need to obtain lock on the index 'name' to modify it, but we also
23042 : : * need to read its owning table's tuple descriptor -- so we need to lock
23043 : : * both. To avoid deadlocks, obtain lock on the table before doing so on
23044 : : * the index. Furthermore, we need to examine the parent table of the
23045 : : * partition, so lock that one too.
23046 : : */
23047 : 286 : state.partitionOid = InvalidOid;
23048 : 286 : state.parentTblOid = parentIdx->rd_index->indrelid;
23049 : 286 : state.lockedParentTbl = false;
23050 : : partIdxId =
23051 : 286 : RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
23052 : : RangeVarCallbackForAttachIndex,
23053 : : &state);
23054 : : /* Not there? */
23055 [ - + ]: 278 : if (!OidIsValid(partIdxId))
23056 [ # # ]: 0 : ereport(ERROR,
23057 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
23058 : : errmsg("index \"%s\" does not exist", name->relname)));
23059 : :
23060 : : /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
23061 : 278 : partIdx = relation_open(partIdxId, AccessExclusiveLock);
23062 : :
23063 : : /* we already hold locks on both tables, so this is safe: */
23064 : 278 : parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
23065 : 278 : partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
23066 : :
23067 : 278 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
23068 : :
23069 : : /*
23070 : : * Check if the index is already attached to the correct parent,
23071 : : * ultimately attempting one round of validation if already the case.
23072 : : */
23073 : 556 : currParent = partIdx->rd_rel->relispartition ?
23074 [ + + ]: 278 : get_partition_parent(partIdxId, false) : InvalidOid;
23075 [ + + ]: 278 : if (currParent != RelationGetRelid(parentIdx))
23076 : : {
23077 : : IndexInfo *childInfo;
23078 : : IndexInfo *parentInfo;
23079 : : AttrMap *attmap;
23080 : : bool found;
23081 : : int i;
23082 : : PartitionDesc partDesc;
23083 : : Oid constraintOid,
23084 : 254 : cldConstrId = InvalidOid;
23085 : :
23086 : : /*
23087 : : * If this partition already has an index attached, refuse the
23088 : : * operation.
23089 : : */
23090 : 254 : refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
23091 : :
23092 [ - + ]: 250 : if (OidIsValid(currParent))
23093 [ # # ]: 0 : ereport(ERROR,
23094 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
23095 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
23096 : : RelationGetRelationName(partIdx),
23097 : : RelationGetRelationName(parentIdx)),
23098 : : errdetail("Index \"%s\" is already attached to another index.",
23099 : : RelationGetRelationName(partIdx))));
23100 : :
23101 : : /* Make sure it indexes a partition of the other index's table */
23102 : 250 : partDesc = RelationGetPartitionDesc(parentTbl, true);
23103 : 250 : found = false;
23104 [ + + ]: 379 : for (i = 0; i < partDesc->nparts; i++)
23105 : : {
23106 [ + + ]: 375 : if (partDesc->oids[i] == state.partitionOid)
23107 : : {
23108 : 246 : found = true;
23109 : 246 : break;
23110 : : }
23111 : : }
23112 [ + + ]: 250 : if (!found)
23113 [ + - ]: 4 : ereport(ERROR,
23114 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
23115 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
23116 : : RelationGetRelationName(partIdx),
23117 : : RelationGetRelationName(parentIdx)),
23118 : : errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
23119 : : RelationGetRelationName(partIdx),
23120 : : RelationGetRelationName(parentTbl))));
23121 : :
23122 : : /* Ensure the indexes are compatible */
23123 : 246 : childInfo = BuildIndexInfo(partIdx);
23124 : 246 : parentInfo = BuildIndexInfo(parentIdx);
23125 : 246 : attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
23126 : : RelationGetDescr(parentTbl),
23127 : : false);
23128 [ + + ]: 246 : if (!CompareIndexInfo(childInfo, parentInfo,
23129 : 246 : partIdx->rd_indcollation,
23130 : 246 : parentIdx->rd_indcollation,
23131 : 246 : partIdx->rd_opfamily,
23132 : 246 : parentIdx->rd_opfamily,
23133 : : attmap))
23134 [ + - ]: 32 : ereport(ERROR,
23135 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
23136 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
23137 : : RelationGetRelationName(partIdx),
23138 : : RelationGetRelationName(parentIdx)),
23139 : : errdetail("The index definitions do not match.")));
23140 : :
23141 : : /*
23142 : : * If there is a constraint in the parent, make sure there is one in
23143 : : * the child too.
23144 : : */
23145 : 214 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
23146 : : RelationGetRelid(parentIdx));
23147 : :
23148 [ + + ]: 214 : if (OidIsValid(constraintOid))
23149 : : {
23150 : 72 : cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
23151 : : partIdxId);
23152 [ + + ]: 72 : if (!OidIsValid(cldConstrId))
23153 [ + - ]: 4 : ereport(ERROR,
23154 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
23155 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
23156 : : RelationGetRelationName(partIdx),
23157 : : RelationGetRelationName(parentIdx)),
23158 : : errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
23159 : : RelationGetRelationName(parentIdx),
23160 : : RelationGetRelationName(parentTbl),
23161 : : RelationGetRelationName(partIdx))));
23162 : : }
23163 : :
23164 : : /*
23165 : : * If it's a primary key, make sure the columns in the partition are
23166 : : * NOT NULL.
23167 : : */
23168 [ + + ]: 210 : if (parentIdx->rd_index->indisprimary)
23169 : 51 : verifyPartitionIndexNotNull(childInfo, partTbl);
23170 : :
23171 : : /* All good -- do it */
23172 : 210 : IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
23173 [ + + ]: 210 : if (OidIsValid(constraintOid))
23174 : 68 : ConstraintSetParentConstraint(cldConstrId, constraintOid,
23175 : : RelationGetRelid(partTbl));
23176 : :
23177 : 210 : free_attrmap(attmap);
23178 : :
23179 : 210 : validatePartitionedIndex(parentIdx, parentTbl);
23180 : : }
23181 [ + + ]: 24 : else if (!parentIdx->rd_index->indisvalid)
23182 : : {
23183 : : /*
23184 : : * The index is attached, but the parent is still invalid; see if it
23185 : : * can be validated now.
23186 : : */
23187 : 12 : validatePartitionedIndex(parentIdx, parentTbl);
23188 : : }
23189 : :
23190 : 234 : relation_close(parentTbl, AccessShareLock);
23191 : : /* keep these locks till commit */
23192 : 234 : relation_close(partTbl, NoLock);
23193 : 234 : relation_close(partIdx, NoLock);
23194 : :
23195 : 234 : return address;
23196 : : }
23197 : :
23198 : : /*
23199 : : * Verify whether the given partition already contains an index attached
23200 : : * to the given partitioned index. If so, raise an error.
23201 : : */
23202 : : static void
23203 : 254 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
23204 : : {
23205 : : Oid existingIdx;
23206 : :
23207 : 254 : existingIdx = index_get_partition(partitionTbl,
23208 : : RelationGetRelid(parentIdx));
23209 [ + + ]: 254 : if (OidIsValid(existingIdx))
23210 [ + - ]: 4 : ereport(ERROR,
23211 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
23212 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
23213 : : RelationGetRelationName(partIdx),
23214 : : RelationGetRelationName(parentIdx)),
23215 : : errdetail("Another index \"%s\" is already attached for partition \"%s\".",
23216 : : get_rel_name(existingIdx),
23217 : : RelationGetRelationName(partitionTbl))));
23218 : 250 : }
23219 : :
23220 : : /*
23221 : : * Verify whether the set of attached partition indexes to a parent index on
23222 : : * a partitioned table is complete. If it is, mark the parent index valid.
23223 : : *
23224 : : * This should be called each time a partition index is attached.
23225 : : */
23226 : : static void
23227 : 254 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
23228 : : {
23229 : : Relation inheritsRel;
23230 : : SysScanDesc scan;
23231 : : ScanKeyData key;
23232 : 254 : int tuples = 0;
23233 : : HeapTuple inhTup;
23234 : 254 : bool updated = false;
23235 : :
23236 : : Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
23237 : :
23238 : : /*
23239 : : * Scan pg_inherits for this parent index. Count each valid index we find
23240 : : * (verifying the pg_index entry for each), and if we reach the total
23241 : : * amount we expect, we can mark this parent index as valid.
23242 : : */
23243 : 254 : inheritsRel = table_open(InheritsRelationId, AccessShareLock);
23244 : 254 : ScanKeyInit(&key, Anum_pg_inherits_inhparent,
23245 : : BTEqualStrategyNumber, F_OIDEQ,
23246 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
23247 : 254 : scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
23248 : : NULL, 1, &key);
23249 [ + + ]: 647 : while ((inhTup = systable_getnext(scan)) != NULL)
23250 : : {
23251 : 393 : Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
23252 : : HeapTuple indTup;
23253 : : Form_pg_index indexForm;
23254 : :
23255 : 393 : indTup = SearchSysCache1(INDEXRELID,
23256 : : ObjectIdGetDatum(inhForm->inhrelid));
23257 [ - + ]: 393 : if (!HeapTupleIsValid(indTup))
23258 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
23259 : 393 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
23260 [ + + ]: 393 : if (indexForm->indisvalid)
23261 : 327 : tuples += 1;
23262 : 393 : ReleaseSysCache(indTup);
23263 : : }
23264 : :
23265 : : /* Done with pg_inherits */
23266 : 254 : systable_endscan(scan);
23267 : 254 : table_close(inheritsRel, AccessShareLock);
23268 : :
23269 : : /*
23270 : : * If we found as many inherited indexes as the partitioned table has
23271 : : * partitions, we're good; update pg_index to set indisvalid.
23272 : : */
23273 [ + + ]: 254 : if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
23274 : : {
23275 : : Relation idxRel;
23276 : : HeapTuple indTup;
23277 : : Form_pg_index indexForm;
23278 : :
23279 : 121 : idxRel = table_open(IndexRelationId, RowExclusiveLock);
23280 : 121 : indTup = SearchSysCacheCopy1(INDEXRELID,
23281 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
23282 [ - + ]: 121 : if (!HeapTupleIsValid(indTup))
23283 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u",
23284 : : RelationGetRelid(partedIdx));
23285 : 121 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
23286 : :
23287 : 121 : indexForm->indisvalid = true;
23288 : 121 : updated = true;
23289 : :
23290 : 121 : CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
23291 : :
23292 : 121 : table_close(idxRel, RowExclusiveLock);
23293 : 121 : heap_freetuple(indTup);
23294 : : }
23295 : :
23296 : : /*
23297 : : * If this index is in turn a partition of a larger index, validating it
23298 : : * might cause the parent to become valid also. Try that.
23299 : : */
23300 [ + + + + ]: 254 : if (updated && partedIdx->rd_rel->relispartition)
23301 : : {
23302 : : Oid parentIdxId,
23303 : : parentTblId;
23304 : : Relation parentIdx,
23305 : : parentTbl;
23306 : :
23307 : : /* make sure we see the validation we just did */
23308 : 32 : CommandCounterIncrement();
23309 : :
23310 : 32 : parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
23311 : 32 : parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
23312 : 32 : parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
23313 : 32 : parentTbl = relation_open(parentTblId, AccessExclusiveLock);
23314 : : Assert(!parentIdx->rd_index->indisvalid);
23315 : :
23316 : 32 : validatePartitionedIndex(parentIdx, parentTbl);
23317 : :
23318 : : /*
23319 : : * Keep these locks until commit so that the concurrent validator of
23320 : : * another index partition cannot miss our uncommitted changes, which
23321 : : * would leave the parent index invalid.
23322 : : */
23323 : 32 : relation_close(parentIdx, NoLock);
23324 : 32 : relation_close(parentTbl, NoLock);
23325 : : }
23326 : 254 : }
23327 : :
23328 : : /*
23329 : : * When attaching an index as a partition of a partitioned index which is a
23330 : : * primary key, verify that all the columns in the partition are marked NOT
23331 : : * NULL.
23332 : : */
23333 : : static void
23334 : 51 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
23335 : : {
23336 [ + + ]: 103 : for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
23337 : : {
23338 : 52 : Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
23339 : 52 : iinfo->ii_IndexAttrNumbers[i] - 1);
23340 : :
23341 [ - + ]: 52 : if (!att->attnotnull)
23342 [ # # ]: 0 : ereport(ERROR,
23343 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
23344 : : errmsg("invalid primary key definition"),
23345 : : errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
23346 : : NameStr(att->attname),
23347 : : RelationGetRelationName(partition)));
23348 : : }
23349 : 51 : }
23350 : :
23351 : : /*
23352 : : * Return an OID list of constraints that reference the given relation
23353 : : * that are marked as having a parent constraints.
23354 : : */
23355 : : static List *
23356 : 626 : GetParentedForeignKeyRefs(Relation partition)
23357 : : {
23358 : : Relation pg_constraint;
23359 : : HeapTuple tuple;
23360 : : SysScanDesc scan;
23361 : : ScanKeyData key;
23362 : 626 : List *constraints = NIL;
23363 : :
23364 : : /*
23365 : : * If no indexes, or no columns are referenceable by FKs, we can avoid the
23366 : : * scan.
23367 : : */
23368 [ + + + + ]: 897 : if (RelationGetIndexList(partition) == NIL ||
23369 : 271 : bms_is_empty(RelationGetIndexAttrBitmap(partition,
23370 : : INDEX_ATTR_BITMAP_KEY)))
23371 : 459 : return NIL;
23372 : :
23373 : : /* Search for constraints referencing this table */
23374 : 167 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
23375 : 167 : ScanKeyInit(&key,
23376 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
23377 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
23378 : :
23379 : : /*
23380 : : * Scan pg_constraint using the index on confrelid, which is only set
23381 : : * nonzero by FK constraints. Filtering on contype in the loop is
23382 : : * therefore just a safety check.
23383 : : */
23384 : 167 : scan = systable_beginscan(pg_constraint, ConstraintForeignRelIndexId, true,
23385 : : NULL, 1, &key);
23386 [ + + ]: 268 : while ((tuple = systable_getnext(scan)) != NULL)
23387 : : {
23388 : 101 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
23389 : :
23390 [ - + ]: 101 : if (constrForm->contype != CONSTRAINT_FOREIGN)
23391 : 0 : continue;
23392 : :
23393 : : /*
23394 : : * We only need to process constraints that are part of larger ones.
23395 : : */
23396 [ - + ]: 101 : if (!OidIsValid(constrForm->conparentid))
23397 : 0 : continue;
23398 : :
23399 : 101 : constraints = lappend_oid(constraints, constrForm->oid);
23400 : : }
23401 : :
23402 : 167 : systable_endscan(scan);
23403 : 167 : table_close(pg_constraint, AccessShareLock);
23404 : :
23405 : 167 : return constraints;
23406 : : }
23407 : :
23408 : : /*
23409 : : * During DETACH PARTITION, verify that any foreign keys pointing to the
23410 : : * partitioned table would not become invalid. An error is raised if any
23411 : : * referenced values exist.
23412 : : */
23413 : : static void
23414 : 334 : ATDetachCheckNoForeignKeyRefs(Relation partition)
23415 : : {
23416 : : List *constraints;
23417 : : ListCell *cell;
23418 : :
23419 : 334 : constraints = GetParentedForeignKeyRefs(partition);
23420 : :
23421 [ + + + + : 377 : foreach(cell, constraints)
+ + ]
23422 : : {
23423 : 65 : Oid constrOid = lfirst_oid(cell);
23424 : : HeapTuple tuple;
23425 : : Form_pg_constraint constrForm;
23426 : : Relation rel;
23427 : 65 : Trigger trig = {0};
23428 : :
23429 : 65 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
23430 [ - + ]: 65 : if (!HeapTupleIsValid(tuple))
23431 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
23432 : 65 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
23433 : :
23434 : : Assert(OidIsValid(constrForm->conparentid));
23435 : : Assert(constrForm->confrelid == RelationGetRelid(partition));
23436 : :
23437 : : /* prevent data changes into the referencing table until commit */
23438 : 65 : rel = table_open(constrForm->conrelid, ShareLock);
23439 : :
23440 : 65 : trig.tgoid = InvalidOid;
23441 : 65 : trig.tgname = NameStr(constrForm->conname);
23442 : 65 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
23443 : 65 : trig.tgisinternal = true;
23444 : 65 : trig.tgconstrrelid = RelationGetRelid(partition);
23445 : 65 : trig.tgconstrindid = constrForm->conindid;
23446 : 65 : trig.tgconstraint = constrForm->oid;
23447 : 65 : trig.tgdeferrable = false;
23448 : 65 : trig.tginitdeferred = false;
23449 : : /* we needn't fill in remaining fields */
23450 : :
23451 : 65 : RI_PartitionRemove_Check(&trig, rel, partition);
23452 : :
23453 : 43 : ReleaseSysCache(tuple);
23454 : :
23455 : 43 : table_close(rel, NoLock);
23456 : : }
23457 : 312 : }
23458 : :
23459 : : /*
23460 : : * resolve column compression specification to compression method.
23461 : : */
23462 : : static char
23463 : 174121 : GetAttributeCompression(Oid atttypid, const char *compression)
23464 : : {
23465 : : char cmethod;
23466 : :
23467 [ + + + + ]: 174121 : if (compression == NULL || strcmp(compression, "default") == 0)
23468 : 174000 : return InvalidCompressionMethod;
23469 : :
23470 : : /*
23471 : : * To specify a nondefault method, the column data type must be toastable.
23472 : : * Note this says nothing about whether the column's attstorage setting
23473 : : * permits compression; we intentionally allow attstorage and
23474 : : * attcompression to be independent. But with a non-toastable type,
23475 : : * attstorage could not be set to a value that would permit compression.
23476 : : *
23477 : : * We don't actually need to enforce this, since nothing bad would happen
23478 : : * if attcompression were non-default; it would never be consulted. But
23479 : : * it seems more user-friendly to complain about a certainly-useless
23480 : : * attempt to set the property.
23481 : : */
23482 [ + + ]: 121 : if (!TypeIsToastable(atttypid))
23483 [ + - ]: 4 : ereport(ERROR,
23484 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
23485 : : errmsg("column data type %s does not support compression",
23486 : : format_type_be(atttypid))));
23487 : :
23488 : 117 : cmethod = CompressionNameToMethod(compression);
23489 [ + + ]: 117 : if (!CompressionMethodIsValid(cmethod))
23490 [ + - ]: 8 : ereport(ERROR,
23491 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
23492 : : errmsg("invalid compression method \"%s\"", compression)));
23493 : :
23494 : 109 : return cmethod;
23495 : : }
23496 : :
23497 : : /*
23498 : : * resolve column storage specification
23499 : : */
23500 : : static char
23501 : 265 : GetAttributeStorage(Oid atttypid, const char *storagemode)
23502 : : {
23503 : 265 : char cstorage = 0;
23504 : :
23505 [ + + ]: 265 : if (pg_strcasecmp(storagemode, "plain") == 0)
23506 : 40 : cstorage = TYPSTORAGE_PLAIN;
23507 [ + + ]: 225 : else if (pg_strcasecmp(storagemode, "external") == 0)
23508 : 155 : cstorage = TYPSTORAGE_EXTERNAL;
23509 [ + + ]: 70 : else if (pg_strcasecmp(storagemode, "extended") == 0)
23510 : 41 : cstorage = TYPSTORAGE_EXTENDED;
23511 [ + + ]: 29 : else if (pg_strcasecmp(storagemode, "main") == 0)
23512 : 25 : cstorage = TYPSTORAGE_MAIN;
23513 [ + - ]: 4 : else if (pg_strcasecmp(storagemode, "default") == 0)
23514 : 4 : cstorage = get_typstorage(atttypid);
23515 : : else
23516 [ # # ]: 0 : ereport(ERROR,
23517 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
23518 : : errmsg("invalid storage type \"%s\"",
23519 : : storagemode)));
23520 : :
23521 : : /*
23522 : : * safety check: do not allow toasted storage modes unless column datatype
23523 : : * is TOAST-aware.
23524 : : */
23525 [ + + + + ]: 265 : if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
23526 [ + - ]: 4 : ereport(ERROR,
23527 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
23528 : : errmsg("column data type %s can only have storage PLAIN",
23529 : : format_type_be(atttypid))));
23530 : :
23531 : 261 : return cstorage;
23532 : : }
|