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-2025, 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/xact.h"
29 : #include "access/xlog.h"
30 : #include "access/xloginsert.h"
31 : #include "catalog/catalog.h"
32 : #include "catalog/heap.h"
33 : #include "catalog/index.h"
34 : #include "catalog/namespace.h"
35 : #include "catalog/objectaccess.h"
36 : #include "catalog/partition.h"
37 : #include "catalog/pg_am.h"
38 : #include "catalog/pg_attrdef.h"
39 : #include "catalog/pg_collation.h"
40 : #include "catalog/pg_constraint.h"
41 : #include "catalog/pg_depend.h"
42 : #include "catalog/pg_foreign_table.h"
43 : #include "catalog/pg_inherits.h"
44 : #include "catalog/pg_largeobject.h"
45 : #include "catalog/pg_namespace.h"
46 : #include "catalog/pg_opclass.h"
47 : #include "catalog/pg_policy.h"
48 : #include "catalog/pg_proc.h"
49 : #include "catalog/pg_publication_rel.h"
50 : #include "catalog/pg_rewrite.h"
51 : #include "catalog/pg_statistic_ext.h"
52 : #include "catalog/pg_tablespace.h"
53 : #include "catalog/pg_trigger.h"
54 : #include "catalog/pg_type.h"
55 : #include "catalog/storage.h"
56 : #include "catalog/storage_xlog.h"
57 : #include "catalog/toasting.h"
58 : #include "commands/cluster.h"
59 : #include "commands/comment.h"
60 : #include "commands/defrem.h"
61 : #include "commands/event_trigger.h"
62 : #include "commands/sequence.h"
63 : #include "commands/tablecmds.h"
64 : #include "commands/tablespace.h"
65 : #include "commands/trigger.h"
66 : #include "commands/typecmds.h"
67 : #include "commands/user.h"
68 : #include "commands/vacuum.h"
69 : #include "common/int.h"
70 : #include "executor/executor.h"
71 : #include "foreign/fdwapi.h"
72 : #include "foreign/foreign.h"
73 : #include "miscadmin.h"
74 : #include "nodes/makefuncs.h"
75 : #include "nodes/nodeFuncs.h"
76 : #include "nodes/parsenodes.h"
77 : #include "optimizer/optimizer.h"
78 : #include "parser/parse_coerce.h"
79 : #include "parser/parse_collate.h"
80 : #include "parser/parse_expr.h"
81 : #include "parser/parse_relation.h"
82 : #include "parser/parse_type.h"
83 : #include "parser/parse_utilcmd.h"
84 : #include "parser/parser.h"
85 : #include "partitioning/partbounds.h"
86 : #include "partitioning/partdesc.h"
87 : #include "pgstat.h"
88 : #include "rewrite/rewriteDefine.h"
89 : #include "rewrite/rewriteHandler.h"
90 : #include "rewrite/rewriteManip.h"
91 : #include "storage/bufmgr.h"
92 : #include "storage/lmgr.h"
93 : #include "storage/lock.h"
94 : #include "storage/predicate.h"
95 : #include "storage/smgr.h"
96 : #include "tcop/utility.h"
97 : #include "utils/acl.h"
98 : #include "utils/builtins.h"
99 : #include "utils/fmgroids.h"
100 : #include "utils/inval.h"
101 : #include "utils/lsyscache.h"
102 : #include "utils/memutils.h"
103 : #include "utils/partcache.h"
104 : #include "utils/relcache.h"
105 : #include "utils/ruleutils.h"
106 : #include "utils/snapmgr.h"
107 : #include "utils/syscache.h"
108 : #include "utils/timestamp.h"
109 : #include "utils/typcache.h"
110 : #include "utils/usercontext.h"
111 :
112 : /*
113 : * ON COMMIT action list
114 : */
115 : typedef struct OnCommitItem
116 : {
117 : Oid relid; /* relid of relation */
118 : OnCommitAction oncommit; /* what to do at end of xact */
119 :
120 : /*
121 : * If this entry was created during the current transaction,
122 : * creating_subid is the ID of the creating subxact; if created in a prior
123 : * transaction, creating_subid is zero. If deleted during the current
124 : * transaction, deleting_subid is the ID of the deleting subxact; if no
125 : * deletion request is pending, deleting_subid is zero.
126 : */
127 : SubTransactionId creating_subid;
128 : SubTransactionId deleting_subid;
129 : } OnCommitItem;
130 :
131 : static List *on_commits = NIL;
132 :
133 :
134 : /*
135 : * State information for ALTER TABLE
136 : *
137 : * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
138 : * structs, one for each table modified by the operation (the named table
139 : * plus any child tables that are affected). We save lists of subcommands
140 : * to apply to this table (possibly modified by parse transformation steps);
141 : * these lists will be executed in Phase 2. If a Phase 3 step is needed,
142 : * necessary information is stored in the constraints and newvals lists.
143 : *
144 : * Phase 2 is divided into multiple passes; subcommands are executed in
145 : * a pass determined by subcommand type.
146 : */
147 :
148 : typedef enum AlterTablePass
149 : {
150 : AT_PASS_UNSET = -1, /* UNSET will cause ERROR */
151 : AT_PASS_DROP, /* DROP (all flavors) */
152 : AT_PASS_ALTER_TYPE, /* ALTER COLUMN TYPE */
153 : AT_PASS_ADD_COL, /* ADD COLUMN */
154 : AT_PASS_SET_EXPRESSION, /* ALTER SET EXPRESSION */
155 : AT_PASS_OLD_INDEX, /* re-add existing indexes */
156 : AT_PASS_OLD_CONSTR, /* re-add existing constraints */
157 : /* We could support a RENAME COLUMN pass here, but not currently used */
158 : AT_PASS_ADD_CONSTR, /* ADD constraints (initial examination) */
159 : AT_PASS_COL_ATTRS, /* set column attributes, eg NOT NULL */
160 : AT_PASS_ADD_INDEXCONSTR, /* ADD index-based constraints */
161 : AT_PASS_ADD_INDEX, /* ADD indexes */
162 : AT_PASS_ADD_OTHERCONSTR, /* ADD other constraints, defaults */
163 : AT_PASS_MISC, /* other stuff */
164 : } AlterTablePass;
165 :
166 : #define AT_NUM_PASSES (AT_PASS_MISC + 1)
167 :
168 : typedef struct AlteredTableInfo
169 : {
170 : /* Information saved before any work commences: */
171 : Oid relid; /* Relation to work on */
172 : char relkind; /* Its relkind */
173 : TupleDesc oldDesc; /* Pre-modification tuple descriptor */
174 :
175 : /*
176 : * Transiently set during Phase 2, normally set to NULL.
177 : *
178 : * ATRewriteCatalogs sets this when it starts, and closes when ATExecCmd
179 : * returns control. This can be exploited by ATExecCmd subroutines to
180 : * close/reopen across transaction boundaries.
181 : */
182 : Relation rel;
183 :
184 : /* Information saved by Phase 1 for Phase 2: */
185 : List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
186 : /* Information saved by Phases 1/2 for Phase 3: */
187 : List *constraints; /* List of NewConstraint */
188 : List *newvals; /* List of NewColumnValue */
189 : List *afterStmts; /* List of utility command parsetrees */
190 : bool verify_new_notnull; /* T if we should recheck NOT NULL */
191 : int rewrite; /* Reason for forced rewrite, if any */
192 : bool chgAccessMethod; /* T if SET ACCESS METHOD is used */
193 : Oid newAccessMethod; /* new access method; 0 means no change,
194 : * if above is true */
195 : Oid newTableSpace; /* new tablespace; 0 means no change */
196 : bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
197 : char newrelpersistence; /* if above is true */
198 : Expr *partition_constraint; /* for attach partition validation */
199 : /* true, if validating default due to some other attach/detach */
200 : bool validate_default;
201 : /* Objects to rebuild after completing ALTER TYPE operations */
202 : List *changedConstraintOids; /* OIDs of constraints to rebuild */
203 : List *changedConstraintDefs; /* string definitions of same */
204 : List *changedIndexOids; /* OIDs of indexes to rebuild */
205 : List *changedIndexDefs; /* string definitions of same */
206 : char *replicaIdentityIndex; /* index to reset as REPLICA IDENTITY */
207 : char *clusterOnIndex; /* index to use for CLUSTER */
208 : List *changedStatisticsOids; /* OIDs of statistics to rebuild */
209 : List *changedStatisticsDefs; /* string definitions of same */
210 : } AlteredTableInfo;
211 :
212 : /* Struct describing one new constraint to check in Phase 3 scan */
213 : /* Note: new not-null constraints are handled elsewhere */
214 : typedef struct NewConstraint
215 : {
216 : char *name; /* Constraint name, or NULL if none */
217 : ConstrType contype; /* CHECK or FOREIGN */
218 : Oid refrelid; /* PK rel, if FOREIGN */
219 : Oid refindid; /* OID of PK's index, if FOREIGN */
220 : bool conwithperiod; /* Whether the new FOREIGN KEY uses PERIOD */
221 : Oid conid; /* OID of pg_constraint entry, if FOREIGN */
222 : Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
223 : ExprState *qualstate; /* Execution state for CHECK expr */
224 : } NewConstraint;
225 :
226 : /*
227 : * Struct describing one new column value that needs to be computed during
228 : * Phase 3 copy (this could be either a new column with a non-null default, or
229 : * a column that we're changing the type of). Columns without such an entry
230 : * are just copied from the old table during ATRewriteTable. Note that the
231 : * expr is an expression over *old* table values, except when is_generated
232 : * is true; then it is an expression over columns of the *new* tuple.
233 : */
234 : typedef struct NewColumnValue
235 : {
236 : AttrNumber attnum; /* which column */
237 : Expr *expr; /* expression to compute */
238 : ExprState *exprstate; /* execution state */
239 : bool is_generated; /* is it a GENERATED expression? */
240 : } NewColumnValue;
241 :
242 : /*
243 : * Error-reporting support for RemoveRelations
244 : */
245 : struct dropmsgstrings
246 : {
247 : char kind;
248 : int nonexistent_code;
249 : const char *nonexistent_msg;
250 : const char *skipping_msg;
251 : const char *nota_msg;
252 : const char *drophint_msg;
253 : };
254 :
255 : static const struct dropmsgstrings dropmsgstringarray[] = {
256 : {RELKIND_RELATION,
257 : ERRCODE_UNDEFINED_TABLE,
258 : gettext_noop("table \"%s\" does not exist"),
259 : gettext_noop("table \"%s\" does not exist, skipping"),
260 : gettext_noop("\"%s\" is not a table"),
261 : gettext_noop("Use DROP TABLE to remove a table.")},
262 : {RELKIND_SEQUENCE,
263 : ERRCODE_UNDEFINED_TABLE,
264 : gettext_noop("sequence \"%s\" does not exist"),
265 : gettext_noop("sequence \"%s\" does not exist, skipping"),
266 : gettext_noop("\"%s\" is not a sequence"),
267 : gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
268 : {RELKIND_VIEW,
269 : ERRCODE_UNDEFINED_TABLE,
270 : gettext_noop("view \"%s\" does not exist"),
271 : gettext_noop("view \"%s\" does not exist, skipping"),
272 : gettext_noop("\"%s\" is not a view"),
273 : gettext_noop("Use DROP VIEW to remove a view.")},
274 : {RELKIND_MATVIEW,
275 : ERRCODE_UNDEFINED_TABLE,
276 : gettext_noop("materialized view \"%s\" does not exist"),
277 : gettext_noop("materialized view \"%s\" does not exist, skipping"),
278 : gettext_noop("\"%s\" is not a materialized view"),
279 : gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
280 : {RELKIND_INDEX,
281 : ERRCODE_UNDEFINED_OBJECT,
282 : gettext_noop("index \"%s\" does not exist"),
283 : gettext_noop("index \"%s\" does not exist, skipping"),
284 : gettext_noop("\"%s\" is not an index"),
285 : gettext_noop("Use DROP INDEX to remove an index.")},
286 : {RELKIND_COMPOSITE_TYPE,
287 : ERRCODE_UNDEFINED_OBJECT,
288 : gettext_noop("type \"%s\" does not exist"),
289 : gettext_noop("type \"%s\" does not exist, skipping"),
290 : gettext_noop("\"%s\" is not a type"),
291 : gettext_noop("Use DROP TYPE to remove a type.")},
292 : {RELKIND_FOREIGN_TABLE,
293 : ERRCODE_UNDEFINED_OBJECT,
294 : gettext_noop("foreign table \"%s\" does not exist"),
295 : gettext_noop("foreign table \"%s\" does not exist, skipping"),
296 : gettext_noop("\"%s\" is not a foreign table"),
297 : gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
298 : {RELKIND_PARTITIONED_TABLE,
299 : ERRCODE_UNDEFINED_TABLE,
300 : gettext_noop("table \"%s\" does not exist"),
301 : gettext_noop("table \"%s\" does not exist, skipping"),
302 : gettext_noop("\"%s\" is not a table"),
303 : gettext_noop("Use DROP TABLE to remove a table.")},
304 : {RELKIND_PARTITIONED_INDEX,
305 : ERRCODE_UNDEFINED_OBJECT,
306 : gettext_noop("index \"%s\" does not exist"),
307 : gettext_noop("index \"%s\" does not exist, skipping"),
308 : gettext_noop("\"%s\" is not an index"),
309 : gettext_noop("Use DROP INDEX to remove an index.")},
310 : {'\0', 0, NULL, NULL, NULL, NULL}
311 : };
312 :
313 : /* communication between RemoveRelations and RangeVarCallbackForDropRelation */
314 : struct DropRelationCallbackState
315 : {
316 : /* These fields are set by RemoveRelations: */
317 : char expected_relkind;
318 : LOCKMODE heap_lockmode;
319 : /* These fields are state to track which subsidiary locks are held: */
320 : Oid heapOid;
321 : Oid partParentOid;
322 : /* These fields are passed back by RangeVarCallbackForDropRelation: */
323 : char actual_relkind;
324 : char actual_relpersistence;
325 : };
326 :
327 : /* Alter table target-type flags for ATSimplePermissions */
328 : #define ATT_TABLE 0x0001
329 : #define ATT_VIEW 0x0002
330 : #define ATT_MATVIEW 0x0004
331 : #define ATT_INDEX 0x0008
332 : #define ATT_COMPOSITE_TYPE 0x0010
333 : #define ATT_FOREIGN_TABLE 0x0020
334 : #define ATT_PARTITIONED_INDEX 0x0040
335 : #define ATT_SEQUENCE 0x0080
336 : #define ATT_PARTITIONED_TABLE 0x0100
337 :
338 : /*
339 : * ForeignTruncateInfo
340 : *
341 : * Information related to truncation of foreign tables. This is used for
342 : * the elements in a hash table. It uses the server OID as lookup key,
343 : * and includes a per-server list of all foreign tables involved in the
344 : * truncation.
345 : */
346 : typedef struct ForeignTruncateInfo
347 : {
348 : Oid serverid;
349 : List *rels;
350 : } ForeignTruncateInfo;
351 :
352 : /* Partial or complete FK creation in addFkConstraint() */
353 : typedef enum addFkConstraintSides
354 : {
355 : addFkReferencedSide,
356 : addFkReferencingSide,
357 : addFkBothSides,
358 : } addFkConstraintSides;
359 :
360 : /*
361 : * Partition tables are expected to be dropped when the parent partitioned
362 : * table gets dropped. Hence for partitioning we use AUTO dependency.
363 : * Otherwise, for regular inheritance use NORMAL dependency.
364 : */
365 : #define child_dependency_type(child_is_partition) \
366 : ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
367 :
368 : static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
369 : static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
370 : static void truncate_check_activity(Relation rel);
371 : static void RangeVarCallbackForTruncate(const RangeVar *relation,
372 : Oid relId, Oid oldRelId, void *arg);
373 : static List *MergeAttributes(List *columns, const List *supers, char relpersistence,
374 : bool is_partition, List **supconstr,
375 : List **supnotnulls);
376 : static List *MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced);
377 : static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef);
378 : static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
379 : static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
380 : static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
381 : static void StoreCatalogInheritance(Oid relationId, List *supers,
382 : bool child_is_partition);
383 : static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
384 : int32 seqNumber, Relation inhRelation,
385 : bool child_is_partition);
386 : static int findAttrByName(const char *attributeName, const List *columns);
387 : static void AlterIndexNamespaces(Relation classRel, Relation rel,
388 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
389 : static void AlterSeqNamespaces(Relation classRel, Relation rel,
390 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
391 : LOCKMODE lockmode);
392 : static ObjectAddress ATExecAlterConstraint(List **wqueue, Relation rel,
393 : ATAlterConstraint *cmdcon,
394 : bool recurse, LOCKMODE lockmode);
395 : static bool ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel,
396 : Relation tgrel, Relation rel, HeapTuple contuple,
397 : bool recurse, LOCKMODE lockmode);
398 : static bool ATExecAlterConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
399 : Relation conrel, Relation tgrel,
400 : Oid fkrelid, Oid pkrelid,
401 : HeapTuple contuple, LOCKMODE lockmode,
402 : Oid ReferencedParentDelTrigger,
403 : Oid ReferencedParentUpdTrigger,
404 : Oid ReferencingParentInsTrigger,
405 : Oid ReferencingParentUpdTrigger);
406 : static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
407 : Relation conrel, Relation tgrel, Relation rel,
408 : HeapTuple contuple, bool recurse,
409 : List **otherrelids, LOCKMODE lockmode);
410 : static bool ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
411 : Relation conrel, Relation rel,
412 : HeapTuple contuple, LOCKMODE lockmode);
413 : static void AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
414 : bool deferrable, bool initdeferred,
415 : List **otherrelids);
416 : static void AlterConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
417 : Relation conrel, Relation tgrel,
418 : Oid fkrelid, Oid pkrelid,
419 : HeapTuple contuple, LOCKMODE lockmode,
420 : Oid ReferencedParentDelTrigger,
421 : Oid ReferencedParentUpdTrigger,
422 : Oid ReferencingParentInsTrigger,
423 : Oid ReferencingParentUpdTrigger);
424 : static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
425 : Relation conrel, Relation tgrel, Relation rel,
426 : HeapTuple contuple, bool recurse,
427 : List **otherrelids, LOCKMODE lockmode);
428 : static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
429 : HeapTuple contuple);
430 : static ObjectAddress ATExecValidateConstraint(List **wqueue,
431 : Relation rel, char *constrName,
432 : bool recurse, bool recursing, LOCKMODE lockmode);
433 : static void QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
434 : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode);
435 : static void QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
436 : char *constrName, HeapTuple contuple,
437 : bool recurse, bool recursing, LOCKMODE lockmode);
438 : static void QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
439 : HeapTuple contuple, bool recurse, bool recursing,
440 : LOCKMODE lockmode);
441 : static int transformColumnNameList(Oid relId, List *colList,
442 : int16 *attnums, Oid *atttypids, Oid *attcollids);
443 : static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
444 : List **attnamelist,
445 : int16 *attnums, Oid *atttypids, Oid *attcollids,
446 : Oid *opclasses, bool *pk_has_without_overlaps);
447 : static Oid transformFkeyCheckAttrs(Relation pkrel,
448 : int numattrs, int16 *attnums,
449 : bool with_period, Oid *opclasses,
450 : bool *pk_has_without_overlaps);
451 : static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
452 : static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
453 : Oid *funcid);
454 : static void validateForeignKeyConstraint(char *conname,
455 : Relation rel, Relation pkrel,
456 : Oid pkindOid, Oid constraintOid, bool hasperiod);
457 : static void CheckAlterTableIsSafe(Relation rel);
458 : static void ATController(AlterTableStmt *parsetree,
459 : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
460 : AlterTableUtilityContext *context);
461 : static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
462 : bool recurse, bool recursing, LOCKMODE lockmode,
463 : AlterTableUtilityContext *context);
464 : static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
465 : AlterTableUtilityContext *context);
466 : static void ATExecCmd(List **wqueue, AlteredTableInfo *tab,
467 : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
468 : AlterTableUtilityContext *context);
469 : static AlterTableCmd *ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab,
470 : Relation rel, AlterTableCmd *cmd,
471 : bool recurse, LOCKMODE lockmode,
472 : AlterTablePass cur_pass,
473 : AlterTableUtilityContext *context);
474 : static void ATRewriteTables(AlterTableStmt *parsetree,
475 : List **wqueue, LOCKMODE lockmode,
476 : AlterTableUtilityContext *context);
477 : static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
478 : static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
479 : static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets);
480 : static void ATSimpleRecursion(List **wqueue, Relation rel,
481 : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
482 : AlterTableUtilityContext *context);
483 : static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
484 : static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
485 : LOCKMODE lockmode,
486 : AlterTableUtilityContext *context);
487 : static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
488 : DropBehavior behavior);
489 : static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
490 : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
491 : AlterTableUtilityContext *context);
492 : static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
493 : Relation rel, AlterTableCmd **cmd,
494 : bool recurse, bool recursing,
495 : LOCKMODE lockmode, AlterTablePass cur_pass,
496 : AlterTableUtilityContext *context);
497 : static bool check_for_column_name_collision(Relation rel, const char *colname,
498 : bool if_not_exists);
499 : static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
500 : static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
501 : static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
502 : LOCKMODE lockmode);
503 : static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
504 : bool is_valid, bool queue_validation);
505 : static ObjectAddress ATExecSetNotNull(List **wqueue, Relation rel,
506 : char *conName, char *colName,
507 : bool recurse, bool recursing,
508 : LOCKMODE lockmode);
509 : static bool NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr);
510 : static bool ConstraintImpliedByRelConstraint(Relation scanrel,
511 : List *testConstraint, List *provenConstraint);
512 : static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
513 : Node *newDefault, LOCKMODE lockmode);
514 : static ObjectAddress ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
515 : Node *newDefault);
516 : static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
517 : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
518 : static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
519 : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
520 : static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
521 : bool recurse, bool recursing);
522 : static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
523 : Node *newExpr, LOCKMODE lockmode);
524 : static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
525 : static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
526 : static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
527 : Node *newValue, LOCKMODE lockmode);
528 : static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
529 : Node *options, bool isReset, LOCKMODE lockmode);
530 : static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
531 : Node *newValue, LOCKMODE lockmode);
532 : static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
533 : AlterTableCmd *cmd, LOCKMODE lockmode,
534 : AlterTableUtilityContext *context);
535 : static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
536 : DropBehavior behavior,
537 : bool recurse, bool recursing,
538 : bool missing_ok, LOCKMODE lockmode,
539 : ObjectAddresses *addrs);
540 : static void ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
541 : bool recurse, LOCKMODE lockmode,
542 : AlterTableUtilityContext *context);
543 : static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
544 : static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
545 : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
546 : static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
547 : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
548 : static ObjectAddress ATExecAddConstraint(List **wqueue,
549 : AlteredTableInfo *tab, Relation rel,
550 : Constraint *newConstraint, bool recurse, bool is_readd,
551 : LOCKMODE lockmode);
552 : static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
553 : static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
554 : IndexStmt *stmt, LOCKMODE lockmode);
555 : static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
556 : AlteredTableInfo *tab, Relation rel,
557 : Constraint *constr,
558 : bool recurse, bool recursing, bool is_readd,
559 : LOCKMODE lockmode);
560 : static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
561 : Relation rel, Constraint *fkconstraint,
562 : bool recurse, bool recursing,
563 : LOCKMODE lockmode);
564 : static int validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
565 : int numfksetcols, int16 *fksetcolsattnums,
566 : List *fksetcols);
567 : static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
568 : char *constraintname,
569 : Constraint *fkconstraint, Relation rel,
570 : Relation pkrel, Oid indexOid,
571 : Oid parentConstr,
572 : int numfks, int16 *pkattnum, int16 *fkattnum,
573 : Oid *pfeqoperators, Oid *ppeqoperators,
574 : Oid *ffeqoperators, int numfkdelsetcols,
575 : int16 *fkdelsetcols, bool is_internal,
576 : bool with_period);
577 : static void addFkRecurseReferenced(Constraint *fkconstraint,
578 : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
579 : int numfks, int16 *pkattnum, int16 *fkattnum,
580 : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
581 : int numfkdelsetcols, int16 *fkdelsetcols,
582 : bool old_check_ok,
583 : Oid parentDelTrigger, Oid parentUpdTrigger,
584 : bool with_period);
585 : static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
586 : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
587 : int numfks, int16 *pkattnum, int16 *fkattnum,
588 : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
589 : int numfkdelsetcols, int16 *fkdelsetcols,
590 : bool old_check_ok, LOCKMODE lockmode,
591 : Oid parentInsTrigger, Oid parentUpdTrigger,
592 : bool with_period);
593 : static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
594 : Relation partitionRel);
595 : static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
596 : static void CloneFkReferencing(List **wqueue, Relation parentRel,
597 : Relation partRel);
598 : static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
599 : Constraint *fkconstraint, Oid constraintOid,
600 : Oid indexOid,
601 : Oid parentInsTrigger, Oid parentUpdTrigger,
602 : Oid *insertTrigOid, Oid *updateTrigOid);
603 : static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
604 : Constraint *fkconstraint, Oid constraintOid,
605 : Oid indexOid,
606 : Oid parentDelTrigger, Oid parentUpdTrigger,
607 : Oid *deleteTrigOid, Oid *updateTrigOid);
608 : static bool tryAttachPartitionForeignKey(List **wqueue,
609 : ForeignKeyCacheInfo *fk,
610 : Relation partition,
611 : Oid parentConstrOid, int numfks,
612 : AttrNumber *mapped_conkey, AttrNumber *confkey,
613 : Oid *conpfeqop,
614 : Oid parentInsTrigger,
615 : Oid parentUpdTrigger,
616 : Relation trigrel);
617 : static void AttachPartitionForeignKey(List **wqueue, Relation partition,
618 : Oid partConstrOid, Oid parentConstrOid,
619 : Oid parentInsTrigger, Oid parentUpdTrigger,
620 : Relation trigrel);
621 : static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
622 : Oid conoid, Oid conrelid);
623 : static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
624 : Oid confrelid, Oid conrelid);
625 : static void GetForeignKeyActionTriggers(Relation trigrel,
626 : Oid conoid, Oid confrelid, Oid conrelid,
627 : Oid *deleteTriggerOid,
628 : Oid *updateTriggerOid);
629 : static void GetForeignKeyCheckTriggers(Relation trigrel,
630 : Oid conoid, Oid confrelid, Oid conrelid,
631 : Oid *insertTriggerOid,
632 : Oid *updateTriggerOid);
633 : static void ATExecDropConstraint(Relation rel, const char *constrName,
634 : DropBehavior behavior, bool recurse,
635 : bool missing_ok, LOCKMODE lockmode);
636 : static ObjectAddress dropconstraint_internal(Relation rel,
637 : HeapTuple constraintTup, DropBehavior behavior,
638 : bool recurse, bool recursing,
639 : bool missing_ok, LOCKMODE lockmode);
640 : static void ATPrepAlterColumnType(List **wqueue,
641 : AlteredTableInfo *tab, Relation rel,
642 : bool recurse, bool recursing,
643 : AlterTableCmd *cmd, LOCKMODE lockmode,
644 : AlterTableUtilityContext *context);
645 : static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
646 : static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
647 : AlterTableCmd *cmd, LOCKMODE lockmode);
648 : static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
649 : Relation rel, AttrNumber attnum, const char *colName);
650 : static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
651 : static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
652 : static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
653 : static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
654 : LOCKMODE lockmode);
655 : static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
656 : char *cmd, List **wqueue, LOCKMODE lockmode,
657 : bool rewrite);
658 : static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
659 : Oid objid, Relation rel, List *domname,
660 : const char *conname);
661 : static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
662 : static void TryReuseForeignKey(Oid oldId, Constraint *con);
663 : static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
664 : List *options, LOCKMODE lockmode);
665 : static void change_owner_fix_column_acls(Oid relationOid,
666 : Oid oldOwnerId, Oid newOwnerId);
667 : static void change_owner_recurse_to_sequences(Oid relationOid,
668 : Oid newOwnerId, LOCKMODE lockmode);
669 : static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
670 : LOCKMODE lockmode);
671 : static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
672 : static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
673 : static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
674 : static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
675 : bool toLogged);
676 : static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
677 : const char *tablespacename, LOCKMODE lockmode);
678 : static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
679 : static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
680 : static void ATExecSetRelOptions(Relation rel, List *defList,
681 : AlterTableType operation,
682 : LOCKMODE lockmode);
683 : static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
684 : char fires_when, bool skip_system, bool recurse,
685 : LOCKMODE lockmode);
686 : static void ATExecEnableDisableRule(Relation rel, const char *rulename,
687 : char fires_when, LOCKMODE lockmode);
688 : static void ATPrepAddInherit(Relation child_rel);
689 : static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
690 : static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
691 : static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
692 : DependencyType deptype);
693 : static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
694 : static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
695 : static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
696 : static void ATExecGenericOptions(Relation rel, List *options);
697 : static void ATExecSetRowSecurity(Relation rel, bool rls);
698 : static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
699 : static ObjectAddress ATExecSetCompression(Relation rel,
700 : const char *column, Node *newValue, LOCKMODE lockmode);
701 :
702 : static void index_copy_data(Relation rel, RelFileLocator newrlocator);
703 : static const char *storage_name(char c);
704 :
705 : static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
706 : Oid oldRelOid, void *arg);
707 : static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
708 : Oid oldrelid, void *arg);
709 : static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
710 : static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
711 : List **partexprs, Oid *partopclass, Oid *partcollation,
712 : PartitionStrategy strategy);
713 : static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
714 : static void RemoveInheritance(Relation child_rel, Relation parent_rel,
715 : bool expect_detached);
716 : static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
717 : PartitionCmd *cmd,
718 : AlterTableUtilityContext *context);
719 : static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
720 : static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
721 : List *partConstraint,
722 : bool validate_default);
723 : static void CloneRowTriggersToPartition(Relation parent, Relation partition);
724 : static void DetachAddConstraintIfNeeded(List **wqueue, Relation partRel);
725 : static void DropClonedTriggersFromPartition(Oid partitionId);
726 : static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
727 : Relation rel, RangeVar *name,
728 : bool concurrent);
729 : static void DetachPartitionFinalize(Relation rel, Relation partRel,
730 : bool concurrent, Oid defaultPartOid);
731 : static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
732 : static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
733 : RangeVar *name);
734 : static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
735 : static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
736 : Relation partitionTbl);
737 : static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
738 : static List *GetParentedForeignKeyRefs(Relation partition);
739 : static void ATDetachCheckNoForeignKeyRefs(Relation partition);
740 : static char GetAttributeCompression(Oid atttypid, const char *compression);
741 : static char GetAttributeStorage(Oid atttypid, const char *storagemode);
742 :
743 :
744 : /* ----------------------------------------------------------------
745 : * DefineRelation
746 : * Creates a new relation.
747 : *
748 : * stmt carries parsetree information from an ordinary CREATE TABLE statement.
749 : * The other arguments are used to extend the behavior for other cases:
750 : * relkind: relkind to assign to the new relation
751 : * ownerId: if not InvalidOid, use this as the new relation's owner.
752 : * typaddress: if not null, it's set to the pg_type entry's address.
753 : * queryString: for error reporting
754 : *
755 : * Note that permissions checks are done against current user regardless of
756 : * ownerId. A nonzero ownerId is used when someone is creating a relation
757 : * "on behalf of" someone else, so we still want to see that the current user
758 : * has permissions to do it.
759 : *
760 : * If successful, returns the address of the new relation.
761 : * ----------------------------------------------------------------
762 : */
763 : ObjectAddress
764 63736 : DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
765 : ObjectAddress *typaddress, const char *queryString)
766 : {
767 : char relname[NAMEDATALEN];
768 : Oid namespaceId;
769 : Oid relationId;
770 : Oid tablespaceId;
771 : Relation rel;
772 : TupleDesc descriptor;
773 : List *inheritOids;
774 : List *old_constraints;
775 : List *old_notnulls;
776 : List *rawDefaults;
777 : List *cookedDefaults;
778 : List *nncols;
779 : Datum reloptions;
780 : ListCell *listptr;
781 : AttrNumber attnum;
782 : bool partitioned;
783 63736 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
784 : Oid ofTypeId;
785 : ObjectAddress address;
786 : LOCKMODE parentLockmode;
787 63736 : Oid accessMethodId = InvalidOid;
788 :
789 : /*
790 : * Truncate relname to appropriate length (probably a waste of time, as
791 : * parser should have done this already).
792 : */
793 63736 : strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
794 :
795 : /*
796 : * Check consistency of arguments
797 : */
798 63736 : if (stmt->oncommit != ONCOMMIT_NOOP
799 188 : && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
800 12 : ereport(ERROR,
801 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
802 : errmsg("ON COMMIT can only be used on temporary tables")));
803 :
804 63724 : if (stmt->partspec != NULL)
805 : {
806 5128 : if (relkind != RELKIND_RELATION)
807 0 : elog(ERROR, "unexpected relkind: %d", (int) relkind);
808 :
809 5128 : relkind = RELKIND_PARTITIONED_TABLE;
810 5128 : partitioned = true;
811 : }
812 : else
813 58596 : partitioned = false;
814 :
815 63724 : if (relkind == RELKIND_PARTITIONED_TABLE &&
816 5128 : stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
817 6 : ereport(ERROR,
818 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
819 : errmsg("partitioned tables cannot be unlogged")));
820 :
821 : /*
822 : * Look up the namespace in which we are supposed to create the relation,
823 : * check we have permission to create there, lock it against concurrent
824 : * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
825 : * namespace is selected.
826 : */
827 : namespaceId =
828 63718 : RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
829 :
830 : /*
831 : * Security check: disallow creating temp tables from security-restricted
832 : * code. This is needed because calling code might not expect untrusted
833 : * tables to appear in pg_temp at the front of its search path.
834 : */
835 63718 : if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
836 3132 : && InSecurityRestrictedOperation())
837 0 : ereport(ERROR,
838 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
839 : errmsg("cannot create temporary table within security-restricted operation")));
840 :
841 : /*
842 : * Determine the lockmode to use when scanning parents. A self-exclusive
843 : * lock is needed here.
844 : *
845 : * For regular inheritance, if two backends attempt to add children to the
846 : * same parent simultaneously, and that parent has no pre-existing
847 : * children, then both will attempt to update the parent's relhassubclass
848 : * field, leading to a "tuple concurrently updated" error. Also, this
849 : * interlocks against a concurrent ANALYZE on the parent table, which
850 : * might otherwise be attempting to clear the parent's relhassubclass
851 : * field, if its previous children were recently dropped.
852 : *
853 : * If the child table is a partition, then we instead grab an exclusive
854 : * lock on the parent because its partition descriptor will be changed by
855 : * addition of the new partition.
856 : */
857 63718 : parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
858 : ShareUpdateExclusiveLock);
859 :
860 : /* Determine the list of OIDs of the parents. */
861 63718 : inheritOids = NIL;
862 74254 : foreach(listptr, stmt->inhRelations)
863 : {
864 10536 : RangeVar *rv = (RangeVar *) lfirst(listptr);
865 : Oid parentOid;
866 :
867 10536 : parentOid = RangeVarGetRelid(rv, parentLockmode, false);
868 :
869 : /*
870 : * Reject duplications in the list of parents.
871 : */
872 10536 : if (list_member_oid(inheritOids, parentOid))
873 0 : ereport(ERROR,
874 : (errcode(ERRCODE_DUPLICATE_TABLE),
875 : errmsg("relation \"%s\" would be inherited from more than once",
876 : get_rel_name(parentOid))));
877 :
878 10536 : inheritOids = lappend_oid(inheritOids, parentOid);
879 : }
880 :
881 : /*
882 : * Select tablespace to use: an explicitly indicated one, or (in the case
883 : * of a partitioned table) the parent's, if it has one.
884 : */
885 63718 : if (stmt->tablespacename)
886 : {
887 118 : tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
888 :
889 112 : if (partitioned && tablespaceId == MyDatabaseTableSpace)
890 6 : ereport(ERROR,
891 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
892 : errmsg("cannot specify default tablespace for partitioned relations")));
893 : }
894 63600 : else if (stmt->partbound)
895 : {
896 : Assert(list_length(inheritOids) == 1);
897 7940 : tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
898 : }
899 : else
900 55660 : tablespaceId = InvalidOid;
901 :
902 : /* still nothing? use the default */
903 63706 : if (!OidIsValid(tablespaceId))
904 63578 : tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
905 : partitioned);
906 :
907 : /* Check permissions except when using database's default */
908 63700 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
909 : {
910 : AclResult aclresult;
911 :
912 146 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
913 : ACL_CREATE);
914 146 : if (aclresult != ACLCHECK_OK)
915 6 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
916 6 : get_tablespace_name(tablespaceId));
917 : }
918 :
919 : /* In all cases disallow placing user relations in pg_global */
920 63694 : if (tablespaceId == GLOBALTABLESPACE_OID)
921 18 : ereport(ERROR,
922 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
923 : errmsg("only shared relations can be placed in pg_global tablespace")));
924 :
925 : /* Identify user ID that will own the table */
926 63676 : if (!OidIsValid(ownerId))
927 63392 : ownerId = GetUserId();
928 :
929 : /*
930 : * Parse and validate reloptions, if any.
931 : */
932 63676 : reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
933 : true, false);
934 :
935 63658 : switch (relkind)
936 : {
937 16666 : case RELKIND_VIEW:
938 16666 : (void) view_reloptions(reloptions, true);
939 16648 : break;
940 5104 : case RELKIND_PARTITIONED_TABLE:
941 5104 : (void) partitioned_table_reloptions(reloptions, true);
942 5098 : break;
943 41888 : default:
944 41888 : (void) heap_reloptions(relkind, reloptions, true);
945 : }
946 :
947 63538 : if (stmt->ofTypename)
948 : {
949 : AclResult aclresult;
950 :
951 98 : ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
952 :
953 98 : aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
954 98 : if (aclresult != ACLCHECK_OK)
955 6 : aclcheck_error_type(aclresult, ofTypeId);
956 : }
957 : else
958 63440 : ofTypeId = InvalidOid;
959 :
960 : /*
961 : * Look up inheritance ancestors and generate relation schema, including
962 : * inherited attributes. (Note that stmt->tableElts is destructively
963 : * modified by MergeAttributes.)
964 : */
965 63292 : stmt->tableElts =
966 63532 : MergeAttributes(stmt->tableElts, inheritOids,
967 63532 : stmt->relation->relpersistence,
968 63532 : stmt->partbound != NULL,
969 : &old_constraints, &old_notnulls);
970 :
971 : /*
972 : * Create a tuple descriptor from the relation schema. Note that this
973 : * deals with column names, types, and in-descriptor NOT NULL flags, but
974 : * not default values, NOT NULL or CHECK constraints; we handle those
975 : * below.
976 : */
977 63292 : descriptor = BuildDescForRelation(stmt->tableElts);
978 :
979 : /*
980 : * Find columns with default values and prepare for insertion of the
981 : * defaults. Pre-cooked (that is, inherited) defaults go into a list of
982 : * CookedConstraint structs that we'll pass to heap_create_with_catalog,
983 : * while raw defaults go into a list of RawColumnDefault structs that will
984 : * be processed by AddRelationNewConstraints. (We can't deal with raw
985 : * expressions until we can do transformExpr.)
986 : */
987 63244 : rawDefaults = NIL;
988 63244 : cookedDefaults = NIL;
989 63244 : attnum = 0;
990 :
991 320770 : foreach(listptr, stmt->tableElts)
992 : {
993 257526 : ColumnDef *colDef = lfirst(listptr);
994 :
995 257526 : attnum++;
996 257526 : if (colDef->raw_default != NULL)
997 : {
998 : RawColumnDefault *rawEnt;
999 :
1000 : Assert(colDef->cooked_default == NULL);
1001 :
1002 3364 : rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
1003 3364 : rawEnt->attnum = attnum;
1004 3364 : rawEnt->raw_default = colDef->raw_default;
1005 3364 : rawEnt->generated = colDef->generated;
1006 3364 : rawDefaults = lappend(rawDefaults, rawEnt);
1007 : }
1008 254162 : else if (colDef->cooked_default != NULL)
1009 : {
1010 : CookedConstraint *cooked;
1011 :
1012 404 : cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
1013 404 : cooked->contype = CONSTR_DEFAULT;
1014 404 : cooked->conoid = InvalidOid; /* until created */
1015 404 : cooked->name = NULL;
1016 404 : cooked->attnum = attnum;
1017 404 : cooked->expr = colDef->cooked_default;
1018 404 : cooked->is_enforced = true;
1019 404 : cooked->skip_validation = false;
1020 404 : cooked->is_local = true; /* not used for defaults */
1021 404 : cooked->inhcount = 0; /* ditto */
1022 404 : cooked->is_no_inherit = false;
1023 404 : cookedDefaults = lappend(cookedDefaults, cooked);
1024 : }
1025 : }
1026 :
1027 : /*
1028 : * For relations with table AM and partitioned tables, select access
1029 : * method to use: an explicitly indicated one, or (in the case of a
1030 : * partitioned table) the parent's, if it has one.
1031 : */
1032 63244 : if (stmt->accessMethod != NULL)
1033 : {
1034 : Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
1035 122 : accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1036 : }
1037 63122 : else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
1038 : {
1039 39590 : if (stmt->partbound)
1040 : {
1041 : Assert(list_length(inheritOids) == 1);
1042 7758 : accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1043 : }
1044 :
1045 39590 : if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
1046 34478 : accessMethodId = get_table_am_oid(default_table_access_method, false);
1047 : }
1048 :
1049 : /*
1050 : * Create the relation. Inherited defaults and CHECK constraints are
1051 : * passed in for immediate handling --- since they don't need parsing,
1052 : * they can be stored immediately.
1053 : */
1054 63226 : relationId = heap_create_with_catalog(relname,
1055 : namespaceId,
1056 : tablespaceId,
1057 : InvalidOid,
1058 : InvalidOid,
1059 : ofTypeId,
1060 : ownerId,
1061 : accessMethodId,
1062 : descriptor,
1063 : list_concat(cookedDefaults,
1064 : old_constraints),
1065 : relkind,
1066 63226 : stmt->relation->relpersistence,
1067 : false,
1068 : false,
1069 : stmt->oncommit,
1070 : reloptions,
1071 : true,
1072 : allowSystemTableMods,
1073 : false,
1074 : InvalidOid,
1075 : typaddress);
1076 :
1077 : /*
1078 : * We must bump the command counter to make the newly-created relation
1079 : * tuple visible for opening.
1080 : */
1081 63178 : CommandCounterIncrement();
1082 :
1083 : /*
1084 : * Open the new relation and acquire exclusive lock on it. This isn't
1085 : * really necessary for locking out other backends (since they can't see
1086 : * the new rel anyway until we commit), but it keeps the lock manager from
1087 : * complaining about deadlock risks.
1088 : */
1089 63178 : rel = relation_open(relationId, AccessExclusiveLock);
1090 :
1091 : /*
1092 : * Now add any newly specified column default and generation expressions
1093 : * to the new relation. These are passed to us in the form of raw
1094 : * parsetrees; we need to transform them to executable expression trees
1095 : * before they can be added. The most convenient way to do that is to
1096 : * apply the parser's transformExpr routine, but transformExpr doesn't
1097 : * work unless we have a pre-existing relation. So, the transformation has
1098 : * to be postponed to this final step of CREATE TABLE.
1099 : *
1100 : * This needs to be before processing the partitioning clauses because
1101 : * those could refer to generated columns.
1102 : */
1103 63178 : if (rawDefaults)
1104 2840 : AddRelationNewConstraints(rel, rawDefaults, NIL,
1105 : true, true, false, queryString);
1106 :
1107 : /*
1108 : * Make column generation expressions visible for use by partitioning.
1109 : */
1110 62986 : CommandCounterIncrement();
1111 :
1112 : /* Process and store partition bound, if any. */
1113 62986 : if (stmt->partbound)
1114 : {
1115 : PartitionBoundSpec *bound;
1116 : ParseState *pstate;
1117 7862 : Oid parentId = linitial_oid(inheritOids),
1118 : defaultPartOid;
1119 : Relation parent,
1120 7862 : defaultRel = NULL;
1121 : ParseNamespaceItem *nsitem;
1122 :
1123 : /* Already have strong enough lock on the parent */
1124 7862 : parent = table_open(parentId, NoLock);
1125 :
1126 : /*
1127 : * We are going to try to validate the partition bound specification
1128 : * against the partition key of parentRel, so it better have one.
1129 : */
1130 7862 : if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1131 18 : ereport(ERROR,
1132 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1133 : errmsg("\"%s\" is not partitioned",
1134 : RelationGetRelationName(parent))));
1135 :
1136 : /*
1137 : * The partition constraint of the default partition depends on the
1138 : * partition bounds of every other partition. It is possible that
1139 : * another backend might be about to execute a query on the default
1140 : * partition table, and that the query relies on previously cached
1141 : * default partition constraints. We must therefore take a table lock
1142 : * strong enough to prevent all queries on the default partition from
1143 : * proceeding until we commit and send out a shared-cache-inval notice
1144 : * that will make them update their index lists.
1145 : *
1146 : * Order of locking: The relation being added won't be visible to
1147 : * other backends until it is committed, hence here in
1148 : * DefineRelation() the order of locking the default partition and the
1149 : * relation being added does not matter. But at all other places we
1150 : * need to lock the default relation before we lock the relation being
1151 : * added or removed i.e. we should take the lock in same order at all
1152 : * the places such that lock parent, lock default partition and then
1153 : * lock the partition so as to avoid a deadlock.
1154 : */
1155 : defaultPartOid =
1156 7844 : get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
1157 : true));
1158 7844 : if (OidIsValid(defaultPartOid))
1159 378 : defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1160 :
1161 : /* Transform the bound values */
1162 7844 : pstate = make_parsestate(NULL);
1163 7844 : pstate->p_sourcetext = queryString;
1164 :
1165 : /*
1166 : * Add an nsitem containing this relation, so that transformExpr
1167 : * called on partition bound expressions is able to report errors
1168 : * using a proper context.
1169 : */
1170 7844 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1171 : NULL, false, false);
1172 7844 : addNSItemToQuery(pstate, nsitem, false, true, true);
1173 :
1174 7844 : bound = transformPartitionBound(pstate, parent, stmt->partbound);
1175 :
1176 : /*
1177 : * Check first that the new partition's bound is valid and does not
1178 : * overlap with any of existing partitions of the parent.
1179 : */
1180 7640 : check_new_partition_bound(relname, parent, bound, pstate);
1181 :
1182 : /*
1183 : * If the default partition exists, its partition constraints will
1184 : * change after the addition of this new partition such that it won't
1185 : * allow any row that qualifies for this new partition. So, check that
1186 : * the existing data in the default partition satisfies the constraint
1187 : * as it will exist after adding this partition.
1188 : */
1189 7526 : if (OidIsValid(defaultPartOid))
1190 : {
1191 348 : check_default_partition_contents(parent, defaultRel, bound);
1192 : /* Keep the lock until commit. */
1193 330 : table_close(defaultRel, NoLock);
1194 : }
1195 :
1196 : /* Update the pg_class entry. */
1197 7508 : StorePartitionBound(rel, parent, bound);
1198 :
1199 7508 : table_close(parent, NoLock);
1200 : }
1201 :
1202 : /* Store inheritance information for new rel. */
1203 62632 : StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1204 :
1205 : /*
1206 : * Process the partitioning specification (if any) and store the partition
1207 : * key information into the catalog.
1208 : */
1209 62632 : if (partitioned)
1210 : {
1211 : ParseState *pstate;
1212 : int partnatts;
1213 : AttrNumber partattrs[PARTITION_MAX_KEYS];
1214 : Oid partopclass[PARTITION_MAX_KEYS];
1215 : Oid partcollation[PARTITION_MAX_KEYS];
1216 5098 : List *partexprs = NIL;
1217 :
1218 5098 : pstate = make_parsestate(NULL);
1219 5098 : pstate->p_sourcetext = queryString;
1220 :
1221 5098 : partnatts = list_length(stmt->partspec->partParams);
1222 :
1223 : /* Protect fixed-size arrays here and in executor */
1224 5098 : if (partnatts > PARTITION_MAX_KEYS)
1225 0 : ereport(ERROR,
1226 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
1227 : errmsg("cannot partition using more than %d columns",
1228 : PARTITION_MAX_KEYS)));
1229 :
1230 : /*
1231 : * We need to transform the raw parsetrees corresponding to partition
1232 : * expressions into executable expression trees. Like column defaults
1233 : * and CHECK constraints, we could not have done the transformation
1234 : * earlier.
1235 : */
1236 5098 : stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1237 :
1238 5068 : ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1239 : partattrs, &partexprs, partopclass,
1240 5068 : partcollation, stmt->partspec->strategy);
1241 :
1242 4972 : StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1243 : partexprs,
1244 : partopclass, partcollation);
1245 :
1246 : /* make it all visible */
1247 4972 : CommandCounterIncrement();
1248 : }
1249 :
1250 : /*
1251 : * If we're creating a partition, create now all the indexes, triggers,
1252 : * FKs defined in the parent.
1253 : *
1254 : * We can't do it earlier, because DefineIndex wants to know the partition
1255 : * key which we just stored.
1256 : */
1257 62506 : if (stmt->partbound)
1258 : {
1259 7502 : Oid parentId = linitial_oid(inheritOids);
1260 : Relation parent;
1261 : List *idxlist;
1262 : ListCell *cell;
1263 :
1264 : /* Already have strong enough lock on the parent */
1265 7502 : parent = table_open(parentId, NoLock);
1266 7502 : idxlist = RelationGetIndexList(parent);
1267 :
1268 : /*
1269 : * For each index in the parent table, create one in the partition
1270 : */
1271 8904 : foreach(cell, idxlist)
1272 : {
1273 1420 : Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1274 : AttrMap *attmap;
1275 : IndexStmt *idxstmt;
1276 : Oid constraintOid;
1277 :
1278 1420 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1279 : {
1280 36 : if (idxRel->rd_index->indisunique)
1281 12 : ereport(ERROR,
1282 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1283 : errmsg("cannot create foreign partition of partitioned table \"%s\"",
1284 : RelationGetRelationName(parent)),
1285 : errdetail("Table \"%s\" contains indexes that are unique.",
1286 : RelationGetRelationName(parent))));
1287 : else
1288 : {
1289 24 : index_close(idxRel, AccessShareLock);
1290 24 : continue;
1291 : }
1292 : }
1293 :
1294 1384 : attmap = build_attrmap_by_name(RelationGetDescr(rel),
1295 : RelationGetDescr(parent),
1296 : false);
1297 : idxstmt =
1298 1384 : generateClonedIndexStmt(NULL, idxRel,
1299 : attmap, &constraintOid);
1300 1384 : DefineIndex(RelationGetRelid(rel),
1301 : idxstmt,
1302 : InvalidOid,
1303 : RelationGetRelid(idxRel),
1304 : constraintOid,
1305 : -1,
1306 : false, false, false, false, false);
1307 :
1308 1378 : index_close(idxRel, AccessShareLock);
1309 : }
1310 :
1311 7484 : list_free(idxlist);
1312 :
1313 : /*
1314 : * If there are any row-level triggers, clone them to the new
1315 : * partition.
1316 : */
1317 7484 : if (parent->trigdesc != NULL)
1318 432 : CloneRowTriggersToPartition(parent, rel);
1319 :
1320 : /*
1321 : * And foreign keys too. Note that because we're freshly creating the
1322 : * table, there is no need to verify these new constraints.
1323 : */
1324 7484 : CloneForeignKeyConstraints(NULL, parent, rel);
1325 :
1326 7484 : table_close(parent, NoLock);
1327 : }
1328 :
1329 : /*
1330 : * Now add any newly specified CHECK constraints to the new relation. Same
1331 : * as for defaults above, but these need to come after partitioning is set
1332 : * up.
1333 : */
1334 62488 : if (stmt->constraints)
1335 784 : AddRelationNewConstraints(rel, NIL, stmt->constraints,
1336 : true, true, false, queryString);
1337 :
1338 : /*
1339 : * Finally, merge the not-null constraints that are declared directly with
1340 : * those that come from parent relations (making sure to count inheritance
1341 : * appropriately for each), create them, and set the attnotnull flag on
1342 : * columns that don't yet have it.
1343 : */
1344 62458 : nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1345 : old_notnulls);
1346 140292 : foreach_int(attrnum, nncols)
1347 15532 : set_attnotnull(NULL, rel, attrnum, true, false);
1348 :
1349 62380 : ObjectAddressSet(address, RelationRelationId, relationId);
1350 :
1351 : /*
1352 : * Clean up. We keep lock on new relation (although it shouldn't be
1353 : * visible to anyone else anyway, until commit).
1354 : */
1355 62380 : relation_close(rel, NoLock);
1356 :
1357 62380 : return address;
1358 : }
1359 :
1360 : /*
1361 : * BuildDescForRelation
1362 : *
1363 : * Given a list of ColumnDef nodes, build a TupleDesc.
1364 : *
1365 : * Note: This is only for the limited purpose of table and view creation. Not
1366 : * everything is filled in. A real tuple descriptor should be obtained from
1367 : * the relcache.
1368 : */
1369 : TupleDesc
1370 66260 : BuildDescForRelation(const List *columns)
1371 : {
1372 : int natts;
1373 : AttrNumber attnum;
1374 : ListCell *l;
1375 : TupleDesc desc;
1376 : char *attname;
1377 : Oid atttypid;
1378 : int32 atttypmod;
1379 : Oid attcollation;
1380 : int attdim;
1381 :
1382 : /*
1383 : * allocate a new tuple descriptor
1384 : */
1385 66260 : natts = list_length(columns);
1386 66260 : desc = CreateTemplateTupleDesc(natts);
1387 :
1388 66260 : attnum = 0;
1389 :
1390 327018 : foreach(l, columns)
1391 : {
1392 260818 : ColumnDef *entry = lfirst(l);
1393 : AclResult aclresult;
1394 : Form_pg_attribute att;
1395 :
1396 : /*
1397 : * for each entry in the list, get the name and type information from
1398 : * the list and have TupleDescInitEntry fill in the attribute
1399 : * information we need.
1400 : */
1401 260818 : attnum++;
1402 :
1403 260818 : attname = entry->colname;
1404 260818 : typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1405 :
1406 260818 : aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1407 260818 : if (aclresult != ACLCHECK_OK)
1408 42 : aclcheck_error_type(aclresult, atttypid);
1409 :
1410 260776 : attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1411 260776 : attdim = list_length(entry->typeName->arrayBounds);
1412 260776 : if (attdim > PG_INT16_MAX)
1413 0 : ereport(ERROR,
1414 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1415 : errmsg("too many array dimensions"));
1416 :
1417 260776 : if (entry->typeName->setof)
1418 0 : ereport(ERROR,
1419 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1420 : errmsg("column \"%s\" cannot be declared SETOF",
1421 : attname)));
1422 :
1423 260776 : TupleDescInitEntry(desc, attnum, attname,
1424 : atttypid, atttypmod, attdim);
1425 260776 : att = TupleDescAttr(desc, attnum - 1);
1426 :
1427 : /* Override TupleDescInitEntry's settings as requested */
1428 260776 : TupleDescInitEntryCollation(desc, attnum, attcollation);
1429 :
1430 : /* Fill in additional stuff not handled by TupleDescInitEntry */
1431 260776 : att->attnotnull = entry->is_not_null;
1432 260776 : att->attislocal = entry->is_local;
1433 260776 : att->attinhcount = entry->inhcount;
1434 260776 : att->attidentity = entry->identity;
1435 260776 : att->attgenerated = entry->generated;
1436 260776 : att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1437 260764 : if (entry->storage)
1438 20162 : att->attstorage = entry->storage;
1439 240602 : else if (entry->storage_name)
1440 20 : att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1441 :
1442 260758 : populate_compact_attribute(desc, attnum - 1);
1443 : }
1444 :
1445 66200 : return desc;
1446 : }
1447 :
1448 : /*
1449 : * Emit the right error or warning message for a "DROP" command issued on a
1450 : * non-existent relation
1451 : */
1452 : static void
1453 1084 : DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
1454 : {
1455 : const struct dropmsgstrings *rentry;
1456 :
1457 1204 : if (rel->schemaname != NULL &&
1458 120 : !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
1459 : {
1460 42 : if (!missing_ok)
1461 : {
1462 0 : ereport(ERROR,
1463 : (errcode(ERRCODE_UNDEFINED_SCHEMA),
1464 : errmsg("schema \"%s\" does not exist", rel->schemaname)));
1465 : }
1466 : else
1467 : {
1468 42 : ereport(NOTICE,
1469 : (errmsg("schema \"%s\" does not exist, skipping",
1470 : rel->schemaname)));
1471 : }
1472 42 : return;
1473 : }
1474 :
1475 1362 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1476 : {
1477 1362 : if (rentry->kind == rightkind)
1478 : {
1479 1042 : if (!missing_ok)
1480 : {
1481 138 : ereport(ERROR,
1482 : (errcode(rentry->nonexistent_code),
1483 : errmsg(rentry->nonexistent_msg, rel->relname)));
1484 : }
1485 : else
1486 : {
1487 904 : ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
1488 904 : break;
1489 : }
1490 : }
1491 : }
1492 :
1493 : Assert(rentry->kind != '\0'); /* Should be impossible */
1494 : }
1495 :
1496 : /*
1497 : * Emit the right error message for a "DROP" command issued on a
1498 : * relation of the wrong type
1499 : */
1500 : static void
1501 0 : DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
1502 : {
1503 : const struct dropmsgstrings *rentry;
1504 : const struct dropmsgstrings *wentry;
1505 :
1506 0 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1507 0 : if (rentry->kind == rightkind)
1508 0 : break;
1509 : Assert(rentry->kind != '\0');
1510 :
1511 0 : for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
1512 0 : if (wentry->kind == wrongkind)
1513 0 : break;
1514 : /* wrongkind could be something we don't have in our table... */
1515 :
1516 0 : ereport(ERROR,
1517 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1518 : errmsg(rentry->nota_msg, relname),
1519 : (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
1520 : }
1521 :
1522 : /*
1523 : * RemoveRelations
1524 : * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
1525 : * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
1526 : */
1527 : void
1528 17062 : RemoveRelations(DropStmt *drop)
1529 : {
1530 : ObjectAddresses *objects;
1531 : char relkind;
1532 : ListCell *cell;
1533 17062 : int flags = 0;
1534 17062 : LOCKMODE lockmode = AccessExclusiveLock;
1535 :
1536 : /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1537 17062 : if (drop->concurrent)
1538 : {
1539 : /*
1540 : * Note that for temporary relations this lock may get upgraded later
1541 : * on, but as no other session can access a temporary relation, this
1542 : * is actually fine.
1543 : */
1544 144 : lockmode = ShareUpdateExclusiveLock;
1545 : Assert(drop->removeType == OBJECT_INDEX);
1546 144 : if (list_length(drop->objects) != 1)
1547 6 : ereport(ERROR,
1548 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1549 : errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1550 138 : if (drop->behavior == DROP_CASCADE)
1551 0 : ereport(ERROR,
1552 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1553 : errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1554 : }
1555 :
1556 : /*
1557 : * First we identify all the relations, then we delete them in a single
1558 : * performMultipleDeletions() call. This is to avoid unwanted DROP
1559 : * RESTRICT errors if one of the relations depends on another.
1560 : */
1561 :
1562 : /* Determine required relkind */
1563 17056 : switch (drop->removeType)
1564 : {
1565 14836 : case OBJECT_TABLE:
1566 14836 : relkind = RELKIND_RELATION;
1567 14836 : break;
1568 :
1569 826 : case OBJECT_INDEX:
1570 826 : relkind = RELKIND_INDEX;
1571 826 : break;
1572 :
1573 170 : case OBJECT_SEQUENCE:
1574 170 : relkind = RELKIND_SEQUENCE;
1575 170 : break;
1576 :
1577 936 : case OBJECT_VIEW:
1578 936 : relkind = RELKIND_VIEW;
1579 936 : break;
1580 :
1581 126 : case OBJECT_MATVIEW:
1582 126 : relkind = RELKIND_MATVIEW;
1583 126 : break;
1584 :
1585 162 : case OBJECT_FOREIGN_TABLE:
1586 162 : relkind = RELKIND_FOREIGN_TABLE;
1587 162 : break;
1588 :
1589 0 : default:
1590 0 : elog(ERROR, "unrecognized drop object type: %d",
1591 : (int) drop->removeType);
1592 : relkind = 0; /* keep compiler quiet */
1593 : break;
1594 : }
1595 :
1596 : /* Lock and validate each relation; build a list of object addresses */
1597 17056 : objects = new_object_addresses();
1598 :
1599 38038 : foreach(cell, drop->objects)
1600 : {
1601 21146 : RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1602 : Oid relOid;
1603 : ObjectAddress obj;
1604 : struct DropRelationCallbackState state;
1605 :
1606 : /*
1607 : * These next few steps are a great deal like relation_openrv, but we
1608 : * don't bother building a relcache entry since we don't need it.
1609 : *
1610 : * Check for shared-cache-inval messages before trying to access the
1611 : * relation. This is needed to cover the case where the name
1612 : * identifies a rel that has been dropped and recreated since the
1613 : * start of our transaction: if we don't flush the old syscache entry,
1614 : * then we'll latch onto that entry and suffer an error later.
1615 : */
1616 21146 : AcceptInvalidationMessages();
1617 :
1618 : /* Look up the appropriate relation using namespace search. */
1619 21146 : state.expected_relkind = relkind;
1620 42292 : state.heap_lockmode = drop->concurrent ?
1621 21146 : ShareUpdateExclusiveLock : AccessExclusiveLock;
1622 : /* We must initialize these fields to show that no locks are held: */
1623 21146 : state.heapOid = InvalidOid;
1624 21146 : state.partParentOid = InvalidOid;
1625 :
1626 21146 : relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1627 : RangeVarCallbackForDropRelation,
1628 : &state);
1629 :
1630 : /* Not there? */
1631 21126 : if (!OidIsValid(relOid))
1632 : {
1633 1084 : DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1634 946 : continue;
1635 : }
1636 :
1637 : /*
1638 : * Decide if concurrent mode needs to be used here or not. The
1639 : * callback retrieved the rel's persistence for us.
1640 : */
1641 20042 : if (drop->concurrent &&
1642 132 : state.actual_relpersistence != RELPERSISTENCE_TEMP)
1643 : {
1644 : Assert(list_length(drop->objects) == 1 &&
1645 : drop->removeType == OBJECT_INDEX);
1646 114 : flags |= PERFORM_DELETION_CONCURRENTLY;
1647 : }
1648 :
1649 : /*
1650 : * Concurrent index drop cannot be used with partitioned indexes,
1651 : * either.
1652 : */
1653 20042 : if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1654 114 : state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1655 6 : ereport(ERROR,
1656 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1657 : errmsg("cannot drop partitioned index \"%s\" concurrently",
1658 : rel->relname)));
1659 :
1660 : /*
1661 : * If we're told to drop a partitioned index, we must acquire lock on
1662 : * all the children of its parent partitioned table before proceeding.
1663 : * Otherwise we'd try to lock the child index partitions before their
1664 : * tables, leading to potential deadlock against other sessions that
1665 : * will lock those objects in the other order.
1666 : */
1667 20036 : if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1668 76 : (void) find_all_inheritors(state.heapOid,
1669 : state.heap_lockmode,
1670 : NULL);
1671 :
1672 : /* OK, we're ready to delete this one */
1673 20036 : obj.classId = RelationRelationId;
1674 20036 : obj.objectId = relOid;
1675 20036 : obj.objectSubId = 0;
1676 :
1677 20036 : add_exact_object_address(&obj, objects);
1678 : }
1679 :
1680 16892 : performMultipleDeletions(objects, drop->behavior, flags);
1681 :
1682 16750 : free_object_addresses(objects);
1683 16750 : }
1684 :
1685 : /*
1686 : * Before acquiring a table lock, check whether we have sufficient rights.
1687 : * In the case of DROP INDEX, also try to lock the table before the index.
1688 : * Also, if the table to be dropped is a partition, we try to lock the parent
1689 : * first.
1690 : */
1691 : static void
1692 21588 : RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
1693 : void *arg)
1694 : {
1695 : HeapTuple tuple;
1696 : struct DropRelationCallbackState *state;
1697 : char expected_relkind;
1698 : bool is_partition;
1699 : Form_pg_class classform;
1700 : LOCKMODE heap_lockmode;
1701 21588 : bool invalid_system_index = false;
1702 :
1703 21588 : state = (struct DropRelationCallbackState *) arg;
1704 21588 : heap_lockmode = state->heap_lockmode;
1705 :
1706 : /*
1707 : * If we previously locked some other index's heap, and the name we're
1708 : * looking up no longer refers to that relation, release the now-useless
1709 : * lock.
1710 : */
1711 21588 : if (relOid != oldRelOid && OidIsValid(state->heapOid))
1712 : {
1713 0 : UnlockRelationOid(state->heapOid, heap_lockmode);
1714 0 : state->heapOid = InvalidOid;
1715 : }
1716 :
1717 : /*
1718 : * Similarly, if we previously locked some other partition's heap, and the
1719 : * name we're looking up no longer refers to that relation, release the
1720 : * now-useless lock.
1721 : */
1722 21588 : if (relOid != oldRelOid && OidIsValid(state->partParentOid))
1723 : {
1724 0 : UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
1725 0 : state->partParentOid = InvalidOid;
1726 : }
1727 :
1728 : /* Didn't find a relation, so no need for locking or permission checks. */
1729 21588 : if (!OidIsValid(relOid))
1730 1098 : return;
1731 :
1732 20490 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1733 20490 : if (!HeapTupleIsValid(tuple))
1734 0 : return; /* concurrently dropped, so nothing to do */
1735 20490 : classform = (Form_pg_class) GETSTRUCT(tuple);
1736 20490 : is_partition = classform->relispartition;
1737 :
1738 : /* Pass back some data to save lookups in RemoveRelations */
1739 20490 : state->actual_relkind = classform->relkind;
1740 20490 : state->actual_relpersistence = classform->relpersistence;
1741 :
1742 : /*
1743 : * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
1744 : * but RemoveRelations() can only pass one relkind for a given relation.
1745 : * It chooses RELKIND_RELATION for both regular and partitioned tables.
1746 : * That means we must be careful before giving the wrong type error when
1747 : * the relation is RELKIND_PARTITIONED_TABLE. An equivalent problem
1748 : * exists with indexes.
1749 : */
1750 20490 : if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1751 2942 : expected_relkind = RELKIND_RELATION;
1752 17548 : else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1753 88 : expected_relkind = RELKIND_INDEX;
1754 : else
1755 17460 : expected_relkind = classform->relkind;
1756 :
1757 20490 : if (state->expected_relkind != expected_relkind)
1758 0 : DropErrorMsgWrongType(rel->relname, classform->relkind,
1759 0 : state->expected_relkind);
1760 :
1761 : /* Allow DROP to either table owner or schema owner */
1762 20490 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
1763 18 : !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
1764 18 : aclcheck_error(ACLCHECK_NOT_OWNER,
1765 18 : get_relkind_objtype(classform->relkind),
1766 18 : rel->relname);
1767 :
1768 : /*
1769 : * Check the case of a system index that might have been invalidated by a
1770 : * failed concurrent process and allow its drop. For the time being, this
1771 : * only concerns indexes of toast relations that became invalid during a
1772 : * REINDEX CONCURRENTLY process.
1773 : */
1774 20472 : if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
1775 : {
1776 : HeapTuple locTuple;
1777 : Form_pg_index indexform;
1778 : bool indisvalid;
1779 :
1780 0 : locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
1781 0 : if (!HeapTupleIsValid(locTuple))
1782 : {
1783 0 : ReleaseSysCache(tuple);
1784 0 : return;
1785 : }
1786 :
1787 0 : indexform = (Form_pg_index) GETSTRUCT(locTuple);
1788 0 : indisvalid = indexform->indisvalid;
1789 0 : ReleaseSysCache(locTuple);
1790 :
1791 : /* Mark object as being an invalid index of system catalogs */
1792 0 : if (!indisvalid)
1793 0 : invalid_system_index = true;
1794 : }
1795 :
1796 : /* In the case of an invalid index, it is fine to bypass this check */
1797 20472 : if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
1798 2 : ereport(ERROR,
1799 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1800 : errmsg("permission denied: \"%s\" is a system catalog",
1801 : rel->relname)));
1802 :
1803 20470 : ReleaseSysCache(tuple);
1804 :
1805 : /*
1806 : * In DROP INDEX, attempt to acquire lock on the parent table before
1807 : * locking the index. index_drop() will need this anyway, and since
1808 : * regular queries lock tables before their indexes, we risk deadlock if
1809 : * we do it the other way around. No error if we don't find a pg_index
1810 : * entry, though --- the relation may have been dropped. Note that this
1811 : * code will execute for either plain or partitioned indexes.
1812 : */
1813 20470 : if (expected_relkind == RELKIND_INDEX &&
1814 : relOid != oldRelOid)
1815 : {
1816 814 : state->heapOid = IndexGetRelation(relOid, true);
1817 814 : if (OidIsValid(state->heapOid))
1818 814 : LockRelationOid(state->heapOid, heap_lockmode);
1819 : }
1820 :
1821 : /*
1822 : * Similarly, if the relation is a partition, we must acquire lock on its
1823 : * parent before locking the partition. That's because queries lock the
1824 : * parent before its partitions, so we risk deadlock if we do it the other
1825 : * way around.
1826 : */
1827 20470 : if (is_partition && relOid != oldRelOid)
1828 : {
1829 612 : state->partParentOid = get_partition_parent(relOid, true);
1830 612 : if (OidIsValid(state->partParentOid))
1831 612 : LockRelationOid(state->partParentOid, AccessExclusiveLock);
1832 : }
1833 : }
1834 :
1835 : /*
1836 : * ExecuteTruncate
1837 : * Executes a TRUNCATE command.
1838 : *
1839 : * This is a multi-relation truncate. We first open and grab exclusive
1840 : * lock on all relations involved, checking permissions and otherwise
1841 : * verifying that the relation is OK for truncation. Note that if relations
1842 : * are foreign tables, at this stage, we have not yet checked that their
1843 : * foreign data in external data sources are OK for truncation. These are
1844 : * checked when foreign data are actually truncated later. In CASCADE mode,
1845 : * relations having FK references to the targeted relations are automatically
1846 : * added to the group; in RESTRICT mode, we check that all FK references are
1847 : * internal to the group that's being truncated. Finally all the relations
1848 : * are truncated and reindexed.
1849 : */
1850 : void
1851 2932 : ExecuteTruncate(TruncateStmt *stmt)
1852 : {
1853 2932 : List *rels = NIL;
1854 2932 : List *relids = NIL;
1855 2932 : List *relids_logged = NIL;
1856 : ListCell *cell;
1857 :
1858 : /*
1859 : * Open, exclusive-lock, and check all the explicitly-specified relations
1860 : */
1861 6076 : foreach(cell, stmt->relations)
1862 : {
1863 3200 : RangeVar *rv = lfirst(cell);
1864 : Relation rel;
1865 3200 : bool recurse = rv->inh;
1866 : Oid myrelid;
1867 3200 : LOCKMODE lockmode = AccessExclusiveLock;
1868 :
1869 3200 : myrelid = RangeVarGetRelidExtended(rv, lockmode,
1870 : 0, RangeVarCallbackForTruncate,
1871 : NULL);
1872 :
1873 : /* don't throw error for "TRUNCATE foo, foo" */
1874 3162 : if (list_member_oid(relids, myrelid))
1875 2 : continue;
1876 :
1877 : /* open the relation, we already hold a lock on it */
1878 3160 : rel = table_open(myrelid, NoLock);
1879 :
1880 : /*
1881 : * RangeVarGetRelidExtended() has done most checks with its callback,
1882 : * but other checks with the now-opened Relation remain.
1883 : */
1884 3160 : truncate_check_activity(rel);
1885 :
1886 3154 : rels = lappend(rels, rel);
1887 3154 : relids = lappend_oid(relids, myrelid);
1888 :
1889 : /* Log this relation only if needed for logical decoding */
1890 3154 : if (RelationIsLogicallyLogged(rel))
1891 68 : relids_logged = lappend_oid(relids_logged, myrelid);
1892 :
1893 3154 : if (recurse)
1894 : {
1895 : ListCell *child;
1896 : List *children;
1897 :
1898 1836 : children = find_all_inheritors(myrelid, lockmode, NULL);
1899 :
1900 5476 : foreach(child, children)
1901 : {
1902 3640 : Oid childrelid = lfirst_oid(child);
1903 :
1904 3640 : if (list_member_oid(relids, childrelid))
1905 1836 : continue;
1906 :
1907 : /* find_all_inheritors already got lock */
1908 1804 : rel = table_open(childrelid, NoLock);
1909 :
1910 : /*
1911 : * It is possible that the parent table has children that are
1912 : * temp tables of other backends. We cannot safely access
1913 : * such tables (because of buffering issues), and the best
1914 : * thing to do is to silently ignore them. Note that this
1915 : * check is the same as one of the checks done in
1916 : * truncate_check_activity() called below, still it is kept
1917 : * here for simplicity.
1918 : */
1919 1804 : if (RELATION_IS_OTHER_TEMP(rel))
1920 : {
1921 8 : table_close(rel, lockmode);
1922 8 : continue;
1923 : }
1924 :
1925 : /*
1926 : * Inherited TRUNCATE commands perform access permission
1927 : * checks on the parent table only. So we skip checking the
1928 : * children's permissions and don't call
1929 : * truncate_check_perms() here.
1930 : */
1931 1796 : truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
1932 1796 : truncate_check_activity(rel);
1933 :
1934 1796 : rels = lappend(rels, rel);
1935 1796 : relids = lappend_oid(relids, childrelid);
1936 :
1937 : /* Log this relation only if needed for logical decoding */
1938 1796 : if (RelationIsLogicallyLogged(rel))
1939 22 : relids_logged = lappend_oid(relids_logged, childrelid);
1940 : }
1941 : }
1942 1318 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1943 12 : ereport(ERROR,
1944 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1945 : errmsg("cannot truncate only a partitioned table"),
1946 : errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1947 : }
1948 :
1949 2876 : ExecuteTruncateGuts(rels, relids, relids_logged,
1950 2876 : stmt->behavior, stmt->restart_seqs, false);
1951 :
1952 : /* And close the rels */
1953 7578 : foreach(cell, rels)
1954 : {
1955 4784 : Relation rel = (Relation) lfirst(cell);
1956 :
1957 4784 : table_close(rel, NoLock);
1958 : }
1959 2794 : }
1960 :
1961 : /*
1962 : * ExecuteTruncateGuts
1963 : *
1964 : * Internal implementation of TRUNCATE. This is called by the actual TRUNCATE
1965 : * command (see above) as well as replication subscribers that execute a
1966 : * replicated TRUNCATE action.
1967 : *
1968 : * explicit_rels is the list of Relations to truncate that the command
1969 : * specified. relids is the list of Oids corresponding to explicit_rels.
1970 : * relids_logged is the list of Oids (a subset of relids) that require
1971 : * WAL-logging. This is all a bit redundant, but the existing callers have
1972 : * this information handy in this form.
1973 : */
1974 : void
1975 2904 : ExecuteTruncateGuts(List *explicit_rels,
1976 : List *relids,
1977 : List *relids_logged,
1978 : DropBehavior behavior, bool restart_seqs,
1979 : bool run_as_table_owner)
1980 : {
1981 : List *rels;
1982 2904 : List *seq_relids = NIL;
1983 2904 : HTAB *ft_htab = NULL;
1984 : EState *estate;
1985 : ResultRelInfo *resultRelInfos;
1986 : ResultRelInfo *resultRelInfo;
1987 : SubTransactionId mySubid;
1988 : ListCell *cell;
1989 : Oid *logrelids;
1990 :
1991 : /*
1992 : * Check the explicitly-specified relations.
1993 : *
1994 : * In CASCADE mode, suck in all referencing relations as well. This
1995 : * requires multiple iterations to find indirectly-dependent relations. At
1996 : * each phase, we need to exclusive-lock new rels before looking for their
1997 : * dependencies, else we might miss something. Also, we check each rel as
1998 : * soon as we open it, to avoid a faux pas such as holding lock for a long
1999 : * time on a rel we have no permissions for.
2000 : */
2001 2904 : rels = list_copy(explicit_rels);
2002 2904 : if (behavior == DROP_CASCADE)
2003 : {
2004 : for (;;)
2005 40 : {
2006 : List *newrelids;
2007 :
2008 80 : newrelids = heap_truncate_find_FKs(relids);
2009 80 : if (newrelids == NIL)
2010 40 : break; /* nothing else to add */
2011 :
2012 134 : foreach(cell, newrelids)
2013 : {
2014 94 : Oid relid = lfirst_oid(cell);
2015 : Relation rel;
2016 :
2017 94 : rel = table_open(relid, AccessExclusiveLock);
2018 94 : ereport(NOTICE,
2019 : (errmsg("truncate cascades to table \"%s\"",
2020 : RelationGetRelationName(rel))));
2021 94 : truncate_check_rel(relid, rel->rd_rel);
2022 94 : truncate_check_perms(relid, rel->rd_rel);
2023 94 : truncate_check_activity(rel);
2024 94 : rels = lappend(rels, rel);
2025 94 : relids = lappend_oid(relids, relid);
2026 :
2027 : /* Log this relation only if needed for logical decoding */
2028 94 : if (RelationIsLogicallyLogged(rel))
2029 0 : relids_logged = lappend_oid(relids_logged, relid);
2030 : }
2031 : }
2032 : }
2033 :
2034 : /*
2035 : * Check foreign key references. In CASCADE mode, this should be
2036 : * unnecessary since we just pulled in all the references; but as a
2037 : * cross-check, do it anyway if in an Assert-enabled build.
2038 : */
2039 : #ifdef USE_ASSERT_CHECKING
2040 : heap_truncate_check_FKs(rels, false);
2041 : #else
2042 2904 : if (behavior == DROP_RESTRICT)
2043 2864 : heap_truncate_check_FKs(rels, false);
2044 : #endif
2045 :
2046 : /*
2047 : * If we are asked to restart sequences, find all the sequences, lock them
2048 : * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2049 : * We want to do this early since it's pointless to do all the truncation
2050 : * work only to fail on sequence permissions.
2051 : */
2052 2830 : if (restart_seqs)
2053 : {
2054 48 : foreach(cell, rels)
2055 : {
2056 24 : Relation rel = (Relation) lfirst(cell);
2057 24 : List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2058 : ListCell *seqcell;
2059 :
2060 58 : foreach(seqcell, seqlist)
2061 : {
2062 34 : Oid seq_relid = lfirst_oid(seqcell);
2063 : Relation seq_rel;
2064 :
2065 34 : seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2066 :
2067 : /* This check must match AlterSequence! */
2068 34 : if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2069 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
2070 0 : RelationGetRelationName(seq_rel));
2071 :
2072 34 : seq_relids = lappend_oid(seq_relids, seq_relid);
2073 :
2074 34 : relation_close(seq_rel, NoLock);
2075 : }
2076 : }
2077 : }
2078 :
2079 : /* Prepare to catch AFTER triggers. */
2080 2830 : AfterTriggerBeginQuery();
2081 :
2082 : /*
2083 : * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2084 : * each relation. We don't need to call ExecOpenIndices, though.
2085 : *
2086 : * We put the ResultRelInfos in the es_opened_result_relations list, even
2087 : * though we don't have a range table and don't populate the
2088 : * es_result_relations array. That's a bit bogus, but it's enough to make
2089 : * ExecGetTriggerResultRel() find them.
2090 : */
2091 2830 : estate = CreateExecutorState();
2092 : resultRelInfos = (ResultRelInfo *)
2093 2830 : palloc(list_length(rels) * sizeof(ResultRelInfo));
2094 2830 : resultRelInfo = resultRelInfos;
2095 7774 : foreach(cell, rels)
2096 : {
2097 4944 : Relation rel = (Relation) lfirst(cell);
2098 :
2099 4944 : InitResultRelInfo(resultRelInfo,
2100 : rel,
2101 : 0, /* dummy rangetable index */
2102 : NULL,
2103 : 0);
2104 4944 : estate->es_opened_result_relations =
2105 4944 : lappend(estate->es_opened_result_relations, resultRelInfo);
2106 4944 : resultRelInfo++;
2107 : }
2108 :
2109 : /*
2110 : * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2111 : * truncating (this is because one of them might throw an error). Also, if
2112 : * we were to allow them to prevent statement execution, that would need
2113 : * to be handled here.
2114 : */
2115 2830 : resultRelInfo = resultRelInfos;
2116 7774 : foreach(cell, rels)
2117 : {
2118 : UserContext ucxt;
2119 :
2120 4944 : if (run_as_table_owner)
2121 58 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2122 : &ucxt);
2123 4944 : ExecBSTruncateTriggers(estate, resultRelInfo);
2124 4944 : if (run_as_table_owner)
2125 58 : RestoreUserContext(&ucxt);
2126 4944 : resultRelInfo++;
2127 : }
2128 :
2129 : /*
2130 : * OK, truncate each table.
2131 : */
2132 2830 : mySubid = GetCurrentSubTransactionId();
2133 :
2134 7774 : foreach(cell, rels)
2135 : {
2136 4944 : Relation rel = (Relation) lfirst(cell);
2137 :
2138 : /* Skip partitioned tables as there is nothing to do */
2139 4944 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2140 704 : continue;
2141 :
2142 : /*
2143 : * Build the lists of foreign tables belonging to each foreign server
2144 : * and pass each list to the foreign data wrapper's callback function,
2145 : * so that each server can truncate its all foreign tables in bulk.
2146 : * Each list is saved as a single entry in a hash table that uses the
2147 : * server OID as lookup key.
2148 : */
2149 4240 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2150 34 : {
2151 34 : Oid serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
2152 : bool found;
2153 : ForeignTruncateInfo *ft_info;
2154 :
2155 : /* First time through, initialize hashtable for foreign tables */
2156 34 : if (!ft_htab)
2157 : {
2158 : HASHCTL hctl;
2159 :
2160 30 : memset(&hctl, 0, sizeof(HASHCTL));
2161 30 : hctl.keysize = sizeof(Oid);
2162 30 : hctl.entrysize = sizeof(ForeignTruncateInfo);
2163 30 : hctl.hcxt = CurrentMemoryContext;
2164 :
2165 30 : ft_htab = hash_create("TRUNCATE for Foreign Tables",
2166 : 32, /* start small and extend */
2167 : &hctl,
2168 : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2169 : }
2170 :
2171 : /* Find or create cached entry for the foreign table */
2172 34 : ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2173 34 : if (!found)
2174 30 : ft_info->rels = NIL;
2175 :
2176 : /*
2177 : * Save the foreign table in the entry of the server that the
2178 : * foreign table belongs to.
2179 : */
2180 34 : ft_info->rels = lappend(ft_info->rels, rel);
2181 34 : continue;
2182 : }
2183 :
2184 : /*
2185 : * Normally, we need a transaction-safe truncation here. However, if
2186 : * the table was either created in the current (sub)transaction or has
2187 : * a new relfilenumber in the current (sub)transaction, then we can
2188 : * just truncate it in-place, because a rollback would cause the whole
2189 : * table or the current physical file to be thrown away anyway.
2190 : */
2191 4206 : if (rel->rd_createSubid == mySubid ||
2192 4180 : rel->rd_newRelfilelocatorSubid == mySubid)
2193 : {
2194 : /* Immediate, non-rollbackable truncation is OK */
2195 90 : heap_truncate_one_rel(rel);
2196 : }
2197 : else
2198 : {
2199 : Oid heap_relid;
2200 : Oid toast_relid;
2201 4116 : ReindexParams reindex_params = {0};
2202 :
2203 : /*
2204 : * This effectively deletes all rows in the table, and may be done
2205 : * in a serializable transaction. In that case we must record a
2206 : * rw-conflict in to this transaction from each transaction
2207 : * holding a predicate lock on the table.
2208 : */
2209 4116 : CheckTableForSerializableConflictIn(rel);
2210 :
2211 : /*
2212 : * Need the full transaction-safe pushups.
2213 : *
2214 : * Create a new empty storage file for the relation, and assign it
2215 : * as the relfilenumber value. The old storage file is scheduled
2216 : * for deletion at commit.
2217 : */
2218 4116 : RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2219 :
2220 4116 : heap_relid = RelationGetRelid(rel);
2221 :
2222 : /*
2223 : * The same for the toast table, if any.
2224 : */
2225 4116 : toast_relid = rel->rd_rel->reltoastrelid;
2226 4116 : if (OidIsValid(toast_relid))
2227 : {
2228 2282 : Relation toastrel = relation_open(toast_relid,
2229 : AccessExclusiveLock);
2230 :
2231 2282 : RelationSetNewRelfilenumber(toastrel,
2232 2282 : toastrel->rd_rel->relpersistence);
2233 2282 : table_close(toastrel, NoLock);
2234 : }
2235 :
2236 : /*
2237 : * Reconstruct the indexes to match, and we're done.
2238 : */
2239 4116 : reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2240 : &reindex_params);
2241 : }
2242 :
2243 4206 : pgstat_count_truncate(rel);
2244 : }
2245 :
2246 : /* Now go through the hash table, and truncate foreign tables */
2247 2830 : if (ft_htab)
2248 : {
2249 : ForeignTruncateInfo *ft_info;
2250 : HASH_SEQ_STATUS seq;
2251 :
2252 30 : hash_seq_init(&seq, ft_htab);
2253 :
2254 30 : PG_TRY();
2255 : {
2256 52 : while ((ft_info = hash_seq_search(&seq)) != NULL)
2257 : {
2258 30 : FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2259 :
2260 : /* truncate_check_rel() has checked that already */
2261 : Assert(routine->ExecForeignTruncate != NULL);
2262 :
2263 30 : routine->ExecForeignTruncate(ft_info->rels,
2264 : behavior,
2265 : restart_seqs);
2266 : }
2267 : }
2268 8 : PG_FINALLY();
2269 : {
2270 30 : hash_destroy(ft_htab);
2271 : }
2272 30 : PG_END_TRY();
2273 : }
2274 :
2275 : /*
2276 : * Restart owned sequences if we were asked to.
2277 : */
2278 2856 : foreach(cell, seq_relids)
2279 : {
2280 34 : Oid seq_relid = lfirst_oid(cell);
2281 :
2282 34 : ResetSequence(seq_relid);
2283 : }
2284 :
2285 : /*
2286 : * Write a WAL record to allow this set of actions to be logically
2287 : * decoded.
2288 : *
2289 : * Assemble an array of relids so we can write a single WAL record for the
2290 : * whole action.
2291 : */
2292 2822 : if (relids_logged != NIL)
2293 : {
2294 : xl_heap_truncate xlrec;
2295 54 : int i = 0;
2296 :
2297 : /* should only get here if wal_level >= logical */
2298 : Assert(XLogLogicalInfoActive());
2299 :
2300 54 : logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
2301 144 : foreach(cell, relids_logged)
2302 90 : logrelids[i++] = lfirst_oid(cell);
2303 :
2304 54 : xlrec.dbId = MyDatabaseId;
2305 54 : xlrec.nrelids = list_length(relids_logged);
2306 54 : xlrec.flags = 0;
2307 54 : if (behavior == DROP_CASCADE)
2308 2 : xlrec.flags |= XLH_TRUNCATE_CASCADE;
2309 54 : if (restart_seqs)
2310 4 : xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
2311 :
2312 54 : XLogBeginInsert();
2313 54 : XLogRegisterData(&xlrec, SizeOfHeapTruncate);
2314 54 : XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
2315 :
2316 54 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2317 :
2318 54 : (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2319 : }
2320 :
2321 : /*
2322 : * Process all AFTER STATEMENT TRUNCATE triggers.
2323 : */
2324 2822 : resultRelInfo = resultRelInfos;
2325 7758 : foreach(cell, rels)
2326 : {
2327 : UserContext ucxt;
2328 :
2329 4936 : if (run_as_table_owner)
2330 58 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2331 : &ucxt);
2332 4936 : ExecASTruncateTriggers(estate, resultRelInfo);
2333 4936 : if (run_as_table_owner)
2334 58 : RestoreUserContext(&ucxt);
2335 4936 : resultRelInfo++;
2336 : }
2337 :
2338 : /* Handle queued AFTER triggers */
2339 2822 : AfterTriggerEndQuery(estate);
2340 :
2341 : /* We can clean up the EState now */
2342 2822 : FreeExecutorState(estate);
2343 :
2344 : /*
2345 : * Close any rels opened by CASCADE (can't do this while EState still
2346 : * holds refs)
2347 : */
2348 2822 : rels = list_difference_ptr(rels, explicit_rels);
2349 2916 : foreach(cell, rels)
2350 : {
2351 94 : Relation rel = (Relation) lfirst(cell);
2352 :
2353 94 : table_close(rel, NoLock);
2354 : }
2355 2822 : }
2356 :
2357 : /*
2358 : * Check that a given relation is safe to truncate. Subroutine for
2359 : * ExecuteTruncate() and RangeVarCallbackForTruncate().
2360 : */
2361 : static void
2362 5332 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
2363 : {
2364 5332 : char *relname = NameStr(reltuple->relname);
2365 :
2366 : /*
2367 : * Only allow truncate on regular tables, foreign tables using foreign
2368 : * data wrappers supporting TRUNCATE and partitioned tables (although, the
2369 : * latter are only being included here for the following checks; no
2370 : * physical truncation will occur in their case.).
2371 : */
2372 5332 : if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
2373 : {
2374 38 : Oid serverid = GetForeignServerIdByRelId(relid);
2375 38 : FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
2376 :
2377 36 : if (!fdwroutine->ExecForeignTruncate)
2378 2 : ereport(ERROR,
2379 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2380 : errmsg("cannot truncate foreign table \"%s\"",
2381 : relname)));
2382 : }
2383 5294 : else if (reltuple->relkind != RELKIND_RELATION &&
2384 716 : reltuple->relkind != RELKIND_PARTITIONED_TABLE)
2385 0 : ereport(ERROR,
2386 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2387 : errmsg("\"%s\" is not a table", relname)));
2388 :
2389 : /*
2390 : * Most system catalogs can't be truncated at all, or at least not unless
2391 : * allow_system_table_mods=on. As an exception, however, we allow
2392 : * pg_largeobject to be truncated as part of pg_upgrade, because we need
2393 : * to change its relfilenode to match the old cluster, and allowing a
2394 : * TRUNCATE command to be executed is the easiest way of doing that.
2395 : */
2396 5328 : if (!allowSystemTableMods && IsSystemClass(relid, reltuple)
2397 50 : && (!IsBinaryUpgrade || relid != LargeObjectRelationId))
2398 2 : ereport(ERROR,
2399 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2400 : errmsg("permission denied: \"%s\" is a system catalog",
2401 : relname)));
2402 :
2403 5326 : InvokeObjectTruncateHook(relid);
2404 5326 : }
2405 :
2406 : /*
2407 : * Check that current user has the permission to truncate given relation.
2408 : */
2409 : static void
2410 3530 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
2411 : {
2412 3530 : char *relname = NameStr(reltuple->relname);
2413 : AclResult aclresult;
2414 :
2415 : /* Permissions checks */
2416 3530 : aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2417 3530 : if (aclresult != ACLCHECK_OK)
2418 32 : aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2419 : relname);
2420 3498 : }
2421 :
2422 : /*
2423 : * Set of extra sanity checks to check if a given relation is safe to
2424 : * truncate. This is split with truncate_check_rel() as
2425 : * RangeVarCallbackForTruncate() cannot open a Relation yet.
2426 : */
2427 : static void
2428 5050 : truncate_check_activity(Relation rel)
2429 : {
2430 : /*
2431 : * Don't allow truncate on temp tables of other backends ... their local
2432 : * buffer manager is not going to cope.
2433 : */
2434 5050 : if (RELATION_IS_OTHER_TEMP(rel))
2435 0 : ereport(ERROR,
2436 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2437 : errmsg("cannot truncate temporary tables of other sessions")));
2438 :
2439 : /*
2440 : * Also check for active uses of the relation in the current transaction,
2441 : * including open scans and pending AFTER trigger events.
2442 : */
2443 5050 : CheckTableNotInUse(rel, "TRUNCATE");
2444 5044 : }
2445 :
2446 : /*
2447 : * storage_name
2448 : * returns the name corresponding to a typstorage/attstorage enum value
2449 : */
2450 : static const char *
2451 24 : storage_name(char c)
2452 : {
2453 24 : switch (c)
2454 : {
2455 0 : case TYPSTORAGE_PLAIN:
2456 0 : return "PLAIN";
2457 0 : case TYPSTORAGE_EXTERNAL:
2458 0 : return "EXTERNAL";
2459 12 : case TYPSTORAGE_EXTENDED:
2460 12 : return "EXTENDED";
2461 12 : case TYPSTORAGE_MAIN:
2462 12 : return "MAIN";
2463 0 : default:
2464 0 : return "???";
2465 : }
2466 : }
2467 :
2468 : /*----------
2469 : * MergeAttributes
2470 : * Returns new schema given initial schema and superclasses.
2471 : *
2472 : * Input arguments:
2473 : * 'columns' is the column/attribute definition for the table. (It's a list
2474 : * of ColumnDef's.) It is destructively changed.
2475 : * 'supers' is a list of OIDs of parent relations, already locked by caller.
2476 : * 'relpersistence' is the persistence type of the table.
2477 : * 'is_partition' tells if the table is a partition.
2478 : *
2479 : * Output arguments:
2480 : * 'supconstr' receives a list of CookedConstraint representing
2481 : * CHECK constraints belonging to parent relations, updated as
2482 : * necessary to be valid for the child.
2483 : * 'supnotnulls' receives a list of CookedConstraint representing
2484 : * not-null constraints based on those from parent relations.
2485 : *
2486 : * Return value:
2487 : * Completed schema list.
2488 : *
2489 : * Notes:
2490 : * The order in which the attributes are inherited is very important.
2491 : * Intuitively, the inherited attributes should come first. If a table
2492 : * inherits from multiple parents, the order of those attributes are
2493 : * according to the order of the parents specified in CREATE TABLE.
2494 : *
2495 : * Here's an example:
2496 : *
2497 : * create table person (name text, age int4, location point);
2498 : * create table emp (salary int4, manager text) inherits(person);
2499 : * create table student (gpa float8) inherits (person);
2500 : * create table stud_emp (percent int4) inherits (emp, student);
2501 : *
2502 : * The order of the attributes of stud_emp is:
2503 : *
2504 : * person {1:name, 2:age, 3:location}
2505 : * / \
2506 : * {6:gpa} student emp {4:salary, 5:manager}
2507 : * \ /
2508 : * stud_emp {7:percent}
2509 : *
2510 : * If the same attribute name appears multiple times, then it appears
2511 : * in the result table in the proper location for its first appearance.
2512 : *
2513 : * Constraints (including not-null constraints) for the child table
2514 : * are the union of all relevant constraints, from both the child schema
2515 : * and parent tables. In addition, in legacy inheritance, each column that
2516 : * appears in a primary key in any of the parents also gets a NOT NULL
2517 : * constraint (partitioning doesn't need this, because the PK itself gets
2518 : * inherited.)
2519 : *
2520 : * The default value for a child column is defined as:
2521 : * (1) If the child schema specifies a default, that value is used.
2522 : * (2) If neither the child nor any parent specifies a default, then
2523 : * the column will not have a default.
2524 : * (3) If conflicting defaults are inherited from different parents
2525 : * (and not overridden by the child), an error is raised.
2526 : * (4) Otherwise the inherited default is used.
2527 : *
2528 : * Note that the default-value infrastructure is used for generated
2529 : * columns' expressions too, so most of the preceding paragraph applies
2530 : * to generation expressions too. We insist that a child column be
2531 : * generated if and only if its parent(s) are, but it need not have
2532 : * the same generation expression.
2533 : *----------
2534 : */
2535 : static List *
2536 63532 : MergeAttributes(List *columns, const List *supers, char relpersistence,
2537 : bool is_partition, List **supconstr, List **supnotnulls)
2538 : {
2539 63532 : List *inh_columns = NIL;
2540 63532 : List *constraints = NIL;
2541 63532 : List *nnconstraints = NIL;
2542 63532 : bool have_bogus_defaults = false;
2543 : int child_attno;
2544 : static Node bogus_marker = {0}; /* marks conflicting defaults */
2545 63532 : List *saved_columns = NIL;
2546 : ListCell *lc;
2547 :
2548 : /*
2549 : * Check for and reject tables with too many columns. We perform this
2550 : * check relatively early for two reasons: (a) we don't run the risk of
2551 : * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
2552 : * okay if we're processing <= 1600 columns, but could take minutes to
2553 : * execute if the user attempts to create a table with hundreds of
2554 : * thousands of columns.
2555 : *
2556 : * Note that we also need to check that we do not exceed this figure after
2557 : * including columns from inherited relations.
2558 : */
2559 63532 : if (list_length(columns) > MaxHeapAttributeNumber)
2560 0 : ereport(ERROR,
2561 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2562 : errmsg("tables can have at most %d columns",
2563 : MaxHeapAttributeNumber)));
2564 :
2565 : /*
2566 : * Check for duplicate names in the explicit list of attributes.
2567 : *
2568 : * Although we might consider merging such entries in the same way that we
2569 : * handle name conflicts for inherited attributes, it seems to make more
2570 : * sense to assume such conflicts are errors.
2571 : *
2572 : * We don't use foreach() here because we have two nested loops over the
2573 : * columns list, with possible element deletions in the inner one. If we
2574 : * used foreach_delete_current() it could only fix up the state of one of
2575 : * the loops, so it seems cleaner to use looping over list indexes for
2576 : * both loops. Note that any deletion will happen beyond where the outer
2577 : * loop is, so its index never needs adjustment.
2578 : */
2579 301848 : for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
2580 : {
2581 238340 : ColumnDef *coldef = list_nth_node(ColumnDef, columns, coldefpos);
2582 :
2583 238340 : if (!is_partition && coldef->typeName == NULL)
2584 : {
2585 : /*
2586 : * Typed table column option that does not belong to a column from
2587 : * the type. This works because the columns from the type come
2588 : * first in the list. (We omit this check for partition column
2589 : * lists; those are processed separately below.)
2590 : */
2591 6 : ereport(ERROR,
2592 : (errcode(ERRCODE_UNDEFINED_COLUMN),
2593 : errmsg("column \"%s\" does not exist",
2594 : coldef->colname)));
2595 : }
2596 :
2597 : /* restpos scans all entries beyond coldef; incr is in loop body */
2598 7774480 : for (int restpos = coldefpos + 1; restpos < list_length(columns);)
2599 : {
2600 7536164 : ColumnDef *restdef = list_nth_node(ColumnDef, columns, restpos);
2601 :
2602 7536164 : if (strcmp(coldef->colname, restdef->colname) == 0)
2603 : {
2604 58 : if (coldef->is_from_type)
2605 : {
2606 : /*
2607 : * merge the column options into the column from the type
2608 : */
2609 40 : coldef->is_not_null = restdef->is_not_null;
2610 40 : coldef->raw_default = restdef->raw_default;
2611 40 : coldef->cooked_default = restdef->cooked_default;
2612 40 : coldef->constraints = restdef->constraints;
2613 40 : coldef->is_from_type = false;
2614 40 : columns = list_delete_nth_cell(columns, restpos);
2615 : }
2616 : else
2617 18 : ereport(ERROR,
2618 : (errcode(ERRCODE_DUPLICATE_COLUMN),
2619 : errmsg("column \"%s\" specified more than once",
2620 : coldef->colname)));
2621 : }
2622 : else
2623 7536106 : restpos++;
2624 : }
2625 : }
2626 :
2627 : /*
2628 : * In case of a partition, there are no new column definitions, only dummy
2629 : * ColumnDefs created for column constraints. Set them aside for now and
2630 : * process them at the end.
2631 : */
2632 63508 : if (is_partition)
2633 : {
2634 7928 : saved_columns = columns;
2635 7928 : columns = NIL;
2636 : }
2637 :
2638 : /*
2639 : * Scan the parents left-to-right, and merge their attributes to form a
2640 : * list of inherited columns (inh_columns).
2641 : */
2642 63508 : child_attno = 0;
2643 73936 : foreach(lc, supers)
2644 : {
2645 10512 : Oid parent = lfirst_oid(lc);
2646 : Relation relation;
2647 : TupleDesc tupleDesc;
2648 : TupleConstr *constr;
2649 : AttrMap *newattmap;
2650 : List *inherited_defaults;
2651 : List *cols_with_defaults;
2652 : List *nnconstrs;
2653 : ListCell *lc1;
2654 : ListCell *lc2;
2655 10512 : Bitmapset *nncols = NULL;
2656 :
2657 : /* caller already got lock */
2658 10512 : relation = table_open(parent, NoLock);
2659 :
2660 : /*
2661 : * Check for active uses of the parent partitioned table in the
2662 : * current transaction, such as being used in some manner by an
2663 : * enclosing command.
2664 : */
2665 10512 : if (is_partition)
2666 7928 : CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
2667 :
2668 : /*
2669 : * We do not allow partitioned tables and partitions to participate in
2670 : * regular inheritance.
2671 : */
2672 10506 : if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
2673 6 : ereport(ERROR,
2674 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2675 : errmsg("cannot inherit from partitioned table \"%s\"",
2676 : RelationGetRelationName(relation))));
2677 10500 : if (relation->rd_rel->relispartition && !is_partition)
2678 6 : ereport(ERROR,
2679 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2680 : errmsg("cannot inherit from partition \"%s\"",
2681 : RelationGetRelationName(relation))));
2682 :
2683 10494 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2684 7924 : relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2685 7904 : relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2686 0 : ereport(ERROR,
2687 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2688 : errmsg("inherited relation \"%s\" is not a table or foreign table",
2689 : RelationGetRelationName(relation))));
2690 :
2691 : /*
2692 : * If the parent is permanent, so must be all of its partitions. Note
2693 : * that inheritance allows that case.
2694 : */
2695 10494 : if (is_partition &&
2696 7922 : relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
2697 : relpersistence == RELPERSISTENCE_TEMP)
2698 6 : ereport(ERROR,
2699 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2700 : errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
2701 : RelationGetRelationName(relation))));
2702 :
2703 : /* Permanent rels cannot inherit from temporary ones */
2704 10488 : if (relpersistence != RELPERSISTENCE_TEMP &&
2705 10134 : relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
2706 24 : ereport(ERROR,
2707 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2708 : errmsg(!is_partition
2709 : ? "cannot inherit from temporary relation \"%s\""
2710 : : "cannot create a permanent relation as partition of temporary relation \"%s\"",
2711 : RelationGetRelationName(relation))));
2712 :
2713 : /* If existing rel is temp, it must belong to this session */
2714 10464 : if (relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
2715 300 : !relation->rd_islocaltemp)
2716 0 : ereport(ERROR,
2717 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2718 : errmsg(!is_partition
2719 : ? "cannot inherit from temporary relation of another session"
2720 : : "cannot create as partition of temporary relation of another session")));
2721 :
2722 : /*
2723 : * We should have an UNDER permission flag for this, but for now,
2724 : * demand that creator of a child table own the parent.
2725 : */
2726 10464 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
2727 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
2728 0 : RelationGetRelationName(relation));
2729 :
2730 10464 : tupleDesc = RelationGetDescr(relation);
2731 10464 : constr = tupleDesc->constr;
2732 :
2733 : /*
2734 : * newattmap->attnums[] will contain the child-table attribute numbers
2735 : * for the attributes of this parent table. (They are not the same
2736 : * for parents after the first one, nor if we have dropped columns.)
2737 : */
2738 10464 : newattmap = make_attrmap(tupleDesc->natts);
2739 :
2740 : /* We can't process inherited defaults until newattmap is complete. */
2741 10464 : inherited_defaults = cols_with_defaults = NIL;
2742 :
2743 : /*
2744 : * Request attnotnull on columns that have a not-null constraint
2745 : * that's not marked NO INHERIT (even if not valid).
2746 : */
2747 10464 : nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
2748 : true, false);
2749 23352 : foreach_ptr(CookedConstraint, cc, nnconstrs)
2750 2424 : nncols = bms_add_member(nncols, cc->attnum);
2751 :
2752 31430 : for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
2753 20966 : parent_attno++)
2754 : {
2755 21002 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2756 : parent_attno - 1);
2757 21002 : char *attributeName = NameStr(attribute->attname);
2758 : int exist_attno;
2759 : ColumnDef *newdef;
2760 : ColumnDef *mergeddef;
2761 :
2762 : /*
2763 : * Ignore dropped columns in the parent.
2764 : */
2765 21002 : if (attribute->attisdropped)
2766 192 : continue; /* leave newattmap->attnums entry as zero */
2767 :
2768 : /*
2769 : * Create new column definition
2770 : */
2771 20810 : newdef = makeColumnDef(attributeName, attribute->atttypid,
2772 : attribute->atttypmod, attribute->attcollation);
2773 20810 : newdef->storage = attribute->attstorage;
2774 20810 : newdef->generated = attribute->attgenerated;
2775 20810 : if (CompressionMethodIsValid(attribute->attcompression))
2776 32 : newdef->compression =
2777 32 : pstrdup(GetCompressionMethodName(attribute->attcompression));
2778 :
2779 : /*
2780 : * Regular inheritance children are independent enough not to
2781 : * inherit identity columns. But partitions are integral part of
2782 : * a partitioned table and inherit identity column.
2783 : */
2784 20810 : if (is_partition)
2785 16066 : newdef->identity = attribute->attidentity;
2786 :
2787 : /*
2788 : * Does it match some previously considered column from another
2789 : * parent?
2790 : */
2791 20810 : exist_attno = findAttrByName(attributeName, inh_columns);
2792 20810 : if (exist_attno > 0)
2793 : {
2794 : /*
2795 : * Yes, try to merge the two column definitions.
2796 : */
2797 390 : mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
2798 :
2799 354 : newattmap->attnums[parent_attno - 1] = exist_attno;
2800 :
2801 : /*
2802 : * Partitions have only one parent, so conflict should never
2803 : * occur.
2804 : */
2805 : Assert(!is_partition);
2806 : }
2807 : else
2808 : {
2809 : /*
2810 : * No, create a new inherited column
2811 : */
2812 20420 : newdef->inhcount = 1;
2813 20420 : newdef->is_local = false;
2814 20420 : inh_columns = lappend(inh_columns, newdef);
2815 :
2816 20420 : newattmap->attnums[parent_attno - 1] = ++child_attno;
2817 20420 : mergeddef = newdef;
2818 : }
2819 :
2820 : /*
2821 : * mark attnotnull if parent has it
2822 : */
2823 20774 : if (bms_is_member(parent_attno, nncols))
2824 2424 : mergeddef->is_not_null = true;
2825 :
2826 : /*
2827 : * Locate default/generation expression if any
2828 : */
2829 20774 : if (attribute->atthasdef)
2830 : {
2831 : Node *this_default;
2832 :
2833 718 : this_default = TupleDescGetDefault(tupleDesc, parent_attno);
2834 718 : if (this_default == NULL)
2835 0 : elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
2836 : parent_attno, RelationGetRelationName(relation));
2837 :
2838 : /*
2839 : * If it's a GENERATED default, it might contain Vars that
2840 : * need to be mapped to the inherited column(s)' new numbers.
2841 : * We can't do that till newattmap is ready, so just remember
2842 : * all the inherited default expressions for the moment.
2843 : */
2844 718 : inherited_defaults = lappend(inherited_defaults, this_default);
2845 718 : cols_with_defaults = lappend(cols_with_defaults, mergeddef);
2846 : }
2847 : }
2848 :
2849 : /*
2850 : * Now process any inherited default expressions, adjusting attnos
2851 : * using the completed newattmap map.
2852 : */
2853 11146 : forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
2854 : {
2855 718 : Node *this_default = (Node *) lfirst(lc1);
2856 718 : ColumnDef *def = (ColumnDef *) lfirst(lc2);
2857 : bool found_whole_row;
2858 :
2859 : /* Adjust Vars to match new table's column numbering */
2860 718 : this_default = map_variable_attnos(this_default,
2861 : 1, 0,
2862 : newattmap,
2863 : InvalidOid, &found_whole_row);
2864 :
2865 : /*
2866 : * For the moment we have to reject whole-row variables. We could
2867 : * convert them, if we knew the new table's rowtype OID, but that
2868 : * hasn't been assigned yet. (A variable could only appear in a
2869 : * generation expression, so the error message is correct.)
2870 : */
2871 718 : if (found_whole_row)
2872 0 : ereport(ERROR,
2873 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2874 : errmsg("cannot convert whole-row table reference"),
2875 : errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
2876 : def->colname,
2877 : RelationGetRelationName(relation))));
2878 :
2879 : /*
2880 : * If we already had a default from some prior parent, check to
2881 : * see if they are the same. If so, no problem; if not, mark the
2882 : * column as having a bogus default. Below, we will complain if
2883 : * the bogus default isn't overridden by the child columns.
2884 : */
2885 : Assert(def->raw_default == NULL);
2886 718 : if (def->cooked_default == NULL)
2887 672 : def->cooked_default = this_default;
2888 46 : else if (!equal(def->cooked_default, this_default))
2889 : {
2890 40 : def->cooked_default = &bogus_marker;
2891 40 : have_bogus_defaults = true;
2892 : }
2893 : }
2894 :
2895 : /*
2896 : * Now copy the CHECK constraints of this parent, adjusting attnos
2897 : * using the completed newattmap map. Identically named constraints
2898 : * are merged if possible, else we throw error.
2899 : */
2900 10428 : if (constr && constr->num_check > 0)
2901 : {
2902 342 : ConstrCheck *check = constr->check;
2903 :
2904 1060 : for (int i = 0; i < constr->num_check; i++)
2905 : {
2906 718 : char *name = check[i].ccname;
2907 : Node *expr;
2908 : bool found_whole_row;
2909 :
2910 : /* ignore if the constraint is non-inheritable */
2911 718 : if (check[i].ccnoinherit)
2912 56 : continue;
2913 :
2914 : /* Adjust Vars to match new table's column numbering */
2915 662 : expr = map_variable_attnos(stringToNode(check[i].ccbin),
2916 : 1, 0,
2917 : newattmap,
2918 : InvalidOid, &found_whole_row);
2919 :
2920 : /*
2921 : * For the moment we have to reject whole-row variables. We
2922 : * could convert them, if we knew the new table's rowtype OID,
2923 : * but that hasn't been assigned yet.
2924 : */
2925 662 : if (found_whole_row)
2926 0 : ereport(ERROR,
2927 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2928 : errmsg("cannot convert whole-row table reference"),
2929 : errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
2930 : name,
2931 : RelationGetRelationName(relation))));
2932 :
2933 662 : constraints = MergeCheckConstraint(constraints, name, expr,
2934 662 : check[i].ccenforced);
2935 : }
2936 : }
2937 :
2938 : /*
2939 : * Also copy the not-null constraints from this parent. The
2940 : * attnotnull markings were already installed above.
2941 : */
2942 23280 : foreach_ptr(CookedConstraint, nn, nnconstrs)
2943 : {
2944 : Assert(nn->contype == CONSTR_NOTNULL);
2945 :
2946 2424 : nn->attnum = newattmap->attnums[nn->attnum - 1];
2947 :
2948 2424 : nnconstraints = lappend(nnconstraints, nn);
2949 : }
2950 :
2951 10428 : free_attrmap(newattmap);
2952 :
2953 : /*
2954 : * Close the parent rel, but keep our lock on it until xact commit.
2955 : * That will prevent someone else from deleting or ALTERing the parent
2956 : * before the child is committed.
2957 : */
2958 10428 : table_close(relation, NoLock);
2959 : }
2960 :
2961 : /*
2962 : * If we had no inherited attributes, the result columns are just the
2963 : * explicitly declared columns. Otherwise, we need to merge the declared
2964 : * columns into the inherited column list. Although, we never have any
2965 : * explicitly declared columns if the table is a partition.
2966 : */
2967 63424 : if (inh_columns != NIL)
2968 : {
2969 9980 : int newcol_attno = 0;
2970 :
2971 11056 : foreach(lc, columns)
2972 : {
2973 1154 : ColumnDef *newdef = lfirst_node(ColumnDef, lc);
2974 1154 : char *attributeName = newdef->colname;
2975 : int exist_attno;
2976 :
2977 : /*
2978 : * Partitions have only one parent and have no column definitions
2979 : * of their own, so conflict should never occur.
2980 : */
2981 : Assert(!is_partition);
2982 :
2983 1154 : newcol_attno++;
2984 :
2985 : /*
2986 : * Does it match some inherited column?
2987 : */
2988 1154 : exist_attno = findAttrByName(attributeName, inh_columns);
2989 1154 : if (exist_attno > 0)
2990 : {
2991 : /*
2992 : * Yes, try to merge the two column definitions.
2993 : */
2994 428 : MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
2995 : }
2996 : else
2997 : {
2998 : /*
2999 : * No, attach new column unchanged to result columns.
3000 : */
3001 726 : inh_columns = lappend(inh_columns, newdef);
3002 : }
3003 : }
3004 :
3005 9902 : columns = inh_columns;
3006 :
3007 : /*
3008 : * Check that we haven't exceeded the legal # of columns after merging
3009 : * in inherited columns.
3010 : */
3011 9902 : if (list_length(columns) > MaxHeapAttributeNumber)
3012 0 : ereport(ERROR,
3013 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
3014 : errmsg("tables can have at most %d columns",
3015 : MaxHeapAttributeNumber)));
3016 : }
3017 :
3018 : /*
3019 : * Now that we have the column definition list for a partition, we can
3020 : * check whether the columns referenced in the column constraint specs
3021 : * actually exist. Also, merge column defaults.
3022 : */
3023 63346 : if (is_partition)
3024 : {
3025 8104 : foreach(lc, saved_columns)
3026 : {
3027 242 : ColumnDef *restdef = lfirst(lc);
3028 242 : bool found = false;
3029 : ListCell *l;
3030 :
3031 900 : foreach(l, columns)
3032 : {
3033 694 : ColumnDef *coldef = lfirst(l);
3034 :
3035 694 : if (strcmp(coldef->colname, restdef->colname) == 0)
3036 : {
3037 242 : found = true;
3038 :
3039 : /*
3040 : * Check for conflicts related to generated columns.
3041 : *
3042 : * Same rules as above: generated-ness has to match the
3043 : * parent, but the contents of the generation expression
3044 : * can be different.
3045 : */
3046 242 : if (coldef->generated)
3047 : {
3048 134 : if (restdef->raw_default && !restdef->generated)
3049 12 : ereport(ERROR,
3050 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3051 : errmsg("column \"%s\" inherits from generated column but specifies default",
3052 : restdef->colname)));
3053 122 : if (restdef->identity)
3054 0 : ereport(ERROR,
3055 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3056 : errmsg("column \"%s\" inherits from generated column but specifies identity",
3057 : restdef->colname)));
3058 : }
3059 : else
3060 : {
3061 108 : if (restdef->generated)
3062 12 : ereport(ERROR,
3063 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3064 : errmsg("child column \"%s\" specifies generation expression",
3065 : restdef->colname),
3066 : errhint("A child table column cannot be generated unless its parent column is.")));
3067 : }
3068 :
3069 218 : if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
3070 12 : ereport(ERROR,
3071 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3072 : errmsg("column \"%s\" inherits from generated column of different kind",
3073 : restdef->colname),
3074 : errdetail("Parent column is %s, child column is %s.",
3075 : coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3076 : restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3077 :
3078 : /*
3079 : * Override the parent's default value for this column
3080 : * (coldef->cooked_default) with the partition's local
3081 : * definition (restdef->raw_default), if there's one. It
3082 : * should be physically impossible to get a cooked default
3083 : * in the local definition or a raw default in the
3084 : * inherited definition, but make sure they're nulls, for
3085 : * future-proofing.
3086 : */
3087 : Assert(restdef->cooked_default == NULL);
3088 : Assert(coldef->raw_default == NULL);
3089 206 : if (restdef->raw_default)
3090 : {
3091 134 : coldef->raw_default = restdef->raw_default;
3092 134 : coldef->cooked_default = NULL;
3093 : }
3094 : }
3095 : }
3096 :
3097 : /* complain for constraints on columns not in parent */
3098 206 : if (!found)
3099 0 : ereport(ERROR,
3100 : (errcode(ERRCODE_UNDEFINED_COLUMN),
3101 : errmsg("column \"%s\" does not exist",
3102 : restdef->colname)));
3103 : }
3104 : }
3105 :
3106 : /*
3107 : * If we found any conflicting parent default values, check to make sure
3108 : * they were overridden by the child.
3109 : */
3110 63310 : if (have_bogus_defaults)
3111 : {
3112 106 : foreach(lc, columns)
3113 : {
3114 84 : ColumnDef *def = lfirst(lc);
3115 :
3116 84 : if (def->cooked_default == &bogus_marker)
3117 : {
3118 18 : if (def->generated)
3119 12 : ereport(ERROR,
3120 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3121 : errmsg("column \"%s\" inherits conflicting generation expressions",
3122 : def->colname),
3123 : errhint("To resolve the conflict, specify a generation expression explicitly.")));
3124 : else
3125 6 : ereport(ERROR,
3126 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3127 : errmsg("column \"%s\" inherits conflicting default values",
3128 : def->colname),
3129 : errhint("To resolve the conflict, specify a default explicitly.")));
3130 : }
3131 : }
3132 : }
3133 :
3134 63292 : *supconstr = constraints;
3135 63292 : *supnotnulls = nnconstraints;
3136 :
3137 63292 : return columns;
3138 : }
3139 :
3140 :
3141 : /*
3142 : * MergeCheckConstraint
3143 : * Try to merge an inherited CHECK constraint with previous ones
3144 : *
3145 : * If we inherit identically-named constraints from multiple parents, we must
3146 : * merge them, or throw an error if they don't have identical definitions.
3147 : *
3148 : * constraints is a list of CookedConstraint structs for previous constraints.
3149 : *
3150 : * If the new constraint matches an existing one, then the existing
3151 : * constraint's inheritance count is updated. If there is a conflict (same
3152 : * name but different expression), throw an error. If the constraint neither
3153 : * matches nor conflicts with an existing one, a new constraint is appended to
3154 : * the list.
3155 : */
3156 : static List *
3157 662 : MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
3158 : {
3159 : ListCell *lc;
3160 : CookedConstraint *newcon;
3161 :
3162 2116 : foreach(lc, constraints)
3163 : {
3164 1604 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
3165 :
3166 : Assert(ccon->contype == CONSTR_CHECK);
3167 :
3168 : /* Non-matching names never conflict */
3169 1604 : if (strcmp(ccon->name, name) != 0)
3170 1454 : continue;
3171 :
3172 150 : if (equal(expr, ccon->expr))
3173 : {
3174 : /* OK to merge constraint with existing */
3175 150 : if (pg_add_s16_overflow(ccon->inhcount, 1,
3176 : &ccon->inhcount))
3177 0 : ereport(ERROR,
3178 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3179 : errmsg("too many inheritance parents"));
3180 :
3181 : /*
3182 : * When enforceability differs, the merged constraint should be
3183 : * marked as ENFORCED because one of the parents is ENFORCED.
3184 : */
3185 150 : if (!ccon->is_enforced && is_enforced)
3186 : {
3187 48 : ccon->is_enforced = true;
3188 48 : ccon->skip_validation = false;
3189 : }
3190 :
3191 150 : return constraints;
3192 : }
3193 :
3194 0 : ereport(ERROR,
3195 : (errcode(ERRCODE_DUPLICATE_OBJECT),
3196 : errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
3197 : name)));
3198 : }
3199 :
3200 : /*
3201 : * Constraint couldn't be merged with an existing one and also didn't
3202 : * conflict with an existing one, so add it as a new one to the list.
3203 : */
3204 512 : newcon = palloc0_object(CookedConstraint);
3205 512 : newcon->contype = CONSTR_CHECK;
3206 512 : newcon->name = pstrdup(name);
3207 512 : newcon->expr = expr;
3208 512 : newcon->inhcount = 1;
3209 512 : newcon->is_enforced = is_enforced;
3210 512 : newcon->skip_validation = !is_enforced;
3211 512 : return lappend(constraints, newcon);
3212 : }
3213 :
3214 : /*
3215 : * MergeChildAttribute
3216 : * Merge given child attribute definition into given inherited attribute.
3217 : *
3218 : * Input arguments:
3219 : * 'inh_columns' is the list of inherited ColumnDefs.
3220 : * 'exist_attno' is the number of the inherited attribute in inh_columns
3221 : * 'newcol_attno' is the attribute number in child table's schema definition
3222 : * 'newdef' is the column/attribute definition from the child table.
3223 : *
3224 : * The ColumnDef in 'inh_columns' list is modified. The child attribute's
3225 : * ColumnDef remains unchanged.
3226 : *
3227 : * Notes:
3228 : * - The attribute is merged according to the rules laid out in the prologue
3229 : * of MergeAttributes().
3230 : * - If matching inherited attribute exists but the child attribute can not be
3231 : * merged into it, the function throws respective errors.
3232 : * - A partition can not have its own column definitions. Hence this function
3233 : * is applicable only to a regular inheritance child.
3234 : */
3235 : static void
3236 428 : MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
3237 : {
3238 428 : char *attributeName = newdef->colname;
3239 : ColumnDef *inhdef;
3240 : Oid inhtypeid,
3241 : newtypeid;
3242 : int32 inhtypmod,
3243 : newtypmod;
3244 : Oid inhcollid,
3245 : newcollid;
3246 :
3247 428 : if (exist_attno == newcol_attno)
3248 366 : ereport(NOTICE,
3249 : (errmsg("merging column \"%s\" with inherited definition",
3250 : attributeName)));
3251 : else
3252 62 : ereport(NOTICE,
3253 : (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
3254 : errdetail("User-specified column moved to the position of the inherited column.")));
3255 :
3256 428 : inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3257 :
3258 : /*
3259 : * Must have the same type and typmod
3260 : */
3261 428 : typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
3262 428 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3263 428 : if (inhtypeid != newtypeid || inhtypmod != newtypmod)
3264 12 : ereport(ERROR,
3265 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3266 : errmsg("column \"%s\" has a type conflict",
3267 : attributeName),
3268 : errdetail("%s versus %s",
3269 : format_type_with_typemod(inhtypeid, inhtypmod),
3270 : format_type_with_typemod(newtypeid, newtypmod))));
3271 :
3272 : /*
3273 : * Must have the same collation
3274 : */
3275 416 : inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
3276 416 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3277 416 : if (inhcollid != newcollid)
3278 6 : ereport(ERROR,
3279 : (errcode(ERRCODE_COLLATION_MISMATCH),
3280 : errmsg("column \"%s\" has a collation conflict",
3281 : attributeName),
3282 : errdetail("\"%s\" versus \"%s\"",
3283 : get_collation_name(inhcollid),
3284 : get_collation_name(newcollid))));
3285 :
3286 : /*
3287 : * Identity is never inherited by a regular inheritance child. Pick
3288 : * child's identity definition if there's one.
3289 : */
3290 410 : inhdef->identity = newdef->identity;
3291 :
3292 : /*
3293 : * Copy storage parameter
3294 : */
3295 410 : if (inhdef->storage == 0)
3296 0 : inhdef->storage = newdef->storage;
3297 410 : else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
3298 6 : ereport(ERROR,
3299 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3300 : errmsg("column \"%s\" has a storage parameter conflict",
3301 : attributeName),
3302 : errdetail("%s versus %s",
3303 : storage_name(inhdef->storage),
3304 : storage_name(newdef->storage))));
3305 :
3306 : /*
3307 : * Copy compression parameter
3308 : */
3309 404 : if (inhdef->compression == NULL)
3310 398 : inhdef->compression = newdef->compression;
3311 6 : else if (newdef->compression != NULL)
3312 : {
3313 6 : if (strcmp(inhdef->compression, newdef->compression) != 0)
3314 6 : ereport(ERROR,
3315 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3316 : errmsg("column \"%s\" has a compression method conflict",
3317 : attributeName),
3318 : errdetail("%s versus %s", inhdef->compression, newdef->compression)));
3319 : }
3320 :
3321 : /*
3322 : * Merge of not-null constraints = OR 'em together
3323 : */
3324 398 : inhdef->is_not_null |= newdef->is_not_null;
3325 :
3326 : /*
3327 : * Check for conflicts related to generated columns.
3328 : *
3329 : * If the parent column is generated, the child column will be made a
3330 : * generated column if it isn't already. If it is a generated column,
3331 : * we'll take its generation expression in preference to the parent's. We
3332 : * must check that the child column doesn't specify a default value or
3333 : * identity, which matches the rules for a single column in
3334 : * parse_utilcmd.c.
3335 : *
3336 : * Conversely, if the parent column is not generated, the child column
3337 : * can't be either. (We used to allow that, but it results in being able
3338 : * to override the generation expression via UPDATEs through the parent.)
3339 : */
3340 398 : if (inhdef->generated)
3341 : {
3342 78 : if (newdef->raw_default && !newdef->generated)
3343 12 : ereport(ERROR,
3344 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3345 : errmsg("column \"%s\" inherits from generated column but specifies default",
3346 : inhdef->colname)));
3347 66 : if (newdef->identity)
3348 12 : ereport(ERROR,
3349 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3350 : errmsg("column \"%s\" inherits from generated column but specifies identity",
3351 : inhdef->colname)));
3352 : }
3353 : else
3354 : {
3355 320 : if (newdef->generated)
3356 12 : ereport(ERROR,
3357 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3358 : errmsg("child column \"%s\" specifies generation expression",
3359 : inhdef->colname),
3360 : errhint("A child table column cannot be generated unless its parent column is.")));
3361 : }
3362 :
3363 362 : if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
3364 12 : ereport(ERROR,
3365 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3366 : errmsg("column \"%s\" inherits from generated column of different kind",
3367 : inhdef->colname),
3368 : errdetail("Parent column is %s, child column is %s.",
3369 : inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3370 : newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3371 :
3372 : /*
3373 : * If new def has a default, override previous default
3374 : */
3375 350 : if (newdef->raw_default != NULL)
3376 : {
3377 38 : inhdef->raw_default = newdef->raw_default;
3378 38 : inhdef->cooked_default = newdef->cooked_default;
3379 : }
3380 :
3381 : /* Mark the column as locally defined */
3382 350 : inhdef->is_local = true;
3383 350 : }
3384 :
3385 : /*
3386 : * MergeInheritedAttribute
3387 : * Merge given parent attribute definition into specified attribute
3388 : * inherited from the previous parents.
3389 : *
3390 : * Input arguments:
3391 : * 'inh_columns' is the list of previously inherited ColumnDefs.
3392 : * 'exist_attno' is the number the existing matching attribute in inh_columns.
3393 : * 'newdef' is the new parent column/attribute definition to be merged.
3394 : *
3395 : * The matching ColumnDef in 'inh_columns' list is modified and returned.
3396 : *
3397 : * Notes:
3398 : * - The attribute is merged according to the rules laid out in the prologue
3399 : * of MergeAttributes().
3400 : * - If matching inherited attribute exists but the new attribute can not be
3401 : * merged into it, the function throws respective errors.
3402 : * - A partition inherits from only a single parent. Hence this function is
3403 : * applicable only to a regular inheritance.
3404 : */
3405 : static ColumnDef *
3406 390 : MergeInheritedAttribute(List *inh_columns,
3407 : int exist_attno,
3408 : const ColumnDef *newdef)
3409 : {
3410 390 : char *attributeName = newdef->colname;
3411 : ColumnDef *prevdef;
3412 : Oid prevtypeid,
3413 : newtypeid;
3414 : int32 prevtypmod,
3415 : newtypmod;
3416 : Oid prevcollid,
3417 : newcollid;
3418 :
3419 390 : ereport(NOTICE,
3420 : (errmsg("merging multiple inherited definitions of column \"%s\"",
3421 : attributeName)));
3422 390 : prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3423 :
3424 : /*
3425 : * Must have the same type and typmod
3426 : */
3427 390 : typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
3428 390 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3429 390 : if (prevtypeid != newtypeid || prevtypmod != newtypmod)
3430 0 : ereport(ERROR,
3431 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3432 : errmsg("inherited column \"%s\" has a type conflict",
3433 : attributeName),
3434 : errdetail("%s versus %s",
3435 : format_type_with_typemod(prevtypeid, prevtypmod),
3436 : format_type_with_typemod(newtypeid, newtypmod))));
3437 :
3438 : /*
3439 : * Must have the same collation
3440 : */
3441 390 : prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
3442 390 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3443 390 : if (prevcollid != newcollid)
3444 0 : ereport(ERROR,
3445 : (errcode(ERRCODE_COLLATION_MISMATCH),
3446 : errmsg("inherited column \"%s\" has a collation conflict",
3447 : attributeName),
3448 : errdetail("\"%s\" versus \"%s\"",
3449 : get_collation_name(prevcollid),
3450 : get_collation_name(newcollid))));
3451 :
3452 : /*
3453 : * Copy/check storage parameter
3454 : */
3455 390 : if (prevdef->storage == 0)
3456 0 : prevdef->storage = newdef->storage;
3457 390 : else if (prevdef->storage != newdef->storage)
3458 6 : ereport(ERROR,
3459 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3460 : errmsg("inherited column \"%s\" has a storage parameter conflict",
3461 : attributeName),
3462 : errdetail("%s versus %s",
3463 : storage_name(prevdef->storage),
3464 : storage_name(newdef->storage))));
3465 :
3466 : /*
3467 : * Copy/check compression parameter
3468 : */
3469 384 : if (prevdef->compression == NULL)
3470 370 : prevdef->compression = newdef->compression;
3471 14 : else if (newdef->compression != NULL)
3472 : {
3473 6 : if (strcmp(prevdef->compression, newdef->compression) != 0)
3474 6 : ereport(ERROR,
3475 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3476 : errmsg("column \"%s\" has a compression method conflict",
3477 : attributeName),
3478 : errdetail("%s versus %s",
3479 : prevdef->compression, newdef->compression)));
3480 : }
3481 :
3482 : /*
3483 : * Check for GENERATED conflicts
3484 : */
3485 378 : if (prevdef->generated != newdef->generated)
3486 24 : ereport(ERROR,
3487 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3488 : errmsg("inherited column \"%s\" has a generation conflict",
3489 : attributeName)));
3490 :
3491 : /*
3492 : * Default and other constraints are handled by the caller.
3493 : */
3494 :
3495 354 : if (pg_add_s16_overflow(prevdef->inhcount, 1,
3496 : &prevdef->inhcount))
3497 0 : ereport(ERROR,
3498 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3499 : errmsg("too many inheritance parents"));
3500 :
3501 354 : return prevdef;
3502 : }
3503 :
3504 : /*
3505 : * StoreCatalogInheritance
3506 : * Updates the system catalogs with proper inheritance information.
3507 : *
3508 : * supers is a list of the OIDs of the new relation's direct ancestors.
3509 : */
3510 : static void
3511 62632 : StoreCatalogInheritance(Oid relationId, List *supers,
3512 : bool child_is_partition)
3513 : {
3514 : Relation relation;
3515 : int32 seqNumber;
3516 : ListCell *entry;
3517 :
3518 : /*
3519 : * sanity checks
3520 : */
3521 : Assert(OidIsValid(relationId));
3522 :
3523 62632 : if (supers == NIL)
3524 53090 : return;
3525 :
3526 : /*
3527 : * Store INHERITS information in pg_inherits using direct ancestors only.
3528 : * Also enter dependencies on the direct ancestors, and make sure they are
3529 : * marked with relhassubclass = true.
3530 : *
3531 : * (Once upon a time, both direct and indirect ancestors were found here
3532 : * and then entered into pg_ipl. Since that catalog doesn't exist
3533 : * anymore, there's no need to look for indirect ancestors.)
3534 : */
3535 9542 : relation = table_open(InheritsRelationId, RowExclusiveLock);
3536 :
3537 9542 : seqNumber = 1;
3538 19430 : foreach(entry, supers)
3539 : {
3540 9888 : Oid parentOid = lfirst_oid(entry);
3541 :
3542 9888 : StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
3543 : child_is_partition);
3544 9888 : seqNumber++;
3545 : }
3546 :
3547 9542 : table_close(relation, RowExclusiveLock);
3548 : }
3549 :
3550 : /*
3551 : * Make catalog entries showing relationId as being an inheritance child
3552 : * of parentOid. inhRelation is the already-opened pg_inherits catalog.
3553 : */
3554 : static void
3555 12726 : StoreCatalogInheritance1(Oid relationId, Oid parentOid,
3556 : int32 seqNumber, Relation inhRelation,
3557 : bool child_is_partition)
3558 : {
3559 : ObjectAddress childobject,
3560 : parentobject;
3561 :
3562 : /* store the pg_inherits row */
3563 12726 : StoreSingleInheritance(relationId, parentOid, seqNumber);
3564 :
3565 : /*
3566 : * Store a dependency too
3567 : */
3568 12726 : parentobject.classId = RelationRelationId;
3569 12726 : parentobject.objectId = parentOid;
3570 12726 : parentobject.objectSubId = 0;
3571 12726 : childobject.classId = RelationRelationId;
3572 12726 : childobject.objectId = relationId;
3573 12726 : childobject.objectSubId = 0;
3574 :
3575 12726 : recordDependencyOn(&childobject, &parentobject,
3576 : child_dependency_type(child_is_partition));
3577 :
3578 : /*
3579 : * Post creation hook of this inheritance. Since object_access_hook
3580 : * doesn't take multiple object identifiers, we relay oid of parent
3581 : * relation using auxiliary_id argument.
3582 : */
3583 12726 : InvokeObjectPostAlterHookArg(InheritsRelationId,
3584 : relationId, 0,
3585 : parentOid, false);
3586 :
3587 : /*
3588 : * Mark the parent as having subclasses.
3589 : */
3590 12726 : SetRelationHasSubclass(parentOid, true);
3591 12726 : }
3592 :
3593 : /*
3594 : * Look for an existing column entry with the given name.
3595 : *
3596 : * Returns the index (starting with 1) if attribute already exists in columns,
3597 : * 0 if it doesn't.
3598 : */
3599 : static int
3600 21964 : findAttrByName(const char *attributeName, const List *columns)
3601 : {
3602 : ListCell *lc;
3603 21964 : int i = 1;
3604 :
3605 39368 : foreach(lc, columns)
3606 : {
3607 18222 : if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
3608 818 : return i;
3609 :
3610 17404 : i++;
3611 : }
3612 21146 : return 0;
3613 : }
3614 :
3615 :
3616 : /*
3617 : * SetRelationHasSubclass
3618 : * Set the value of the relation's relhassubclass field in pg_class.
3619 : *
3620 : * It's always safe to set this field to true, because all SQL commands are
3621 : * ready to see true and then find no children. On the other hand, commands
3622 : * generally assume zero children if this is false.
3623 : *
3624 : * Caller must hold any self-exclusive lock until end of transaction. If the
3625 : * new value is false, caller must have acquired that lock before reading the
3626 : * evidence that justified the false value. That way, it properly waits if
3627 : * another backend is simultaneously concluding no need to change the tuple
3628 : * (new and old values are true).
3629 : *
3630 : * NOTE: an important side-effect of this operation is that an SI invalidation
3631 : * message is sent out to all backends --- including me --- causing plans
3632 : * referencing the relation to be rebuilt with the new list of children.
3633 : * This must happen even if we find that no change is needed in the pg_class
3634 : * row.
3635 : */
3636 : void
3637 15854 : SetRelationHasSubclass(Oid relationId, bool relhassubclass)
3638 : {
3639 : Relation relationRelation;
3640 : HeapTuple tuple;
3641 : Form_pg_class classtuple;
3642 :
3643 : Assert(CheckRelationOidLockedByMe(relationId,
3644 : ShareUpdateExclusiveLock, false) ||
3645 : CheckRelationOidLockedByMe(relationId,
3646 : ShareRowExclusiveLock, true));
3647 :
3648 : /*
3649 : * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3650 : */
3651 15854 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3652 15854 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3653 15854 : if (!HeapTupleIsValid(tuple))
3654 0 : elog(ERROR, "cache lookup failed for relation %u", relationId);
3655 15854 : classtuple = (Form_pg_class) GETSTRUCT(tuple);
3656 :
3657 15854 : if (classtuple->relhassubclass != relhassubclass)
3658 : {
3659 7990 : classtuple->relhassubclass = relhassubclass;
3660 7990 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3661 : }
3662 : else
3663 : {
3664 : /* no need to change tuple, but force relcache rebuild anyway */
3665 7864 : CacheInvalidateRelcacheByTuple(tuple);
3666 : }
3667 :
3668 15854 : heap_freetuple(tuple);
3669 15854 : table_close(relationRelation, RowExclusiveLock);
3670 15854 : }
3671 :
3672 : /*
3673 : * CheckRelationTableSpaceMove
3674 : * Check if relation can be moved to new tablespace.
3675 : *
3676 : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3677 : *
3678 : * Returns true if the relation can be moved to the new tablespace; raises
3679 : * an error if it is not possible to do the move; returns false if the move
3680 : * would have no effect.
3681 : */
3682 : bool
3683 226 : CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
3684 : {
3685 : Oid oldTableSpaceId;
3686 :
3687 : /*
3688 : * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3689 : * stored as 0.
3690 : */
3691 226 : oldTableSpaceId = rel->rd_rel->reltablespace;
3692 226 : if (newTableSpaceId == oldTableSpaceId ||
3693 218 : (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3694 10 : return false;
3695 :
3696 : /*
3697 : * We cannot support moving mapped relations into different tablespaces.
3698 : * (In particular this eliminates all shared catalogs.)
3699 : */
3700 216 : if (RelationIsMapped(rel))
3701 0 : ereport(ERROR,
3702 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3703 : errmsg("cannot move system relation \"%s\"",
3704 : RelationGetRelationName(rel))));
3705 :
3706 : /* Cannot move a non-shared relation into pg_global */
3707 216 : if (newTableSpaceId == GLOBALTABLESPACE_OID)
3708 12 : ereport(ERROR,
3709 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3710 : errmsg("only shared relations can be placed in pg_global tablespace")));
3711 :
3712 : /*
3713 : * Do not allow moving temp tables of other backends ... their local
3714 : * buffer manager is not going to cope.
3715 : */
3716 204 : if (RELATION_IS_OTHER_TEMP(rel))
3717 0 : ereport(ERROR,
3718 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3719 : errmsg("cannot move temporary tables of other sessions")));
3720 :
3721 204 : return true;
3722 : }
3723 :
3724 : /*
3725 : * SetRelationTableSpace
3726 : * Set new reltablespace and relfilenumber in pg_class entry.
3727 : *
3728 : * newTableSpaceId is the new tablespace for the relation, and
3729 : * newRelFilenumber its new filenumber. If newRelFilenumber is
3730 : * InvalidRelFileNumber, this field is not updated.
3731 : *
3732 : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3733 : *
3734 : * The caller of this routine had better check if a relation can be
3735 : * moved to this new tablespace by calling CheckRelationTableSpaceMove()
3736 : * first, and is responsible for making the change visible with
3737 : * CommandCounterIncrement().
3738 : */
3739 : void
3740 204 : SetRelationTableSpace(Relation rel,
3741 : Oid newTableSpaceId,
3742 : RelFileNumber newRelFilenumber)
3743 : {
3744 : Relation pg_class;
3745 : HeapTuple tuple;
3746 : ItemPointerData otid;
3747 : Form_pg_class rd_rel;
3748 204 : Oid reloid = RelationGetRelid(rel);
3749 :
3750 : Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3751 :
3752 : /* Get a modifiable copy of the relation's pg_class row. */
3753 204 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
3754 :
3755 204 : tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3756 204 : if (!HeapTupleIsValid(tuple))
3757 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
3758 204 : otid = tuple->t_self;
3759 204 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3760 :
3761 : /* Update the pg_class row. */
3762 408 : rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3763 204 : InvalidOid : newTableSpaceId;
3764 204 : if (RelFileNumberIsValid(newRelFilenumber))
3765 160 : rd_rel->relfilenode = newRelFilenumber;
3766 204 : CatalogTupleUpdate(pg_class, &otid, tuple);
3767 204 : UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3768 :
3769 : /*
3770 : * Record dependency on tablespace. This is only required for relations
3771 : * that have no physical storage.
3772 : */
3773 204 : if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3774 30 : changeDependencyOnTablespace(RelationRelationId, reloid,
3775 : rd_rel->reltablespace);
3776 :
3777 204 : heap_freetuple(tuple);
3778 204 : table_close(pg_class, RowExclusiveLock);
3779 204 : }
3780 :
3781 : /*
3782 : * renameatt_check - basic sanity checks before attribute rename
3783 : */
3784 : static void
3785 1008 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3786 : {
3787 1008 : char relkind = classform->relkind;
3788 :
3789 1008 : if (classform->reloftype && !recursing)
3790 6 : ereport(ERROR,
3791 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3792 : errmsg("cannot rename column of typed table")));
3793 :
3794 : /*
3795 : * Renaming the columns of sequences or toast tables doesn't actually
3796 : * break anything from the system's point of view, since internal
3797 : * references are by attnum. But it doesn't seem right to allow users to
3798 : * change names that are hardcoded into the system, hence the following
3799 : * restriction.
3800 : */
3801 1002 : if (relkind != RELKIND_RELATION &&
3802 84 : relkind != RELKIND_VIEW &&
3803 84 : relkind != RELKIND_MATVIEW &&
3804 36 : relkind != RELKIND_COMPOSITE_TYPE &&
3805 36 : relkind != RELKIND_INDEX &&
3806 36 : relkind != RELKIND_PARTITIONED_INDEX &&
3807 0 : relkind != RELKIND_FOREIGN_TABLE &&
3808 : relkind != RELKIND_PARTITIONED_TABLE)
3809 0 : ereport(ERROR,
3810 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3811 : errmsg("cannot rename columns of relation \"%s\"",
3812 : NameStr(classform->relname)),
3813 : errdetail_relkind_not_supported(relkind)));
3814 :
3815 : /*
3816 : * permissions checking. only the owner of a class can change its schema.
3817 : */
3818 1002 : if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
3819 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
3820 0 : NameStr(classform->relname));
3821 1002 : if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
3822 2 : ereport(ERROR,
3823 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3824 : errmsg("permission denied: \"%s\" is a system catalog",
3825 : NameStr(classform->relname))));
3826 1000 : }
3827 :
3828 : /*
3829 : * renameatt_internal - workhorse for renameatt
3830 : *
3831 : * Return value is the attribute number in the 'myrelid' relation.
3832 : */
3833 : static AttrNumber
3834 552 : renameatt_internal(Oid myrelid,
3835 : const char *oldattname,
3836 : const char *newattname,
3837 : bool recurse,
3838 : bool recursing,
3839 : int expected_parents,
3840 : DropBehavior behavior)
3841 : {
3842 : Relation targetrelation;
3843 : Relation attrelation;
3844 : HeapTuple atttup;
3845 : Form_pg_attribute attform;
3846 : AttrNumber attnum;
3847 :
3848 : /*
3849 : * Grab an exclusive lock on the target table, which we will NOT release
3850 : * until end of transaction.
3851 : */
3852 552 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
3853 552 : renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
3854 :
3855 : /*
3856 : * if the 'recurse' flag is set then we are supposed to rename this
3857 : * attribute in all classes that inherit from 'relname' (as well as in
3858 : * 'relname').
3859 : *
3860 : * any permissions or problems with duplicate attributes will cause the
3861 : * whole transaction to abort, which is what we want -- all or nothing.
3862 : */
3863 552 : if (recurse)
3864 : {
3865 : List *child_oids,
3866 : *child_numparents;
3867 : ListCell *lo,
3868 : *li;
3869 :
3870 : /*
3871 : * we need the number of parents for each child so that the recursive
3872 : * calls to renameatt() can determine whether there are any parents
3873 : * outside the inheritance hierarchy being processed.
3874 : */
3875 248 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3876 : &child_numparents);
3877 :
3878 : /*
3879 : * find_all_inheritors does the recursive search of the inheritance
3880 : * hierarchy, so all we have to do is process all of the relids in the
3881 : * list that it returns.
3882 : */
3883 734 : forboth(lo, child_oids, li, child_numparents)
3884 : {
3885 516 : Oid childrelid = lfirst_oid(lo);
3886 516 : int numparents = lfirst_int(li);
3887 :
3888 516 : if (childrelid == myrelid)
3889 248 : continue;
3890 : /* note we need not recurse again */
3891 268 : renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
3892 : }
3893 : }
3894 : else
3895 : {
3896 : /*
3897 : * If we are told not to recurse, there had better not be any child
3898 : * tables; else the rename would put them out of step.
3899 : *
3900 : * expected_parents will only be 0 if we are not already recursing.
3901 : */
3902 340 : if (expected_parents == 0 &&
3903 36 : find_inheritance_children(myrelid, NoLock) != NIL)
3904 12 : ereport(ERROR,
3905 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3906 : errmsg("inherited column \"%s\" must be renamed in child tables too",
3907 : oldattname)));
3908 : }
3909 :
3910 : /* rename attributes in typed tables of composite type */
3911 510 : if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
3912 : {
3913 : List *child_oids;
3914 : ListCell *lo;
3915 :
3916 24 : child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
3917 24 : RelationGetRelationName(targetrelation),
3918 : behavior);
3919 :
3920 24 : foreach(lo, child_oids)
3921 6 : renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
3922 : }
3923 :
3924 504 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
3925 :
3926 504 : atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
3927 504 : if (!HeapTupleIsValid(atttup))
3928 24 : ereport(ERROR,
3929 : (errcode(ERRCODE_UNDEFINED_COLUMN),
3930 : errmsg("column \"%s\" does not exist",
3931 : oldattname)));
3932 480 : attform = (Form_pg_attribute) GETSTRUCT(atttup);
3933 :
3934 480 : attnum = attform->attnum;
3935 480 : if (attnum <= 0)
3936 0 : ereport(ERROR,
3937 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3938 : errmsg("cannot rename system column \"%s\"",
3939 : oldattname)));
3940 :
3941 : /*
3942 : * if the attribute is inherited, forbid the renaming. if this is a
3943 : * top-level call to renameatt(), then expected_parents will be 0, so the
3944 : * effect of this code will be to prohibit the renaming if the attribute
3945 : * is inherited at all. if this is a recursive call to renameatt(),
3946 : * expected_parents will be the number of parents the current relation has
3947 : * within the inheritance hierarchy being processed, so we'll prohibit the
3948 : * renaming only if there are additional parents from elsewhere.
3949 : */
3950 480 : if (attform->attinhcount > expected_parents)
3951 30 : ereport(ERROR,
3952 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3953 : errmsg("cannot rename inherited column \"%s\"",
3954 : oldattname)));
3955 :
3956 : /* new name should not already exist */
3957 450 : (void) check_for_column_name_collision(targetrelation, newattname, false);
3958 :
3959 : /* apply the update */
3960 438 : namestrcpy(&(attform->attname), newattname);
3961 :
3962 438 : CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
3963 :
3964 438 : InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
3965 :
3966 438 : heap_freetuple(atttup);
3967 :
3968 438 : table_close(attrelation, RowExclusiveLock);
3969 :
3970 438 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
3971 :
3972 438 : return attnum;
3973 : }
3974 :
3975 : /*
3976 : * Perform permissions and integrity checks before acquiring a relation lock.
3977 : */
3978 : static void
3979 412 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
3980 : void *arg)
3981 : {
3982 : HeapTuple tuple;
3983 : Form_pg_class form;
3984 :
3985 412 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
3986 412 : if (!HeapTupleIsValid(tuple))
3987 40 : return; /* concurrently dropped */
3988 372 : form = (Form_pg_class) GETSTRUCT(tuple);
3989 372 : renameatt_check(relid, form, false);
3990 364 : ReleaseSysCache(tuple);
3991 : }
3992 :
3993 : /*
3994 : * renameatt - changes the name of an attribute in a relation
3995 : *
3996 : * The returned ObjectAddress is that of the renamed column.
3997 : */
3998 : ObjectAddress
3999 316 : renameatt(RenameStmt *stmt)
4000 : {
4001 : Oid relid;
4002 : AttrNumber attnum;
4003 : ObjectAddress address;
4004 :
4005 : /* lock level taken here should match renameatt_internal */
4006 316 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4007 316 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4008 : RangeVarCallbackForRenameAttribute,
4009 : NULL);
4010 :
4011 302 : if (!OidIsValid(relid))
4012 : {
4013 24 : ereport(NOTICE,
4014 : (errmsg("relation \"%s\" does not exist, skipping",
4015 : stmt->relation->relname)));
4016 24 : return InvalidObjectAddress;
4017 : }
4018 :
4019 : attnum =
4020 278 : renameatt_internal(relid,
4021 278 : stmt->subname, /* old att name */
4022 278 : stmt->newname, /* new att name */
4023 278 : stmt->relation->inh, /* recursive? */
4024 : false, /* recursing? */
4025 : 0, /* expected inhcount */
4026 : stmt->behavior);
4027 :
4028 194 : ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4029 :
4030 194 : return address;
4031 : }
4032 :
4033 : /*
4034 : * same logic as renameatt_internal
4035 : */
4036 : static ObjectAddress
4037 90 : rename_constraint_internal(Oid myrelid,
4038 : Oid mytypid,
4039 : const char *oldconname,
4040 : const char *newconname,
4041 : bool recurse,
4042 : bool recursing,
4043 : int expected_parents)
4044 : {
4045 90 : Relation targetrelation = NULL;
4046 : Oid constraintOid;
4047 : HeapTuple tuple;
4048 : Form_pg_constraint con;
4049 : ObjectAddress address;
4050 :
4051 : Assert(!myrelid || !mytypid);
4052 :
4053 90 : if (mytypid)
4054 : {
4055 6 : constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
4056 : }
4057 : else
4058 : {
4059 84 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
4060 :
4061 : /*
4062 : * don't tell it whether we're recursing; we allow changing typed
4063 : * tables here
4064 : */
4065 84 : renameatt_check(myrelid, RelationGetForm(targetrelation), false);
4066 :
4067 84 : constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
4068 : }
4069 :
4070 90 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
4071 90 : if (!HeapTupleIsValid(tuple))
4072 0 : elog(ERROR, "cache lookup failed for constraint %u",
4073 : constraintOid);
4074 90 : con = (Form_pg_constraint) GETSTRUCT(tuple);
4075 :
4076 90 : if (myrelid &&
4077 84 : (con->contype == CONSTRAINT_CHECK ||
4078 24 : con->contype == CONSTRAINT_NOTNULL) &&
4079 66 : !con->connoinherit)
4080 : {
4081 54 : if (recurse)
4082 : {
4083 : List *child_oids,
4084 : *child_numparents;
4085 : ListCell *lo,
4086 : *li;
4087 :
4088 36 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
4089 : &child_numparents);
4090 :
4091 84 : forboth(lo, child_oids, li, child_numparents)
4092 : {
4093 48 : Oid childrelid = lfirst_oid(lo);
4094 48 : int numparents = lfirst_int(li);
4095 :
4096 48 : if (childrelid == myrelid)
4097 36 : continue;
4098 :
4099 12 : rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
4100 : }
4101 : }
4102 : else
4103 : {
4104 24 : if (expected_parents == 0 &&
4105 6 : find_inheritance_children(myrelid, NoLock) != NIL)
4106 6 : ereport(ERROR,
4107 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4108 : errmsg("inherited constraint \"%s\" must be renamed in child tables too",
4109 : oldconname)));
4110 : }
4111 :
4112 48 : if (con->coninhcount > expected_parents)
4113 6 : ereport(ERROR,
4114 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4115 : errmsg("cannot rename inherited constraint \"%s\"",
4116 : oldconname)));
4117 : }
4118 :
4119 78 : if (con->conindid
4120 18 : && (con->contype == CONSTRAINT_PRIMARY
4121 6 : || con->contype == CONSTRAINT_UNIQUE
4122 0 : || con->contype == CONSTRAINT_EXCLUSION))
4123 : /* rename the index; this renames the constraint as well */
4124 18 : RenameRelationInternal(con->conindid, newconname, false, true);
4125 : else
4126 60 : RenameConstraintById(constraintOid, newconname);
4127 :
4128 78 : ObjectAddressSet(address, ConstraintRelationId, constraintOid);
4129 :
4130 78 : ReleaseSysCache(tuple);
4131 :
4132 78 : if (targetrelation)
4133 : {
4134 : /*
4135 : * Invalidate relcache so as others can see the new constraint name.
4136 : */
4137 72 : CacheInvalidateRelcache(targetrelation);
4138 :
4139 72 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4140 : }
4141 :
4142 78 : return address;
4143 : }
4144 :
4145 : ObjectAddress
4146 84 : RenameConstraint(RenameStmt *stmt)
4147 : {
4148 84 : Oid relid = InvalidOid;
4149 84 : Oid typid = InvalidOid;
4150 :
4151 84 : if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4152 : {
4153 : Relation rel;
4154 : HeapTuple tup;
4155 :
4156 6 : typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4157 6 : rel = table_open(TypeRelationId, RowExclusiveLock);
4158 6 : tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4159 6 : if (!HeapTupleIsValid(tup))
4160 0 : elog(ERROR, "cache lookup failed for type %u", typid);
4161 6 : checkDomainOwner(tup);
4162 6 : ReleaseSysCache(tup);
4163 6 : table_close(rel, NoLock);
4164 : }
4165 : else
4166 : {
4167 : /* lock level taken here should match rename_constraint_internal */
4168 78 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4169 78 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4170 : RangeVarCallbackForRenameAttribute,
4171 : NULL);
4172 78 : if (!OidIsValid(relid))
4173 : {
4174 6 : ereport(NOTICE,
4175 : (errmsg("relation \"%s\" does not exist, skipping",
4176 : stmt->relation->relname)));
4177 6 : return InvalidObjectAddress;
4178 : }
4179 : }
4180 :
4181 : return
4182 78 : rename_constraint_internal(relid, typid,
4183 78 : stmt->subname,
4184 78 : stmt->newname,
4185 150 : (stmt->relation &&
4186 72 : stmt->relation->inh), /* recursive? */
4187 : false, /* recursing? */
4188 : 0 /* expected inhcount */ );
4189 : }
4190 :
4191 : /*
4192 : * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
4193 : * RENAME
4194 : */
4195 : ObjectAddress
4196 510 : RenameRelation(RenameStmt *stmt)
4197 : {
4198 510 : bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4199 : Oid relid;
4200 : ObjectAddress address;
4201 :
4202 : /*
4203 : * Grab an exclusive lock on the target table, index, sequence, view,
4204 : * materialized view, or foreign table, which we will NOT release until
4205 : * end of transaction.
4206 : *
4207 : * Lock level used here should match RenameRelationInternal, to avoid lock
4208 : * escalation. However, because ALTER INDEX can be used with any relation
4209 : * type, we mustn't believe without verification.
4210 : */
4211 : for (;;)
4212 12 : {
4213 : LOCKMODE lockmode;
4214 : char relkind;
4215 : bool obj_is_index;
4216 :
4217 522 : lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4218 :
4219 522 : relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4220 522 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4221 : RangeVarCallbackForAlterRelation,
4222 : stmt);
4223 :
4224 472 : if (!OidIsValid(relid))
4225 : {
4226 18 : ereport(NOTICE,
4227 : (errmsg("relation \"%s\" does not exist, skipping",
4228 : stmt->relation->relname)));
4229 18 : return InvalidObjectAddress;
4230 : }
4231 :
4232 : /*
4233 : * We allow mismatched statement and object types (e.g., ALTER INDEX
4234 : * to rename a table), but we might've used the wrong lock level. If
4235 : * that happens, retry with the correct lock level. We don't bother
4236 : * if we already acquired AccessExclusiveLock with an index, however.
4237 : */
4238 454 : relkind = get_rel_relkind(relid);
4239 454 : obj_is_index = (relkind == RELKIND_INDEX ||
4240 : relkind == RELKIND_PARTITIONED_INDEX);
4241 454 : if (obj_is_index || is_index_stmt == obj_is_index)
4242 : break;
4243 :
4244 12 : UnlockRelationOid(relid, lockmode);
4245 12 : is_index_stmt = obj_is_index;
4246 : }
4247 :
4248 : /* Do the work */
4249 442 : RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4250 :
4251 430 : ObjectAddressSet(address, RelationRelationId, relid);
4252 :
4253 430 : return address;
4254 : }
4255 :
4256 : /*
4257 : * RenameRelationInternal - change the name of a relation
4258 : */
4259 : void
4260 1702 : RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
4261 : {
4262 : Relation targetrelation;
4263 : Relation relrelation; /* for RELATION relation */
4264 : ItemPointerData otid;
4265 : HeapTuple reltup;
4266 : Form_pg_class relform;
4267 : Oid namespaceId;
4268 :
4269 : /*
4270 : * Grab a lock on the target relation, which we will NOT release until end
4271 : * of transaction. We need at least a self-exclusive lock so that
4272 : * concurrent DDL doesn't overwrite the rename if they start updating
4273 : * while still seeing the old version. The lock also guards against
4274 : * triggering relcache reloads in concurrent sessions, which might not
4275 : * handle this information changing under them. For indexes, we can use a
4276 : * reduced lock level because RelationReloadIndexInfo() handles indexes
4277 : * specially.
4278 : */
4279 1702 : targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4280 1702 : namespaceId = RelationGetNamespace(targetrelation);
4281 :
4282 : /*
4283 : * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4284 : */
4285 1702 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4286 :
4287 1702 : reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
4288 1702 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4289 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4290 1702 : otid = reltup->t_self;
4291 1702 : relform = (Form_pg_class) GETSTRUCT(reltup);
4292 :
4293 1702 : if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4294 12 : ereport(ERROR,
4295 : (errcode(ERRCODE_DUPLICATE_TABLE),
4296 : errmsg("relation \"%s\" already exists",
4297 : newrelname)));
4298 :
4299 : /*
4300 : * RenameRelation is careful not to believe the caller's idea of the
4301 : * relation kind being handled. We don't have to worry about this, but
4302 : * let's not be totally oblivious to it. We can process an index as
4303 : * not-an-index, but not the other way around.
4304 : */
4305 : Assert(!is_index ||
4306 : is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4307 : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4308 :
4309 : /*
4310 : * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4311 : * because it's a copy...)
4312 : */
4313 1690 : namestrcpy(&(relform->relname), newrelname);
4314 :
4315 1690 : CatalogTupleUpdate(relrelation, &otid, reltup);
4316 1690 : UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
4317 :
4318 1690 : InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4319 : InvalidOid, is_internal);
4320 :
4321 1690 : heap_freetuple(reltup);
4322 1690 : table_close(relrelation, RowExclusiveLock);
4323 :
4324 : /*
4325 : * Also rename the associated type, if any.
4326 : */
4327 1690 : if (OidIsValid(targetrelation->rd_rel->reltype))
4328 124 : RenameTypeInternal(targetrelation->rd_rel->reltype,
4329 : newrelname, namespaceId);
4330 :
4331 : /*
4332 : * Also rename the associated constraint, if any.
4333 : */
4334 1690 : if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4335 886 : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4336 : {
4337 822 : Oid constraintId = get_index_constraint(myrelid);
4338 :
4339 822 : if (OidIsValid(constraintId))
4340 36 : RenameConstraintById(constraintId, newrelname);
4341 : }
4342 :
4343 : /*
4344 : * Close rel, but keep lock!
4345 : */
4346 1690 : relation_close(targetrelation, NoLock);
4347 1690 : }
4348 :
4349 : /*
4350 : * ResetRelRewrite - reset relrewrite
4351 : */
4352 : void
4353 610 : ResetRelRewrite(Oid myrelid)
4354 : {
4355 : Relation relrelation; /* for RELATION relation */
4356 : HeapTuple reltup;
4357 : Form_pg_class relform;
4358 :
4359 : /*
4360 : * Find relation's pg_class tuple.
4361 : */
4362 610 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4363 :
4364 610 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4365 610 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4366 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4367 610 : relform = (Form_pg_class) GETSTRUCT(reltup);
4368 :
4369 : /*
4370 : * Update pg_class tuple.
4371 : */
4372 610 : relform->relrewrite = InvalidOid;
4373 :
4374 610 : CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4375 :
4376 610 : heap_freetuple(reltup);
4377 610 : table_close(relrelation, RowExclusiveLock);
4378 610 : }
4379 :
4380 : /*
4381 : * Disallow ALTER TABLE (and similar commands) when the current backend has
4382 : * any open reference to the target table besides the one just acquired by
4383 : * the calling command; this implies there's an open cursor or active plan.
4384 : * We need this check because our lock doesn't protect us against stomping
4385 : * on our own foot, only other people's feet!
4386 : *
4387 : * For ALTER TABLE, the only case known to cause serious trouble is ALTER
4388 : * COLUMN TYPE, and some changes are obviously pretty benign, so this could
4389 : * possibly be relaxed to only error out for certain types of alterations.
4390 : * But the use-case for allowing any of these things is not obvious, so we
4391 : * won't work hard at it for now.
4392 : *
4393 : * We also reject these commands if there are any pending AFTER trigger events
4394 : * for the rel. This is certainly necessary for the rewriting variants of
4395 : * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
4396 : * events would try to fetch the wrong tuples. It might be overly cautious
4397 : * in other cases, but again it seems better to err on the side of paranoia.
4398 : *
4399 : * REINDEX calls this with "rel" referencing the index to be rebuilt; here
4400 : * we are worried about active indexscans on the index. The trigger-event
4401 : * check can be skipped, since we are doing no damage to the parent table.
4402 : *
4403 : * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
4404 : */
4405 : void
4406 172492 : CheckTableNotInUse(Relation rel, const char *stmt)
4407 : {
4408 : int expected_refcnt;
4409 :
4410 172492 : expected_refcnt = rel->rd_isnailed ? 2 : 1;
4411 172492 : if (rel->rd_refcnt != expected_refcnt)
4412 42 : ereport(ERROR,
4413 : (errcode(ERRCODE_OBJECT_IN_USE),
4414 : /* translator: first %s is a SQL command, eg ALTER TABLE */
4415 : errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4416 : stmt, RelationGetRelationName(rel))));
4417 :
4418 172450 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
4419 282006 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4420 139920 : AfterTriggerPendingOnRel(RelationGetRelid(rel)))
4421 18 : ereport(ERROR,
4422 : (errcode(ERRCODE_OBJECT_IN_USE),
4423 : /* translator: first %s is a SQL command, eg ALTER TABLE */
4424 : errmsg("cannot %s \"%s\" because it has pending trigger events",
4425 : stmt, RelationGetRelationName(rel))));
4426 172432 : }
4427 :
4428 : /*
4429 : * CheckAlterTableIsSafe
4430 : * Verify that it's safe to allow ALTER TABLE on this relation.
4431 : *
4432 : * This consists of CheckTableNotInUse() plus a check that the relation
4433 : * isn't another session's temp table. We must split out the temp-table
4434 : * check because there are callers of CheckTableNotInUse() that don't want
4435 : * that, notably DROP TABLE. (We must allow DROP or we couldn't clean out
4436 : * an orphaned temp schema.) Compare truncate_check_activity().
4437 : */
4438 : static void
4439 63808 : CheckAlterTableIsSafe(Relation rel)
4440 : {
4441 : /*
4442 : * Don't allow ALTER on temp tables of other backends. Their local buffer
4443 : * manager is not going to cope if we need to change the table's contents.
4444 : * Even if we don't, there may be optimizations that assume temp tables
4445 : * aren't subject to such interference.
4446 : */
4447 63808 : if (RELATION_IS_OTHER_TEMP(rel))
4448 0 : ereport(ERROR,
4449 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4450 : errmsg("cannot alter temporary tables of other sessions")));
4451 :
4452 : /*
4453 : * Also check for active uses of the relation in the current transaction,
4454 : * including open scans and pending AFTER trigger events.
4455 : */
4456 63808 : CheckTableNotInUse(rel, "ALTER TABLE");
4457 63772 : }
4458 :
4459 : /*
4460 : * AlterTableLookupRelation
4461 : * Look up, and lock, the OID for the relation named by an alter table
4462 : * statement.
4463 : */
4464 : Oid
4465 34538 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
4466 : {
4467 68988 : return RangeVarGetRelidExtended(stmt->relation, lockmode,
4468 34538 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4469 : RangeVarCallbackForAlterRelation,
4470 : stmt);
4471 : }
4472 :
4473 : /*
4474 : * AlterTable
4475 : * Execute ALTER TABLE, which can be a list of subcommands
4476 : *
4477 : * ALTER TABLE is performed in three phases:
4478 : * 1. Examine subcommands and perform pre-transformation checking.
4479 : * 2. Validate and transform subcommands, and update system catalogs.
4480 : * 3. Scan table(s) to check new constraints, and optionally recopy
4481 : * the data into new table(s).
4482 : * Phase 3 is not performed unless one or more of the subcommands requires
4483 : * it. The intention of this design is to allow multiple independent
4484 : * updates of the table schema to be performed with only one pass over the
4485 : * data.
4486 : *
4487 : * ATPrepCmd performs phase 1. A "work queue" entry is created for
4488 : * each table to be affected (there may be multiple affected tables if the
4489 : * commands traverse a table inheritance hierarchy). Also we do preliminary
4490 : * validation of the subcommands. Because earlier subcommands may change
4491 : * the catalog state seen by later commands, there are limits to what can
4492 : * be done in this phase. Generally, this phase acquires table locks,
4493 : * checks permissions and relkind, and recurses to find child tables.
4494 : *
4495 : * ATRewriteCatalogs performs phase 2 for each affected table.
4496 : * Certain subcommands need to be performed before others to avoid
4497 : * unnecessary conflicts; for example, DROP COLUMN should come before
4498 : * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
4499 : * lists, one for each logical "pass" of phase 2.
4500 : *
4501 : * ATRewriteTables performs phase 3 for those tables that need it.
4502 : *
4503 : * For most subcommand types, phases 2 and 3 do no explicit recursion,
4504 : * since phase 1 already does it. However, for certain subcommand types
4505 : * it is only possible to determine how to recurse at phase 2 time; for
4506 : * those cases, phase 1 sets the cmd->recurse flag.
4507 : *
4508 : * Thanks to the magic of MVCC, an error anywhere along the way rolls back
4509 : * the whole operation; we don't have to do anything special to clean up.
4510 : *
4511 : * The caller must lock the relation, with an appropriate lock level
4512 : * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
4513 : * or higher. We pass the lock level down
4514 : * so that we can apply it recursively to inherited tables. Note that the
4515 : * lock level we want as we recurse might well be higher than required for
4516 : * that specific subcommand. So we pass down the overall lock requirement,
4517 : * rather than reassess it at lower levels.
4518 : *
4519 : * The caller also provides a "context" which is to be passed back to
4520 : * utility.c when we need to execute a subcommand such as CREATE INDEX.
4521 : * Some of the fields therein, such as the relid, are used here as well.
4522 : */
4523 : void
4524 34312 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
4525 : AlterTableUtilityContext *context)
4526 : {
4527 : Relation rel;
4528 :
4529 : /* Caller is required to provide an adequate lock. */
4530 34312 : rel = relation_open(context->relid, NoLock);
4531 :
4532 34312 : CheckAlterTableIsSafe(rel);
4533 :
4534 34294 : ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4535 30622 : }
4536 :
4537 : /*
4538 : * AlterTableInternal
4539 : *
4540 : * ALTER TABLE with target specified by OID
4541 : *
4542 : * We do not reject if the relation is already open, because it's quite
4543 : * likely that one or more layers of caller have it open. That means it
4544 : * is unsafe to use this entry point for alterations that could break
4545 : * existing query plans. On the assumption it's not used for such, we
4546 : * don't have to reject pending AFTER triggers, either.
4547 : *
4548 : * Also, since we don't have an AlterTableUtilityContext, this cannot be
4549 : * used for any subcommand types that require parse transformation or
4550 : * could generate subcommands that have to be passed to ProcessUtility.
4551 : */
4552 : void
4553 282 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
4554 : {
4555 : Relation rel;
4556 282 : LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4557 :
4558 282 : rel = relation_open(relid, lockmode);
4559 :
4560 282 : EventTriggerAlterTableRelid(relid);
4561 :
4562 282 : ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4563 282 : }
4564 :
4565 : /*
4566 : * AlterTableGetLockLevel
4567 : *
4568 : * Sets the overall lock level required for the supplied list of subcommands.
4569 : * Policy for doing this set according to needs of AlterTable(), see
4570 : * comments there for overall explanation.
4571 : *
4572 : * Function is called before and after parsing, so it must give same
4573 : * answer each time it is called. Some subcommands are transformed
4574 : * into other subcommand types, so the transform must never be made to a
4575 : * lower lock level than previously assigned. All transforms are noted below.
4576 : *
4577 : * Since this is called before we lock the table we cannot use table metadata
4578 : * to influence the type of lock we acquire.
4579 : *
4580 : * There should be no lockmodes hardcoded into the subcommand functions. All
4581 : * lockmode decisions for ALTER TABLE are made here only. The one exception is
4582 : * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
4583 : * and does not travel through this section of code and cannot be combined with
4584 : * any of the subcommands given here.
4585 : *
4586 : * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
4587 : * so any changes that might affect SELECTs running on standbys need to use
4588 : * AccessExclusiveLocks even if you think a lesser lock would do, unless you
4589 : * have a solution for that also.
4590 : *
4591 : * Also note that pg_dump uses only an AccessShareLock, meaning that anything
4592 : * that takes a lock less than AccessExclusiveLock can change object definitions
4593 : * while pg_dump is running. Be careful to check that the appropriate data is
4594 : * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
4595 : * otherwise we might end up with an inconsistent dump that can't restore.
4596 : */
4597 : LOCKMODE
4598 34820 : AlterTableGetLockLevel(List *cmds)
4599 : {
4600 : /*
4601 : * This only works if we read catalog tables using MVCC snapshots.
4602 : */
4603 : ListCell *lcmd;
4604 34820 : LOCKMODE lockmode = ShareUpdateExclusiveLock;
4605 :
4606 70812 : foreach(lcmd, cmds)
4607 : {
4608 35992 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4609 35992 : LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4610 :
4611 35992 : switch (cmd->subtype)
4612 : {
4613 : /*
4614 : * These subcommands rewrite the heap, so require full locks.
4615 : */
4616 3584 : case AT_AddColumn: /* may rewrite heap, in some cases and visible
4617 : * to SELECT */
4618 : case AT_SetAccessMethod: /* must rewrite heap */
4619 : case AT_SetTableSpace: /* must rewrite heap */
4620 : case AT_AlterColumnType: /* must rewrite heap */
4621 3584 : cmd_lockmode = AccessExclusiveLock;
4622 3584 : break;
4623 :
4624 : /*
4625 : * These subcommands may require addition of toast tables. If
4626 : * we add a toast table to a table currently being scanned, we
4627 : * might miss data added to the new toast table by concurrent
4628 : * insert transactions.
4629 : */
4630 224 : case AT_SetStorage: /* may add toast tables, see
4631 : * ATRewriteCatalogs() */
4632 224 : cmd_lockmode = AccessExclusiveLock;
4633 224 : break;
4634 :
4635 : /*
4636 : * Removing constraints can affect SELECTs that have been
4637 : * optimized assuming the constraint holds true. See also
4638 : * CloneFkReferenced.
4639 : */
4640 1110 : case AT_DropConstraint: /* as DROP INDEX */
4641 : case AT_DropNotNull: /* may change some SQL plans */
4642 1110 : cmd_lockmode = AccessExclusiveLock;
4643 1110 : break;
4644 :
4645 : /*
4646 : * Subcommands that may be visible to concurrent SELECTs
4647 : */
4648 1758 : case AT_DropColumn: /* change visible to SELECT */
4649 : case AT_AddColumnToView: /* CREATE VIEW */
4650 : case AT_DropOids: /* used to equiv to DropColumn */
4651 : case AT_EnableAlwaysRule: /* may change SELECT rules */
4652 : case AT_EnableReplicaRule: /* may change SELECT rules */
4653 : case AT_EnableRule: /* may change SELECT rules */
4654 : case AT_DisableRule: /* may change SELECT rules */
4655 1758 : cmd_lockmode = AccessExclusiveLock;
4656 1758 : break;
4657 :
4658 : /*
4659 : * Changing owner may remove implicit SELECT privileges
4660 : */
4661 3610 : case AT_ChangeOwner: /* change visible to SELECT */
4662 3610 : cmd_lockmode = AccessExclusiveLock;
4663 3610 : break;
4664 :
4665 : /*
4666 : * Changing foreign table options may affect optimization.
4667 : */
4668 254 : case AT_GenericOptions:
4669 : case AT_AlterColumnGenericOptions:
4670 254 : cmd_lockmode = AccessExclusiveLock;
4671 254 : break;
4672 :
4673 : /*
4674 : * These subcommands affect write operations only.
4675 : */
4676 346 : case AT_EnableTrig:
4677 : case AT_EnableAlwaysTrig:
4678 : case AT_EnableReplicaTrig:
4679 : case AT_EnableTrigAll:
4680 : case AT_EnableTrigUser:
4681 : case AT_DisableTrig:
4682 : case AT_DisableTrigAll:
4683 : case AT_DisableTrigUser:
4684 346 : cmd_lockmode = ShareRowExclusiveLock;
4685 346 : break;
4686 :
4687 : /*
4688 : * These subcommands affect write operations only. XXX
4689 : * Theoretically, these could be ShareRowExclusiveLock.
4690 : */
4691 2952 : case AT_ColumnDefault:
4692 : case AT_CookedColumnDefault:
4693 : case AT_AlterConstraint:
4694 : case AT_AddIndex: /* from ADD CONSTRAINT */
4695 : case AT_AddIndexConstraint:
4696 : case AT_ReplicaIdentity:
4697 : case AT_SetNotNull:
4698 : case AT_EnableRowSecurity:
4699 : case AT_DisableRowSecurity:
4700 : case AT_ForceRowSecurity:
4701 : case AT_NoForceRowSecurity:
4702 : case AT_AddIdentity:
4703 : case AT_DropIdentity:
4704 : case AT_SetIdentity:
4705 : case AT_SetExpression:
4706 : case AT_DropExpression:
4707 : case AT_SetCompression:
4708 2952 : cmd_lockmode = AccessExclusiveLock;
4709 2952 : break;
4710 :
4711 15846 : case AT_AddConstraint:
4712 : case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4713 : case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4714 15846 : if (IsA(cmd->def, Constraint))
4715 : {
4716 15846 : Constraint *con = (Constraint *) cmd->def;
4717 :
4718 15846 : switch (con->contype)
4719 : {
4720 12166 : case CONSTR_EXCLUSION:
4721 : case CONSTR_PRIMARY:
4722 : case CONSTR_UNIQUE:
4723 :
4724 : /*
4725 : * Cases essentially the same as CREATE INDEX. We
4726 : * could reduce the lock strength to ShareLock if
4727 : * we can work out how to allow concurrent catalog
4728 : * updates. XXX Might be set down to
4729 : * ShareRowExclusiveLock but requires further
4730 : * analysis.
4731 : */
4732 12166 : cmd_lockmode = AccessExclusiveLock;
4733 12166 : break;
4734 2572 : case CONSTR_FOREIGN:
4735 :
4736 : /*
4737 : * We add triggers to both tables when we add a
4738 : * Foreign Key, so the lock level must be at least
4739 : * as strong as CREATE TRIGGER.
4740 : */
4741 2572 : cmd_lockmode = ShareRowExclusiveLock;
4742 2572 : break;
4743 :
4744 1108 : default:
4745 1108 : cmd_lockmode = AccessExclusiveLock;
4746 : }
4747 : }
4748 15846 : break;
4749 :
4750 : /*
4751 : * These subcommands affect inheritance behaviour. Queries
4752 : * started before us will continue to see the old inheritance
4753 : * behaviour, while queries started after we commit will see
4754 : * new behaviour. No need to prevent reads or writes to the
4755 : * subtable while we hook it up though. Changing the TupDesc
4756 : * may be a problem, so keep highest lock.
4757 : */
4758 530 : case AT_AddInherit:
4759 : case AT_DropInherit:
4760 530 : cmd_lockmode = AccessExclusiveLock;
4761 530 : break;
4762 :
4763 : /*
4764 : * These subcommands affect implicit row type conversion. They
4765 : * have affects similar to CREATE/DROP CAST on queries. don't
4766 : * provide for invalidating parse trees as a result of such
4767 : * changes, so we keep these at AccessExclusiveLock.
4768 : */
4769 72 : case AT_AddOf:
4770 : case AT_DropOf:
4771 72 : cmd_lockmode = AccessExclusiveLock;
4772 72 : break;
4773 :
4774 : /*
4775 : * Only used by CREATE OR REPLACE VIEW which must conflict
4776 : * with an SELECTs currently using the view.
4777 : */
4778 198 : case AT_ReplaceRelOptions:
4779 198 : cmd_lockmode = AccessExclusiveLock;
4780 198 : break;
4781 :
4782 : /*
4783 : * These subcommands affect general strategies for performance
4784 : * and maintenance, though don't change the semantic results
4785 : * from normal data reads and writes. Delaying an ALTER TABLE
4786 : * behind currently active writes only delays the point where
4787 : * the new strategy begins to take effect, so there is no
4788 : * benefit in waiting. In this case the minimum restriction
4789 : * applies: we don't currently allow concurrent catalog
4790 : * updates.
4791 : */
4792 234 : case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4793 : case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4794 : case AT_DropCluster: /* Uses MVCC in getIndexes() */
4795 : case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4796 : case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4797 234 : cmd_lockmode = ShareUpdateExclusiveLock;
4798 234 : break;
4799 :
4800 112 : case AT_SetLogged:
4801 : case AT_SetUnLogged:
4802 112 : cmd_lockmode = AccessExclusiveLock;
4803 112 : break;
4804 :
4805 476 : case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4806 476 : cmd_lockmode = ShareUpdateExclusiveLock;
4807 476 : break;
4808 :
4809 : /*
4810 : * Rel options are more complex than first appears. Options
4811 : * are set here for tables, views and indexes; for historical
4812 : * reasons these can all be used with ALTER TABLE, so we can't
4813 : * decide between them using the basic grammar.
4814 : */
4815 764 : case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4816 : * getTables() */
4817 : case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4818 : * getTables() */
4819 764 : cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4820 764 : break;
4821 :
4822 3314 : case AT_AttachPartition:
4823 3314 : cmd_lockmode = ShareUpdateExclusiveLock;
4824 3314 : break;
4825 :
4826 588 : case AT_DetachPartition:
4827 588 : if (((PartitionCmd *) cmd->def)->concurrent)
4828 164 : cmd_lockmode = ShareUpdateExclusiveLock;
4829 : else
4830 424 : cmd_lockmode = AccessExclusiveLock;
4831 588 : break;
4832 :
4833 20 : case AT_DetachPartitionFinalize:
4834 20 : cmd_lockmode = ShareUpdateExclusiveLock;
4835 20 : break;
4836 :
4837 0 : default: /* oops */
4838 0 : elog(ERROR, "unrecognized alter table type: %d",
4839 : (int) cmd->subtype);
4840 : break;
4841 : }
4842 :
4843 : /*
4844 : * Take the greatest lockmode from any subcommand
4845 : */
4846 35992 : if (cmd_lockmode > lockmode)
4847 30036 : lockmode = cmd_lockmode;
4848 : }
4849 :
4850 34820 : return lockmode;
4851 : }
4852 :
4853 : /*
4854 : * ATController provides top level control over the phases.
4855 : *
4856 : * parsetree is passed in to allow it to be passed to event triggers
4857 : * when requested.
4858 : */
4859 : static void
4860 34576 : ATController(AlterTableStmt *parsetree,
4861 : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4862 : AlterTableUtilityContext *context)
4863 : {
4864 34576 : List *wqueue = NIL;
4865 : ListCell *lcmd;
4866 :
4867 : /* Phase 1: preliminary examination of commands, create work queue */
4868 69912 : foreach(lcmd, cmds)
4869 : {
4870 35742 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4871 :
4872 35742 : ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4873 : }
4874 :
4875 : /* Close the relation, but keep lock until commit */
4876 34170 : relation_close(rel, NoLock);
4877 :
4878 : /* Phase 2: update system catalogs */
4879 34170 : ATRewriteCatalogs(&wqueue, lockmode, context);
4880 :
4881 : /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4882 31348 : ATRewriteTables(parsetree, &wqueue, lockmode, context);
4883 30904 : }
4884 :
4885 : /*
4886 : * ATPrepCmd
4887 : *
4888 : * Traffic cop for ALTER TABLE Phase 1 operations, including simple
4889 : * recursion and permission checks.
4890 : *
4891 : * Caller must have acquired appropriate lock type on relation already.
4892 : * This lock should be held until commit.
4893 : */
4894 : static void
4895 36682 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4896 : bool recurse, bool recursing, LOCKMODE lockmode,
4897 : AlterTableUtilityContext *context)
4898 : {
4899 : AlteredTableInfo *tab;
4900 36682 : AlterTablePass pass = AT_PASS_UNSET;
4901 :
4902 : /* Find or create work queue entry for this table */
4903 36682 : tab = ATGetQueueEntry(wqueue, rel);
4904 :
4905 : /*
4906 : * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
4907 : * partitions that are pending detach.
4908 : */
4909 36682 : if (rel->rd_rel->relispartition &&
4910 3068 : cmd->subtype != AT_DetachPartitionFinalize &&
4911 1534 : PartitionHasPendingDetach(RelationGetRelid(rel)))
4912 2 : ereport(ERROR,
4913 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4914 : errmsg("cannot alter partition \"%s\" with an incomplete detach",
4915 : RelationGetRelationName(rel)),
4916 : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
4917 :
4918 : /*
4919 : * Copy the original subcommand for each table, so we can scribble on it.
4920 : * This avoids conflicts when different child tables need to make
4921 : * different parse transformations (for example, the same column may have
4922 : * different column numbers in different children).
4923 : */
4924 36680 : cmd = copyObject(cmd);
4925 :
4926 : /*
4927 : * Do permissions and relkind checking, recursion to child tables if
4928 : * needed, and any additional phase-1 processing needed. (But beware of
4929 : * adding any processing that looks at table details that another
4930 : * subcommand could change. In some cases we reject multiple subcommands
4931 : * that could try to change the same state in contrary ways.)
4932 : */
4933 36680 : switch (cmd->subtype)
4934 : {
4935 2164 : case AT_AddColumn: /* ADD COLUMN */
4936 2164 : ATSimplePermissions(cmd->subtype, rel,
4937 : ATT_TABLE | ATT_PARTITIONED_TABLE |
4938 : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
4939 2164 : ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
4940 : lockmode, context);
4941 : /* Recursion occurs during execution phase */
4942 2152 : pass = AT_PASS_ADD_COL;
4943 2152 : break;
4944 24 : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
4945 24 : ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
4946 24 : ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
4947 : lockmode, context);
4948 : /* Recursion occurs during execution phase */
4949 24 : pass = AT_PASS_ADD_COL;
4950 24 : break;
4951 648 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
4952 :
4953 : /*
4954 : * We allow defaults on views so that INSERT into a view can have
4955 : * default-ish behavior. This works because the rewriter
4956 : * substitutes default values into INSERTs before it expands
4957 : * rules.
4958 : */
4959 648 : ATSimplePermissions(cmd->subtype, rel,
4960 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
4961 : ATT_FOREIGN_TABLE);
4962 648 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
4963 : /* No command-specific prep needed */
4964 648 : pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
4965 648 : break;
4966 80 : case AT_CookedColumnDefault: /* add a pre-cooked default */
4967 : /* This is currently used only in CREATE TABLE */
4968 : /* (so the permission check really isn't necessary) */
4969 80 : ATSimplePermissions(cmd->subtype, rel,
4970 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
4971 : /* This command never recurses */
4972 80 : pass = AT_PASS_ADD_OTHERCONSTR;
4973 80 : break;
4974 210 : case AT_AddIdentity:
4975 210 : ATSimplePermissions(cmd->subtype, rel,
4976 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
4977 : ATT_FOREIGN_TABLE);
4978 : /* Set up recursion for phase 2; no other prep needed */
4979 210 : if (recurse)
4980 204 : cmd->recurse = true;
4981 210 : pass = AT_PASS_ADD_OTHERCONSTR;
4982 210 : break;
4983 62 : case AT_SetIdentity:
4984 62 : ATSimplePermissions(cmd->subtype, rel,
4985 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
4986 : ATT_FOREIGN_TABLE);
4987 : /* Set up recursion for phase 2; no other prep needed */
4988 62 : if (recurse)
4989 56 : cmd->recurse = true;
4990 : /* This should run after AddIdentity, so do it in MISC pass */
4991 62 : pass = AT_PASS_MISC;
4992 62 : break;
4993 56 : case AT_DropIdentity:
4994 56 : ATSimplePermissions(cmd->subtype, rel,
4995 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
4996 : ATT_FOREIGN_TABLE);
4997 : /* Set up recursion for phase 2; no other prep needed */
4998 56 : if (recurse)
4999 50 : cmd->recurse = true;
5000 56 : pass = AT_PASS_DROP;
5001 56 : break;
5002 274 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5003 274 : ATSimplePermissions(cmd->subtype, rel,
5004 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5005 : /* Set up recursion for phase 2; no other prep needed */
5006 268 : if (recurse)
5007 250 : cmd->recurse = true;
5008 268 : pass = AT_PASS_DROP;
5009 268 : break;
5010 414 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5011 414 : ATSimplePermissions(cmd->subtype, rel,
5012 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5013 : /* Set up recursion for phase 2; no other prep needed */
5014 408 : if (recurse)
5015 384 : cmd->recurse = true;
5016 408 : pass = AT_PASS_COL_ATTRS;
5017 408 : break;
5018 180 : case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */
5019 180 : ATSimplePermissions(cmd->subtype, rel,
5020 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5021 180 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5022 180 : pass = AT_PASS_SET_EXPRESSION;
5023 180 : break;
5024 86 : case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
5025 86 : ATSimplePermissions(cmd->subtype, rel,
5026 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5027 86 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5028 86 : ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
5029 62 : pass = AT_PASS_DROP;
5030 62 : break;
5031 164 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5032 164 : ATSimplePermissions(cmd->subtype, rel,
5033 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
5034 : ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
5035 164 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5036 : /* No command-specific prep needed */
5037 164 : pass = AT_PASS_MISC;
5038 164 : break;
5039 44 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5040 : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5041 44 : ATSimplePermissions(cmd->subtype, rel,
5042 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5043 : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5044 : /* This command never recurses */
5045 32 : pass = AT_PASS_MISC;
5046 32 : break;
5047 246 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5048 246 : ATSimplePermissions(cmd->subtype, rel,
5049 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5050 : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5051 246 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5052 : /* No command-specific prep needed */
5053 246 : pass = AT_PASS_MISC;
5054 246 : break;
5055 90 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5056 90 : ATSimplePermissions(cmd->subtype, rel,
5057 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5058 : /* This command never recurses */
5059 : /* No command-specific prep needed */
5060 90 : pass = AT_PASS_MISC;
5061 90 : break;
5062 1658 : case AT_DropColumn: /* DROP COLUMN */
5063 1658 : ATSimplePermissions(cmd->subtype, rel,
5064 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5065 : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5066 1652 : ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
5067 : lockmode, context);
5068 : /* Recursion occurs during execution phase */
5069 1640 : pass = AT_PASS_DROP;
5070 1640 : break;
5071 0 : case AT_AddIndex: /* ADD INDEX */
5072 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5073 : /* This command never recurses */
5074 : /* No command-specific prep needed */
5075 0 : pass = AT_PASS_ADD_INDEX;
5076 0 : break;
5077 16310 : case AT_AddConstraint: /* ADD CONSTRAINT */
5078 16310 : ATSimplePermissions(cmd->subtype, rel,
5079 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5080 16310 : ATPrepAddPrimaryKey(wqueue, rel, cmd, recurse, lockmode, context);
5081 16280 : if (recurse)
5082 : {
5083 : /* recurses at exec time; lock descendants and set flag */
5084 15620 : (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5085 15620 : cmd->recurse = true;
5086 : }
5087 16280 : pass = AT_PASS_ADD_CONSTR;
5088 16280 : break;
5089 0 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5090 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5091 : /* This command never recurses */
5092 : /* No command-specific prep needed */
5093 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5094 0 : break;
5095 798 : case AT_DropConstraint: /* DROP CONSTRAINT */
5096 798 : ATSimplePermissions(cmd->subtype, rel,
5097 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5098 798 : ATCheckPartitionsNotInUse(rel, lockmode);
5099 : /* Other recursion occurs during execution phase */
5100 : /* No command-specific prep needed except saving recurse flag */
5101 792 : if (recurse)
5102 756 : cmd->recurse = true;
5103 792 : pass = AT_PASS_DROP;
5104 792 : break;
5105 1306 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5106 1306 : ATSimplePermissions(cmd->subtype, rel,
5107 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5108 : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5109 : /* See comments for ATPrepAlterColumnType */
5110 1306 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
5111 : AT_PASS_UNSET, context);
5112 : Assert(cmd != NULL);
5113 : /* Performs own recursion */
5114 1300 : ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
5115 : lockmode, context);
5116 1102 : pass = AT_PASS_ALTER_TYPE;
5117 1102 : break;
5118 172 : case AT_AlterColumnGenericOptions:
5119 172 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5120 : /* This command never recurses */
5121 : /* No command-specific prep needed */
5122 172 : pass = AT_PASS_MISC;
5123 172 : break;
5124 3586 : case AT_ChangeOwner: /* ALTER OWNER */
5125 : /* This command never recurses */
5126 : /* No command-specific prep needed */
5127 3586 : pass = AT_PASS_MISC;
5128 3586 : break;
5129 64 : case AT_ClusterOn: /* CLUSTER ON */
5130 : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5131 64 : ATSimplePermissions(cmd->subtype, rel,
5132 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5133 : /* These commands never recurse */
5134 : /* No command-specific prep needed */
5135 64 : pass = AT_PASS_MISC;
5136 64 : break;
5137 112 : case AT_SetLogged: /* SET LOGGED */
5138 : case AT_SetUnLogged: /* SET UNLOGGED */
5139 112 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
5140 100 : if (tab->chgPersistence)
5141 0 : ereport(ERROR,
5142 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5143 : errmsg("cannot change persistence setting twice")));
5144 100 : ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
5145 88 : pass = AT_PASS_MISC;
5146 88 : break;
5147 6 : case AT_DropOids: /* SET WITHOUT OIDS */
5148 6 : ATSimplePermissions(cmd->subtype, rel,
5149 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5150 6 : pass = AT_PASS_DROP;
5151 6 : break;
5152 128 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5153 128 : ATSimplePermissions(cmd->subtype, rel,
5154 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5155 :
5156 : /* check if another access method change was already requested */
5157 128 : if (tab->chgAccessMethod)
5158 18 : ereport(ERROR,
5159 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5160 : errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
5161 :
5162 110 : ATPrepSetAccessMethod(tab, rel, cmd->name);
5163 110 : pass = AT_PASS_MISC; /* does not matter; no work in Phase 2 */
5164 110 : break;
5165 158 : case AT_SetTableSpace: /* SET TABLESPACE */
5166 158 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
5167 : ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
5168 : /* This command never recurses */
5169 158 : ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
5170 158 : pass = AT_PASS_MISC; /* doesn't actually matter */
5171 158 : break;
5172 960 : case AT_SetRelOptions: /* SET (...) */
5173 : case AT_ResetRelOptions: /* RESET (...) */
5174 : case AT_ReplaceRelOptions: /* reset them all, then set just these */
5175 960 : ATSimplePermissions(cmd->subtype, rel,
5176 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5177 : ATT_MATVIEW | ATT_INDEX);
5178 : /* This command never recurses */
5179 : /* No command-specific prep needed */
5180 958 : pass = AT_PASS_MISC;
5181 958 : break;
5182 444 : case AT_AddInherit: /* INHERIT */
5183 444 : ATSimplePermissions(cmd->subtype, rel,
5184 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5185 : /* This command never recurses */
5186 444 : ATPrepAddInherit(rel);
5187 426 : pass = AT_PASS_MISC;
5188 426 : break;
5189 86 : case AT_DropInherit: /* NO INHERIT */
5190 86 : ATSimplePermissions(cmd->subtype, rel,
5191 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5192 : /* This command never recurses */
5193 : /* No command-specific prep needed */
5194 86 : pass = AT_PASS_MISC;
5195 86 : break;
5196 294 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5197 294 : ATSimplePermissions(cmd->subtype, rel,
5198 : ATT_TABLE | ATT_PARTITIONED_TABLE);
5199 : /* Recursion occurs during execution phase */
5200 288 : if (recurse)
5201 288 : cmd->recurse = true;
5202 288 : pass = AT_PASS_MISC;
5203 288 : break;
5204 476 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5205 476 : ATSimplePermissions(cmd->subtype, rel,
5206 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5207 : /* Recursion occurs during execution phase */
5208 : /* No command-specific prep needed except saving recurse flag */
5209 476 : if (recurse)
5210 476 : cmd->recurse = true;
5211 476 : pass = AT_PASS_MISC;
5212 476 : break;
5213 490 : case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
5214 490 : ATSimplePermissions(cmd->subtype, rel,
5215 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5216 490 : pass = AT_PASS_MISC;
5217 : /* This command never recurses */
5218 : /* No command-specific prep needed */
5219 490 : break;
5220 346 : case AT_EnableTrig: /* ENABLE TRIGGER variants */
5221 : case AT_EnableAlwaysTrig:
5222 : case AT_EnableReplicaTrig:
5223 : case AT_EnableTrigAll:
5224 : case AT_EnableTrigUser:
5225 : case AT_DisableTrig: /* DISABLE TRIGGER variants */
5226 : case AT_DisableTrigAll:
5227 : case AT_DisableTrigUser:
5228 346 : ATSimplePermissions(cmd->subtype, rel,
5229 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5230 : /* Set up recursion for phase 2; no other prep needed */
5231 346 : if (recurse)
5232 318 : cmd->recurse = true;
5233 346 : pass = AT_PASS_MISC;
5234 346 : break;
5235 576 : case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
5236 : case AT_EnableAlwaysRule:
5237 : case AT_EnableReplicaRule:
5238 : case AT_DisableRule:
5239 : case AT_AddOf: /* OF */
5240 : case AT_DropOf: /* NOT OF */
5241 : case AT_EnableRowSecurity:
5242 : case AT_DisableRowSecurity:
5243 : case AT_ForceRowSecurity:
5244 : case AT_NoForceRowSecurity:
5245 576 : ATSimplePermissions(cmd->subtype, rel,
5246 : ATT_TABLE | ATT_PARTITIONED_TABLE);
5247 : /* These commands never recurse */
5248 : /* No command-specific prep needed */
5249 576 : pass = AT_PASS_MISC;
5250 576 : break;
5251 58 : case AT_GenericOptions:
5252 58 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5253 : /* No command-specific prep needed */
5254 58 : pass = AT_PASS_MISC;
5255 58 : break;
5256 3302 : case AT_AttachPartition:
5257 3302 : ATSimplePermissions(cmd->subtype, rel,
5258 : ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
5259 : /* No command-specific prep needed */
5260 3296 : pass = AT_PASS_MISC;
5261 3296 : break;
5262 588 : case AT_DetachPartition:
5263 588 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5264 : /* No command-specific prep needed */
5265 570 : pass = AT_PASS_MISC;
5266 570 : break;
5267 20 : case AT_DetachPartitionFinalize:
5268 20 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5269 : /* No command-specific prep needed */
5270 14 : pass = AT_PASS_MISC;
5271 14 : break;
5272 0 : default: /* oops */
5273 0 : elog(ERROR, "unrecognized alter table type: %d",
5274 : (int) cmd->subtype);
5275 : pass = AT_PASS_UNSET; /* keep compiler quiet */
5276 : break;
5277 : }
5278 : Assert(pass > AT_PASS_UNSET);
5279 :
5280 : /* Add the subcommand to the appropriate list for phase 2 */
5281 36264 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
5282 36264 : }
5283 :
5284 : /*
5285 : * ATRewriteCatalogs
5286 : *
5287 : * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
5288 : * dispatched in a "safe" execution order (designed to avoid unnecessary
5289 : * conflicts).
5290 : */
5291 : static void
5292 34170 : ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
5293 : AlterTableUtilityContext *context)
5294 : {
5295 : ListCell *ltab;
5296 :
5297 : /*
5298 : * We process all the tables "in parallel", one pass at a time. This is
5299 : * needed because we may have to propagate work from one table to another
5300 : * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
5301 : * re-adding of the foreign key constraint to the other table). Work can
5302 : * only be propagated into later passes, however.
5303 : */
5304 431614 : for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
5305 : {
5306 : /* Go through each table that needs to be processed */
5307 814010 : foreach(ltab, *wqueue)
5308 : {
5309 416566 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5310 416566 : List *subcmds = tab->subcmds[pass];
5311 : ListCell *lcmd;
5312 :
5313 416566 : if (subcmds == NIL)
5314 358584 : continue;
5315 :
5316 : /*
5317 : * Open the relation and store it in tab. This allows subroutines
5318 : * close and reopen, if necessary. Appropriate lock was obtained
5319 : * by phase 1, needn't get it again.
5320 : */
5321 57982 : tab->rel = relation_open(tab->relid, NoLock);
5322 :
5323 116800 : foreach(lcmd, subcmds)
5324 61640 : ATExecCmd(wqueue, tab,
5325 61640 : lfirst_node(AlterTableCmd, lcmd),
5326 : lockmode, pass, context);
5327 :
5328 : /*
5329 : * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
5330 : * (this is not done in ATExecAlterColumnType since it should be
5331 : * done only once if multiple columns of a table are altered).
5332 : */
5333 55160 : if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
5334 1132 : ATPostAlterTypeCleanup(wqueue, tab, lockmode);
5335 :
5336 55160 : if (tab->rel)
5337 : {
5338 55160 : relation_close(tab->rel, NoLock);
5339 55160 : tab->rel = NULL;
5340 : }
5341 : }
5342 : }
5343 :
5344 : /* Check to see if a toast table must be added. */
5345 67308 : foreach(ltab, *wqueue)
5346 : {
5347 35960 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5348 :
5349 : /*
5350 : * If the table is source table of ATTACH PARTITION command, we did
5351 : * not modify anything about it that will change its toasting
5352 : * requirement, so no need to check.
5353 : */
5354 35960 : if (((tab->relkind == RELKIND_RELATION ||
5355 7000 : tab->relkind == RELKIND_PARTITIONED_TABLE) &&
5356 33778 : tab->partition_constraint == NULL) ||
5357 4602 : tab->relkind == RELKIND_MATVIEW)
5358 31426 : AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
5359 : }
5360 31348 : }
5361 :
5362 : /*
5363 : * ATExecCmd: dispatch a subcommand to appropriate execution routine
5364 : */
5365 : static void
5366 61640 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
5367 : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
5368 : AlterTableUtilityContext *context)
5369 : {
5370 61640 : ObjectAddress address = InvalidObjectAddress;
5371 61640 : Relation rel = tab->rel;
5372 :
5373 61640 : switch (cmd->subtype)
5374 : {
5375 2170 : case AT_AddColumn: /* ADD COLUMN */
5376 : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5377 2170 : address = ATExecAddColumn(wqueue, tab, rel, &cmd,
5378 2170 : cmd->recurse, false,
5379 : lockmode, cur_pass, context);
5380 2032 : break;
5381 612 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5382 612 : address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
5383 546 : break;
5384 80 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5385 80 : address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
5386 80 : break;
5387 210 : case AT_AddIdentity:
5388 210 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5389 : cur_pass, context);
5390 : Assert(cmd != NULL);
5391 198 : address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5392 150 : break;
5393 62 : case AT_SetIdentity:
5394 62 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5395 : cur_pass, context);
5396 : Assert(cmd != NULL);
5397 62 : address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5398 38 : break;
5399 56 : case AT_DropIdentity:
5400 56 : address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
5401 38 : break;
5402 268 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5403 268 : address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
5404 166 : break;
5405 408 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5406 408 : address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
5407 408 : cmd->recurse, false, lockmode);
5408 378 : break;
5409 180 : case AT_SetExpression:
5410 180 : address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
5411 150 : break;
5412 56 : case AT_DropExpression:
5413 56 : address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
5414 32 : break;
5415 164 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5416 164 : address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
5417 116 : break;
5418 26 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5419 26 : address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
5420 26 : break;
5421 6 : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5422 6 : address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
5423 6 : break;
5424 246 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5425 246 : address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
5426 234 : break;
5427 90 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5428 90 : address = ATExecSetCompression(rel, cmd->name, cmd->def,
5429 : lockmode);
5430 84 : break;
5431 1640 : case AT_DropColumn: /* DROP COLUMN */
5432 1640 : address = ATExecDropColumn(wqueue, rel, cmd->name,
5433 1640 : cmd->behavior, cmd->recurse, false,
5434 1640 : cmd->missing_ok, lockmode,
5435 : NULL);
5436 1460 : break;
5437 1444 : case AT_AddIndex: /* ADD INDEX */
5438 1444 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
5439 : lockmode);
5440 1274 : break;
5441 444 : case AT_ReAddIndex: /* ADD INDEX */
5442 444 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
5443 : lockmode);
5444 444 : break;
5445 14 : case AT_ReAddStatistics: /* ADD STATISTICS */
5446 14 : address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
5447 : true, lockmode);
5448 14 : break;
5449 28756 : case AT_AddConstraint: /* ADD CONSTRAINT */
5450 : /* Transform the command only during initial examination */
5451 28756 : if (cur_pass == AT_PASS_ADD_CONSTR)
5452 16250 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
5453 16280 : cmd->recurse, lockmode,
5454 : cur_pass, context);
5455 : /* Depending on constraint type, might be no more work to do now */
5456 28726 : if (cmd != NULL)
5457 : address =
5458 12476 : ATExecAddConstraint(wqueue, tab, rel,
5459 12476 : (Constraint *) cmd->def,
5460 12476 : cmd->recurse, false, lockmode);
5461 28046 : break;
5462 332 : case AT_ReAddConstraint: /* Re-add pre-existing check constraint */
5463 : address =
5464 332 : ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
5465 : true, true, lockmode);
5466 320 : break;
5467 14 : case AT_ReAddDomainConstraint: /* Re-add pre-existing domain check
5468 : * constraint */
5469 : address =
5470 14 : AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
5471 14 : ((AlterDomainStmt *) cmd->def)->def,
5472 : NULL);
5473 8 : break;
5474 78 : case AT_ReAddComment: /* Re-add existing comment */
5475 78 : address = CommentObject((CommentStmt *) cmd->def);
5476 78 : break;
5477 10640 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5478 10640 : address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
5479 : lockmode);
5480 10628 : break;
5481 288 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5482 288 : address = ATExecAlterConstraint(wqueue, rel,
5483 288 : castNode(ATAlterConstraint, cmd->def),
5484 288 : cmd->recurse, lockmode);
5485 222 : break;
5486 476 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5487 476 : address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
5488 : false, lockmode);
5489 470 : break;
5490 792 : case AT_DropConstraint: /* DROP CONSTRAINT */
5491 792 : ATExecDropConstraint(rel, cmd->name, cmd->behavior,
5492 792 : cmd->recurse,
5493 792 : cmd->missing_ok, lockmode);
5494 582 : break;
5495 1066 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5496 : /* parse transformation was done earlier */
5497 1066 : address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
5498 1024 : break;
5499 172 : case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
5500 : address =
5501 172 : ATExecAlterColumnGenericOptions(rel, cmd->name,
5502 172 : (List *) cmd->def, lockmode);
5503 166 : break;
5504 3586 : case AT_ChangeOwner: /* ALTER OWNER */
5505 3580 : ATExecChangeOwner(RelationGetRelid(rel),
5506 3586 : get_rolespec_oid(cmd->newowner, false),
5507 : false, lockmode);
5508 3568 : break;
5509 64 : case AT_ClusterOn: /* CLUSTER ON */
5510 64 : address = ATExecClusterOn(rel, cmd->name, lockmode);
5511 58 : break;
5512 18 : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5513 18 : ATExecDropCluster(rel, lockmode);
5514 12 : break;
5515 88 : case AT_SetLogged: /* SET LOGGED */
5516 : case AT_SetUnLogged: /* SET UNLOGGED */
5517 88 : break;
5518 6 : case AT_DropOids: /* SET WITHOUT OIDS */
5519 : /* nothing to do here, oid columns don't exist anymore */
5520 6 : break;
5521 92 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5522 :
5523 : /*
5524 : * Only do this for partitioned tables, for which this is just a
5525 : * catalog change. Tables with storage are handled by Phase 3.
5526 : */
5527 92 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
5528 50 : tab->chgAccessMethod)
5529 44 : ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
5530 92 : break;
5531 158 : case AT_SetTableSpace: /* SET TABLESPACE */
5532 :
5533 : /*
5534 : * Only do this for partitioned tables and indexes, for which this
5535 : * is just a catalog change. Other relation types which have
5536 : * storage are handled by Phase 3.
5537 : */
5538 158 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
5539 146 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
5540 36 : ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
5541 :
5542 152 : break;
5543 958 : case AT_SetRelOptions: /* SET (...) */
5544 : case AT_ResetRelOptions: /* RESET (...) */
5545 : case AT_ReplaceRelOptions: /* replace entire option list */
5546 958 : ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
5547 906 : break;
5548 122 : case AT_EnableTrig: /* ENABLE TRIGGER name */
5549 122 : ATExecEnableDisableTrigger(rel, cmd->name,
5550 : TRIGGER_FIRES_ON_ORIGIN, false,
5551 122 : cmd->recurse,
5552 : lockmode);
5553 122 : break;
5554 44 : case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
5555 44 : ATExecEnableDisableTrigger(rel, cmd->name,
5556 : TRIGGER_FIRES_ALWAYS, false,
5557 44 : cmd->recurse,
5558 : lockmode);
5559 44 : break;
5560 16 : case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
5561 16 : ATExecEnableDisableTrigger(rel, cmd->name,
5562 : TRIGGER_FIRES_ON_REPLICA, false,
5563 16 : cmd->recurse,
5564 : lockmode);
5565 16 : break;
5566 140 : case AT_DisableTrig: /* DISABLE TRIGGER name */
5567 140 : ATExecEnableDisableTrigger(rel, cmd->name,
5568 : TRIGGER_DISABLED, false,
5569 140 : cmd->recurse,
5570 : lockmode);
5571 140 : break;
5572 0 : case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
5573 0 : ATExecEnableDisableTrigger(rel, NULL,
5574 : TRIGGER_FIRES_ON_ORIGIN, false,
5575 0 : cmd->recurse,
5576 : lockmode);
5577 0 : break;
5578 12 : case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
5579 12 : ATExecEnableDisableTrigger(rel, NULL,
5580 : TRIGGER_DISABLED, false,
5581 12 : cmd->recurse,
5582 : lockmode);
5583 12 : break;
5584 0 : case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
5585 0 : ATExecEnableDisableTrigger(rel, NULL,
5586 : TRIGGER_FIRES_ON_ORIGIN, true,
5587 0 : cmd->recurse,
5588 : lockmode);
5589 0 : break;
5590 12 : case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
5591 12 : ATExecEnableDisableTrigger(rel, NULL,
5592 : TRIGGER_DISABLED, true,
5593 12 : cmd->recurse,
5594 : lockmode);
5595 12 : break;
5596 :
5597 8 : case AT_EnableRule: /* ENABLE RULE name */
5598 8 : ATExecEnableDisableRule(rel, cmd->name,
5599 : RULE_FIRES_ON_ORIGIN, lockmode);
5600 8 : break;
5601 0 : case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
5602 0 : ATExecEnableDisableRule(rel, cmd->name,
5603 : RULE_FIRES_ALWAYS, lockmode);
5604 0 : break;
5605 6 : case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
5606 6 : ATExecEnableDisableRule(rel, cmd->name,
5607 : RULE_FIRES_ON_REPLICA, lockmode);
5608 6 : break;
5609 38 : case AT_DisableRule: /* DISABLE RULE name */
5610 38 : ATExecEnableDisableRule(rel, cmd->name,
5611 : RULE_DISABLED, lockmode);
5612 38 : break;
5613 :
5614 426 : case AT_AddInherit:
5615 426 : address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
5616 306 : break;
5617 86 : case AT_DropInherit:
5618 86 : address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
5619 80 : break;
5620 66 : case AT_AddOf:
5621 66 : address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
5622 30 : break;
5623 6 : case AT_DropOf:
5624 6 : ATExecDropOf(rel, lockmode);
5625 6 : break;
5626 508 : case AT_ReplicaIdentity:
5627 508 : ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
5628 460 : break;
5629 308 : case AT_EnableRowSecurity:
5630 308 : ATExecSetRowSecurity(rel, true);
5631 308 : break;
5632 10 : case AT_DisableRowSecurity:
5633 10 : ATExecSetRowSecurity(rel, false);
5634 10 : break;
5635 102 : case AT_ForceRowSecurity:
5636 102 : ATExecForceNoForceRowSecurity(rel, true);
5637 102 : break;
5638 32 : case AT_NoForceRowSecurity:
5639 32 : ATExecForceNoForceRowSecurity(rel, false);
5640 32 : break;
5641 58 : case AT_GenericOptions:
5642 58 : ATExecGenericOptions(rel, (List *) cmd->def);
5643 56 : break;
5644 3296 : case AT_AttachPartition:
5645 3296 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5646 : cur_pass, context);
5647 : Assert(cmd != NULL);
5648 3272 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5649 2796 : address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
5650 : context);
5651 : else
5652 476 : address = ATExecAttachPartitionIdx(wqueue, rel,
5653 476 : ((PartitionCmd *) cmd->def)->name);
5654 2882 : break;
5655 570 : case AT_DetachPartition:
5656 570 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5657 : cur_pass, context);
5658 : Assert(cmd != NULL);
5659 : /* ATPrepCmd ensures it must be a table */
5660 : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5661 570 : address = ATExecDetachPartition(wqueue, tab, rel,
5662 570 : ((PartitionCmd *) cmd->def)->name,
5663 570 : ((PartitionCmd *) cmd->def)->concurrent);
5664 440 : break;
5665 14 : case AT_DetachPartitionFinalize:
5666 14 : address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
5667 14 : break;
5668 0 : default: /* oops */
5669 0 : elog(ERROR, "unrecognized alter table type: %d",
5670 : (int) cmd->subtype);
5671 : break;
5672 : }
5673 :
5674 : /*
5675 : * Report the subcommand to interested event triggers.
5676 : */
5677 58818 : if (cmd)
5678 42568 : EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
5679 :
5680 : /*
5681 : * Bump the command counter to ensure the next subcommand in the sequence
5682 : * can see the changes so far
5683 : */
5684 58818 : CommandCounterIncrement();
5685 58818 : }
5686 :
5687 : /*
5688 : * ATParseTransformCmd: perform parse transformation for one subcommand
5689 : *
5690 : * Returns the transformed subcommand tree, if there is one, else NULL.
5691 : *
5692 : * The parser may hand back additional AlterTableCmd(s) and/or other
5693 : * utility statements, either before or after the original subcommand.
5694 : * Other AlterTableCmds are scheduled into the appropriate slot of the
5695 : * AlteredTableInfo (they had better be for later passes than the current one).
5696 : * Utility statements that are supposed to happen before the AlterTableCmd
5697 : * are executed immediately. Those that are supposed to happen afterwards
5698 : * are added to the tab->afterStmts list to be done at the very end.
5699 : */
5700 : static AlterTableCmd *
5701 23774 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
5702 : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
5703 : AlterTablePass cur_pass, AlterTableUtilityContext *context)
5704 : {
5705 23774 : AlterTableCmd *newcmd = NULL;
5706 23774 : AlterTableStmt *atstmt = makeNode(AlterTableStmt);
5707 : List *beforeStmts;
5708 : List *afterStmts;
5709 : ListCell *lc;
5710 :
5711 : /* Gin up an AlterTableStmt with just this subcommand and this table */
5712 23774 : atstmt->relation =
5713 23774 : makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5714 23774 : pstrdup(RelationGetRelationName(rel)),
5715 : -1);
5716 23774 : atstmt->relation->inh = recurse;
5717 23774 : atstmt->cmds = list_make1(cmd);
5718 23774 : atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
5719 23774 : atstmt->missing_ok = false;
5720 :
5721 : /* Transform the AlterTableStmt */
5722 23774 : atstmt = transformAlterTableStmt(RelationGetRelid(rel),
5723 : atstmt,
5724 : context->queryString,
5725 : &beforeStmts,
5726 : &afterStmts);
5727 :
5728 : /* Execute any statements that should happen before these subcommand(s) */
5729 24270 : foreach(lc, beforeStmts)
5730 : {
5731 574 : Node *stmt = (Node *) lfirst(lc);
5732 :
5733 574 : ProcessUtilityForAlterTable(stmt, context);
5734 562 : CommandCounterIncrement();
5735 : }
5736 :
5737 : /* Examine the transformed subcommands and schedule them appropriately */
5738 55738 : foreach(lc, atstmt->cmds)
5739 : {
5740 32042 : AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
5741 : AlterTablePass pass;
5742 :
5743 : /*
5744 : * This switch need only cover the subcommand types that can be added
5745 : * by parse_utilcmd.c; otherwise, we'll use the default strategy of
5746 : * executing the subcommand immediately, as a substitute for the
5747 : * original subcommand. (Note, however, that this does cause
5748 : * AT_AddConstraint subcommands to be rescheduled into later passes,
5749 : * which is important for index and foreign key constraints.)
5750 : *
5751 : * We assume we needn't do any phase-1 checks for added subcommands.
5752 : */
5753 32042 : switch (cmd2->subtype)
5754 : {
5755 1468 : case AT_AddIndex:
5756 1468 : pass = AT_PASS_ADD_INDEX;
5757 1468 : break;
5758 10640 : case AT_AddIndexConstraint:
5759 10640 : pass = AT_PASS_ADD_INDEXCONSTR;
5760 10640 : break;
5761 12488 : case AT_AddConstraint:
5762 : /* Recursion occurs during execution phase */
5763 12488 : if (recurse)
5764 12414 : cmd2->recurse = true;
5765 12488 : switch (castNode(Constraint, cmd2->def)->contype)
5766 : {
5767 8996 : case CONSTR_NOTNULL:
5768 8996 : pass = AT_PASS_COL_ATTRS;
5769 8996 : break;
5770 0 : case CONSTR_PRIMARY:
5771 : case CONSTR_UNIQUE:
5772 : case CONSTR_EXCLUSION:
5773 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5774 0 : break;
5775 3492 : default:
5776 3492 : pass = AT_PASS_ADD_OTHERCONSTR;
5777 3492 : break;
5778 : }
5779 12488 : break;
5780 0 : case AT_AlterColumnGenericOptions:
5781 : /* This command never recurses */
5782 : /* No command-specific prep needed */
5783 0 : pass = AT_PASS_MISC;
5784 0 : break;
5785 7446 : default:
5786 7446 : pass = cur_pass;
5787 7446 : break;
5788 : }
5789 :
5790 32042 : if (pass < cur_pass)
5791 : {
5792 : /* Cannot schedule into a pass we already finished */
5793 0 : elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
5794 : pass);
5795 : }
5796 32042 : else if (pass > cur_pass)
5797 : {
5798 : /* OK, queue it up for later */
5799 24596 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
5800 : }
5801 : else
5802 : {
5803 : /*
5804 : * We should see at most one subcommand for the current pass,
5805 : * which is the transformed version of the original subcommand.
5806 : */
5807 7446 : if (newcmd == NULL && cmd->subtype == cmd2->subtype)
5808 : {
5809 : /* Found the transformed version of our subcommand */
5810 7446 : newcmd = cmd2;
5811 : }
5812 : else
5813 0 : elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
5814 : pass);
5815 : }
5816 : }
5817 :
5818 : /* Queue up any after-statements to happen at the end */
5819 23696 : tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
5820 :
5821 23696 : return newcmd;
5822 : }
5823 :
5824 : /*
5825 : * ATRewriteTables: ALTER TABLE phase 3
5826 : */
5827 : static void
5828 31348 : ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
5829 : AlterTableUtilityContext *context)
5830 : {
5831 : ListCell *ltab;
5832 :
5833 : /* Go through each table that needs to be checked or rewritten */
5834 66920 : foreach(ltab, *wqueue)
5835 : {
5836 35924 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5837 :
5838 : /* Relations without storage may be ignored here */
5839 35924 : if (!RELKIND_HAS_STORAGE(tab->relkind))
5840 6612 : continue;
5841 :
5842 : /*
5843 : * If we change column data types, the operation has to be propagated
5844 : * to tables that use this table's rowtype as a column type.
5845 : * tab->newvals will also be non-NULL in the case where we're adding a
5846 : * column with a default. We choose to forbid that case as well,
5847 : * since composite types might eventually support defaults.
5848 : *
5849 : * (Eventually we'll probably need to check for composite type
5850 : * dependencies even when we're just scanning the table without a
5851 : * rewrite, but at the moment a composite type does not enforce any
5852 : * constraints, so it's not necessary/appropriate to enforce them just
5853 : * during ALTER.)
5854 : */
5855 29312 : if (tab->newvals != NIL || tab->rewrite > 0)
5856 : {
5857 : Relation rel;
5858 :
5859 1704 : rel = table_open(tab->relid, NoLock);
5860 1704 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
5861 1680 : table_close(rel, NoLock);
5862 : }
5863 :
5864 : /*
5865 : * We only need to rewrite the table if at least one column needs to
5866 : * be recomputed, or we are changing its persistence or access method.
5867 : *
5868 : * There are two reasons for requiring a rewrite when changing
5869 : * persistence: on one hand, we need to ensure that the buffers
5870 : * belonging to each of the two relations are marked with or without
5871 : * BM_PERMANENT properly. On the other hand, since rewriting creates
5872 : * and assigns a new relfilenumber, we automatically create or drop an
5873 : * init fork for the relation as appropriate.
5874 : */
5875 29288 : if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
5876 934 : {
5877 : /* Build a temporary relation and copy data */
5878 : Relation OldHeap;
5879 : Oid OIDNewHeap;
5880 : Oid NewAccessMethod;
5881 : Oid NewTableSpace;
5882 : char persistence;
5883 :
5884 990 : OldHeap = table_open(tab->relid, NoLock);
5885 :
5886 : /*
5887 : * We don't support rewriting of system catalogs; there are too
5888 : * many corner cases and too little benefit. In particular this
5889 : * is certainly not going to work for mapped catalogs.
5890 : */
5891 990 : if (IsSystemRelation(OldHeap))
5892 0 : ereport(ERROR,
5893 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5894 : errmsg("cannot rewrite system relation \"%s\"",
5895 : RelationGetRelationName(OldHeap))));
5896 :
5897 990 : if (RelationIsUsedAsCatalogTable(OldHeap))
5898 2 : ereport(ERROR,
5899 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5900 : errmsg("cannot rewrite table \"%s\" used as a catalog table",
5901 : RelationGetRelationName(OldHeap))));
5902 :
5903 : /*
5904 : * Don't allow rewrite on temp tables of other backends ... their
5905 : * local buffer manager is not going to cope. (This is redundant
5906 : * with the check in CheckAlterTableIsSafe, but for safety we'll
5907 : * check here too.)
5908 : */
5909 988 : if (RELATION_IS_OTHER_TEMP(OldHeap))
5910 0 : ereport(ERROR,
5911 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5912 : errmsg("cannot rewrite temporary tables of other sessions")));
5913 :
5914 : /*
5915 : * Select destination tablespace (same as original unless user
5916 : * requested a change)
5917 : */
5918 988 : if (tab->newTableSpace)
5919 0 : NewTableSpace = tab->newTableSpace;
5920 : else
5921 988 : NewTableSpace = OldHeap->rd_rel->reltablespace;
5922 :
5923 : /*
5924 : * Select destination access method (same as original unless user
5925 : * requested a change)
5926 : */
5927 988 : if (tab->chgAccessMethod)
5928 36 : NewAccessMethod = tab->newAccessMethod;
5929 : else
5930 952 : NewAccessMethod = OldHeap->rd_rel->relam;
5931 :
5932 : /*
5933 : * Select persistence of transient table (same as original unless
5934 : * user requested a change)
5935 : */
5936 988 : persistence = tab->chgPersistence ?
5937 936 : tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
5938 :
5939 988 : table_close(OldHeap, NoLock);
5940 :
5941 : /*
5942 : * Fire off an Event Trigger now, before actually rewriting the
5943 : * table.
5944 : *
5945 : * We don't support Event Trigger for nested commands anywhere,
5946 : * here included, and parsetree is given NULL when coming from
5947 : * AlterTableInternal.
5948 : *
5949 : * And fire it only once.
5950 : */
5951 988 : if (parsetree)
5952 988 : EventTriggerTableRewrite((Node *) parsetree,
5953 : tab->relid,
5954 : tab->rewrite);
5955 :
5956 : /*
5957 : * Create transient table that will receive the modified data.
5958 : *
5959 : * Ensure it is marked correctly as logged or unlogged. We have
5960 : * to do this here so that buffers for the new relfilenumber will
5961 : * have the right persistence set, and at the same time ensure
5962 : * that the original filenumbers's buffers will get read in with
5963 : * the correct setting (i.e. the original one). Otherwise a
5964 : * rollback after the rewrite would possibly result with buffers
5965 : * for the original filenumbers having the wrong persistence
5966 : * setting.
5967 : *
5968 : * NB: This relies on swap_relation_files() also swapping the
5969 : * persistence. That wouldn't work for pg_class, but that can't be
5970 : * unlogged anyway.
5971 : */
5972 982 : OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
5973 : persistence, lockmode);
5974 :
5975 : /*
5976 : * Copy the heap data into the new table with the desired
5977 : * modifications, and test the current data within the table
5978 : * against new constraints generated by ALTER TABLE commands.
5979 : */
5980 982 : ATRewriteTable(tab, OIDNewHeap);
5981 :
5982 : /*
5983 : * Swap the physical files of the old and new heaps, then rebuild
5984 : * indexes and discard the old heap. We can use RecentXmin for
5985 : * the table's new relfrozenxid because we rewrote all the tuples
5986 : * in ATRewriteTable, so no older Xid remains in the table. Also,
5987 : * we never try to swap toast tables by content, since we have no
5988 : * interest in letting this code work on system catalogs.
5989 : */
5990 940 : finish_heap_swap(tab->relid, OIDNewHeap,
5991 : false, false, true,
5992 940 : !OidIsValid(tab->newTableSpace),
5993 : RecentXmin,
5994 : ReadNextMultiXactId(),
5995 : persistence);
5996 :
5997 934 : InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
5998 : }
5999 28298 : else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
6000 : {
6001 24 : if (tab->chgPersistence)
6002 24 : SequenceChangePersistence(tab->relid, tab->newrelpersistence);
6003 : }
6004 : else
6005 : {
6006 : /*
6007 : * If required, test the current data within the table against new
6008 : * constraints generated by ALTER TABLE commands, but don't
6009 : * rebuild data.
6010 : */
6011 28274 : if (tab->constraints != NIL || tab->verify_new_notnull ||
6012 25342 : tab->partition_constraint != NULL)
6013 5198 : ATRewriteTable(tab, InvalidOid);
6014 :
6015 : /*
6016 : * If we had SET TABLESPACE but no reason to reconstruct tuples,
6017 : * just do a block-by-block copy.
6018 : */
6019 28002 : if (tab->newTableSpace)
6020 122 : ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
6021 : }
6022 :
6023 : /*
6024 : * Also change persistence of owned sequences, so that it matches the
6025 : * table persistence.
6026 : */
6027 28960 : if (tab->chgPersistence)
6028 : {
6029 76 : List *seqlist = getOwnedSequences(tab->relid);
6030 : ListCell *lc;
6031 :
6032 124 : foreach(lc, seqlist)
6033 : {
6034 48 : Oid seq_relid = lfirst_oid(lc);
6035 :
6036 48 : SequenceChangePersistence(seq_relid, tab->newrelpersistence);
6037 : }
6038 : }
6039 : }
6040 :
6041 : /*
6042 : * Foreign key constraints are checked in a final pass, since (a) it's
6043 : * generally best to examine each one separately, and (b) it's at least
6044 : * theoretically possible that we have changed both relations of the
6045 : * foreign key, and we'd better have finished both rewrites before we try
6046 : * to read the tables.
6047 : */
6048 66310 : foreach(ltab, *wqueue)
6049 : {
6050 35406 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6051 35406 : Relation rel = NULL;
6052 : ListCell *lcon;
6053 :
6054 : /* Relations without storage may be ignored here too */
6055 35406 : if (!RELKIND_HAS_STORAGE(tab->relkind))
6056 6508 : continue;
6057 :
6058 30756 : foreach(lcon, tab->constraints)
6059 : {
6060 1950 : NewConstraint *con = lfirst(lcon);
6061 :
6062 1950 : if (con->contype == CONSTR_FOREIGN)
6063 : {
6064 1230 : Constraint *fkconstraint = (Constraint *) con->qual;
6065 : Relation refrel;
6066 :
6067 1230 : if (rel == NULL)
6068 : {
6069 : /* Long since locked, no need for another */
6070 1218 : rel = table_open(tab->relid, NoLock);
6071 : }
6072 :
6073 1230 : refrel = table_open(con->refrelid, RowShareLock);
6074 :
6075 1230 : validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
6076 : con->refindid,
6077 : con->conid,
6078 1230 : con->conwithperiod);
6079 :
6080 : /*
6081 : * No need to mark the constraint row as validated, we did
6082 : * that when we inserted the row earlier.
6083 : */
6084 :
6085 1138 : table_close(refrel, NoLock);
6086 : }
6087 : }
6088 :
6089 28806 : if (rel)
6090 1126 : table_close(rel, NoLock);
6091 : }
6092 :
6093 : /* Finally, run any afterStmts that were queued up */
6094 66174 : foreach(ltab, *wqueue)
6095 : {
6096 35270 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6097 : ListCell *lc;
6098 :
6099 35356 : foreach(lc, tab->afterStmts)
6100 : {
6101 86 : Node *stmt = (Node *) lfirst(lc);
6102 :
6103 86 : ProcessUtilityForAlterTable(stmt, context);
6104 86 : CommandCounterIncrement();
6105 : }
6106 : }
6107 30904 : }
6108 :
6109 : /*
6110 : * ATRewriteTable: scan or rewrite one table
6111 : *
6112 : * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
6113 : * must already hold AccessExclusiveLock on it.
6114 : */
6115 : static void
6116 6180 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
6117 : {
6118 : Relation oldrel;
6119 : Relation newrel;
6120 : TupleDesc oldTupDesc;
6121 : TupleDesc newTupDesc;
6122 6180 : bool needscan = false;
6123 : List *notnull_attrs;
6124 : List *notnull_virtual_attrs;
6125 : int i;
6126 : ListCell *l;
6127 : EState *estate;
6128 : CommandId mycid;
6129 : BulkInsertState bistate;
6130 : int ti_options;
6131 6180 : ExprState *partqualstate = NULL;
6132 :
6133 : /*
6134 : * Open the relation(s). We have surely already locked the existing
6135 : * table.
6136 : */
6137 6180 : oldrel = table_open(tab->relid, NoLock);
6138 6180 : oldTupDesc = tab->oldDesc;
6139 6180 : newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
6140 :
6141 6180 : if (OidIsValid(OIDNewHeap))
6142 : {
6143 : Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
6144 : false));
6145 982 : newrel = table_open(OIDNewHeap, NoLock);
6146 : }
6147 : else
6148 5198 : newrel = NULL;
6149 :
6150 : /*
6151 : * Prepare a BulkInsertState and options for table_tuple_insert. The FSM
6152 : * is empty, so don't bother using it.
6153 : */
6154 6180 : if (newrel)
6155 : {
6156 982 : mycid = GetCurrentCommandId(true);
6157 982 : bistate = GetBulkInsertState();
6158 982 : ti_options = TABLE_INSERT_SKIP_FSM;
6159 : }
6160 : else
6161 : {
6162 : /* keep compiler quiet about using these uninitialized */
6163 5198 : mycid = 0;
6164 5198 : bistate = NULL;
6165 5198 : ti_options = 0;
6166 : }
6167 :
6168 : /*
6169 : * Generate the constraint and default execution states
6170 : */
6171 :
6172 6180 : estate = CreateExecutorState();
6173 :
6174 : /* Build the needed expression execution states */
6175 8250 : foreach(l, tab->constraints)
6176 : {
6177 2070 : NewConstraint *con = lfirst(l);
6178 :
6179 2070 : switch (con->contype)
6180 : {
6181 834 : case CONSTR_CHECK:
6182 834 : needscan = true;
6183 834 : con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
6184 834 : break;
6185 1236 : case CONSTR_FOREIGN:
6186 : /* Nothing to do here */
6187 1236 : break;
6188 0 : default:
6189 0 : elog(ERROR, "unrecognized constraint type: %d",
6190 : (int) con->contype);
6191 : }
6192 : }
6193 :
6194 : /* Build expression execution states for partition check quals */
6195 6180 : if (tab->partition_constraint)
6196 : {
6197 2414 : needscan = true;
6198 2414 : partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
6199 : }
6200 :
6201 7224 : foreach(l, tab->newvals)
6202 : {
6203 1044 : NewColumnValue *ex = lfirst(l);
6204 :
6205 : /* expr already planned */
6206 1044 : ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
6207 : }
6208 :
6209 6180 : notnull_attrs = notnull_virtual_attrs = NIL;
6210 6180 : if (newrel || tab->verify_new_notnull)
6211 : {
6212 : /*
6213 : * If we are rebuilding the tuples OR if we added any new but not
6214 : * verified not-null constraints, check all *valid* not-null
6215 : * constraints. This is a bit of overkill but it minimizes risk of
6216 : * bugs.
6217 : *
6218 : * notnull_attrs does *not* collect attribute numbers for valid
6219 : * not-null constraints over virtual generated columns; instead, they
6220 : * are collected in notnull_virtual_attrs for verification elsewhere.
6221 : */
6222 7502 : for (i = 0; i < newTupDesc->natts; i++)
6223 : {
6224 5488 : CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
6225 :
6226 5488 : if (attr->attnullability == ATTNULLABLE_VALID &&
6227 2112 : !attr->attisdropped)
6228 : {
6229 2112 : Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
6230 :
6231 2112 : if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
6232 2022 : notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
6233 : else
6234 90 : notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
6235 90 : wholeatt->attnum);
6236 : }
6237 : }
6238 2014 : if (notnull_attrs || notnull_virtual_attrs)
6239 1550 : needscan = true;
6240 : }
6241 :
6242 6180 : if (newrel || needscan)
6243 : {
6244 : ExprContext *econtext;
6245 : TupleTableSlot *oldslot;
6246 : TupleTableSlot *newslot;
6247 : TableScanDesc scan;
6248 : MemoryContext oldCxt;
6249 5146 : List *dropped_attrs = NIL;
6250 : ListCell *lc;
6251 : Snapshot snapshot;
6252 5146 : ResultRelInfo *rInfo = NULL;
6253 :
6254 : /*
6255 : * When adding or changing a virtual generated column with a not-null
6256 : * constraint, we need to evaluate whether the generation expression
6257 : * is null. For that, we borrow ExecRelGenVirtualNotNull(). Here, we
6258 : * prepare a dummy ResultRelInfo.
6259 : */
6260 5146 : if (notnull_virtual_attrs != NIL)
6261 : {
6262 : MemoryContext oldcontext;
6263 :
6264 : Assert(newTupDesc->constr->has_generated_virtual);
6265 : Assert(newTupDesc->constr->has_not_null);
6266 60 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
6267 60 : rInfo = makeNode(ResultRelInfo);
6268 60 : InitResultRelInfo(rInfo,
6269 : oldrel,
6270 : 0, /* dummy rangetable index */
6271 : NULL,
6272 : estate->es_instrument);
6273 60 : MemoryContextSwitchTo(oldcontext);
6274 : }
6275 :
6276 5146 : if (newrel)
6277 982 : ereport(DEBUG1,
6278 : (errmsg_internal("rewriting table \"%s\"",
6279 : RelationGetRelationName(oldrel))));
6280 : else
6281 4164 : ereport(DEBUG1,
6282 : (errmsg_internal("verifying table \"%s\"",
6283 : RelationGetRelationName(oldrel))));
6284 :
6285 5146 : if (newrel)
6286 : {
6287 : /*
6288 : * All predicate locks on the tuples or pages are about to be made
6289 : * invalid, because we move tuples around. Promote them to
6290 : * relation locks.
6291 : */
6292 982 : TransferPredicateLocksToHeapRelation(oldrel);
6293 : }
6294 :
6295 5146 : econtext = GetPerTupleExprContext(estate);
6296 :
6297 : /*
6298 : * Create necessary tuple slots. When rewriting, two slots are needed,
6299 : * otherwise one suffices. In the case where one slot suffices, we
6300 : * need to use the new tuple descriptor, otherwise some constraints
6301 : * can't be evaluated. Note that even when the tuple layout is the
6302 : * same and no rewrite is required, the tupDescs might not be
6303 : * (consider ADD COLUMN without a default).
6304 : */
6305 5146 : if (tab->rewrite)
6306 : {
6307 : Assert(newrel != NULL);
6308 982 : oldslot = MakeSingleTupleTableSlot(oldTupDesc,
6309 : table_slot_callbacks(oldrel));
6310 982 : newslot = MakeSingleTupleTableSlot(newTupDesc,
6311 : table_slot_callbacks(newrel));
6312 :
6313 : /*
6314 : * Set all columns in the new slot to NULL initially, to ensure
6315 : * columns added as part of the rewrite are initialized to NULL.
6316 : * That is necessary as tab->newvals will not contain an
6317 : * expression for columns with a NULL default, e.g. when adding a
6318 : * column without a default together with a column with a default
6319 : * requiring an actual rewrite.
6320 : */
6321 982 : ExecStoreAllNullTuple(newslot);
6322 : }
6323 : else
6324 : {
6325 4164 : oldslot = MakeSingleTupleTableSlot(newTupDesc,
6326 : table_slot_callbacks(oldrel));
6327 4164 : newslot = NULL;
6328 : }
6329 :
6330 : /*
6331 : * Any attributes that are dropped according to the new tuple
6332 : * descriptor can be set to NULL. We precompute the list of dropped
6333 : * attributes to avoid needing to do so in the per-tuple loop.
6334 : */
6335 18138 : for (i = 0; i < newTupDesc->natts; i++)
6336 : {
6337 12992 : if (TupleDescAttr(newTupDesc, i)->attisdropped)
6338 790 : dropped_attrs = lappend_int(dropped_attrs, i);
6339 : }
6340 :
6341 : /*
6342 : * Scan through the rows, generating a new row if needed and then
6343 : * checking all the constraints.
6344 : */
6345 5146 : snapshot = RegisterSnapshot(GetLatestSnapshot());
6346 5146 : scan = table_beginscan(oldrel, snapshot, 0, NULL);
6347 :
6348 : /*
6349 : * Switch to per-tuple memory context and reset it for each tuple
6350 : * produced, so we don't leak memory.
6351 : */
6352 5146 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6353 :
6354 775204 : while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
6355 : {
6356 : TupleTableSlot *insertslot;
6357 :
6358 765226 : if (tab->rewrite > 0)
6359 : {
6360 : /* Extract data from old tuple */
6361 99834 : slot_getallattrs(oldslot);
6362 99834 : ExecClearTuple(newslot);
6363 :
6364 : /* copy attributes */
6365 99834 : memcpy(newslot->tts_values, oldslot->tts_values,
6366 99834 : sizeof(Datum) * oldslot->tts_nvalid);
6367 99834 : memcpy(newslot->tts_isnull, oldslot->tts_isnull,
6368 99834 : sizeof(bool) * oldslot->tts_nvalid);
6369 :
6370 : /* Set dropped attributes to null in new tuple */
6371 99950 : foreach(lc, dropped_attrs)
6372 116 : newslot->tts_isnull[lfirst_int(lc)] = true;
6373 :
6374 : /*
6375 : * Constraints and GENERATED expressions might reference the
6376 : * tableoid column, so fill tts_tableOid with the desired
6377 : * value. (We must do this each time, because it gets
6378 : * overwritten with newrel's OID during storing.)
6379 : */
6380 99834 : newslot->tts_tableOid = RelationGetRelid(oldrel);
6381 :
6382 : /*
6383 : * Process supplied expressions to replace selected columns.
6384 : *
6385 : * First, evaluate expressions whose inputs come from the old
6386 : * tuple.
6387 : */
6388 99834 : econtext->ecxt_scantuple = oldslot;
6389 :
6390 205620 : foreach(l, tab->newvals)
6391 : {
6392 105798 : NewColumnValue *ex = lfirst(l);
6393 :
6394 105798 : if (ex->is_generated)
6395 312 : continue;
6396 :
6397 105486 : newslot->tts_values[ex->attnum - 1]
6398 105474 : = ExecEvalExpr(ex->exprstate,
6399 : econtext,
6400 105486 : &newslot->tts_isnull[ex->attnum - 1]);
6401 : }
6402 :
6403 99822 : ExecStoreVirtualTuple(newslot);
6404 :
6405 : /*
6406 : * Now, evaluate any expressions whose inputs come from the
6407 : * new tuple. We assume these columns won't reference each
6408 : * other, so that there's no ordering dependency.
6409 : */
6410 99822 : econtext->ecxt_scantuple = newslot;
6411 :
6412 205608 : foreach(l, tab->newvals)
6413 : {
6414 105786 : NewColumnValue *ex = lfirst(l);
6415 :
6416 105786 : if (!ex->is_generated)
6417 105474 : continue;
6418 :
6419 312 : newslot->tts_values[ex->attnum - 1]
6420 312 : = ExecEvalExpr(ex->exprstate,
6421 : econtext,
6422 312 : &newslot->tts_isnull[ex->attnum - 1]);
6423 : }
6424 :
6425 99822 : insertslot = newslot;
6426 : }
6427 : else
6428 : {
6429 : /*
6430 : * If there's no rewrite, old and new table are guaranteed to
6431 : * have the same AM, so we can just use the old slot to verify
6432 : * new constraints etc.
6433 : */
6434 665392 : insertslot = oldslot;
6435 : }
6436 :
6437 : /* Now check any constraints on the possibly-changed tuple */
6438 765214 : econtext->ecxt_scantuple = insertslot;
6439 :
6440 4106698 : foreach_int(attn, notnull_attrs)
6441 : {
6442 2576474 : if (slot_attisnull(insertslot, attn))
6443 : {
6444 102 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
6445 :
6446 102 : ereport(ERROR,
6447 : (errcode(ERRCODE_NOT_NULL_VIOLATION),
6448 : errmsg("column \"%s\" of relation \"%s\" contains null values",
6449 : NameStr(attr->attname),
6450 : RelationGetRelationName(oldrel)),
6451 : errtablecol(oldrel, attn)));
6452 : }
6453 : }
6454 :
6455 765112 : if (notnull_virtual_attrs != NIL)
6456 : {
6457 : AttrNumber attnum;
6458 :
6459 84 : attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
6460 : estate,
6461 : notnull_virtual_attrs);
6462 84 : if (attnum != InvalidAttrNumber)
6463 : {
6464 30 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
6465 :
6466 30 : ereport(ERROR,
6467 : errcode(ERRCODE_NOT_NULL_VIOLATION),
6468 : errmsg("column \"%s\" of relation \"%s\" contains null values",
6469 : NameStr(attr->attname),
6470 : RelationGetRelationName(oldrel)),
6471 : errtablecol(oldrel, attnum));
6472 : }
6473 : }
6474 :
6475 773246 : foreach(l, tab->constraints)
6476 : {
6477 8260 : NewConstraint *con = lfirst(l);
6478 :
6479 8260 : switch (con->contype)
6480 : {
6481 8154 : case CONSTR_CHECK:
6482 8154 : if (!ExecCheck(con->qualstate, econtext))
6483 96 : ereport(ERROR,
6484 : (errcode(ERRCODE_CHECK_VIOLATION),
6485 : errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
6486 : con->name,
6487 : RelationGetRelationName(oldrel)),
6488 : errtableconstraint(oldrel, con->name)));
6489 8058 : break;
6490 106 : case CONSTR_NOTNULL:
6491 : case CONSTR_FOREIGN:
6492 : /* Nothing to do here */
6493 106 : break;
6494 0 : default:
6495 0 : elog(ERROR, "unrecognized constraint type: %d",
6496 : (int) con->contype);
6497 : }
6498 : }
6499 :
6500 764986 : if (partqualstate && !ExecCheck(partqualstate, econtext))
6501 : {
6502 74 : if (tab->validate_default)
6503 26 : ereport(ERROR,
6504 : (errcode(ERRCODE_CHECK_VIOLATION),
6505 : errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
6506 : RelationGetRelationName(oldrel)),
6507 : errtable(oldrel)));
6508 : else
6509 48 : ereport(ERROR,
6510 : (errcode(ERRCODE_CHECK_VIOLATION),
6511 : errmsg("partition constraint of relation \"%s\" is violated by some row",
6512 : RelationGetRelationName(oldrel)),
6513 : errtable(oldrel)));
6514 : }
6515 :
6516 : /* Write the tuple out to the new relation */
6517 764912 : if (newrel)
6518 99792 : table_tuple_insert(newrel, insertslot, mycid,
6519 : ti_options, bistate);
6520 :
6521 764912 : ResetExprContext(econtext);
6522 :
6523 764912 : CHECK_FOR_INTERRUPTS();
6524 : }
6525 :
6526 4832 : MemoryContextSwitchTo(oldCxt);
6527 4832 : table_endscan(scan);
6528 4832 : UnregisterSnapshot(snapshot);
6529 :
6530 4832 : ExecDropSingleTupleTableSlot(oldslot);
6531 4832 : if (newslot)
6532 940 : ExecDropSingleTupleTableSlot(newslot);
6533 : }
6534 :
6535 5866 : FreeExecutorState(estate);
6536 :
6537 5866 : table_close(oldrel, NoLock);
6538 5866 : if (newrel)
6539 : {
6540 940 : FreeBulkInsertState(bistate);
6541 :
6542 940 : table_finish_bulk_insert(newrel, ti_options);
6543 :
6544 940 : table_close(newrel, NoLock);
6545 : }
6546 5866 : }
6547 :
6548 : /*
6549 : * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
6550 : */
6551 : static AlteredTableInfo *
6552 44258 : ATGetQueueEntry(List **wqueue, Relation rel)
6553 : {
6554 44258 : Oid relid = RelationGetRelid(rel);
6555 : AlteredTableInfo *tab;
6556 : ListCell *ltab;
6557 :
6558 54458 : foreach(ltab, *wqueue)
6559 : {
6560 15074 : tab = (AlteredTableInfo *) lfirst(ltab);
6561 15074 : if (tab->relid == relid)
6562 4874 : return tab;
6563 : }
6564 :
6565 : /*
6566 : * Not there, so add it. Note that we make a copy of the relation's
6567 : * existing descriptor before anything interesting can happen to it.
6568 : */
6569 39384 : tab = (AlteredTableInfo *) palloc0(sizeof(AlteredTableInfo));
6570 39384 : tab->relid = relid;
6571 39384 : tab->rel = NULL; /* set later */
6572 39384 : tab->relkind = rel->rd_rel->relkind;
6573 39384 : tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
6574 39384 : tab->newAccessMethod = InvalidOid;
6575 39384 : tab->chgAccessMethod = false;
6576 39384 : tab->newTableSpace = InvalidOid;
6577 39384 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
6578 39384 : tab->chgPersistence = false;
6579 :
6580 39384 : *wqueue = lappend(*wqueue, tab);
6581 :
6582 39384 : return tab;
6583 : }
6584 :
6585 : static const char *
6586 80 : alter_table_type_to_string(AlterTableType cmdtype)
6587 : {
6588 80 : switch (cmdtype)
6589 : {
6590 0 : case AT_AddColumn:
6591 : case AT_AddColumnToView:
6592 0 : return "ADD COLUMN";
6593 0 : case AT_ColumnDefault:
6594 : case AT_CookedColumnDefault:
6595 0 : return "ALTER COLUMN ... SET DEFAULT";
6596 6 : case AT_DropNotNull:
6597 6 : return "ALTER COLUMN ... DROP NOT NULL";
6598 6 : case AT_SetNotNull:
6599 6 : return "ALTER COLUMN ... SET NOT NULL";
6600 0 : case AT_SetExpression:
6601 0 : return "ALTER COLUMN ... SET EXPRESSION";
6602 0 : case AT_DropExpression:
6603 0 : return "ALTER COLUMN ... DROP EXPRESSION";
6604 0 : case AT_SetStatistics:
6605 0 : return "ALTER COLUMN ... SET STATISTICS";
6606 12 : case AT_SetOptions:
6607 12 : return "ALTER COLUMN ... SET";
6608 0 : case AT_ResetOptions:
6609 0 : return "ALTER COLUMN ... RESET";
6610 0 : case AT_SetStorage:
6611 0 : return "ALTER COLUMN ... SET STORAGE";
6612 0 : case AT_SetCompression:
6613 0 : return "ALTER COLUMN ... SET COMPRESSION";
6614 6 : case AT_DropColumn:
6615 6 : return "DROP COLUMN";
6616 0 : case AT_AddIndex:
6617 : case AT_ReAddIndex:
6618 0 : return NULL; /* not real grammar */
6619 0 : case AT_AddConstraint:
6620 : case AT_ReAddConstraint:
6621 : case AT_ReAddDomainConstraint:
6622 : case AT_AddIndexConstraint:
6623 0 : return "ADD CONSTRAINT";
6624 6 : case AT_AlterConstraint:
6625 6 : return "ALTER CONSTRAINT";
6626 0 : case AT_ValidateConstraint:
6627 0 : return "VALIDATE CONSTRAINT";
6628 0 : case AT_DropConstraint:
6629 0 : return "DROP CONSTRAINT";
6630 0 : case AT_ReAddComment:
6631 0 : return NULL; /* not real grammar */
6632 0 : case AT_AlterColumnType:
6633 0 : return "ALTER COLUMN ... SET DATA TYPE";
6634 0 : case AT_AlterColumnGenericOptions:
6635 0 : return "ALTER COLUMN ... OPTIONS";
6636 0 : case AT_ChangeOwner:
6637 0 : return "OWNER TO";
6638 0 : case AT_ClusterOn:
6639 0 : return "CLUSTER ON";
6640 0 : case AT_DropCluster:
6641 0 : return "SET WITHOUT CLUSTER";
6642 0 : case AT_SetAccessMethod:
6643 0 : return "SET ACCESS METHOD";
6644 6 : case AT_SetLogged:
6645 6 : return "SET LOGGED";
6646 6 : case AT_SetUnLogged:
6647 6 : return "SET UNLOGGED";
6648 0 : case AT_DropOids:
6649 0 : return "SET WITHOUT OIDS";
6650 0 : case AT_SetTableSpace:
6651 0 : return "SET TABLESPACE";
6652 2 : case AT_SetRelOptions:
6653 2 : return "SET";
6654 0 : case AT_ResetRelOptions:
6655 0 : return "RESET";
6656 0 : case AT_ReplaceRelOptions:
6657 0 : return NULL; /* not real grammar */
6658 0 : case AT_EnableTrig:
6659 0 : return "ENABLE TRIGGER";
6660 0 : case AT_EnableAlwaysTrig:
6661 0 : return "ENABLE ALWAYS TRIGGER";
6662 0 : case AT_EnableReplicaTrig:
6663 0 : return "ENABLE REPLICA TRIGGER";
6664 0 : case AT_DisableTrig:
6665 0 : return "DISABLE TRIGGER";
6666 0 : case AT_EnableTrigAll:
6667 0 : return "ENABLE TRIGGER ALL";
6668 0 : case AT_DisableTrigAll:
6669 0 : return "DISABLE TRIGGER ALL";
6670 0 : case AT_EnableTrigUser:
6671 0 : return "ENABLE TRIGGER USER";
6672 0 : case AT_DisableTrigUser:
6673 0 : return "DISABLE TRIGGER USER";
6674 0 : case AT_EnableRule:
6675 0 : return "ENABLE RULE";
6676 0 : case AT_EnableAlwaysRule:
6677 0 : return "ENABLE ALWAYS RULE";
6678 0 : case AT_EnableReplicaRule:
6679 0 : return "ENABLE REPLICA RULE";
6680 0 : case AT_DisableRule:
6681 0 : return "DISABLE RULE";
6682 0 : case AT_AddInherit:
6683 0 : return "INHERIT";
6684 0 : case AT_DropInherit:
6685 0 : return "NO INHERIT";
6686 0 : case AT_AddOf:
6687 0 : return "OF";
6688 0 : case AT_DropOf:
6689 0 : return "NOT OF";
6690 0 : case AT_ReplicaIdentity:
6691 0 : return "REPLICA IDENTITY";
6692 0 : case AT_EnableRowSecurity:
6693 0 : return "ENABLE ROW SECURITY";
6694 0 : case AT_DisableRowSecurity:
6695 0 : return "DISABLE ROW SECURITY";
6696 0 : case AT_ForceRowSecurity:
6697 0 : return "FORCE ROW SECURITY";
6698 0 : case AT_NoForceRowSecurity:
6699 0 : return "NO FORCE ROW SECURITY";
6700 0 : case AT_GenericOptions:
6701 0 : return "OPTIONS";
6702 6 : case AT_AttachPartition:
6703 6 : return "ATTACH PARTITION";
6704 18 : case AT_DetachPartition:
6705 18 : return "DETACH PARTITION";
6706 6 : case AT_DetachPartitionFinalize:
6707 6 : return "DETACH PARTITION ... FINALIZE";
6708 0 : case AT_AddIdentity:
6709 0 : return "ALTER COLUMN ... ADD IDENTITY";
6710 0 : case AT_SetIdentity:
6711 0 : return "ALTER COLUMN ... SET";
6712 0 : case AT_DropIdentity:
6713 0 : return "ALTER COLUMN ... DROP IDENTITY";
6714 0 : case AT_ReAddStatistics:
6715 0 : return NULL; /* not real grammar */
6716 : }
6717 :
6718 0 : return NULL;
6719 : }
6720 :
6721 : /*
6722 : * ATSimplePermissions
6723 : *
6724 : * - Ensure that it is a relation (or possibly a view)
6725 : * - Ensure this user is the owner
6726 : * - Ensure that it is not a system table
6727 : */
6728 : static void
6729 38930 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
6730 : {
6731 : int actual_target;
6732 :
6733 38930 : switch (rel->rd_rel->relkind)
6734 : {
6735 30444 : case RELKIND_RELATION:
6736 30444 : actual_target = ATT_TABLE;
6737 30444 : break;
6738 6118 : case RELKIND_PARTITIONED_TABLE:
6739 6118 : actual_target = ATT_PARTITIONED_TABLE;
6740 6118 : break;
6741 406 : case RELKIND_VIEW:
6742 406 : actual_target = ATT_VIEW;
6743 406 : break;
6744 48 : case RELKIND_MATVIEW:
6745 48 : actual_target = ATT_MATVIEW;
6746 48 : break;
6747 228 : case RELKIND_INDEX:
6748 228 : actual_target = ATT_INDEX;
6749 228 : break;
6750 518 : case RELKIND_PARTITIONED_INDEX:
6751 518 : actual_target = ATT_PARTITIONED_INDEX;
6752 518 : break;
6753 216 : case RELKIND_COMPOSITE_TYPE:
6754 216 : actual_target = ATT_COMPOSITE_TYPE;
6755 216 : break;
6756 926 : case RELKIND_FOREIGN_TABLE:
6757 926 : actual_target = ATT_FOREIGN_TABLE;
6758 926 : break;
6759 24 : case RELKIND_SEQUENCE:
6760 24 : actual_target = ATT_SEQUENCE;
6761 24 : break;
6762 2 : default:
6763 2 : actual_target = 0;
6764 2 : break;
6765 : }
6766 :
6767 : /* Wrong target type? */
6768 38930 : if ((actual_target & allowed_targets) == 0)
6769 : {
6770 80 : const char *action_str = alter_table_type_to_string(cmdtype);
6771 :
6772 80 : if (action_str)
6773 80 : ereport(ERROR,
6774 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6775 : /* translator: %s is a group of some SQL keywords */
6776 : errmsg("ALTER action %s cannot be performed on relation \"%s\"",
6777 : action_str, RelationGetRelationName(rel)),
6778 : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
6779 : else
6780 : /* internal error? */
6781 0 : elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
6782 : RelationGetRelationName(rel));
6783 : }
6784 :
6785 : /* Permissions checks */
6786 38850 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
6787 12 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
6788 12 : RelationGetRelationName(rel));
6789 :
6790 38838 : if (!allowSystemTableMods && IsSystemRelation(rel))
6791 0 : ereport(ERROR,
6792 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6793 : errmsg("permission denied: \"%s\" is a system catalog",
6794 : RelationGetRelationName(rel))));
6795 38838 : }
6796 :
6797 : /*
6798 : * ATSimpleRecursion
6799 : *
6800 : * Simple table recursion sufficient for most ALTER TABLE operations.
6801 : * All direct and indirect children are processed in an unspecified order.
6802 : * Note that if a child inherits from the original table via multiple
6803 : * inheritance paths, it will be visited just once.
6804 : */
6805 : static void
6806 1324 : ATSimpleRecursion(List **wqueue, Relation rel,
6807 : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
6808 : AlterTableUtilityContext *context)
6809 : {
6810 : /*
6811 : * Propagate to children, if desired and if there are (or might be) any
6812 : * children.
6813 : */
6814 1324 : if (recurse && rel->rd_rel->relhassubclass)
6815 : {
6816 84 : Oid relid = RelationGetRelid(rel);
6817 : ListCell *child;
6818 : List *children;
6819 :
6820 84 : children = find_all_inheritors(relid, lockmode, NULL);
6821 :
6822 : /*
6823 : * find_all_inheritors does the recursive search of the inheritance
6824 : * hierarchy, so all we have to do is process all of the relids in the
6825 : * list that it returns.
6826 : */
6827 366 : foreach(child, children)
6828 : {
6829 282 : Oid childrelid = lfirst_oid(child);
6830 : Relation childrel;
6831 :
6832 282 : if (childrelid == relid)
6833 84 : continue;
6834 : /* find_all_inheritors already got lock */
6835 198 : childrel = relation_open(childrelid, NoLock);
6836 198 : CheckAlterTableIsSafe(childrel);
6837 198 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
6838 198 : relation_close(childrel, NoLock);
6839 : }
6840 : }
6841 1324 : }
6842 :
6843 : /*
6844 : * Obtain list of partitions of the given table, locking them all at the given
6845 : * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
6846 : *
6847 : * This function is a no-op if the given relation is not a partitioned table;
6848 : * in particular, nothing is done if it's a legacy inheritance parent.
6849 : */
6850 : static void
6851 798 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
6852 : {
6853 798 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6854 : {
6855 : List *inh;
6856 : ListCell *cell;
6857 :
6858 176 : inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
6859 : /* first element is the parent rel; must ignore it */
6860 574 : for_each_from(cell, inh, 1)
6861 : {
6862 : Relation childrel;
6863 :
6864 : /* find_all_inheritors already got lock */
6865 404 : childrel = table_open(lfirst_oid(cell), NoLock);
6866 404 : CheckAlterTableIsSafe(childrel);
6867 398 : table_close(childrel, NoLock);
6868 : }
6869 170 : list_free(inh);
6870 : }
6871 792 : }
6872 :
6873 : /*
6874 : * ATTypedTableRecursion
6875 : *
6876 : * Propagate ALTER TYPE operations to the typed tables of that type.
6877 : * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
6878 : * recursion to inheritance children of the typed tables.
6879 : */
6880 : static void
6881 192 : ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
6882 : LOCKMODE lockmode, AlterTableUtilityContext *context)
6883 : {
6884 : ListCell *child;
6885 : List *children;
6886 :
6887 : Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6888 :
6889 192 : children = find_typed_table_dependencies(rel->rd_rel->reltype,
6890 192 : RelationGetRelationName(rel),
6891 : cmd->behavior);
6892 :
6893 204 : foreach(child, children)
6894 : {
6895 30 : Oid childrelid = lfirst_oid(child);
6896 : Relation childrel;
6897 :
6898 30 : childrel = relation_open(childrelid, lockmode);
6899 30 : CheckAlterTableIsSafe(childrel);
6900 30 : ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
6901 30 : relation_close(childrel, NoLock);
6902 : }
6903 174 : }
6904 :
6905 :
6906 : /*
6907 : * find_composite_type_dependencies
6908 : *
6909 : * Check to see if the type "typeOid" is being used as a column in some table
6910 : * (possibly nested several levels deep in composite types, arrays, etc!).
6911 : * Eventually, we'd like to propagate the check or rewrite operation
6912 : * into such tables, but for now, just error out if we find any.
6913 : *
6914 : * Caller should provide either the associated relation of a rowtype,
6915 : * or a type name (not both) for use in the error message, if any.
6916 : *
6917 : * Note that "typeOid" is not necessarily a composite type; it could also be
6918 : * another container type such as an array or range, or a domain over one of
6919 : * these things. The name of this function is therefore somewhat historical,
6920 : * but it's not worth changing.
6921 : *
6922 : * We assume that functions and views depending on the type are not reasons
6923 : * to reject the ALTER. (How safe is this really?)
6924 : */
6925 : void
6926 4464 : find_composite_type_dependencies(Oid typeOid, Relation origRelation,
6927 : const char *origTypeName)
6928 : {
6929 : Relation depRel;
6930 : ScanKeyData key[2];
6931 : SysScanDesc depScan;
6932 : HeapTuple depTup;
6933 :
6934 : /* since this function recurses, it could be driven to stack overflow */
6935 4464 : check_stack_depth();
6936 :
6937 : /*
6938 : * We scan pg_depend to find those things that depend on the given type.
6939 : * (We assume we can ignore refobjsubid for a type.)
6940 : */
6941 4464 : depRel = table_open(DependRelationId, AccessShareLock);
6942 :
6943 4464 : ScanKeyInit(&key[0],
6944 : Anum_pg_depend_refclassid,
6945 : BTEqualStrategyNumber, F_OIDEQ,
6946 : ObjectIdGetDatum(TypeRelationId));
6947 4464 : ScanKeyInit(&key[1],
6948 : Anum_pg_depend_refobjid,
6949 : BTEqualStrategyNumber, F_OIDEQ,
6950 : ObjectIdGetDatum(typeOid));
6951 :
6952 4464 : depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
6953 : NULL, 2, key);
6954 :
6955 6864 : while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
6956 : {
6957 2526 : Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
6958 : Relation rel;
6959 : TupleDesc tupleDesc;
6960 : Form_pg_attribute att;
6961 :
6962 : /* Check for directly dependent types */
6963 2526 : if (pg_depend->classid == TypeRelationId)
6964 : {
6965 : /*
6966 : * This must be an array, domain, or range containing the given
6967 : * type, so recursively check for uses of this type. Note that
6968 : * any error message will mention the original type not the
6969 : * container; this is intentional.
6970 : */
6971 2150 : find_composite_type_dependencies(pg_depend->objid,
6972 : origRelation, origTypeName);
6973 2126 : continue;
6974 : }
6975 :
6976 : /* Else, ignore dependees that aren't relations */
6977 376 : if (pg_depend->classid != RelationRelationId)
6978 122 : continue;
6979 :
6980 254 : rel = relation_open(pg_depend->objid, AccessShareLock);
6981 254 : tupleDesc = RelationGetDescr(rel);
6982 :
6983 : /*
6984 : * If objsubid identifies a specific column, refer to that in error
6985 : * messages. Otherwise, search to see if there's a user column of the
6986 : * type. (We assume system columns are never of interesting types.)
6987 : * The search is needed because an index containing an expression
6988 : * column of the target type will just be recorded as a whole-relation
6989 : * dependency. If we do not find a column of the type, the dependency
6990 : * must indicate that the type is transiently referenced in an index
6991 : * expression but not stored on disk, which we assume is OK, just as
6992 : * we do for references in views. (It could also be that the target
6993 : * type is embedded in some container type that is stored in an index
6994 : * column, but the previous recursion should catch such cases.)
6995 : */
6996 254 : if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
6997 96 : att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
6998 : else
6999 : {
7000 158 : att = NULL;
7001 406 : for (int attno = 1; attno <= tupleDesc->natts; attno++)
7002 : {
7003 254 : att = TupleDescAttr(tupleDesc, attno - 1);
7004 254 : if (att->atttypid == typeOid && !att->attisdropped)
7005 6 : break;
7006 248 : att = NULL;
7007 : }
7008 158 : if (att == NULL)
7009 : {
7010 : /* No such column, so assume OK */
7011 152 : relation_close(rel, AccessShareLock);
7012 152 : continue;
7013 : }
7014 : }
7015 :
7016 : /*
7017 : * We definitely should reject if the relation has storage. If it's
7018 : * partitioned, then perhaps we don't have to reject: if there are
7019 : * partitions then we'll fail when we find one, else there is no
7020 : * stored data to worry about. However, it's possible that the type
7021 : * change would affect conclusions about whether the type is sortable
7022 : * or hashable and thus (if it's a partitioning column) break the
7023 : * partitioning rule. For now, reject for partitioned rels too.
7024 : */
7025 102 : if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
7026 0 : RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7027 : {
7028 102 : if (origTypeName)
7029 30 : ereport(ERROR,
7030 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7031 : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7032 : origTypeName,
7033 : RelationGetRelationName(rel),
7034 : NameStr(att->attname))));
7035 72 : else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7036 18 : ereport(ERROR,
7037 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7038 : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7039 : RelationGetRelationName(origRelation),
7040 : RelationGetRelationName(rel),
7041 : NameStr(att->attname))));
7042 54 : else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7043 6 : ereport(ERROR,
7044 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7045 : errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7046 : RelationGetRelationName(origRelation),
7047 : RelationGetRelationName(rel),
7048 : NameStr(att->attname))));
7049 : else
7050 48 : ereport(ERROR,
7051 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7052 : errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7053 : RelationGetRelationName(origRelation),
7054 : RelationGetRelationName(rel),
7055 : NameStr(att->attname))));
7056 : }
7057 0 : else if (OidIsValid(rel->rd_rel->reltype))
7058 : {
7059 : /*
7060 : * A view or composite type itself isn't a problem, but we must
7061 : * recursively check for indirect dependencies via its rowtype.
7062 : */
7063 0 : find_composite_type_dependencies(rel->rd_rel->reltype,
7064 : origRelation, origTypeName);
7065 : }
7066 :
7067 0 : relation_close(rel, AccessShareLock);
7068 : }
7069 :
7070 4338 : systable_endscan(depScan);
7071 :
7072 4338 : relation_close(depRel, AccessShareLock);
7073 4338 : }
7074 :
7075 :
7076 : /*
7077 : * find_typed_table_dependencies
7078 : *
7079 : * Check to see if a composite type is being used as the type of a
7080 : * typed table. Abort if any are found and behavior is RESTRICT.
7081 : * Else return the list of tables.
7082 : */
7083 : static List *
7084 216 : find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
7085 : {
7086 : Relation classRel;
7087 : ScanKeyData key[1];
7088 : TableScanDesc scan;
7089 : HeapTuple tuple;
7090 216 : List *result = NIL;
7091 :
7092 216 : classRel = table_open(RelationRelationId, AccessShareLock);
7093 :
7094 216 : ScanKeyInit(&key[0],
7095 : Anum_pg_class_reloftype,
7096 : BTEqualStrategyNumber, F_OIDEQ,
7097 : ObjectIdGetDatum(typeOid));
7098 :
7099 216 : scan = table_beginscan_catalog(classRel, 1, key);
7100 :
7101 252 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7102 : {
7103 60 : Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
7104 :
7105 60 : if (behavior == DROP_RESTRICT)
7106 24 : ereport(ERROR,
7107 : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
7108 : errmsg("cannot alter type \"%s\" because it is the type of a typed table",
7109 : typeName),
7110 : errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
7111 : else
7112 36 : result = lappend_oid(result, classform->oid);
7113 : }
7114 :
7115 192 : table_endscan(scan);
7116 192 : table_close(classRel, AccessShareLock);
7117 :
7118 192 : return result;
7119 : }
7120 :
7121 :
7122 : /*
7123 : * check_of_type
7124 : *
7125 : * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
7126 : * isn't suitable, throw an error. Currently, we require that the type
7127 : * originated with CREATE TYPE AS. We could support any row type, but doing so
7128 : * would require handling a number of extra corner cases in the DDL commands.
7129 : * (Also, allowing domain-over-composite would open up a can of worms about
7130 : * whether and how the domain's constraints should apply to derived tables.)
7131 : */
7132 : void
7133 194 : check_of_type(HeapTuple typetuple)
7134 : {
7135 194 : Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7136 194 : bool typeOk = false;
7137 :
7138 194 : if (typ->typtype == TYPTYPE_COMPOSITE)
7139 : {
7140 : Relation typeRelation;
7141 :
7142 : Assert(OidIsValid(typ->typrelid));
7143 188 : typeRelation = relation_open(typ->typrelid, AccessShareLock);
7144 188 : typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7145 :
7146 : /*
7147 : * Close the parent rel, but keep our AccessShareLock on it until xact
7148 : * commit. That will prevent someone else from deleting or ALTERing
7149 : * the type before the typed table creation/conversion commits.
7150 : */
7151 188 : relation_close(typeRelation, NoLock);
7152 :
7153 188 : if (!typeOk)
7154 6 : ereport(ERROR,
7155 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7156 : errmsg("type %s is the row type of another table",
7157 : format_type_be(typ->oid)),
7158 : errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7159 : }
7160 : else
7161 6 : ereport(ERROR,
7162 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7163 : errmsg("type %s is not a composite type",
7164 : format_type_be(typ->oid))));
7165 182 : }
7166 :
7167 :
7168 : /*
7169 : * ALTER TABLE ADD COLUMN
7170 : *
7171 : * Adds an additional attribute to a relation making the assumption that
7172 : * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
7173 : * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
7174 : * AlterTableCmd's.
7175 : *
7176 : * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
7177 : * have to decide at runtime whether to recurse or not depending on whether we
7178 : * actually add a column or merely merge with an existing column. (We can't
7179 : * check this in a static pre-pass because it won't handle multiple inheritance
7180 : * situations correctly.)
7181 : */
7182 : static void
7183 2188 : ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
7184 : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
7185 : AlterTableUtilityContext *context)
7186 : {
7187 2188 : if (rel->rd_rel->reloftype && !recursing)
7188 6 : ereport(ERROR,
7189 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7190 : errmsg("cannot add column to typed table")));
7191 :
7192 2182 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7193 58 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
7194 :
7195 2176 : if (recurse && !is_view)
7196 2076 : cmd->recurse = true;
7197 2176 : }
7198 :
7199 : /*
7200 : * Add a column to a table. The return value is the address of the
7201 : * new column in the parent relation.
7202 : *
7203 : * cmd is pass-by-ref so that we can replace it with the parse-transformed
7204 : * copy (but that happens only after we check for IF NOT EXISTS).
7205 : */
7206 : static ObjectAddress
7207 2908 : ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
7208 : AlterTableCmd **cmd, bool recurse, bool recursing,
7209 : LOCKMODE lockmode, AlterTablePass cur_pass,
7210 : AlterTableUtilityContext *context)
7211 : {
7212 2908 : Oid myrelid = RelationGetRelid(rel);
7213 2908 : ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
7214 2908 : bool if_not_exists = (*cmd)->missing_ok;
7215 : Relation pgclass,
7216 : attrdesc;
7217 : HeapTuple reltup;
7218 : Form_pg_class relform;
7219 : Form_pg_attribute attribute;
7220 : int newattnum;
7221 : char relkind;
7222 : Expr *defval;
7223 : List *children;
7224 : ListCell *child;
7225 : AlterTableCmd *childcmd;
7226 : ObjectAddress address;
7227 : TupleDesc tupdesc;
7228 :
7229 : /* since this function recurses, it could be driven to stack overflow */
7230 2908 : check_stack_depth();
7231 :
7232 : /* At top level, permission check was done in ATPrepCmd, else do it */
7233 2908 : if (recursing)
7234 738 : ATSimplePermissions((*cmd)->subtype, rel,
7235 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
7236 :
7237 2908 : if (rel->rd_rel->relispartition && !recursing)
7238 12 : ereport(ERROR,
7239 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7240 : errmsg("cannot add column to a partition")));
7241 :
7242 2896 : attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
7243 :
7244 : /*
7245 : * Are we adding the column to a recursion child? If so, check whether to
7246 : * merge with an existing definition for the column. If we do merge, we
7247 : * must not recurse. Children will already have the column, and recursing
7248 : * into them would mess up attinhcount.
7249 : */
7250 2896 : if (colDef->inhcount > 0)
7251 : {
7252 : HeapTuple tuple;
7253 :
7254 : /* Does child already have a column by this name? */
7255 738 : tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
7256 738 : if (HeapTupleIsValid(tuple))
7257 : {
7258 60 : Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7259 : Oid ctypeId;
7260 : int32 ctypmod;
7261 : Oid ccollid;
7262 :
7263 : /* Child column must match on type, typmod, and collation */
7264 60 : typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
7265 60 : if (ctypeId != childatt->atttypid ||
7266 60 : ctypmod != childatt->atttypmod)
7267 0 : ereport(ERROR,
7268 : (errcode(ERRCODE_DATATYPE_MISMATCH),
7269 : errmsg("child table \"%s\" has different type for column \"%s\"",
7270 : RelationGetRelationName(rel), colDef->colname)));
7271 60 : ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
7272 60 : if (ccollid != childatt->attcollation)
7273 0 : ereport(ERROR,
7274 : (errcode(ERRCODE_COLLATION_MISMATCH),
7275 : errmsg("child table \"%s\" has different collation for column \"%s\"",
7276 : RelationGetRelationName(rel), colDef->colname),
7277 : errdetail("\"%s\" versus \"%s\"",
7278 : get_collation_name(ccollid),
7279 : get_collation_name(childatt->attcollation))));
7280 :
7281 : /* Bump the existing child att's inhcount */
7282 60 : if (pg_add_s16_overflow(childatt->attinhcount, 1,
7283 : &childatt->attinhcount))
7284 0 : ereport(ERROR,
7285 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7286 : errmsg("too many inheritance parents"));
7287 60 : CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
7288 :
7289 60 : heap_freetuple(tuple);
7290 :
7291 : /* Inform the user about the merge */
7292 60 : ereport(NOTICE,
7293 : (errmsg("merging definition of column \"%s\" for child \"%s\"",
7294 : colDef->colname, RelationGetRelationName(rel))));
7295 :
7296 60 : table_close(attrdesc, RowExclusiveLock);
7297 :
7298 : /* Make the child column change visible */
7299 60 : CommandCounterIncrement();
7300 :
7301 60 : return InvalidObjectAddress;
7302 : }
7303 : }
7304 :
7305 : /* skip if the name already exists and if_not_exists is true */
7306 2836 : if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
7307 : {
7308 54 : table_close(attrdesc, RowExclusiveLock);
7309 54 : return InvalidObjectAddress;
7310 : }
7311 :
7312 : /*
7313 : * Okay, we need to add the column, so go ahead and do parse
7314 : * transformation. This can result in queueing up, or even immediately
7315 : * executing, subsidiary operations (such as creation of unique indexes);
7316 : * so we mustn't do it until we have made the if_not_exists check.
7317 : *
7318 : * When recursing, the command was already transformed and we needn't do
7319 : * so again. Also, if context isn't given we can't transform. (That
7320 : * currently happens only for AT_AddColumnToView; we expect that view.c
7321 : * passed us a ColumnDef that doesn't need work.)
7322 : */
7323 2752 : if (context != NULL && !recursing)
7324 : {
7325 2050 : *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
7326 : cur_pass, context);
7327 : Assert(*cmd != NULL);
7328 2044 : colDef = castNode(ColumnDef, (*cmd)->def);
7329 : }
7330 :
7331 : /*
7332 : * Regular inheritance children are independent enough not to inherit the
7333 : * identity column from parent hence cannot recursively add identity
7334 : * column if the table has inheritance children.
7335 : *
7336 : * Partitions, on the other hand, are integral part of a partitioned table
7337 : * and inherit identity column. Hence propagate identity column down the
7338 : * partition hierarchy.
7339 : */
7340 2746 : if (colDef->identity &&
7341 54 : recurse &&
7342 102 : rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
7343 48 : find_inheritance_children(myrelid, NoLock) != NIL)
7344 6 : ereport(ERROR,
7345 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7346 : errmsg("cannot recursively add identity column to table that has child tables")));
7347 :
7348 2740 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
7349 :
7350 2740 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
7351 2740 : if (!HeapTupleIsValid(reltup))
7352 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
7353 2740 : relform = (Form_pg_class) GETSTRUCT(reltup);
7354 2740 : relkind = relform->relkind;
7355 :
7356 : /* Determine the new attribute's number */
7357 2740 : newattnum = relform->relnatts + 1;
7358 2740 : if (newattnum > MaxHeapAttributeNumber)
7359 0 : ereport(ERROR,
7360 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
7361 : errmsg("tables can have at most %d columns",
7362 : MaxHeapAttributeNumber)));
7363 :
7364 : /*
7365 : * Construct new attribute's pg_attribute entry.
7366 : */
7367 2740 : tupdesc = BuildDescForRelation(list_make1(colDef));
7368 :
7369 2728 : attribute = TupleDescAttr(tupdesc, 0);
7370 :
7371 : /* Fix up attribute number */
7372 2728 : attribute->attnum = newattnum;
7373 :
7374 : /* make sure datatype is legal for a column */
7375 5456 : CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
7376 2728 : list_make1_oid(rel->rd_rel->reltype),
7377 2728 : (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
7378 :
7379 2692 : InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
7380 :
7381 2692 : table_close(attrdesc, RowExclusiveLock);
7382 :
7383 : /*
7384 : * Update pg_class tuple as appropriate
7385 : */
7386 2692 : relform->relnatts = newattnum;
7387 :
7388 2692 : CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
7389 :
7390 2692 : heap_freetuple(reltup);
7391 :
7392 : /* Post creation hook for new attribute */
7393 2692 : InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
7394 :
7395 2692 : table_close(pgclass, RowExclusiveLock);
7396 :
7397 : /* Make the attribute's catalog entry visible */
7398 2692 : CommandCounterIncrement();
7399 :
7400 : /*
7401 : * Store the DEFAULT, if any, in the catalogs
7402 : */
7403 2692 : if (colDef->raw_default)
7404 : {
7405 : RawColumnDefault *rawEnt;
7406 :
7407 924 : rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
7408 924 : rawEnt->attnum = attribute->attnum;
7409 924 : rawEnt->raw_default = copyObject(colDef->raw_default);
7410 924 : rawEnt->generated = colDef->generated;
7411 :
7412 : /*
7413 : * This function is intended for CREATE TABLE, so it processes a
7414 : * _list_ of defaults, but we just do one.
7415 : */
7416 924 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
7417 : false, true, false, NULL);
7418 :
7419 : /* Make the additional catalog changes visible */
7420 900 : CommandCounterIncrement();
7421 : }
7422 :
7423 : /*
7424 : * Tell Phase 3 to fill in the default expression, if there is one.
7425 : *
7426 : * If there is no default, Phase 3 doesn't have to do anything, because
7427 : * that effectively means that the default is NULL. The heap tuple access
7428 : * routines always check for attnum > # of attributes in tuple, and return
7429 : * NULL if so, so without any modification of the tuple data we will get
7430 : * the effect of NULL values in the new column.
7431 : *
7432 : * An exception occurs when the new column is of a domain type: the domain
7433 : * might have a not-null constraint, or a check constraint that indirectly
7434 : * rejects nulls. If there are any domain constraints then we construct
7435 : * an explicit NULL default value that will be passed through
7436 : * CoerceToDomain processing. (This is a tad inefficient, since it causes
7437 : * rewriting the table which we really wouldn't have to do; but we do it
7438 : * to preserve the historical behavior that such a failure will be raised
7439 : * only if the table currently contains some rows.)
7440 : *
7441 : * Note: we use build_column_default, and not just the cooked default
7442 : * returned by AddRelationNewConstraints, so that the right thing happens
7443 : * when a datatype's default applies.
7444 : *
7445 : * Note: it might seem that this should happen at the end of Phase 2, so
7446 : * that the effects of subsequent subcommands can be taken into account.
7447 : * It's intentional that we do it now, though. The new column should be
7448 : * filled according to what is said in the ADD COLUMN subcommand, so that
7449 : * the effects are the same as if this subcommand had been run by itself
7450 : * and the later subcommands had been issued in new ALTER TABLE commands.
7451 : *
7452 : * We can skip this entirely for relations without storage, since Phase 3
7453 : * is certainly not going to touch them.
7454 : */
7455 2668 : if (RELKIND_HAS_STORAGE(relkind))
7456 : {
7457 : bool has_domain_constraints;
7458 2292 : bool has_missing = false;
7459 :
7460 : /*
7461 : * For an identity column, we can't use build_column_default(),
7462 : * because the sequence ownership isn't set yet. So do it manually.
7463 : */
7464 2292 : if (colDef->identity)
7465 : {
7466 42 : NextValueExpr *nve = makeNode(NextValueExpr);
7467 :
7468 42 : nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
7469 42 : nve->typeId = attribute->atttypid;
7470 :
7471 42 : defval = (Expr *) nve;
7472 : }
7473 : else
7474 2250 : defval = (Expr *) build_column_default(rel, attribute->attnum);
7475 :
7476 : /* Build CoerceToDomain(NULL) expression if needed */
7477 2292 : has_domain_constraints = DomainHasConstraints(attribute->atttypid);
7478 2292 : if (!defval && has_domain_constraints)
7479 : {
7480 : Oid baseTypeId;
7481 : int32 baseTypeMod;
7482 : Oid baseTypeColl;
7483 :
7484 6 : baseTypeMod = attribute->atttypmod;
7485 6 : baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
7486 6 : baseTypeColl = get_typcollation(baseTypeId);
7487 6 : defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
7488 6 : defval = (Expr *) coerce_to_target_type(NULL,
7489 : (Node *) defval,
7490 : baseTypeId,
7491 : attribute->atttypid,
7492 : attribute->atttypmod,
7493 : COERCION_ASSIGNMENT,
7494 : COERCE_IMPLICIT_CAST,
7495 : -1);
7496 6 : if (defval == NULL) /* should not happen */
7497 0 : elog(ERROR, "failed to coerce base type to domain");
7498 : }
7499 :
7500 2292 : if (defval)
7501 : {
7502 : NewColumnValue *newval;
7503 :
7504 : /* Prepare defval for execution, either here or in Phase 3 */
7505 808 : defval = expression_planner(defval);
7506 :
7507 : /* Add the new default to the newvals list */
7508 808 : newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
7509 808 : newval->attnum = attribute->attnum;
7510 808 : newval->expr = defval;
7511 808 : newval->is_generated = (colDef->generated != '\0');
7512 :
7513 808 : tab->newvals = lappend(tab->newvals, newval);
7514 :
7515 : /*
7516 : * Attempt to skip a complete table rewrite by storing the
7517 : * specified DEFAULT value outside of the heap. This is only
7518 : * allowed for plain relations and non-generated columns, and the
7519 : * default expression can't be volatile (stable is OK). Note that
7520 : * contain_volatile_functions deems CoerceToDomain immutable, but
7521 : * here we consider that coercion to a domain with constraints is
7522 : * volatile; else it might fail even when the table is empty.
7523 : */
7524 808 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
7525 808 : !colDef->generated &&
7526 682 : !has_domain_constraints &&
7527 670 : !contain_volatile_functions((Node *) defval))
7528 502 : {
7529 : EState *estate;
7530 : ExprState *exprState;
7531 : Datum missingval;
7532 : bool missingIsNull;
7533 :
7534 : /* Evaluate the default expression */
7535 502 : estate = CreateExecutorState();
7536 502 : exprState = ExecPrepareExpr(defval, estate);
7537 502 : missingval = ExecEvalExpr(exprState,
7538 502 : GetPerTupleExprContext(estate),
7539 : &missingIsNull);
7540 : /* If it turns out NULL, nothing to do; else store it */
7541 502 : if (!missingIsNull)
7542 : {
7543 502 : StoreAttrMissingVal(rel, attribute->attnum, missingval);
7544 : /* Make the additional catalog change visible */
7545 502 : CommandCounterIncrement();
7546 502 : has_missing = true;
7547 : }
7548 502 : FreeExecutorState(estate);
7549 : }
7550 : else
7551 : {
7552 : /*
7553 : * Failed to use missing mode. We have to do a table rewrite
7554 : * to install the value --- unless it's a virtual generated
7555 : * column.
7556 : */
7557 306 : if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
7558 216 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
7559 : }
7560 : }
7561 :
7562 2292 : if (!has_missing)
7563 : {
7564 : /*
7565 : * If the new column is NOT NULL, and there is no missing value,
7566 : * tell Phase 3 it needs to check for NULLs.
7567 : */
7568 1790 : tab->verify_new_notnull |= colDef->is_not_null;
7569 : }
7570 : }
7571 :
7572 : /*
7573 : * Add needed dependency entries for the new column.
7574 : */
7575 2668 : add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
7576 2668 : add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
7577 :
7578 : /*
7579 : * Propagate to children as appropriate. Unlike most other ALTER
7580 : * routines, we have to do this one level of recursion at a time; we can't
7581 : * use find_all_inheritors to do it in one pass.
7582 : */
7583 : children =
7584 2668 : find_inheritance_children(RelationGetRelid(rel), lockmode);
7585 :
7586 : /*
7587 : * If we are told not to recurse, there had better not be any child
7588 : * tables; else the addition would put them out of step.
7589 : */
7590 2668 : if (children && !recurse)
7591 12 : ereport(ERROR,
7592 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7593 : errmsg("column must be added to child tables too")));
7594 :
7595 : /* Children should see column as singly inherited */
7596 2656 : if (!recursing)
7597 : {
7598 1978 : childcmd = copyObject(*cmd);
7599 1978 : colDef = castNode(ColumnDef, childcmd->def);
7600 1978 : colDef->inhcount = 1;
7601 1978 : colDef->is_local = false;
7602 : }
7603 : else
7604 678 : childcmd = *cmd; /* no need to copy again */
7605 :
7606 3394 : foreach(child, children)
7607 : {
7608 738 : Oid childrelid = lfirst_oid(child);
7609 : Relation childrel;
7610 : AlteredTableInfo *childtab;
7611 :
7612 : /* find_inheritance_children already got lock */
7613 738 : childrel = table_open(childrelid, NoLock);
7614 738 : CheckAlterTableIsSafe(childrel);
7615 :
7616 : /* Find or create work queue entry for this table */
7617 738 : childtab = ATGetQueueEntry(wqueue, childrel);
7618 :
7619 : /* Recurse to child; return value is ignored */
7620 738 : ATExecAddColumn(wqueue, childtab, childrel,
7621 : &childcmd, recurse, true,
7622 : lockmode, cur_pass, context);
7623 :
7624 738 : table_close(childrel, NoLock);
7625 : }
7626 :
7627 2656 : ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
7628 2656 : return address;
7629 : }
7630 :
7631 : /*
7632 : * If a new or renamed column will collide with the name of an existing
7633 : * column and if_not_exists is false then error out, else do nothing.
7634 : */
7635 : static bool
7636 3286 : check_for_column_name_collision(Relation rel, const char *colname,
7637 : bool if_not_exists)
7638 : {
7639 : HeapTuple attTuple;
7640 : int attnum;
7641 :
7642 : /*
7643 : * this test is deliberately not attisdropped-aware, since if one tries to
7644 : * add a column matching a dropped column name, it's gonna fail anyway.
7645 : */
7646 3286 : attTuple = SearchSysCache2(ATTNAME,
7647 : ObjectIdGetDatum(RelationGetRelid(rel)),
7648 : PointerGetDatum(colname));
7649 3286 : if (!HeapTupleIsValid(attTuple))
7650 3190 : return true;
7651 :
7652 96 : attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
7653 96 : ReleaseSysCache(attTuple);
7654 :
7655 : /*
7656 : * We throw a different error message for conflicts with system column
7657 : * names, since they are normally not shown and the user might otherwise
7658 : * be confused about the reason for the conflict.
7659 : */
7660 96 : if (attnum <= 0)
7661 12 : ereport(ERROR,
7662 : (errcode(ERRCODE_DUPLICATE_COLUMN),
7663 : errmsg("column name \"%s\" conflicts with a system column name",
7664 : colname)));
7665 : else
7666 : {
7667 84 : if (if_not_exists)
7668 : {
7669 54 : ereport(NOTICE,
7670 : (errcode(ERRCODE_DUPLICATE_COLUMN),
7671 : errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
7672 : colname, RelationGetRelationName(rel))));
7673 54 : return false;
7674 : }
7675 :
7676 30 : ereport(ERROR,
7677 : (errcode(ERRCODE_DUPLICATE_COLUMN),
7678 : errmsg("column \"%s\" of relation \"%s\" already exists",
7679 : colname, RelationGetRelationName(rel))));
7680 : }
7681 :
7682 : return true;
7683 : }
7684 :
7685 : /*
7686 : * Install a column's dependency on its datatype.
7687 : */
7688 : static void
7689 3692 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
7690 : {
7691 : ObjectAddress myself,
7692 : referenced;
7693 :
7694 3692 : myself.classId = RelationRelationId;
7695 3692 : myself.objectId = relid;
7696 3692 : myself.objectSubId = attnum;
7697 3692 : referenced.classId = TypeRelationId;
7698 3692 : referenced.objectId = typid;
7699 3692 : referenced.objectSubId = 0;
7700 3692 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7701 3692 : }
7702 :
7703 : /*
7704 : * Install a column's dependency on its collation.
7705 : */
7706 : static void
7707 3692 : add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
7708 : {
7709 : ObjectAddress myself,
7710 : referenced;
7711 :
7712 : /* We know the default collation is pinned, so don't bother recording it */
7713 3692 : if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
7714 : {
7715 18 : myself.classId = RelationRelationId;
7716 18 : myself.objectId = relid;
7717 18 : myself.objectSubId = attnum;
7718 18 : referenced.classId = CollationRelationId;
7719 18 : referenced.objectId = collid;
7720 18 : referenced.objectSubId = 0;
7721 18 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7722 : }
7723 3692 : }
7724 :
7725 : /*
7726 : * ALTER TABLE ALTER COLUMN DROP NOT NULL
7727 : *
7728 : * Return the address of the modified column. If the column was already
7729 : * nullable, InvalidObjectAddress is returned.
7730 : */
7731 : static ObjectAddress
7732 268 : ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
7733 : LOCKMODE lockmode)
7734 : {
7735 : HeapTuple tuple;
7736 : HeapTuple conTup;
7737 : Form_pg_attribute attTup;
7738 : AttrNumber attnum;
7739 : Relation attr_rel;
7740 : ObjectAddress address;
7741 :
7742 : /*
7743 : * lookup the attribute
7744 : */
7745 268 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7746 :
7747 268 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7748 268 : if (!HeapTupleIsValid(tuple))
7749 18 : ereport(ERROR,
7750 : (errcode(ERRCODE_UNDEFINED_COLUMN),
7751 : errmsg("column \"%s\" of relation \"%s\" does not exist",
7752 : colName, RelationGetRelationName(rel))));
7753 250 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7754 250 : attnum = attTup->attnum;
7755 250 : ObjectAddressSubSet(address, RelationRelationId,
7756 : RelationGetRelid(rel), attnum);
7757 :
7758 : /* If the column is already nullable there's nothing to do. */
7759 250 : if (!attTup->attnotnull)
7760 : {
7761 0 : table_close(attr_rel, RowExclusiveLock);
7762 0 : return InvalidObjectAddress;
7763 : }
7764 :
7765 : /* Prevent them from altering a system attribute */
7766 250 : if (attnum <= 0)
7767 0 : ereport(ERROR,
7768 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7769 : errmsg("cannot alter system column \"%s\"",
7770 : colName)));
7771 :
7772 250 : if (attTup->attidentity)
7773 18 : ereport(ERROR,
7774 : (errcode(ERRCODE_SYNTAX_ERROR),
7775 : errmsg("column \"%s\" of relation \"%s\" is an identity column",
7776 : colName, RelationGetRelationName(rel))));
7777 :
7778 : /*
7779 : * If rel is partition, shouldn't drop NOT NULL if parent has the same.
7780 : */
7781 232 : if (rel->rd_rel->relispartition)
7782 : {
7783 12 : Oid parentId = get_partition_parent(RelationGetRelid(rel), false);
7784 12 : Relation parent = table_open(parentId, AccessShareLock);
7785 12 : TupleDesc tupDesc = RelationGetDescr(parent);
7786 : AttrNumber parent_attnum;
7787 :
7788 12 : parent_attnum = get_attnum(parentId, colName);
7789 12 : if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
7790 12 : ereport(ERROR,
7791 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7792 : errmsg("column \"%s\" is marked NOT NULL in parent table",
7793 : colName)));
7794 0 : table_close(parent, AccessShareLock);
7795 : }
7796 :
7797 : /*
7798 : * Find the constraint that makes this column NOT NULL, and drop it.
7799 : * dropconstraint_internal() resets attnotnull.
7800 : */
7801 220 : conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7802 220 : if (conTup == NULL)
7803 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
7804 : colName, RelationGetRelationName(rel));
7805 :
7806 : /* The normal case: we have a pg_constraint row, remove it */
7807 220 : dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
7808 : false, lockmode);
7809 166 : heap_freetuple(conTup);
7810 :
7811 166 : InvokeObjectPostAlterHook(RelationRelationId,
7812 : RelationGetRelid(rel), attnum);
7813 :
7814 166 : table_close(attr_rel, RowExclusiveLock);
7815 :
7816 166 : return address;
7817 : }
7818 :
7819 : /*
7820 : * set_attnotnull
7821 : * Helper to update/validate the pg_attribute status of a not-null
7822 : * constraint
7823 : *
7824 : * pg_attribute.attnotnull is set true, if it isn't already.
7825 : * If queue_validation is true, also set up wqueue to validate the constraint.
7826 : * wqueue may be given as NULL when validation is not needed (e.g., on table
7827 : * creation).
7828 : */
7829 : static void
7830 25496 : set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
7831 : bool is_valid, bool queue_validation)
7832 : {
7833 : Form_pg_attribute attr;
7834 : CompactAttribute *thisatt;
7835 :
7836 : Assert(!queue_validation || wqueue);
7837 :
7838 25496 : CheckAlterTableIsSafe(rel);
7839 :
7840 : /*
7841 : * Exit quickly by testing attnotnull from the tupledesc's copy of the
7842 : * attribute.
7843 : */
7844 25496 : attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
7845 25496 : if (attr->attisdropped)
7846 0 : return;
7847 :
7848 25496 : if (!attr->attnotnull)
7849 : {
7850 : Relation attr_rel;
7851 : HeapTuple tuple;
7852 :
7853 1478 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7854 :
7855 1478 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
7856 1478 : if (!HeapTupleIsValid(tuple))
7857 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
7858 : attnum, RelationGetRelid(rel));
7859 :
7860 1478 : thisatt = TupleDescCompactAttr(RelationGetDescr(rel), attnum - 1);
7861 1478 : thisatt->attnullability = ATTNULLABLE_VALID;
7862 :
7863 1478 : attr = (Form_pg_attribute) GETSTRUCT(tuple);
7864 :
7865 1478 : attr->attnotnull = true;
7866 1478 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
7867 :
7868 : /*
7869 : * If the nullness isn't already proven by validated constraints, have
7870 : * ALTER TABLE phase 3 test for it.
7871 : */
7872 1478 : if (queue_validation && wqueue &&
7873 1238 : !NotNullImpliedByRelConstraints(rel, attr))
7874 : {
7875 : AlteredTableInfo *tab;
7876 :
7877 1188 : tab = ATGetQueueEntry(wqueue, rel);
7878 1188 : tab->verify_new_notnull = true;
7879 : }
7880 :
7881 1478 : CommandCounterIncrement();
7882 :
7883 1478 : table_close(attr_rel, RowExclusiveLock);
7884 1478 : heap_freetuple(tuple);
7885 : }
7886 : else
7887 : {
7888 24018 : CacheInvalidateRelcache(rel);
7889 : }
7890 : }
7891 :
7892 : /*
7893 : * ALTER TABLE ALTER COLUMN SET NOT NULL
7894 : *
7895 : * Add a not-null constraint to a single table and its children. Returns
7896 : * the address of the constraint added to the parent relation, if one gets
7897 : * added, or InvalidObjectAddress otherwise.
7898 : *
7899 : * We must recurse to child tables during execution, rather than using
7900 : * ALTER TABLE's normal prep-time recursion.
7901 : */
7902 : static ObjectAddress
7903 706 : ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
7904 : bool recurse, bool recursing, LOCKMODE lockmode)
7905 : {
7906 : HeapTuple tuple;
7907 : AttrNumber attnum;
7908 : ObjectAddress address;
7909 : Constraint *constraint;
7910 : CookedConstraint *ccon;
7911 : List *cooked;
7912 706 : bool is_no_inherit = false;
7913 :
7914 : /* Guard against stack overflow due to overly deep inheritance tree. */
7915 706 : check_stack_depth();
7916 :
7917 : /* At top level, permission check was done in ATPrepCmd, else do it */
7918 706 : if (recursing)
7919 : {
7920 298 : ATSimplePermissions(AT_AddConstraint, rel,
7921 : ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
7922 : Assert(conName != NULL);
7923 : }
7924 :
7925 706 : attnum = get_attnum(RelationGetRelid(rel), colName);
7926 706 : if (attnum == InvalidAttrNumber)
7927 18 : ereport(ERROR,
7928 : (errcode(ERRCODE_UNDEFINED_COLUMN),
7929 : errmsg("column \"%s\" of relation \"%s\" does not exist",
7930 : colName, RelationGetRelationName(rel))));
7931 :
7932 : /* Prevent them from altering a system attribute */
7933 688 : if (attnum <= 0)
7934 0 : ereport(ERROR,
7935 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7936 : errmsg("cannot alter system column \"%s\"",
7937 : colName)));
7938 :
7939 : /* See if there's already a constraint */
7940 688 : tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7941 688 : if (HeapTupleIsValid(tuple))
7942 : {
7943 158 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
7944 158 : bool changed = false;
7945 :
7946 : /*
7947 : * Don't let a NO INHERIT constraint be changed into inherit.
7948 : */
7949 158 : if (conForm->connoinherit && recurse)
7950 12 : ereport(ERROR,
7951 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7952 : errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
7953 : NameStr(conForm->conname),
7954 : RelationGetRelationName(rel)));
7955 :
7956 : /*
7957 : * If we find an appropriate constraint, we're almost done, but just
7958 : * need to change some properties on it: if we're recursing, increment
7959 : * coninhcount; if not, set conislocal if not already set.
7960 : */
7961 146 : if (recursing)
7962 : {
7963 102 : if (pg_add_s16_overflow(conForm->coninhcount, 1,
7964 : &conForm->coninhcount))
7965 0 : ereport(ERROR,
7966 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7967 : errmsg("too many inheritance parents"));
7968 102 : changed = true;
7969 : }
7970 44 : else if (!conForm->conislocal)
7971 : {
7972 0 : conForm->conislocal = true;
7973 0 : changed = true;
7974 : }
7975 44 : else if (!conForm->convalidated)
7976 : {
7977 : /*
7978 : * Flip attnotnull and convalidated, and also validate the
7979 : * constraint.
7980 : */
7981 24 : return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
7982 : recurse, recursing, lockmode);
7983 : }
7984 :
7985 122 : if (changed)
7986 : {
7987 : Relation constr_rel;
7988 :
7989 102 : constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
7990 :
7991 102 : CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
7992 102 : ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
7993 102 : table_close(constr_rel, RowExclusiveLock);
7994 : }
7995 :
7996 122 : if (changed)
7997 102 : return address;
7998 : else
7999 20 : return InvalidObjectAddress;
8000 : }
8001 :
8002 : /*
8003 : * If we're asked not to recurse, and children exist, raise an error for
8004 : * partitioned tables. For inheritance, we act as if NO INHERIT had been
8005 : * specified.
8006 : */
8007 554 : if (!recurse &&
8008 24 : find_inheritance_children(RelationGetRelid(rel),
8009 : NoLock) != NIL)
8010 : {
8011 18 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8012 6 : ereport(ERROR,
8013 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8014 : errmsg("constraint must be added to child tables too"),
8015 : errhint("Do not specify the ONLY keyword."));
8016 : else
8017 12 : is_no_inherit = true;
8018 : }
8019 :
8020 : /*
8021 : * No constraint exists; we must add one. First determine a name to use,
8022 : * if we haven't already.
8023 : */
8024 524 : if (!recursing)
8025 : {
8026 : Assert(conName == NULL);
8027 334 : conName = ChooseConstraintName(RelationGetRelationName(rel),
8028 : colName, "not_null",
8029 334 : RelationGetNamespace(rel),
8030 : NIL);
8031 : }
8032 :
8033 524 : constraint = makeNotNullConstraint(makeString(colName));
8034 524 : constraint->is_no_inherit = is_no_inherit;
8035 524 : constraint->conname = conName;
8036 :
8037 : /* and do it */
8038 524 : cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
8039 524 : false, !recursing, false, NULL);
8040 524 : ccon = linitial(cooked);
8041 524 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8042 :
8043 524 : InvokeObjectPostAlterHook(RelationRelationId,
8044 : RelationGetRelid(rel), attnum);
8045 :
8046 : /* Mark pg_attribute.attnotnull for the column and queue validation */
8047 524 : set_attnotnull(wqueue, rel, attnum, true, true);
8048 :
8049 : /*
8050 : * Recurse to propagate the constraint to children that don't have one.
8051 : */
8052 524 : if (recurse)
8053 : {
8054 : List *children;
8055 :
8056 506 : children = find_inheritance_children(RelationGetRelid(rel),
8057 : lockmode);
8058 :
8059 1244 : foreach_oid(childoid, children)
8060 : {
8061 244 : Relation childrel = table_open(childoid, NoLock);
8062 :
8063 244 : CommandCounterIncrement();
8064 :
8065 244 : ATExecSetNotNull(wqueue, childrel, conName, colName,
8066 : recurse, true, lockmode);
8067 238 : table_close(childrel, NoLock);
8068 : }
8069 : }
8070 :
8071 518 : return address;
8072 : }
8073 :
8074 : /*
8075 : * NotNullImpliedByRelConstraints
8076 : * Does rel's existing constraints imply NOT NULL for the given attribute?
8077 : */
8078 : static bool
8079 1238 : NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
8080 : {
8081 1238 : NullTest *nnulltest = makeNode(NullTest);
8082 :
8083 2476 : nnulltest->arg = (Expr *) makeVar(1,
8084 1238 : attr->attnum,
8085 : attr->atttypid,
8086 : attr->atttypmod,
8087 : attr->attcollation,
8088 : 0);
8089 1238 : nnulltest->nulltesttype = IS_NOT_NULL;
8090 :
8091 : /*
8092 : * argisrow = false is correct even for a composite column, because
8093 : * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
8094 : * case, just IS DISTINCT FROM NULL.
8095 : */
8096 1238 : nnulltest->argisrow = false;
8097 1238 : nnulltest->location = -1;
8098 :
8099 1238 : if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
8100 : {
8101 50 : ereport(DEBUG1,
8102 : (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
8103 : RelationGetRelationName(rel), NameStr(attr->attname))));
8104 50 : return true;
8105 : }
8106 :
8107 1188 : return false;
8108 : }
8109 :
8110 : /*
8111 : * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
8112 : *
8113 : * Return the address of the affected column.
8114 : */
8115 : static ObjectAddress
8116 612 : ATExecColumnDefault(Relation rel, const char *colName,
8117 : Node *newDefault, LOCKMODE lockmode)
8118 : {
8119 612 : TupleDesc tupdesc = RelationGetDescr(rel);
8120 : AttrNumber attnum;
8121 : ObjectAddress address;
8122 :
8123 : /*
8124 : * get the number of the attribute
8125 : */
8126 612 : attnum = get_attnum(RelationGetRelid(rel), colName);
8127 612 : if (attnum == InvalidAttrNumber)
8128 30 : ereport(ERROR,
8129 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8130 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8131 : colName, RelationGetRelationName(rel))));
8132 :
8133 : /* Prevent them from altering a system attribute */
8134 582 : if (attnum <= 0)
8135 0 : ereport(ERROR,
8136 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8137 : errmsg("cannot alter system column \"%s\"",
8138 : colName)));
8139 :
8140 582 : if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
8141 18 : ereport(ERROR,
8142 : (errcode(ERRCODE_SYNTAX_ERROR),
8143 : errmsg("column \"%s\" of relation \"%s\" is an identity column",
8144 : colName, RelationGetRelationName(rel)),
8145 : /* translator: %s is an SQL ALTER command */
8146 : newDefault ? 0 : errhint("Use %s instead.",
8147 : "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
8148 :
8149 564 : if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
8150 12 : ereport(ERROR,
8151 : (errcode(ERRCODE_SYNTAX_ERROR),
8152 : errmsg("column \"%s\" of relation \"%s\" is a generated column",
8153 : colName, RelationGetRelationName(rel)),
8154 : newDefault ?
8155 : /* translator: %s is an SQL ALTER command */
8156 : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
8157 : (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
8158 : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
8159 :
8160 : /*
8161 : * Remove any old default for the column. We use RESTRICT here for
8162 : * safety, but at present we do not expect anything to depend on the
8163 : * default.
8164 : *
8165 : * We treat removing the existing default as an internal operation when it
8166 : * is preparatory to adding a new default, but as a user-initiated
8167 : * operation when the user asked for a drop.
8168 : */
8169 552 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8170 : newDefault != NULL);
8171 :
8172 552 : if (newDefault)
8173 : {
8174 : /* SET DEFAULT */
8175 : RawColumnDefault *rawEnt;
8176 :
8177 378 : rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
8178 378 : rawEnt->attnum = attnum;
8179 378 : rawEnt->raw_default = newDefault;
8180 378 : rawEnt->generated = '\0';
8181 :
8182 : /*
8183 : * This function is intended for CREATE TABLE, so it processes a
8184 : * _list_ of defaults, but we just do one.
8185 : */
8186 378 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8187 : false, true, false, NULL);
8188 : }
8189 :
8190 546 : ObjectAddressSubSet(address, RelationRelationId,
8191 : RelationGetRelid(rel), attnum);
8192 546 : return address;
8193 : }
8194 :
8195 : /*
8196 : * Add a pre-cooked default expression.
8197 : *
8198 : * Return the address of the affected column.
8199 : */
8200 : static ObjectAddress
8201 80 : ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
8202 : Node *newDefault)
8203 : {
8204 : ObjectAddress address;
8205 :
8206 : /* We assume no checking is required */
8207 :
8208 : /*
8209 : * Remove any old default for the column. We use RESTRICT here for
8210 : * safety, but at present we do not expect anything to depend on the
8211 : * default. (In ordinary cases, there could not be a default in place
8212 : * anyway, but it's possible when combining LIKE with inheritance.)
8213 : */
8214 80 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8215 : true);
8216 :
8217 80 : (void) StoreAttrDefault(rel, attnum, newDefault, true);
8218 :
8219 80 : ObjectAddressSubSet(address, RelationRelationId,
8220 : RelationGetRelid(rel), attnum);
8221 80 : return address;
8222 : }
8223 :
8224 : /*
8225 : * ALTER TABLE ALTER COLUMN ADD IDENTITY
8226 : *
8227 : * Return the address of the affected column.
8228 : */
8229 : static ObjectAddress
8230 204 : ATExecAddIdentity(Relation rel, const char *colName,
8231 : Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
8232 : {
8233 : Relation attrelation;
8234 : HeapTuple tuple;
8235 : Form_pg_attribute attTup;
8236 : AttrNumber attnum;
8237 : ObjectAddress address;
8238 204 : ColumnDef *cdef = castNode(ColumnDef, def);
8239 : bool ispartitioned;
8240 :
8241 204 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8242 204 : if (ispartitioned && !recurse)
8243 6 : ereport(ERROR,
8244 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8245 : errmsg("cannot add identity to a column of only the partitioned table"),
8246 : errhint("Do not specify the ONLY keyword.")));
8247 :
8248 198 : if (rel->rd_rel->relispartition && !recursing)
8249 12 : ereport(ERROR,
8250 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8251 : errmsg("cannot add identity to a column of a partition"));
8252 :
8253 186 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8254 :
8255 186 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8256 186 : if (!HeapTupleIsValid(tuple))
8257 0 : ereport(ERROR,
8258 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8259 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8260 : colName, RelationGetRelationName(rel))));
8261 186 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8262 186 : attnum = attTup->attnum;
8263 :
8264 : /* Can't alter a system attribute */
8265 186 : if (attnum <= 0)
8266 0 : ereport(ERROR,
8267 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8268 : errmsg("cannot alter system column \"%s\"",
8269 : colName)));
8270 :
8271 : /*
8272 : * Creating a column as identity implies NOT NULL, so adding the identity
8273 : * to an existing column that is not NOT NULL would create a state that
8274 : * cannot be reproduced without contortions.
8275 : */
8276 186 : if (!attTup->attnotnull)
8277 6 : ereport(ERROR,
8278 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8279 : errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
8280 : colName, RelationGetRelationName(rel))));
8281 :
8282 180 : if (attTup->attidentity)
8283 18 : ereport(ERROR,
8284 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8285 : errmsg("column \"%s\" of relation \"%s\" is already an identity column",
8286 : colName, RelationGetRelationName(rel))));
8287 :
8288 162 : if (attTup->atthasdef)
8289 6 : ereport(ERROR,
8290 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8291 : errmsg("column \"%s\" of relation \"%s\" already has a default value",
8292 : colName, RelationGetRelationName(rel))));
8293 :
8294 156 : attTup->attidentity = cdef->identity;
8295 156 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8296 :
8297 156 : InvokeObjectPostAlterHook(RelationRelationId,
8298 : RelationGetRelid(rel),
8299 : attTup->attnum);
8300 156 : ObjectAddressSubSet(address, RelationRelationId,
8301 : RelationGetRelid(rel), attnum);
8302 156 : heap_freetuple(tuple);
8303 :
8304 156 : table_close(attrelation, RowExclusiveLock);
8305 :
8306 : /*
8307 : * Recurse to propagate the identity column to partitions. Identity is
8308 : * not inherited in regular inheritance children.
8309 : */
8310 156 : if (recurse && ispartitioned)
8311 : {
8312 : List *children;
8313 : ListCell *lc;
8314 :
8315 14 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8316 :
8317 20 : foreach(lc, children)
8318 : {
8319 : Relation childrel;
8320 :
8321 6 : childrel = table_open(lfirst_oid(lc), NoLock);
8322 6 : ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
8323 6 : table_close(childrel, NoLock);
8324 : }
8325 : }
8326 :
8327 156 : return address;
8328 : }
8329 :
8330 : /*
8331 : * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
8332 : *
8333 : * Return the address of the affected column.
8334 : */
8335 : static ObjectAddress
8336 74 : ATExecSetIdentity(Relation rel, const char *colName, Node *def,
8337 : LOCKMODE lockmode, bool recurse, bool recursing)
8338 : {
8339 : ListCell *option;
8340 74 : DefElem *generatedEl = NULL;
8341 : HeapTuple tuple;
8342 : Form_pg_attribute attTup;
8343 : AttrNumber attnum;
8344 : Relation attrelation;
8345 : ObjectAddress address;
8346 : bool ispartitioned;
8347 :
8348 74 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8349 74 : if (ispartitioned && !recurse)
8350 6 : ereport(ERROR,
8351 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8352 : errmsg("cannot change identity column of only the partitioned table"),
8353 : errhint("Do not specify the ONLY keyword.")));
8354 :
8355 68 : if (rel->rd_rel->relispartition && !recursing)
8356 12 : ereport(ERROR,
8357 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8358 : errmsg("cannot change identity column of a partition"));
8359 :
8360 100 : foreach(option, castNode(List, def))
8361 : {
8362 44 : DefElem *defel = lfirst_node(DefElem, option);
8363 :
8364 44 : if (strcmp(defel->defname, "generated") == 0)
8365 : {
8366 44 : if (generatedEl)
8367 0 : ereport(ERROR,
8368 : (errcode(ERRCODE_SYNTAX_ERROR),
8369 : errmsg("conflicting or redundant options")));
8370 44 : generatedEl = defel;
8371 : }
8372 : else
8373 0 : elog(ERROR, "option \"%s\" not recognized",
8374 : defel->defname);
8375 : }
8376 :
8377 : /*
8378 : * Even if there is nothing to change here, we run all the checks. There
8379 : * will be a subsequent ALTER SEQUENCE that relies on everything being
8380 : * there.
8381 : */
8382 :
8383 56 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8384 56 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8385 56 : if (!HeapTupleIsValid(tuple))
8386 0 : ereport(ERROR,
8387 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8388 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8389 : colName, RelationGetRelationName(rel))));
8390 :
8391 56 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8392 56 : attnum = attTup->attnum;
8393 :
8394 56 : if (attnum <= 0)
8395 0 : ereport(ERROR,
8396 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8397 : errmsg("cannot alter system column \"%s\"",
8398 : colName)));
8399 :
8400 56 : if (!attTup->attidentity)
8401 6 : ereport(ERROR,
8402 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8403 : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8404 : colName, RelationGetRelationName(rel))));
8405 :
8406 50 : if (generatedEl)
8407 : {
8408 44 : attTup->attidentity = defGetInt32(generatedEl);
8409 44 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8410 :
8411 44 : InvokeObjectPostAlterHook(RelationRelationId,
8412 : RelationGetRelid(rel),
8413 : attTup->attnum);
8414 44 : ObjectAddressSubSet(address, RelationRelationId,
8415 : RelationGetRelid(rel), attnum);
8416 : }
8417 : else
8418 6 : address = InvalidObjectAddress;
8419 :
8420 50 : heap_freetuple(tuple);
8421 50 : table_close(attrelation, RowExclusiveLock);
8422 :
8423 : /*
8424 : * Recurse to propagate the identity change to partitions. Identity is not
8425 : * inherited in regular inheritance children.
8426 : */
8427 50 : if (generatedEl && recurse && ispartitioned)
8428 : {
8429 : List *children;
8430 : ListCell *lc;
8431 :
8432 6 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8433 :
8434 18 : foreach(lc, children)
8435 : {
8436 : Relation childrel;
8437 :
8438 12 : childrel = table_open(lfirst_oid(lc), NoLock);
8439 12 : ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
8440 12 : table_close(childrel, NoLock);
8441 : }
8442 : }
8443 :
8444 50 : return address;
8445 : }
8446 :
8447 : /*
8448 : * ALTER TABLE ALTER COLUMN DROP IDENTITY
8449 : *
8450 : * Return the address of the affected column.
8451 : */
8452 : static ObjectAddress
8453 68 : ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
8454 : bool recurse, bool recursing)
8455 : {
8456 : HeapTuple tuple;
8457 : Form_pg_attribute attTup;
8458 : AttrNumber attnum;
8459 : Relation attrelation;
8460 : ObjectAddress address;
8461 : Oid seqid;
8462 : ObjectAddress seqaddress;
8463 : bool ispartitioned;
8464 :
8465 68 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8466 68 : if (ispartitioned && !recurse)
8467 6 : ereport(ERROR,
8468 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8469 : errmsg("cannot drop identity from a column of only the partitioned table"),
8470 : errhint("Do not specify the ONLY keyword.")));
8471 :
8472 62 : if (rel->rd_rel->relispartition && !recursing)
8473 6 : ereport(ERROR,
8474 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8475 : errmsg("cannot drop identity from a column of a partition"));
8476 :
8477 56 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8478 56 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8479 56 : if (!HeapTupleIsValid(tuple))
8480 0 : ereport(ERROR,
8481 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8482 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8483 : colName, RelationGetRelationName(rel))));
8484 :
8485 56 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8486 56 : attnum = attTup->attnum;
8487 :
8488 56 : if (attnum <= 0)
8489 0 : ereport(ERROR,
8490 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8491 : errmsg("cannot alter system column \"%s\"",
8492 : colName)));
8493 :
8494 56 : if (!attTup->attidentity)
8495 : {
8496 12 : if (!missing_ok)
8497 6 : ereport(ERROR,
8498 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8499 : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8500 : colName, RelationGetRelationName(rel))));
8501 : else
8502 : {
8503 6 : ereport(NOTICE,
8504 : (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
8505 : colName, RelationGetRelationName(rel))));
8506 6 : heap_freetuple(tuple);
8507 6 : table_close(attrelation, RowExclusiveLock);
8508 6 : return InvalidObjectAddress;
8509 : }
8510 : }
8511 :
8512 44 : attTup->attidentity = '\0';
8513 44 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8514 :
8515 44 : InvokeObjectPostAlterHook(RelationRelationId,
8516 : RelationGetRelid(rel),
8517 : attTup->attnum);
8518 44 : ObjectAddressSubSet(address, RelationRelationId,
8519 : RelationGetRelid(rel), attnum);
8520 44 : heap_freetuple(tuple);
8521 :
8522 44 : table_close(attrelation, RowExclusiveLock);
8523 :
8524 : /*
8525 : * Recurse to drop the identity from column in partitions. Identity is
8526 : * not inherited in regular inheritance children so ignore them.
8527 : */
8528 44 : if (recurse && ispartitioned)
8529 : {
8530 : List *children;
8531 : ListCell *lc;
8532 :
8533 6 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8534 :
8535 12 : foreach(lc, children)
8536 : {
8537 : Relation childrel;
8538 :
8539 6 : childrel = table_open(lfirst_oid(lc), NoLock);
8540 6 : ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
8541 6 : table_close(childrel, NoLock);
8542 : }
8543 : }
8544 :
8545 44 : if (!recursing)
8546 : {
8547 : /* drop the internal sequence */
8548 32 : seqid = getIdentitySequence(rel, attnum, false);
8549 32 : deleteDependencyRecordsForClass(RelationRelationId, seqid,
8550 : RelationRelationId, DEPENDENCY_INTERNAL);
8551 32 : CommandCounterIncrement();
8552 32 : seqaddress.classId = RelationRelationId;
8553 32 : seqaddress.objectId = seqid;
8554 32 : seqaddress.objectSubId = 0;
8555 32 : performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8556 : }
8557 :
8558 44 : return address;
8559 : }
8560 :
8561 : /*
8562 : * ALTER TABLE ALTER COLUMN SET EXPRESSION
8563 : *
8564 : * Return the address of the affected column.
8565 : */
8566 : static ObjectAddress
8567 180 : ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
8568 : Node *newExpr, LOCKMODE lockmode)
8569 : {
8570 : HeapTuple tuple;
8571 : Form_pg_attribute attTup;
8572 : AttrNumber attnum;
8573 : char attgenerated;
8574 : bool rewrite;
8575 : Oid attrdefoid;
8576 : ObjectAddress address;
8577 : Expr *defval;
8578 : NewColumnValue *newval;
8579 : RawColumnDefault *rawEnt;
8580 :
8581 180 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8582 180 : if (!HeapTupleIsValid(tuple))
8583 0 : ereport(ERROR,
8584 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8585 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8586 : colName, RelationGetRelationName(rel))));
8587 :
8588 180 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8589 :
8590 180 : attnum = attTup->attnum;
8591 180 : if (attnum <= 0)
8592 0 : ereport(ERROR,
8593 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8594 : errmsg("cannot alter system column \"%s\"",
8595 : colName)));
8596 :
8597 180 : attgenerated = attTup->attgenerated;
8598 180 : if (!attgenerated)
8599 12 : ereport(ERROR,
8600 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8601 : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8602 : colName, RelationGetRelationName(rel))));
8603 :
8604 : /*
8605 : * TODO: This could be done, just need to recheck any constraints
8606 : * afterwards.
8607 : */
8608 168 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
8609 90 : rel->rd_att->constr && rel->rd_att->constr->num_check > 0)
8610 12 : ereport(ERROR,
8611 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8612 : errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables with check constraints"),
8613 : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8614 : colName, RelationGetRelationName(rel))));
8615 :
8616 156 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
8617 24 : tab->verify_new_notnull = true;
8618 :
8619 : /*
8620 : * We need to prevent this because a change of expression could affect a
8621 : * row filter and inject expressions that are not permitted in a row
8622 : * filter. XXX We could try to have a more precise check to catch only
8623 : * publications with row filters, or even re-verify the row filter
8624 : * expressions.
8625 : */
8626 234 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
8627 78 : GetRelationPublications(RelationGetRelid(rel)) != NIL)
8628 6 : ereport(ERROR,
8629 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8630 : errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
8631 : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8632 : colName, RelationGetRelationName(rel))));
8633 :
8634 150 : rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
8635 :
8636 150 : ReleaseSysCache(tuple);
8637 :
8638 150 : if (rewrite)
8639 : {
8640 : /*
8641 : * Clear all the missing values if we're rewriting the table, since
8642 : * this renders them pointless.
8643 : */
8644 78 : RelationClearMissing(rel);
8645 :
8646 : /* make sure we don't conflict with later attribute modifications */
8647 78 : CommandCounterIncrement();
8648 :
8649 : /*
8650 : * Find everything that depends on the column (constraints, indexes,
8651 : * etc), and record enough information to let us recreate the objects
8652 : * after rewrite.
8653 : */
8654 78 : RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
8655 : }
8656 :
8657 : /*
8658 : * Drop the dependency records of the GENERATED expression, in particular
8659 : * its INTERNAL dependency on the column, which would otherwise cause
8660 : * dependency.c to refuse to perform the deletion.
8661 : */
8662 150 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8663 150 : if (!OidIsValid(attrdefoid))
8664 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8665 : RelationGetRelid(rel), attnum);
8666 150 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8667 :
8668 : /* Make above changes visible */
8669 150 : CommandCounterIncrement();
8670 :
8671 : /*
8672 : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8673 : * safety, but at present we do not expect anything to depend on the
8674 : * expression.
8675 : */
8676 150 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8677 : false, false);
8678 :
8679 : /* Prepare to store the new expression, in the catalogs */
8680 150 : rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
8681 150 : rawEnt->attnum = attnum;
8682 150 : rawEnt->raw_default = newExpr;
8683 150 : rawEnt->generated = attgenerated;
8684 :
8685 : /* Store the generated expression */
8686 150 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8687 : false, true, false, NULL);
8688 :
8689 : /* Make above new expression visible */
8690 150 : CommandCounterIncrement();
8691 :
8692 150 : if (rewrite)
8693 : {
8694 : /* Prepare for table rewrite */
8695 78 : defval = (Expr *) build_column_default(rel, attnum);
8696 :
8697 78 : newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
8698 78 : newval->attnum = attnum;
8699 78 : newval->expr = expression_planner(defval);
8700 78 : newval->is_generated = true;
8701 :
8702 78 : tab->newvals = lappend(tab->newvals, newval);
8703 78 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
8704 : }
8705 :
8706 : /* Drop any pg_statistic entry for the column */
8707 150 : RemoveStatistics(RelationGetRelid(rel), attnum);
8708 :
8709 150 : InvokeObjectPostAlterHook(RelationRelationId,
8710 : RelationGetRelid(rel), attnum);
8711 :
8712 150 : ObjectAddressSubSet(address, RelationRelationId,
8713 : RelationGetRelid(rel), attnum);
8714 150 : return address;
8715 : }
8716 :
8717 : /*
8718 : * ALTER TABLE ALTER COLUMN DROP EXPRESSION
8719 : */
8720 : static void
8721 86 : ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
8722 : {
8723 : /*
8724 : * Reject ONLY if there are child tables. We could implement this, but it
8725 : * is a bit complicated. GENERATED clauses must be attached to the column
8726 : * definition and cannot be added later like DEFAULT, so if a child table
8727 : * has a generation expression that the parent does not have, the child
8728 : * column will necessarily be an attislocal column. So to implement ONLY
8729 : * here, we'd need extra code to update attislocal of the direct child
8730 : * tables, somewhat similar to how DROP COLUMN does it, so that the
8731 : * resulting state can be properly dumped and restored.
8732 : */
8733 110 : if (!recurse &&
8734 24 : find_inheritance_children(RelationGetRelid(rel), lockmode))
8735 12 : ereport(ERROR,
8736 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8737 : errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
8738 :
8739 : /*
8740 : * Cannot drop generation expression from inherited columns.
8741 : */
8742 74 : if (!recursing)
8743 : {
8744 : HeapTuple tuple;
8745 : Form_pg_attribute attTup;
8746 :
8747 62 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
8748 62 : if (!HeapTupleIsValid(tuple))
8749 0 : ereport(ERROR,
8750 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8751 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8752 : cmd->name, RelationGetRelationName(rel))));
8753 :
8754 62 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8755 :
8756 62 : if (attTup->attinhcount > 0)
8757 12 : ereport(ERROR,
8758 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8759 : errmsg("cannot drop generation expression from inherited column")));
8760 : }
8761 62 : }
8762 :
8763 : /*
8764 : * Return the address of the affected column.
8765 : */
8766 : static ObjectAddress
8767 56 : ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
8768 : {
8769 : HeapTuple tuple;
8770 : Form_pg_attribute attTup;
8771 : AttrNumber attnum;
8772 : Relation attrelation;
8773 : Oid attrdefoid;
8774 : ObjectAddress address;
8775 :
8776 56 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8777 56 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8778 56 : if (!HeapTupleIsValid(tuple))
8779 0 : ereport(ERROR,
8780 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8781 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8782 : colName, RelationGetRelationName(rel))));
8783 :
8784 56 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8785 56 : attnum = attTup->attnum;
8786 :
8787 56 : if (attnum <= 0)
8788 0 : ereport(ERROR,
8789 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8790 : errmsg("cannot alter system column \"%s\"",
8791 : colName)));
8792 :
8793 : /*
8794 : * TODO: This could be done, but it would need a table rewrite to
8795 : * materialize the generated values. Note that for the time being, we
8796 : * still error with missing_ok, so that we don't silently leave the column
8797 : * as generated.
8798 : */
8799 56 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
8800 12 : ereport(ERROR,
8801 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8802 : errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
8803 : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8804 : colName, RelationGetRelationName(rel))));
8805 :
8806 44 : if (!attTup->attgenerated)
8807 : {
8808 24 : if (!missing_ok)
8809 12 : ereport(ERROR,
8810 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8811 : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8812 : colName, RelationGetRelationName(rel))));
8813 : else
8814 : {
8815 12 : ereport(NOTICE,
8816 : (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
8817 : colName, RelationGetRelationName(rel))));
8818 12 : heap_freetuple(tuple);
8819 12 : table_close(attrelation, RowExclusiveLock);
8820 12 : return InvalidObjectAddress;
8821 : }
8822 : }
8823 :
8824 : /*
8825 : * Mark the column as no longer generated. (The atthasdef flag needs to
8826 : * get cleared too, but RemoveAttrDefault will handle that.)
8827 : */
8828 20 : attTup->attgenerated = '\0';
8829 20 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8830 :
8831 20 : InvokeObjectPostAlterHook(RelationRelationId,
8832 : RelationGetRelid(rel),
8833 : attnum);
8834 20 : heap_freetuple(tuple);
8835 :
8836 20 : table_close(attrelation, RowExclusiveLock);
8837 :
8838 : /*
8839 : * Drop the dependency records of the GENERATED expression, in particular
8840 : * its INTERNAL dependency on the column, which would otherwise cause
8841 : * dependency.c to refuse to perform the deletion.
8842 : */
8843 20 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8844 20 : if (!OidIsValid(attrdefoid))
8845 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8846 : RelationGetRelid(rel), attnum);
8847 20 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8848 :
8849 : /* Make above changes visible */
8850 20 : CommandCounterIncrement();
8851 :
8852 : /*
8853 : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8854 : * safety, but at present we do not expect anything to depend on the
8855 : * default.
8856 : */
8857 20 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8858 : false, false);
8859 :
8860 20 : ObjectAddressSubSet(address, RelationRelationId,
8861 : RelationGetRelid(rel), attnum);
8862 20 : return address;
8863 : }
8864 :
8865 : /*
8866 : * ALTER TABLE ALTER COLUMN SET STATISTICS
8867 : *
8868 : * Return value is the address of the modified column
8869 : */
8870 : static ObjectAddress
8871 164 : ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
8872 : {
8873 164 : int newtarget = 0;
8874 : bool newtarget_default;
8875 : Relation attrelation;
8876 : HeapTuple tuple,
8877 : newtuple;
8878 : Form_pg_attribute attrtuple;
8879 : AttrNumber attnum;
8880 : ObjectAddress address;
8881 : Datum repl_val[Natts_pg_attribute];
8882 : bool repl_null[Natts_pg_attribute];
8883 : bool repl_repl[Natts_pg_attribute];
8884 :
8885 : /*
8886 : * We allow referencing columns by numbers only for indexes, since table
8887 : * column numbers could contain gaps if columns are later dropped.
8888 : */
8889 164 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
8890 100 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
8891 : !colName)
8892 0 : ereport(ERROR,
8893 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8894 : errmsg("cannot refer to non-index column by number")));
8895 :
8896 : /* -1 was used in previous versions for the default setting */
8897 164 : if (newValue && intVal(newValue) != -1)
8898 : {
8899 120 : newtarget = intVal(newValue);
8900 120 : newtarget_default = false;
8901 : }
8902 : else
8903 44 : newtarget_default = true;
8904 :
8905 164 : if (!newtarget_default)
8906 : {
8907 : /*
8908 : * Limit target to a sane range
8909 : */
8910 120 : if (newtarget < 0)
8911 : {
8912 0 : ereport(ERROR,
8913 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8914 : errmsg("statistics target %d is too low",
8915 : newtarget)));
8916 : }
8917 120 : else if (newtarget > MAX_STATISTICS_TARGET)
8918 : {
8919 0 : newtarget = MAX_STATISTICS_TARGET;
8920 0 : ereport(WARNING,
8921 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8922 : errmsg("lowering statistics target to %d",
8923 : newtarget)));
8924 : }
8925 : }
8926 :
8927 164 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8928 :
8929 164 : if (colName)
8930 : {
8931 100 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8932 :
8933 100 : if (!HeapTupleIsValid(tuple))
8934 12 : ereport(ERROR,
8935 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8936 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8937 : colName, RelationGetRelationName(rel))));
8938 : }
8939 : else
8940 : {
8941 64 : tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
8942 :
8943 64 : if (!HeapTupleIsValid(tuple))
8944 12 : ereport(ERROR,
8945 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8946 : errmsg("column number %d of relation \"%s\" does not exist",
8947 : colNum, RelationGetRelationName(rel))));
8948 : }
8949 :
8950 140 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
8951 :
8952 140 : attnum = attrtuple->attnum;
8953 140 : if (attnum <= 0)
8954 0 : ereport(ERROR,
8955 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8956 : errmsg("cannot alter system column \"%s\"",
8957 : colName)));
8958 :
8959 : /*
8960 : * Prevent this as long as the ANALYZE code skips virtual generated
8961 : * columns.
8962 : */
8963 140 : if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
8964 0 : ereport(ERROR,
8965 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8966 : errmsg("cannot alter statistics on virtual generated column \"%s\"",
8967 : colName)));
8968 :
8969 140 : if (rel->rd_rel->relkind == RELKIND_INDEX ||
8970 88 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
8971 : {
8972 52 : if (attnum > rel->rd_index->indnkeyatts)
8973 6 : ereport(ERROR,
8974 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8975 : errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
8976 : NameStr(attrtuple->attname), RelationGetRelationName(rel))));
8977 46 : else if (rel->rd_index->indkey.values[attnum - 1] != 0)
8978 18 : ereport(ERROR,
8979 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8980 : errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
8981 : NameStr(attrtuple->attname), RelationGetRelationName(rel)),
8982 : errhint("Alter statistics on table column instead.")));
8983 : }
8984 :
8985 : /* Build new tuple. */
8986 116 : memset(repl_null, false, sizeof(repl_null));
8987 116 : memset(repl_repl, false, sizeof(repl_repl));
8988 116 : if (!newtarget_default)
8989 72 : repl_val[Anum_pg_attribute_attstattarget - 1] = newtarget;
8990 : else
8991 44 : repl_null[Anum_pg_attribute_attstattarget - 1] = true;
8992 116 : repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
8993 116 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
8994 : repl_val, repl_null, repl_repl);
8995 116 : CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
8996 :
8997 116 : InvokeObjectPostAlterHook(RelationRelationId,
8998 : RelationGetRelid(rel),
8999 : attrtuple->attnum);
9000 116 : ObjectAddressSubSet(address, RelationRelationId,
9001 : RelationGetRelid(rel), attnum);
9002 :
9003 116 : heap_freetuple(newtuple);
9004 :
9005 116 : ReleaseSysCache(tuple);
9006 :
9007 116 : table_close(attrelation, RowExclusiveLock);
9008 :
9009 116 : return address;
9010 : }
9011 :
9012 : /*
9013 : * Return value is the address of the modified column
9014 : */
9015 : static ObjectAddress
9016 32 : ATExecSetOptions(Relation rel, const char *colName, Node *options,
9017 : bool isReset, LOCKMODE lockmode)
9018 : {
9019 : Relation attrelation;
9020 : HeapTuple tuple,
9021 : newtuple;
9022 : Form_pg_attribute attrtuple;
9023 : AttrNumber attnum;
9024 : Datum datum,
9025 : newOptions;
9026 : bool isnull;
9027 : ObjectAddress address;
9028 : Datum repl_val[Natts_pg_attribute];
9029 : bool repl_null[Natts_pg_attribute];
9030 : bool repl_repl[Natts_pg_attribute];
9031 :
9032 32 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9033 :
9034 32 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9035 :
9036 32 : if (!HeapTupleIsValid(tuple))
9037 0 : ereport(ERROR,
9038 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9039 : errmsg("column \"%s\" of relation \"%s\" does not exist",
9040 : colName, RelationGetRelationName(rel))));
9041 32 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9042 :
9043 32 : attnum = attrtuple->attnum;
9044 32 : if (attnum <= 0)
9045 0 : ereport(ERROR,
9046 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9047 : errmsg("cannot alter system column \"%s\"",
9048 : colName)));
9049 :
9050 : /* Generate new proposed attoptions (text array) */
9051 32 : datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
9052 : &isnull);
9053 32 : newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9054 : castNode(List, options), NULL, NULL,
9055 : false, isReset);
9056 : /* Validate new options */
9057 32 : (void) attribute_reloptions(newOptions, true);
9058 :
9059 : /* Build new tuple. */
9060 32 : memset(repl_null, false, sizeof(repl_null));
9061 32 : memset(repl_repl, false, sizeof(repl_repl));
9062 32 : if (newOptions != (Datum) 0)
9063 32 : repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
9064 : else
9065 0 : repl_null[Anum_pg_attribute_attoptions - 1] = true;
9066 32 : repl_repl[Anum_pg_attribute_attoptions - 1] = true;
9067 32 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9068 : repl_val, repl_null, repl_repl);
9069 :
9070 : /* Update system catalog. */
9071 32 : CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
9072 :
9073 32 : InvokeObjectPostAlterHook(RelationRelationId,
9074 : RelationGetRelid(rel),
9075 : attrtuple->attnum);
9076 32 : ObjectAddressSubSet(address, RelationRelationId,
9077 : RelationGetRelid(rel), attnum);
9078 :
9079 32 : heap_freetuple(newtuple);
9080 :
9081 32 : ReleaseSysCache(tuple);
9082 :
9083 32 : table_close(attrelation, RowExclusiveLock);
9084 :
9085 32 : return address;
9086 : }
9087 :
9088 : /*
9089 : * Helper function for ATExecSetStorage and ATExecSetCompression
9090 : *
9091 : * Set the attstorage and/or attcompression fields for index columns
9092 : * associated with the specified table column.
9093 : */
9094 : static void
9095 318 : SetIndexStorageProperties(Relation rel, Relation attrelation,
9096 : AttrNumber attnum,
9097 : bool setstorage, char newstorage,
9098 : bool setcompression, char newcompression,
9099 : LOCKMODE lockmode)
9100 : {
9101 : ListCell *lc;
9102 :
9103 402 : foreach(lc, RelationGetIndexList(rel))
9104 : {
9105 84 : Oid indexoid = lfirst_oid(lc);
9106 : Relation indrel;
9107 84 : AttrNumber indattnum = 0;
9108 : HeapTuple tuple;
9109 :
9110 84 : indrel = index_open(indexoid, lockmode);
9111 :
9112 144 : for (int i = 0; i < indrel->rd_index->indnatts; i++)
9113 : {
9114 90 : if (indrel->rd_index->indkey.values[i] == attnum)
9115 : {
9116 30 : indattnum = i + 1;
9117 30 : break;
9118 : }
9119 : }
9120 :
9121 84 : if (indattnum == 0)
9122 : {
9123 54 : index_close(indrel, lockmode);
9124 54 : continue;
9125 : }
9126 :
9127 30 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
9128 :
9129 30 : if (HeapTupleIsValid(tuple))
9130 : {
9131 30 : Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9132 :
9133 30 : if (setstorage)
9134 24 : attrtuple->attstorage = newstorage;
9135 :
9136 30 : if (setcompression)
9137 6 : attrtuple->attcompression = newcompression;
9138 :
9139 30 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9140 :
9141 30 : InvokeObjectPostAlterHook(RelationRelationId,
9142 : RelationGetRelid(rel),
9143 : attrtuple->attnum);
9144 :
9145 30 : heap_freetuple(tuple);
9146 : }
9147 :
9148 30 : index_close(indrel, lockmode);
9149 : }
9150 318 : }
9151 :
9152 : /*
9153 : * ALTER TABLE ALTER COLUMN SET STORAGE
9154 : *
9155 : * Return value is the address of the modified column
9156 : */
9157 : static ObjectAddress
9158 246 : ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
9159 : {
9160 : Relation attrelation;
9161 : HeapTuple tuple;
9162 : Form_pg_attribute attrtuple;
9163 : AttrNumber attnum;
9164 : ObjectAddress address;
9165 :
9166 246 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9167 :
9168 246 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9169 :
9170 246 : if (!HeapTupleIsValid(tuple))
9171 12 : ereport(ERROR,
9172 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9173 : errmsg("column \"%s\" of relation \"%s\" does not exist",
9174 : colName, RelationGetRelationName(rel))));
9175 234 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9176 :
9177 234 : attnum = attrtuple->attnum;
9178 234 : if (attnum <= 0)
9179 0 : ereport(ERROR,
9180 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9181 : errmsg("cannot alter system column \"%s\"",
9182 : colName)));
9183 :
9184 234 : attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
9185 :
9186 234 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9187 :
9188 234 : InvokeObjectPostAlterHook(RelationRelationId,
9189 : RelationGetRelid(rel),
9190 : attrtuple->attnum);
9191 :
9192 : /*
9193 : * Apply the change to indexes as well (only for simple index columns,
9194 : * matching behavior of index.c ConstructTupleDescriptor()).
9195 : */
9196 234 : SetIndexStorageProperties(rel, attrelation, attnum,
9197 234 : true, attrtuple->attstorage,
9198 : false, 0,
9199 : lockmode);
9200 :
9201 234 : heap_freetuple(tuple);
9202 :
9203 234 : table_close(attrelation, RowExclusiveLock);
9204 :
9205 234 : ObjectAddressSubSet(address, RelationRelationId,
9206 : RelationGetRelid(rel), attnum);
9207 234 : return address;
9208 : }
9209 :
9210 :
9211 : /*
9212 : * ALTER TABLE DROP COLUMN
9213 : *
9214 : * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
9215 : * because we have to decide at runtime whether to recurse or not depending
9216 : * on whether attinhcount goes to zero or not. (We can't check this in a
9217 : * static pre-pass because it won't handle multiple inheritance situations
9218 : * correctly.)
9219 : */
9220 : static void
9221 1652 : ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
9222 : AlterTableCmd *cmd, LOCKMODE lockmode,
9223 : AlterTableUtilityContext *context)
9224 : {
9225 1652 : if (rel->rd_rel->reloftype && !recursing)
9226 6 : ereport(ERROR,
9227 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9228 : errmsg("cannot drop column from typed table")));
9229 :
9230 1646 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
9231 84 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
9232 :
9233 1640 : if (recurse)
9234 1360 : cmd->recurse = true;
9235 1640 : }
9236 :
9237 : /*
9238 : * Drops column 'colName' from relation 'rel' and returns the address of the
9239 : * dropped column. The column is also dropped (or marked as no longer
9240 : * inherited from relation) from the relation's inheritance children, if any.
9241 : *
9242 : * In the recursive invocations for inheritance child relations, instead of
9243 : * dropping the column directly (if to be dropped at all), its object address
9244 : * is added to 'addrs', which must be non-NULL in such invocations. All
9245 : * columns are dropped at the same time after all the children have been
9246 : * checked recursively.
9247 : */
9248 : static ObjectAddress
9249 2196 : ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
9250 : DropBehavior behavior,
9251 : bool recurse, bool recursing,
9252 : bool missing_ok, LOCKMODE lockmode,
9253 : ObjectAddresses *addrs)
9254 : {
9255 : HeapTuple tuple;
9256 : Form_pg_attribute targetatt;
9257 : AttrNumber attnum;
9258 : List *children;
9259 : ObjectAddress object;
9260 : bool is_expr;
9261 :
9262 : /* At top level, permission check was done in ATPrepCmd, else do it */
9263 2196 : if (recursing)
9264 556 : ATSimplePermissions(AT_DropColumn, rel,
9265 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9266 :
9267 : /* Initialize addrs on the first invocation */
9268 : Assert(!recursing || addrs != NULL);
9269 :
9270 : /* since this function recurses, it could be driven to stack overflow */
9271 2196 : check_stack_depth();
9272 :
9273 2196 : if (!recursing)
9274 1640 : addrs = new_object_addresses();
9275 :
9276 : /*
9277 : * get the number of the attribute
9278 : */
9279 2196 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9280 2196 : if (!HeapTupleIsValid(tuple))
9281 : {
9282 54 : if (!missing_ok)
9283 : {
9284 36 : ereport(ERROR,
9285 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9286 : errmsg("column \"%s\" of relation \"%s\" does not exist",
9287 : colName, RelationGetRelationName(rel))));
9288 : }
9289 : else
9290 : {
9291 18 : ereport(NOTICE,
9292 : (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
9293 : colName, RelationGetRelationName(rel))));
9294 18 : return InvalidObjectAddress;
9295 : }
9296 : }
9297 2142 : targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
9298 :
9299 2142 : attnum = targetatt->attnum;
9300 :
9301 : /* Can't drop a system attribute */
9302 2142 : if (attnum <= 0)
9303 6 : ereport(ERROR,
9304 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9305 : errmsg("cannot drop system column \"%s\"",
9306 : colName)));
9307 :
9308 : /*
9309 : * Don't drop inherited columns, unless recursing (presumably from a drop
9310 : * of the parent column)
9311 : */
9312 2136 : if (targetatt->attinhcount > 0 && !recursing)
9313 48 : ereport(ERROR,
9314 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9315 : errmsg("cannot drop inherited column \"%s\"",
9316 : colName)));
9317 :
9318 : /*
9319 : * Don't drop columns used in the partition key, either. (If we let this
9320 : * go through, the key column's dependencies would cause a cascaded drop
9321 : * of the whole table, which is surely not what the user expected.)
9322 : */
9323 2088 : if (has_partition_attrs(rel,
9324 : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
9325 : &is_expr))
9326 30 : ereport(ERROR,
9327 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9328 : errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
9329 : colName, RelationGetRelationName(rel))));
9330 :
9331 2058 : ReleaseSysCache(tuple);
9332 :
9333 : /*
9334 : * Propagate to children as appropriate. Unlike most other ALTER
9335 : * routines, we have to do this one level of recursion at a time; we can't
9336 : * use find_all_inheritors to do it in one pass.
9337 : */
9338 : children =
9339 2058 : find_inheritance_children(RelationGetRelid(rel), lockmode);
9340 :
9341 2058 : if (children)
9342 : {
9343 : Relation attr_rel;
9344 : ListCell *child;
9345 :
9346 : /*
9347 : * In case of a partitioned table, the column must be dropped from the
9348 : * partitions as well.
9349 : */
9350 302 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
9351 6 : ereport(ERROR,
9352 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9353 : errmsg("cannot drop column from only the partitioned table when partitions exist"),
9354 : errhint("Do not specify the ONLY keyword.")));
9355 :
9356 296 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
9357 882 : foreach(child, children)
9358 : {
9359 592 : Oid childrelid = lfirst_oid(child);
9360 : Relation childrel;
9361 : Form_pg_attribute childatt;
9362 :
9363 : /* find_inheritance_children already got lock */
9364 592 : childrel = table_open(childrelid, NoLock);
9365 592 : CheckAlterTableIsSafe(childrel);
9366 :
9367 592 : tuple = SearchSysCacheCopyAttName(childrelid, colName);
9368 592 : if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
9369 0 : elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
9370 : colName, childrelid);
9371 592 : childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9372 :
9373 592 : if (childatt->attinhcount <= 0) /* shouldn't happen */
9374 0 : elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
9375 : childrelid, colName);
9376 :
9377 592 : if (recurse)
9378 : {
9379 : /*
9380 : * If the child column has other definition sources, just
9381 : * decrement its inheritance count; if not, recurse to delete
9382 : * it.
9383 : */
9384 568 : if (childatt->attinhcount == 1 && !childatt->attislocal)
9385 : {
9386 : /* Time to delete this child column, too */
9387 556 : ATExecDropColumn(wqueue, childrel, colName,
9388 : behavior, true, true,
9389 : false, lockmode, addrs);
9390 : }
9391 : else
9392 : {
9393 : /* Child column must survive my deletion */
9394 12 : childatt->attinhcount--;
9395 :
9396 12 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9397 :
9398 : /* Make update visible */
9399 12 : CommandCounterIncrement();
9400 : }
9401 : }
9402 : else
9403 : {
9404 : /*
9405 : * If we were told to drop ONLY in this table (no recursion),
9406 : * we need to mark the inheritors' attributes as locally
9407 : * defined rather than inherited.
9408 : */
9409 24 : childatt->attinhcount--;
9410 24 : childatt->attislocal = true;
9411 :
9412 24 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9413 :
9414 : /* Make update visible */
9415 24 : CommandCounterIncrement();
9416 : }
9417 :
9418 586 : heap_freetuple(tuple);
9419 :
9420 586 : table_close(childrel, NoLock);
9421 : }
9422 290 : table_close(attr_rel, RowExclusiveLock);
9423 : }
9424 :
9425 : /* Add object to delete */
9426 2046 : object.classId = RelationRelationId;
9427 2046 : object.objectId = RelationGetRelid(rel);
9428 2046 : object.objectSubId = attnum;
9429 2046 : add_exact_object_address(&object, addrs);
9430 :
9431 2046 : if (!recursing)
9432 : {
9433 : /* Recursion has ended, drop everything that was collected */
9434 1496 : performMultipleDeletions(addrs, behavior, 0);
9435 1442 : free_object_addresses(addrs);
9436 : }
9437 :
9438 1992 : return object;
9439 : }
9440 :
9441 : /*
9442 : * Prepare to add a primary key on a table, by adding not-null constraints
9443 : * on all columns.
9444 : *
9445 : * The not-null constraints for a primary key must cover the whole inheritance
9446 : * hierarchy (failing to ensure that leads to funny corner cases). For the
9447 : * normal case where we're asked to recurse, this routine checks if the
9448 : * not-null constraints exist already, and if not queues a requirement for
9449 : * them to be created by phase 2.
9450 : *
9451 : * For the case where we're asked not to recurse, we verify that a not-null
9452 : * constraint exists on each column of each (direct) child table, throwing an
9453 : * error if not. Not throwing an error would also work, because a not-null
9454 : * constraint would be created anyway, but it'd cause a silent scan of the
9455 : * child table to verify absence of nulls. We prefer to let the user know so
9456 : * that they can add the constraint manually without having to hold
9457 : * AccessExclusiveLock while at it.
9458 : *
9459 : * However, it's also important that we do not acquire locks on children if
9460 : * the not-null constraints already exist on the parent, to avoid risking
9461 : * deadlocks during parallel pg_restore of PKs on partitioned tables.
9462 : */
9463 : static void
9464 16310 : ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
9465 : bool recurse, LOCKMODE lockmode,
9466 : AlterTableUtilityContext *context)
9467 : {
9468 : Constraint *pkconstr;
9469 16310 : List *children = NIL;
9470 16310 : bool got_children = false;
9471 :
9472 16310 : pkconstr = castNode(Constraint, cmd->def);
9473 16310 : if (pkconstr->contype != CONSTR_PRIMARY)
9474 9208 : return;
9475 :
9476 : /* Verify that columns are not-null, or request that they be made so */
9477 15468 : foreach_node(String, column, pkconstr->keys)
9478 : {
9479 : AlterTableCmd *newcmd;
9480 : Constraint *nnconstr;
9481 : HeapTuple tuple;
9482 :
9483 : /*
9484 : * First check if a suitable constraint exists. If it does, we don't
9485 : * need to request another one. We do need to bail out if it's not
9486 : * valid, though.
9487 : */
9488 1324 : tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
9489 1324 : if (tuple != NULL)
9490 : {
9491 814 : verifyNotNullPKCompatible(tuple, strVal(column));
9492 :
9493 : /* All good with this one; don't request another */
9494 802 : heap_freetuple(tuple);
9495 802 : continue;
9496 : }
9497 510 : else if (!recurse)
9498 : {
9499 : /*
9500 : * No constraint on this column. Asked not to recurse, we won't
9501 : * create one here, but verify that all children have one.
9502 : */
9503 36 : if (!got_children)
9504 : {
9505 36 : children = find_inheritance_children(RelationGetRelid(rel),
9506 : lockmode);
9507 : /* only search for children on the first time through */
9508 36 : got_children = true;
9509 : }
9510 :
9511 72 : foreach_oid(childrelid, children)
9512 : {
9513 : HeapTuple tup;
9514 :
9515 36 : tup = findNotNullConstraint(childrelid, strVal(column));
9516 36 : if (!tup)
9517 6 : ereport(ERROR,
9518 : errmsg("column \"%s\" of table \"%s\" is not marked NOT NULL",
9519 : strVal(column), get_rel_name(childrelid)));
9520 : /* verify it's good enough */
9521 30 : verifyNotNullPKCompatible(tup, strVal(column));
9522 : }
9523 : }
9524 :
9525 : /* This column is not already not-null, so add it to the queue */
9526 492 : nnconstr = makeNotNullConstraint(column);
9527 :
9528 492 : newcmd = makeNode(AlterTableCmd);
9529 492 : newcmd->subtype = AT_AddConstraint;
9530 : /* note we force recurse=true here; see above */
9531 492 : newcmd->recurse = true;
9532 492 : newcmd->def = (Node *) nnconstr;
9533 :
9534 492 : ATPrepCmd(wqueue, rel, newcmd, true, false, lockmode, context);
9535 : }
9536 : }
9537 :
9538 : /*
9539 : * Verify whether the given not-null constraint is compatible with a
9540 : * primary key. If not, an error is thrown.
9541 : */
9542 : static void
9543 844 : verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
9544 : {
9545 844 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
9546 :
9547 844 : if (conForm->contype != CONSTRAINT_NOTNULL)
9548 0 : elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
9549 :
9550 : /* a NO INHERIT constraint is no good */
9551 844 : if (conForm->connoinherit)
9552 12 : ereport(ERROR,
9553 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9554 : errmsg("cannot create primary key on column \"%s\"", colname),
9555 : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9556 : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9557 : NameStr(conForm->conname), colname,
9558 : get_rel_name(conForm->conrelid), "NO INHERIT"),
9559 : errhint("You might need to make the existing constraint inheritable using %s.",
9560 : "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
9561 :
9562 : /* an unvalidated constraint is no good */
9563 832 : if (!conForm->convalidated)
9564 12 : ereport(ERROR,
9565 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9566 : errmsg("cannot create primary key on column \"%s\"", colname),
9567 : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9568 : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9569 : NameStr(conForm->conname), colname,
9570 : get_rel_name(conForm->conrelid), "NOT VALID"),
9571 : errhint("You might need to validate it using %s.",
9572 : "ALTER TABLE ... VALIDATE CONSTRAINT"));
9573 820 : }
9574 :
9575 : /*
9576 : * ALTER TABLE ADD INDEX
9577 : *
9578 : * There is no such command in the grammar, but parse_utilcmd.c converts
9579 : * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
9580 : * us schedule creation of the index at the appropriate time during ALTER.
9581 : *
9582 : * Return value is the address of the new index.
9583 : */
9584 : static ObjectAddress
9585 1888 : ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
9586 : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9587 : {
9588 : bool check_rights;
9589 : bool skip_build;
9590 : bool quiet;
9591 : ObjectAddress address;
9592 :
9593 : Assert(IsA(stmt, IndexStmt));
9594 : Assert(!stmt->concurrent);
9595 :
9596 : /* The IndexStmt has already been through transformIndexStmt */
9597 : Assert(stmt->transformed);
9598 :
9599 : /* suppress schema rights check when rebuilding existing index */
9600 1888 : check_rights = !is_rebuild;
9601 : /* skip index build if phase 3 will do it or we're reusing an old one */
9602 1888 : skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
9603 : /* suppress notices when rebuilding existing index */
9604 1888 : quiet = is_rebuild;
9605 :
9606 1888 : address = DefineIndex(RelationGetRelid(rel),
9607 : stmt,
9608 : InvalidOid, /* no predefined OID */
9609 : InvalidOid, /* no parent index */
9610 : InvalidOid, /* no parent constraint */
9611 : -1, /* total_parts unknown */
9612 : true, /* is_alter_table */
9613 : check_rights,
9614 : false, /* check_not_in_use - we did it already */
9615 : skip_build,
9616 : quiet);
9617 :
9618 : /*
9619 : * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
9620 : * new index instead of building from scratch. Restore associated fields.
9621 : * This may store InvalidSubTransactionId in both fields, in which case
9622 : * relcache.c will assume it can rebuild the relcache entry. Hence, do
9623 : * this after the CCI that made catalog rows visible to any rebuild. The
9624 : * DROP of the old edition of this index will have scheduled the storage
9625 : * for deletion at commit, so cancel that pending deletion.
9626 : */
9627 1718 : if (RelFileNumberIsValid(stmt->oldNumber))
9628 : {
9629 74 : Relation irel = index_open(address.objectId, NoLock);
9630 :
9631 74 : irel->rd_createSubid = stmt->oldCreateSubid;
9632 74 : irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
9633 74 : RelationPreserveStorage(irel->rd_locator, true);
9634 74 : index_close(irel, NoLock);
9635 : }
9636 :
9637 1718 : return address;
9638 : }
9639 :
9640 : /*
9641 : * ALTER TABLE ADD STATISTICS
9642 : *
9643 : * This is no such command in the grammar, but we use this internally to add
9644 : * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
9645 : * column type change.
9646 : */
9647 : static ObjectAddress
9648 14 : ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
9649 : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9650 : {
9651 : ObjectAddress address;
9652 :
9653 : Assert(IsA(stmt, CreateStatsStmt));
9654 :
9655 : /* The CreateStatsStmt has already been through transformStatsStmt */
9656 : Assert(stmt->transformed);
9657 :
9658 14 : address = CreateStatistics(stmt);
9659 :
9660 14 : return address;
9661 : }
9662 :
9663 : /*
9664 : * ALTER TABLE ADD CONSTRAINT USING INDEX
9665 : *
9666 : * Returns the address of the new constraint.
9667 : */
9668 : static ObjectAddress
9669 10640 : ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
9670 : IndexStmt *stmt, LOCKMODE lockmode)
9671 : {
9672 10640 : Oid index_oid = stmt->indexOid;
9673 : Relation indexRel;
9674 : char *indexName;
9675 : IndexInfo *indexInfo;
9676 : char *constraintName;
9677 : char constraintType;
9678 : ObjectAddress address;
9679 : bits16 flags;
9680 :
9681 : Assert(IsA(stmt, IndexStmt));
9682 : Assert(OidIsValid(index_oid));
9683 : Assert(stmt->isconstraint);
9684 :
9685 : /*
9686 : * Doing this on partitioned tables is not a simple feature to implement,
9687 : * so let's punt for now.
9688 : */
9689 10640 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
9690 6 : ereport(ERROR,
9691 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9692 : errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
9693 :
9694 10634 : indexRel = index_open(index_oid, AccessShareLock);
9695 :
9696 10634 : indexName = pstrdup(RelationGetRelationName(indexRel));
9697 :
9698 10634 : indexInfo = BuildIndexInfo(indexRel);
9699 :
9700 : /* this should have been checked at parse time */
9701 10634 : if (!indexInfo->ii_Unique)
9702 0 : elog(ERROR, "index \"%s\" is not unique", indexName);
9703 :
9704 : /*
9705 : * Determine name to assign to constraint. We require a constraint to
9706 : * have the same name as the underlying index; therefore, use the index's
9707 : * existing name as the default constraint name, and if the user
9708 : * explicitly gives some other name for the constraint, rename the index
9709 : * to match.
9710 : */
9711 10634 : constraintName = stmt->idxname;
9712 10634 : if (constraintName == NULL)
9713 10608 : constraintName = indexName;
9714 26 : else if (strcmp(constraintName, indexName) != 0)
9715 : {
9716 20 : ereport(NOTICE,
9717 : (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
9718 : indexName, constraintName)));
9719 20 : RenameRelationInternal(index_oid, constraintName, false, true);
9720 : }
9721 :
9722 : /* Extra checks needed if making primary key */
9723 10634 : if (stmt->primary)
9724 6006 : index_check_primary_key(rel, indexInfo, true, stmt);
9725 :
9726 : /* Note we currently don't support EXCLUSION constraints here */
9727 10628 : if (stmt->primary)
9728 6000 : constraintType = CONSTRAINT_PRIMARY;
9729 : else
9730 4628 : constraintType = CONSTRAINT_UNIQUE;
9731 :
9732 : /* Create the catalog entries for the constraint */
9733 10628 : flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
9734 : INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
9735 21256 : (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
9736 10628 : (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
9737 10628 : (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
9738 :
9739 10628 : address = index_constraint_create(rel,
9740 : index_oid,
9741 : InvalidOid,
9742 : indexInfo,
9743 : constraintName,
9744 : constraintType,
9745 : flags,
9746 : allowSystemTableMods,
9747 : false); /* is_internal */
9748 :
9749 10628 : index_close(indexRel, NoLock);
9750 :
9751 10628 : return address;
9752 : }
9753 :
9754 : /*
9755 : * ALTER TABLE ADD CONSTRAINT
9756 : *
9757 : * Return value is the address of the new constraint; if no constraint was
9758 : * added, InvalidObjectAddress is returned.
9759 : */
9760 : static ObjectAddress
9761 12808 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9762 : Constraint *newConstraint, bool recurse, bool is_readd,
9763 : LOCKMODE lockmode)
9764 : {
9765 12808 : ObjectAddress address = InvalidObjectAddress;
9766 :
9767 : Assert(IsA(newConstraint, Constraint));
9768 :
9769 : /*
9770 : * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
9771 : * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
9772 : * parse_utilcmd.c).
9773 : */
9774 12808 : switch (newConstraint->contype)
9775 : {
9776 10158 : case CONSTR_CHECK:
9777 : case CONSTR_NOTNULL:
9778 : address =
9779 10158 : ATAddCheckNNConstraint(wqueue, tab, rel,
9780 : newConstraint, recurse, false, is_readd,
9781 : lockmode);
9782 10014 : break;
9783 :
9784 2650 : case CONSTR_FOREIGN:
9785 :
9786 : /*
9787 : * Assign or validate constraint name
9788 : */
9789 2650 : if (newConstraint->conname)
9790 : {
9791 1238 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
9792 : RelationGetRelid(rel),
9793 1238 : newConstraint->conname))
9794 0 : ereport(ERROR,
9795 : (errcode(ERRCODE_DUPLICATE_OBJECT),
9796 : errmsg("constraint \"%s\" for relation \"%s\" already exists",
9797 : newConstraint->conname,
9798 : RelationGetRelationName(rel))));
9799 : }
9800 : else
9801 1412 : newConstraint->conname =
9802 1412 : ChooseConstraintName(RelationGetRelationName(rel),
9803 1412 : ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
9804 : "fkey",
9805 1412 : RelationGetNamespace(rel),
9806 : NIL);
9807 :
9808 2650 : address = ATAddForeignKeyConstraint(wqueue, tab, rel,
9809 : newConstraint,
9810 : recurse, false,
9811 : lockmode);
9812 2102 : break;
9813 :
9814 0 : default:
9815 0 : elog(ERROR, "unrecognized constraint type: %d",
9816 : (int) newConstraint->contype);
9817 : }
9818 :
9819 12116 : return address;
9820 : }
9821 :
9822 : /*
9823 : * Generate the column-name portion of the constraint name for a new foreign
9824 : * key given the list of column names that reference the referenced
9825 : * table. This will be passed to ChooseConstraintName along with the parent
9826 : * table name and the "fkey" suffix.
9827 : *
9828 : * We know that less than NAMEDATALEN characters will actually be used, so we
9829 : * can truncate the result once we've generated that many.
9830 : *
9831 : * XXX see also ChooseExtendedStatisticNameAddition and
9832 : * ChooseIndexNameAddition.
9833 : */
9834 : static char *
9835 1412 : ChooseForeignKeyConstraintNameAddition(List *colnames)
9836 : {
9837 : char buf[NAMEDATALEN * 2];
9838 1412 : int buflen = 0;
9839 : ListCell *lc;
9840 :
9841 1412 : buf[0] = '\0';
9842 3216 : foreach(lc, colnames)
9843 : {
9844 1804 : const char *name = strVal(lfirst(lc));
9845 :
9846 1804 : if (buflen > 0)
9847 392 : buf[buflen++] = '_'; /* insert _ between names */
9848 :
9849 : /*
9850 : * At this point we have buflen <= NAMEDATALEN. name should be less
9851 : * than NAMEDATALEN already, but use strlcpy for paranoia.
9852 : */
9853 1804 : strlcpy(buf + buflen, name, NAMEDATALEN);
9854 1804 : buflen += strlen(buf + buflen);
9855 1804 : if (buflen >= NAMEDATALEN)
9856 0 : break;
9857 : }
9858 1412 : return pstrdup(buf);
9859 : }
9860 :
9861 : /*
9862 : * Add a check or not-null constraint to a single table and its children.
9863 : * Returns the address of the constraint added to the parent relation,
9864 : * if one gets added, or InvalidObjectAddress otherwise.
9865 : *
9866 : * Subroutine for ATExecAddConstraint.
9867 : *
9868 : * We must recurse to child tables during execution, rather than using
9869 : * ALTER TABLE's normal prep-time recursion. The reason is that all the
9870 : * constraints *must* be given the same name, else they won't be seen as
9871 : * related later. If the user didn't explicitly specify a name, then
9872 : * AddRelationNewConstraints would normally assign different names to the
9873 : * child constraints. To fix that, we must capture the name assigned at
9874 : * the parent table and pass that down.
9875 : */
9876 : static ObjectAddress
9877 11110 : ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9878 : Constraint *constr, bool recurse, bool recursing,
9879 : bool is_readd, LOCKMODE lockmode)
9880 : {
9881 : List *newcons;
9882 : ListCell *lcon;
9883 : List *children;
9884 : ListCell *child;
9885 11110 : ObjectAddress address = InvalidObjectAddress;
9886 :
9887 : /* Guard against stack overflow due to overly deep inheritance tree. */
9888 11110 : check_stack_depth();
9889 :
9890 : /* At top level, permission check was done in ATPrepCmd, else do it */
9891 11110 : if (recursing)
9892 818 : ATSimplePermissions(AT_AddConstraint, rel,
9893 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9894 :
9895 : /*
9896 : * Call AddRelationNewConstraints to do the work, making sure it works on
9897 : * a copy of the Constraint so transformExpr can't modify the original. It
9898 : * returns a list of cooked constraints.
9899 : *
9900 : * If the constraint ends up getting merged with a pre-existing one, it's
9901 : * omitted from the returned list, which is what we want: we do not need
9902 : * to do any validation work. That can only happen at child tables,
9903 : * though, since we disallow merging at the top level.
9904 : */
9905 11110 : newcons = AddRelationNewConstraints(rel, NIL,
9906 11110 : list_make1(copyObject(constr)),
9907 11110 : recursing || is_readd, /* allow_merge */
9908 11110 : !recursing, /* is_local */
9909 : is_readd, /* is_internal */
9910 11110 : NULL); /* queryString not available
9911 : * here */
9912 :
9913 : /* we don't expect more than one constraint here */
9914 : Assert(list_length(newcons) <= 1);
9915 :
9916 : /* Add each to-be-validated constraint to Phase 3's queue */
9917 21734 : foreach(lcon, newcons)
9918 : {
9919 10762 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
9920 :
9921 10762 : if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
9922 : {
9923 : NewConstraint *newcon;
9924 :
9925 894 : newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
9926 894 : newcon->name = ccon->name;
9927 894 : newcon->contype = ccon->contype;
9928 894 : newcon->qual = ccon->expr;
9929 :
9930 894 : tab->constraints = lappend(tab->constraints, newcon);
9931 : }
9932 :
9933 : /* Save the actually assigned name if it was defaulted */
9934 10762 : if (constr->conname == NULL)
9935 9032 : constr->conname = ccon->name;
9936 :
9937 : /*
9938 : * If adding a valid not-null constraint, set the pg_attribute flag
9939 : * and tell phase 3 to verify existing rows, if needed. For an
9940 : * invalid constraint, just set attnotnull, without queueing
9941 : * verification.
9942 : */
9943 10762 : if (constr->contype == CONSTR_NOTNULL)
9944 9328 : set_attnotnull(wqueue, rel, ccon->attnum,
9945 9328 : !constr->skip_validation,
9946 9328 : !constr->skip_validation);
9947 :
9948 10762 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
9949 : }
9950 :
9951 : /* At this point we must have a locked-down name to use */
9952 : Assert(newcons == NIL || constr->conname != NULL);
9953 :
9954 : /* Advance command counter in case same table is visited multiple times */
9955 10972 : CommandCounterIncrement();
9956 :
9957 : /*
9958 : * If the constraint got merged with an existing constraint, we're done.
9959 : * We mustn't recurse to child tables in this case, because they've
9960 : * already got the constraint, and visiting them again would lead to an
9961 : * incorrect value for coninhcount.
9962 : */
9963 10972 : if (newcons == NIL)
9964 210 : return address;
9965 :
9966 : /*
9967 : * If adding a NO INHERIT constraint, no need to find our children.
9968 : */
9969 10762 : if (constr->is_no_inherit)
9970 84 : return address;
9971 :
9972 : /*
9973 : * Propagate to children as appropriate. Unlike most other ALTER
9974 : * routines, we have to do this one level of recursion at a time; we can't
9975 : * use find_all_inheritors to do it in one pass.
9976 : */
9977 : children =
9978 10678 : find_inheritance_children(RelationGetRelid(rel), lockmode);
9979 :
9980 : /*
9981 : * Check if ONLY was specified with ALTER TABLE. If so, allow the
9982 : * constraint creation only if there are no children currently. Error out
9983 : * otherwise.
9984 : */
9985 10678 : if (!recurse && children != NIL)
9986 6 : ereport(ERROR,
9987 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9988 : errmsg("constraint must be added to child tables too")));
9989 :
9990 : /*
9991 : * Recurse to create the constraint on each child.
9992 : */
9993 11460 : foreach(child, children)
9994 : {
9995 818 : Oid childrelid = lfirst_oid(child);
9996 : Relation childrel;
9997 : AlteredTableInfo *childtab;
9998 :
9999 : /* find_inheritance_children already got lock */
10000 818 : childrel = table_open(childrelid, NoLock);
10001 818 : CheckAlterTableIsSafe(childrel);
10002 :
10003 : /* Find or create work queue entry for this table */
10004 818 : childtab = ATGetQueueEntry(wqueue, childrel);
10005 :
10006 : /* Recurse to this child */
10007 818 : ATAddCheckNNConstraint(wqueue, childtab, childrel,
10008 : constr, recurse, true, is_readd, lockmode);
10009 :
10010 788 : table_close(childrel, NoLock);
10011 : }
10012 :
10013 10642 : return address;
10014 : }
10015 :
10016 : /*
10017 : * Add a foreign-key constraint to a single table; return the new constraint's
10018 : * address.
10019 : *
10020 : * Subroutine for ATExecAddConstraint. Must already hold exclusive
10021 : * lock on the rel, and have done appropriate validity checks for it.
10022 : * We do permissions checks here, however.
10023 : *
10024 : * When the referenced or referencing tables (or both) are partitioned,
10025 : * multiple pg_constraint rows are required -- one for each partitioned table
10026 : * and each partition on each side (fortunately, not one for every combination
10027 : * thereof). We also need action triggers on each leaf partition on the
10028 : * referenced side, and check triggers on each leaf partition on the
10029 : * referencing side.
10030 : */
10031 : static ObjectAddress
10032 2650 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10033 : Constraint *fkconstraint,
10034 : bool recurse, bool recursing, LOCKMODE lockmode)
10035 : {
10036 : Relation pkrel;
10037 2650 : int16 pkattnum[INDEX_MAX_KEYS] = {0};
10038 2650 : int16 fkattnum[INDEX_MAX_KEYS] = {0};
10039 2650 : Oid pktypoid[INDEX_MAX_KEYS] = {0};
10040 2650 : Oid fktypoid[INDEX_MAX_KEYS] = {0};
10041 2650 : Oid pkcolloid[INDEX_MAX_KEYS] = {0};
10042 2650 : Oid fkcolloid[INDEX_MAX_KEYS] = {0};
10043 2650 : Oid opclasses[INDEX_MAX_KEYS] = {0};
10044 2650 : Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
10045 2650 : Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
10046 2650 : Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
10047 2650 : int16 fkdelsetcols[INDEX_MAX_KEYS] = {0};
10048 : bool with_period;
10049 : bool pk_has_without_overlaps;
10050 : int i;
10051 : int numfks,
10052 : numpks,
10053 : numfkdelsetcols;
10054 : Oid indexOid;
10055 : bool old_check_ok;
10056 : ObjectAddress address;
10057 2650 : ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
10058 :
10059 : /*
10060 : * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
10061 : * delete rows out from under us.
10062 : */
10063 2650 : if (OidIsValid(fkconstraint->old_pktable_oid))
10064 72 : pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
10065 : else
10066 2578 : pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
10067 :
10068 : /*
10069 : * Validity checks (permission checks wait till we have the column
10070 : * numbers)
10071 : */
10072 2644 : if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10073 6 : ereport(ERROR,
10074 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
10075 : errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
10076 : RelationGetRelationName(rel),
10077 : RelationGetRelationName(pkrel)));
10078 :
10079 2638 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10080 352 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10081 0 : ereport(ERROR,
10082 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10083 : errmsg("referenced relation \"%s\" is not a table",
10084 : RelationGetRelationName(pkrel))));
10085 :
10086 2638 : if (!allowSystemTableMods && IsSystemRelation(pkrel))
10087 2 : ereport(ERROR,
10088 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10089 : errmsg("permission denied: \"%s\" is a system catalog",
10090 : RelationGetRelationName(pkrel))));
10091 :
10092 : /*
10093 : * References from permanent or unlogged tables to temp tables, and from
10094 : * permanent tables to unlogged tables, are disallowed because the
10095 : * referenced data can vanish out from under us. References from temp
10096 : * tables to any other table type are also disallowed, because other
10097 : * backends might need to run the RI triggers on the perm table, but they
10098 : * can't reliably see tuples in the local buffers of other backends.
10099 : */
10100 2636 : switch (rel->rd_rel->relpersistence)
10101 : {
10102 2346 : case RELPERSISTENCE_PERMANENT:
10103 2346 : if (!RelationIsPermanent(pkrel))
10104 0 : ereport(ERROR,
10105 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10106 : errmsg("constraints on permanent tables may reference only permanent tables")));
10107 2346 : break;
10108 12 : case RELPERSISTENCE_UNLOGGED:
10109 12 : if (!RelationIsPermanent(pkrel)
10110 12 : && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
10111 0 : ereport(ERROR,
10112 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10113 : errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
10114 12 : break;
10115 278 : case RELPERSISTENCE_TEMP:
10116 278 : if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10117 0 : ereport(ERROR,
10118 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10119 : errmsg("constraints on temporary tables may reference only temporary tables")));
10120 278 : if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
10121 0 : ereport(ERROR,
10122 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10123 : errmsg("constraints on temporary tables must involve temporary tables of this session")));
10124 278 : break;
10125 : }
10126 :
10127 : /*
10128 : * Look up the referencing attributes to make sure they exist, and record
10129 : * their attnums and type and collation OIDs.
10130 : */
10131 2636 : numfks = transformColumnNameList(RelationGetRelid(rel),
10132 : fkconstraint->fk_attrs,
10133 : fkattnum, fktypoid, fkcolloid);
10134 2606 : with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
10135 2606 : if (with_period && !fkconstraint->fk_with_period)
10136 24 : ereport(ERROR,
10137 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10138 : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10139 :
10140 2582 : numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
10141 : fkconstraint->fk_del_set_cols,
10142 : fkdelsetcols, NULL, NULL);
10143 2576 : numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
10144 : numfkdelsetcols,
10145 : fkdelsetcols,
10146 : fkconstraint->fk_del_set_cols);
10147 :
10148 : /*
10149 : * If the attribute list for the referenced table was omitted, lookup the
10150 : * definition of the primary key and use it. Otherwise, validate the
10151 : * supplied attribute list. In either case, discover the index OID and
10152 : * index opclasses, and the attnums and type and collation OIDs of the
10153 : * attributes.
10154 : */
10155 2570 : if (fkconstraint->pk_attrs == NIL)
10156 : {
10157 1196 : numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
10158 : &fkconstraint->pk_attrs,
10159 : pkattnum, pktypoid, pkcolloid,
10160 : opclasses, &pk_has_without_overlaps);
10161 :
10162 : /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
10163 1196 : if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
10164 24 : ereport(ERROR,
10165 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10166 : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10167 : }
10168 : else
10169 : {
10170 1374 : numpks = transformColumnNameList(RelationGetRelid(pkrel),
10171 : fkconstraint->pk_attrs,
10172 : pkattnum, pktypoid, pkcolloid);
10173 :
10174 : /* Since we got pk_attrs, one should be a period. */
10175 1344 : if (with_period && !fkconstraint->pk_with_period)
10176 24 : ereport(ERROR,
10177 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10178 : errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
10179 :
10180 : /* Look for an index matching the column list */
10181 1320 : indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
10182 : with_period, opclasses, &pk_has_without_overlaps);
10183 : }
10184 :
10185 : /*
10186 : * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
10187 : * must use PERIOD.
10188 : */
10189 2456 : if (pk_has_without_overlaps && !with_period)
10190 12 : ereport(ERROR,
10191 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10192 : errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
10193 :
10194 : /*
10195 : * Now we can check permissions.
10196 : */
10197 2444 : checkFkeyPermissions(pkrel, pkattnum, numpks);
10198 :
10199 : /*
10200 : * Check some things for generated columns.
10201 : */
10202 5740 : for (i = 0; i < numfks; i++)
10203 : {
10204 3326 : char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
10205 :
10206 3326 : if (attgenerated)
10207 : {
10208 : /*
10209 : * Check restrictions on UPDATE/DELETE actions, per SQL standard
10210 : */
10211 48 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10212 48 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
10213 48 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
10214 12 : ereport(ERROR,
10215 : (errcode(ERRCODE_SYNTAX_ERROR),
10216 : errmsg("invalid %s action for foreign key constraint containing generated column",
10217 : "ON UPDATE")));
10218 36 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10219 24 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10220 12 : ereport(ERROR,
10221 : (errcode(ERRCODE_SYNTAX_ERROR),
10222 : errmsg("invalid %s action for foreign key constraint containing generated column",
10223 : "ON DELETE")));
10224 : }
10225 :
10226 : /*
10227 : * FKs on virtual columns are not supported. This would require
10228 : * various additional support in ri_triggers.c, including special
10229 : * handling in ri_NullCheck(), ri_KeysEqual(),
10230 : * RI_FKey_fk_upd_check_required() (since all virtual columns appear
10231 : * as NULL there). Also not really practical as long as you can't
10232 : * index virtual columns.
10233 : */
10234 3302 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
10235 6 : ereport(ERROR,
10236 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10237 : errmsg("foreign key constraints on virtual generated columns are not supported")));
10238 : }
10239 :
10240 : /*
10241 : * Some actions are currently unsupported for foreign keys using PERIOD.
10242 : */
10243 2414 : if (fkconstraint->fk_with_period)
10244 : {
10245 248 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
10246 236 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
10247 218 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10248 200 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
10249 66 : ereport(ERROR,
10250 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10251 : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10252 : "ON UPDATE"));
10253 :
10254 182 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
10255 176 : fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
10256 176 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10257 176 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10258 6 : ereport(ERROR,
10259 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10260 : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10261 : "ON DELETE"));
10262 : }
10263 :
10264 : /*
10265 : * Look up the equality operators to use in the constraint.
10266 : *
10267 : * Note that we have to be careful about the difference between the actual
10268 : * PK column type and the opclass' declared input type, which might be
10269 : * only binary-compatible with it. The declared opcintype is the right
10270 : * thing to probe pg_amop with.
10271 : */
10272 2342 : if (numfks != numpks)
10273 0 : ereport(ERROR,
10274 : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
10275 : errmsg("number of referencing and referenced columns for foreign key disagree")));
10276 :
10277 : /*
10278 : * On the strength of a previous constraint, we might avoid scanning
10279 : * tables to validate this one. See below.
10280 : */
10281 2342 : old_check_ok = (fkconstraint->old_conpfeqop != NIL);
10282 : Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
10283 :
10284 5110 : for (i = 0; i < numpks; i++)
10285 : {
10286 3008 : Oid pktype = pktypoid[i];
10287 3008 : Oid fktype = fktypoid[i];
10288 : Oid fktyped;
10289 3008 : Oid pkcoll = pkcolloid[i];
10290 3008 : Oid fkcoll = fkcolloid[i];
10291 : HeapTuple cla_ht;
10292 : Form_pg_opclass cla_tup;
10293 : Oid amid;
10294 : Oid opfamily;
10295 : Oid opcintype;
10296 : bool for_overlaps;
10297 : CompareType cmptype;
10298 : Oid pfeqop;
10299 : Oid ppeqop;
10300 : Oid ffeqop;
10301 : int16 eqstrategy;
10302 : Oid pfeqop_right;
10303 :
10304 : /* We need several fields out of the pg_opclass entry */
10305 3008 : cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
10306 3008 : if (!HeapTupleIsValid(cla_ht))
10307 0 : elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
10308 3008 : cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
10309 3008 : amid = cla_tup->opcmethod;
10310 3008 : opfamily = cla_tup->opcfamily;
10311 3008 : opcintype = cla_tup->opcintype;
10312 3008 : ReleaseSysCache(cla_ht);
10313 :
10314 : /*
10315 : * Get strategy number from index AM.
10316 : *
10317 : * For a normal foreign-key constraint, this should not fail, since we
10318 : * already checked that the index is unique and should therefore have
10319 : * appropriate equal operators. For a period foreign key, this could
10320 : * fail if we selected a non-matching exclusion constraint earlier.
10321 : * (XXX Maybe we should do these lookups earlier so we don't end up
10322 : * doing that.)
10323 : */
10324 3008 : for_overlaps = with_period && i == numpks - 1;
10325 3008 : cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
10326 3008 : eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
10327 3008 : if (eqstrategy == InvalidStrategy)
10328 0 : ereport(ERROR,
10329 : errcode(ERRCODE_UNDEFINED_OBJECT),
10330 : for_overlaps
10331 : ? errmsg("could not identify an overlaps operator for foreign key")
10332 : : errmsg("could not identify an equality operator for foreign key"),
10333 : errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
10334 : cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
10335 :
10336 : /*
10337 : * There had better be a primary equality operator for the index.
10338 : * We'll use it for PK = PK comparisons.
10339 : */
10340 3008 : ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
10341 : eqstrategy);
10342 :
10343 3008 : if (!OidIsValid(ppeqop))
10344 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
10345 : eqstrategy, opcintype, opcintype, opfamily);
10346 :
10347 : /*
10348 : * Are there equality operators that take exactly the FK type? Assume
10349 : * we should look through any domain here.
10350 : */
10351 3008 : fktyped = getBaseType(fktype);
10352 :
10353 3008 : pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
10354 : eqstrategy);
10355 3008 : if (OidIsValid(pfeqop))
10356 : {
10357 2368 : pfeqop_right = fktyped;
10358 2368 : ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
10359 : eqstrategy);
10360 : }
10361 : else
10362 : {
10363 : /* keep compiler quiet */
10364 640 : pfeqop_right = InvalidOid;
10365 640 : ffeqop = InvalidOid;
10366 : }
10367 :
10368 3008 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10369 : {
10370 : /*
10371 : * Otherwise, look for an implicit cast from the FK type to the
10372 : * opcintype, and if found, use the primary equality operator.
10373 : * This is a bit tricky because opcintype might be a polymorphic
10374 : * type such as ANYARRAY or ANYENUM; so what we have to test is
10375 : * whether the two actual column types can be concurrently cast to
10376 : * that type. (Otherwise, we'd fail to reject combinations such
10377 : * as int[] and point[].)
10378 : */
10379 : Oid input_typeids[2];
10380 : Oid target_typeids[2];
10381 :
10382 640 : input_typeids[0] = pktype;
10383 640 : input_typeids[1] = fktype;
10384 640 : target_typeids[0] = opcintype;
10385 640 : target_typeids[1] = opcintype;
10386 640 : if (can_coerce_type(2, input_typeids, target_typeids,
10387 : COERCION_IMPLICIT))
10388 : {
10389 412 : pfeqop = ffeqop = ppeqop;
10390 412 : pfeqop_right = opcintype;
10391 : }
10392 : }
10393 :
10394 3008 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10395 228 : ereport(ERROR,
10396 : (errcode(ERRCODE_DATATYPE_MISMATCH),
10397 : errmsg("foreign key constraint \"%s\" cannot be implemented",
10398 : fkconstraint->conname),
10399 : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10400 : "are of incompatible types: %s and %s.",
10401 : strVal(list_nth(fkconstraint->fk_attrs, i)),
10402 : strVal(list_nth(fkconstraint->pk_attrs, i)),
10403 : format_type_be(fktype),
10404 : format_type_be(pktype))));
10405 :
10406 : /*
10407 : * This shouldn't be possible, but better check to make sure we have a
10408 : * consistent state for the check below.
10409 : */
10410 2780 : if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
10411 0 : elog(ERROR, "key columns are not both collatable");
10412 :
10413 2780 : if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
10414 : {
10415 : bool pkcolldet;
10416 : bool fkcolldet;
10417 :
10418 106 : pkcolldet = get_collation_isdeterministic(pkcoll);
10419 106 : fkcolldet = get_collation_isdeterministic(fkcoll);
10420 :
10421 : /*
10422 : * SQL requires that both collations are the same. This is
10423 : * because we need a consistent notion of equality on both
10424 : * columns. We relax this by allowing different collations if
10425 : * they are both deterministic. (This is also for backward
10426 : * compatibility, because PostgreSQL has always allowed this.)
10427 : */
10428 106 : if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
10429 12 : ereport(ERROR,
10430 : (errcode(ERRCODE_COLLATION_MISMATCH),
10431 : errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
10432 : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10433 : "have incompatible collations: \"%s\" and \"%s\". "
10434 : "If either collation is nondeterministic, then both collations have to be the same.",
10435 : strVal(list_nth(fkconstraint->fk_attrs, i)),
10436 : strVal(list_nth(fkconstraint->pk_attrs, i)),
10437 : get_collation_name(fkcoll),
10438 : get_collation_name(pkcoll))));
10439 : }
10440 :
10441 2768 : if (old_check_ok)
10442 : {
10443 : /*
10444 : * When a pfeqop changes, revalidate the constraint. We could
10445 : * permit intra-opfamily changes, but that adds subtle complexity
10446 : * without any concrete benefit for core types. We need not
10447 : * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
10448 : */
10449 6 : old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
10450 6 : old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
10451 : old_pfeqop_item);
10452 : }
10453 2768 : if (old_check_ok)
10454 : {
10455 : Oid old_fktype;
10456 : Oid new_fktype;
10457 : CoercionPathType old_pathtype;
10458 : CoercionPathType new_pathtype;
10459 : Oid old_castfunc;
10460 : Oid new_castfunc;
10461 : Oid old_fkcoll;
10462 : Oid new_fkcoll;
10463 6 : Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
10464 6 : fkattnum[i] - 1);
10465 :
10466 : /*
10467 : * Identify coercion pathways from each of the old and new FK-side
10468 : * column types to the right (foreign) operand type of the pfeqop.
10469 : * We may assume that pg_constraint.conkey is not changing.
10470 : */
10471 6 : old_fktype = attr->atttypid;
10472 6 : new_fktype = fktype;
10473 6 : old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
10474 : &old_castfunc);
10475 6 : new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
10476 : &new_castfunc);
10477 :
10478 6 : old_fkcoll = attr->attcollation;
10479 6 : new_fkcoll = fkcoll;
10480 :
10481 : /*
10482 : * Upon a change to the cast from the FK column to its pfeqop
10483 : * operand, revalidate the constraint. For this evaluation, a
10484 : * binary coercion cast is equivalent to no cast at all. While
10485 : * type implementors should design implicit casts with an eye
10486 : * toward consistency of operations like equality, we cannot
10487 : * assume here that they have done so.
10488 : *
10489 : * A function with a polymorphic argument could change behavior
10490 : * arbitrarily in response to get_fn_expr_argtype(). Therefore,
10491 : * when the cast destination is polymorphic, we only avoid
10492 : * revalidation if the input type has not changed at all. Given
10493 : * just the core data types and operator classes, this requirement
10494 : * prevents no would-be optimizations.
10495 : *
10496 : * If the cast converts from a base type to a domain thereon, then
10497 : * that domain type must be the opcintype of the unique index.
10498 : * Necessarily, the primary key column must then be of the domain
10499 : * type. Since the constraint was previously valid, all values on
10500 : * the foreign side necessarily exist on the primary side and in
10501 : * turn conform to the domain. Consequently, we need not treat
10502 : * domains specially here.
10503 : *
10504 : * If the collation changes, revalidation is required, unless both
10505 : * collations are deterministic, because those share the same
10506 : * notion of equality (because texteq reduces to bitwise
10507 : * equality).
10508 : *
10509 : * We need not directly consider the PK type. It's necessarily
10510 : * binary coercible to the opcintype of the unique index column,
10511 : * and ri_triggers.c will only deal with PK datums in terms of
10512 : * that opcintype. Changing the opcintype also changes pfeqop.
10513 : */
10514 6 : old_check_ok = (new_pathtype == old_pathtype &&
10515 6 : new_castfunc == old_castfunc &&
10516 6 : (!IsPolymorphicType(pfeqop_right) ||
10517 12 : new_fktype == old_fktype) &&
10518 0 : (new_fkcoll == old_fkcoll ||
10519 0 : (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
10520 : }
10521 :
10522 2768 : pfeqoperators[i] = pfeqop;
10523 2768 : ppeqoperators[i] = ppeqop;
10524 2768 : ffeqoperators[i] = ffeqop;
10525 : }
10526 :
10527 : /*
10528 : * For FKs with PERIOD we need additional operators to check whether the
10529 : * referencing row's range is contained by the aggregated ranges of the
10530 : * referenced row(s). For rangetypes and multirangetypes this is
10531 : * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
10532 : * support for now. FKs will look these up at "runtime", but we should
10533 : * make sure the lookup works here, even if we don't use the values.
10534 : */
10535 2102 : if (with_period)
10536 : {
10537 : Oid periodoperoid;
10538 : Oid aggedperiodoperoid;
10539 : Oid intersectoperoid;
10540 :
10541 158 : FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
10542 : &intersectoperoid);
10543 : }
10544 :
10545 : /* First, create the constraint catalog entry itself. */
10546 2102 : address = addFkConstraint(addFkBothSides,
10547 : fkconstraint->conname, fkconstraint, rel, pkrel,
10548 : indexOid,
10549 : InvalidOid, /* no parent constraint */
10550 : numfks,
10551 : pkattnum,
10552 : fkattnum,
10553 : pfeqoperators,
10554 : ppeqoperators,
10555 : ffeqoperators,
10556 : numfkdelsetcols,
10557 : fkdelsetcols,
10558 : false,
10559 : with_period);
10560 :
10561 : /* Next process the action triggers at the referenced side and recurse */
10562 2102 : addFkRecurseReferenced(fkconstraint, rel, pkrel,
10563 : indexOid,
10564 : address.objectId,
10565 : numfks,
10566 : pkattnum,
10567 : fkattnum,
10568 : pfeqoperators,
10569 : ppeqoperators,
10570 : ffeqoperators,
10571 : numfkdelsetcols,
10572 : fkdelsetcols,
10573 : old_check_ok,
10574 : InvalidOid, InvalidOid,
10575 : with_period);
10576 :
10577 : /* Lastly create the check triggers at the referencing side and recurse */
10578 2102 : addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
10579 : indexOid,
10580 : address.objectId,
10581 : numfks,
10582 : pkattnum,
10583 : fkattnum,
10584 : pfeqoperators,
10585 : ppeqoperators,
10586 : ffeqoperators,
10587 : numfkdelsetcols,
10588 : fkdelsetcols,
10589 : old_check_ok,
10590 : lockmode,
10591 : InvalidOid, InvalidOid,
10592 : with_period);
10593 :
10594 : /*
10595 : * Done. Close pk table, but keep lock until we've committed.
10596 : */
10597 2102 : table_close(pkrel, NoLock);
10598 :
10599 2102 : return address;
10600 : }
10601 :
10602 : /*
10603 : * validateFkOnDeleteSetColumns
10604 : * Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
10605 : * column lists are valid.
10606 : *
10607 : * If there are duplicates in the fksetcolsattnums[] array, this silently
10608 : * removes the dups. The new count of numfksetcols is returned.
10609 : */
10610 : static int
10611 2576 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
10612 : int numfksetcols, int16 *fksetcolsattnums,
10613 : List *fksetcols)
10614 : {
10615 2576 : int numcolsout = 0;
10616 :
10617 2606 : for (int i = 0; i < numfksetcols; i++)
10618 : {
10619 36 : int16 setcol_attnum = fksetcolsattnums[i];
10620 36 : bool seen = false;
10621 :
10622 : /* Make sure it's in fkattnums[] */
10623 66 : for (int j = 0; j < numfks; j++)
10624 : {
10625 60 : if (fkattnums[j] == setcol_attnum)
10626 : {
10627 30 : seen = true;
10628 30 : break;
10629 : }
10630 : }
10631 :
10632 36 : if (!seen)
10633 : {
10634 6 : char *col = strVal(list_nth(fksetcols, i));
10635 :
10636 6 : ereport(ERROR,
10637 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
10638 : errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
10639 : }
10640 :
10641 : /* Now check for dups */
10642 30 : seen = false;
10643 30 : for (int j = 0; j < numcolsout; j++)
10644 : {
10645 6 : if (fksetcolsattnums[j] == setcol_attnum)
10646 : {
10647 6 : seen = true;
10648 6 : break;
10649 : }
10650 : }
10651 30 : if (!seen)
10652 24 : fksetcolsattnums[numcolsout++] = setcol_attnum;
10653 : }
10654 2570 : return numcolsout;
10655 : }
10656 :
10657 : /*
10658 : * addFkConstraint
10659 : * Install pg_constraint entries to implement a foreign key constraint.
10660 : * Caller must separately invoke addFkRecurseReferenced and
10661 : * addFkRecurseReferencing, as appropriate, to install pg_trigger entries
10662 : * and (for partitioned tables) recurse to partitions.
10663 : *
10664 : * fkside: the side of the FK (or both) to create. Caller should
10665 : * call addFkRecurseReferenced if this is addFkReferencedSide,
10666 : * addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
10667 : * addFkBothSides.
10668 : * constraintname: the base name for the constraint being added,
10669 : * copied to fkconstraint->conname if the latter is not set
10670 : * fkconstraint: the constraint being added
10671 : * rel: the root referencing relation
10672 : * pkrel: the referenced relation; might be a partition, if recursing
10673 : * indexOid: the OID of the index (on pkrel) implementing this constraint
10674 : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10675 : * top-level constraint
10676 : * numfks: the number of columns in the foreign key
10677 : * pkattnum: the attnum array of referenced attributes
10678 : * fkattnum: the attnum array of referencing attributes
10679 : * pf/pp/ffeqoperators: OID array of operators between columns
10680 : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
10681 : * (...) clause
10682 : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10683 : * NULL/DEFAULT clause
10684 : * with_period: true if this is a temporal FK
10685 : */
10686 : static ObjectAddress
10687 4146 : addFkConstraint(addFkConstraintSides fkside,
10688 : char *constraintname, Constraint *fkconstraint,
10689 : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
10690 : int numfks, int16 *pkattnum,
10691 : int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
10692 : Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
10693 : bool is_internal, bool with_period)
10694 : {
10695 : ObjectAddress address;
10696 : Oid constrOid;
10697 : char *conname;
10698 : bool conislocal;
10699 : int16 coninhcount;
10700 : bool connoinherit;
10701 :
10702 : /*
10703 : * Verify relkind for each referenced partition. At the top level, this
10704 : * is redundant with a previous check, but we need it when recursing.
10705 : */
10706 4146 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10707 904 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10708 0 : ereport(ERROR,
10709 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10710 : errmsg("referenced relation \"%s\" is not a table",
10711 : RelationGetRelationName(pkrel))));
10712 :
10713 : /*
10714 : * Caller supplies us with a constraint name; however, it may be used in
10715 : * this partition, so come up with a different one in that case. Unless
10716 : * truncation to NAMEDATALEN dictates otherwise, the new name will be the
10717 : * supplied name with an underscore and digit(s) appended.
10718 : */
10719 4146 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
10720 : RelationGetRelid(rel),
10721 : constraintname))
10722 1208 : conname = ChooseConstraintName(constraintname,
10723 : NULL,
10724 : "",
10725 1208 : RelationGetNamespace(rel), NIL);
10726 : else
10727 2938 : conname = constraintname;
10728 :
10729 4146 : if (fkconstraint->conname == NULL)
10730 424 : fkconstraint->conname = pstrdup(conname);
10731 :
10732 4146 : if (OidIsValid(parentConstr))
10733 : {
10734 2044 : conislocal = false;
10735 2044 : coninhcount = 1;
10736 2044 : connoinherit = false;
10737 : }
10738 : else
10739 : {
10740 2102 : conislocal = true;
10741 2102 : coninhcount = 0;
10742 :
10743 : /*
10744 : * always inherit for partitioned tables, never for legacy inheritance
10745 : */
10746 2102 : connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
10747 : }
10748 :
10749 : /*
10750 : * Record the FK constraint in pg_constraint.
10751 : */
10752 4146 : constrOid = CreateConstraintEntry(conname,
10753 4146 : RelationGetNamespace(rel),
10754 : CONSTRAINT_FOREIGN,
10755 4146 : fkconstraint->deferrable,
10756 4146 : fkconstraint->initdeferred,
10757 4146 : fkconstraint->is_enforced,
10758 4146 : fkconstraint->initially_valid,
10759 : parentConstr,
10760 : RelationGetRelid(rel),
10761 : fkattnum,
10762 : numfks,
10763 : numfks,
10764 : InvalidOid, /* not a domain constraint */
10765 : indexOid,
10766 : RelationGetRelid(pkrel),
10767 : pkattnum,
10768 : pfeqoperators,
10769 : ppeqoperators,
10770 : ffeqoperators,
10771 : numfks,
10772 4146 : fkconstraint->fk_upd_action,
10773 4146 : fkconstraint->fk_del_action,
10774 : fkdelsetcols,
10775 : numfkdelsetcols,
10776 4146 : fkconstraint->fk_matchtype,
10777 : NULL, /* no exclusion constraint */
10778 : NULL, /* no check constraint */
10779 : NULL,
10780 : conislocal, /* islocal */
10781 : coninhcount, /* inhcount */
10782 : connoinherit, /* conNoInherit */
10783 : with_period, /* conPeriod */
10784 : is_internal); /* is_internal */
10785 :
10786 4146 : ObjectAddressSet(address, ConstraintRelationId, constrOid);
10787 :
10788 : /*
10789 : * In partitioning cases, create the dependency entries for this
10790 : * constraint. (For non-partitioned cases, relevant entries were created
10791 : * by CreateConstraintEntry.)
10792 : *
10793 : * On the referenced side, we need the constraint to have an internal
10794 : * dependency on its parent constraint; this means that this constraint
10795 : * cannot be dropped on its own -- only through the parent constraint. It
10796 : * also means the containing partition cannot be dropped on its own, but
10797 : * it can be detached, at which point this dependency is removed (after
10798 : * verifying that no rows are referenced via this FK.)
10799 : *
10800 : * When processing the referencing side, we link the constraint via the
10801 : * special partitioning dependencies: the parent constraint is the primary
10802 : * dependent, and the partition on which the foreign key exists is the
10803 : * secondary dependency. That way, this constraint is dropped if either
10804 : * of these objects is.
10805 : *
10806 : * Note that this is only necessary for the subsidiary pg_constraint rows
10807 : * in partitions; the topmost row doesn't need any of this.
10808 : */
10809 4146 : if (OidIsValid(parentConstr))
10810 : {
10811 : ObjectAddress referenced;
10812 :
10813 2044 : ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
10814 :
10815 : Assert(fkside != addFkBothSides);
10816 2044 : if (fkside == addFkReferencedSide)
10817 1202 : recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
10818 : else
10819 : {
10820 842 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
10821 842 : ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
10822 842 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
10823 : }
10824 : }
10825 :
10826 : /* make new constraint visible, in case we add more */
10827 4146 : CommandCounterIncrement();
10828 :
10829 4146 : return address;
10830 : }
10831 :
10832 : /*
10833 : * addFkRecurseReferenced
10834 : * Recursive helper for the referenced side of foreign key creation,
10835 : * which creates the action triggers and recurses
10836 : *
10837 : * If the referenced relation is a plain relation, create the necessary action
10838 : * triggers that implement the constraint. If the referenced relation is a
10839 : * partitioned table, then we create a pg_constraint row referencing the parent
10840 : * of the referencing side for it and recurse on this routine for each
10841 : * partition.
10842 : *
10843 : * fkconstraint: the constraint being added
10844 : * rel: the root referencing relation
10845 : * pkrel: the referenced relation; might be a partition, if recursing
10846 : * indexOid: the OID of the index (on pkrel) implementing this constraint
10847 : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10848 : * top-level constraint
10849 : * numfks: the number of columns in the foreign key
10850 : * pkattnum: the attnum array of referenced attributes
10851 : * fkattnum: the attnum array of referencing attributes
10852 : * numfkdelsetcols: the number of columns in the ON DELETE SET
10853 : * NULL/DEFAULT (...) clause
10854 : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10855 : * NULL/DEFAULT clause
10856 : * pf/pp/ffeqoperators: OID array of operators between columns
10857 : * old_check_ok: true if this constraint replaces an existing one that
10858 : * was already validated (thus this one doesn't need validation)
10859 : * parentDelTrigger and parentUpdTrigger: when recursively called on a
10860 : * partition, the OIDs of the parent action triggers for DELETE and
10861 : * UPDATE respectively.
10862 : * with_period: true if this is a temporal FK
10863 : */
10864 : static void
10865 3406 : addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
10866 : Relation pkrel, Oid indexOid, Oid parentConstr,
10867 : int numfks,
10868 : int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
10869 : Oid *ppeqoperators, Oid *ffeqoperators,
10870 : int numfkdelsetcols, int16 *fkdelsetcols,
10871 : bool old_check_ok,
10872 : Oid parentDelTrigger, Oid parentUpdTrigger,
10873 : bool with_period)
10874 : {
10875 3406 : Oid deleteTriggerOid = InvalidOid,
10876 3406 : updateTriggerOid = InvalidOid;
10877 :
10878 : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
10879 : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
10880 :
10881 : /*
10882 : * Create action triggers to enforce the constraint, or skip them if the
10883 : * constraint is NOT ENFORCED.
10884 : */
10885 3406 : if (fkconstraint->is_enforced)
10886 3358 : createForeignKeyActionTriggers(RelationGetRelid(rel),
10887 : RelationGetRelid(pkrel),
10888 : fkconstraint,
10889 : parentConstr, indexOid,
10890 : parentDelTrigger, parentUpdTrigger,
10891 : &deleteTriggerOid, &updateTriggerOid);
10892 :
10893 : /*
10894 : * If the referenced table is partitioned, recurse on ourselves to handle
10895 : * each partition. We need one pg_constraint row created for each
10896 : * partition in addition to the pg_constraint row for the parent table.
10897 : */
10898 3406 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10899 : {
10900 570 : PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
10901 :
10902 1550 : for (int i = 0; i < pd->nparts; i++)
10903 : {
10904 : Relation partRel;
10905 : AttrMap *map;
10906 : AttrNumber *mapped_pkattnum;
10907 : Oid partIndexId;
10908 : ObjectAddress address;
10909 :
10910 : /* XXX would it be better to acquire these locks beforehand? */
10911 980 : partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
10912 :
10913 : /*
10914 : * Map the attribute numbers in the referenced side of the FK
10915 : * definition to match the partition's column layout.
10916 : */
10917 980 : map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
10918 : RelationGetDescr(pkrel),
10919 : false);
10920 980 : if (map)
10921 : {
10922 130 : mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
10923 272 : for (int j = 0; j < numfks; j++)
10924 142 : mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
10925 : }
10926 : else
10927 850 : mapped_pkattnum = pkattnum;
10928 :
10929 : /* Determine the index to use at this level */
10930 980 : partIndexId = index_get_partition(partRel, indexOid);
10931 980 : if (!OidIsValid(partIndexId))
10932 0 : elog(ERROR, "index for %u not found in partition %s",
10933 : indexOid, RelationGetRelationName(partRel));
10934 :
10935 : /* Create entry at this level ... */
10936 980 : address = addFkConstraint(addFkReferencedSide,
10937 : fkconstraint->conname, fkconstraint, rel,
10938 : partRel, partIndexId, parentConstr,
10939 : numfks, mapped_pkattnum,
10940 : fkattnum, pfeqoperators, ppeqoperators,
10941 : ffeqoperators, numfkdelsetcols,
10942 : fkdelsetcols, true, with_period);
10943 : /* ... and recurse to our children */
10944 980 : addFkRecurseReferenced(fkconstraint, rel, partRel,
10945 : partIndexId, address.objectId, numfks,
10946 : mapped_pkattnum, fkattnum,
10947 : pfeqoperators, ppeqoperators, ffeqoperators,
10948 : numfkdelsetcols, fkdelsetcols,
10949 : old_check_ok,
10950 : deleteTriggerOid, updateTriggerOid,
10951 : with_period);
10952 :
10953 : /* Done -- clean up (but keep the lock) */
10954 980 : table_close(partRel, NoLock);
10955 980 : if (map)
10956 : {
10957 130 : pfree(mapped_pkattnum);
10958 130 : free_attrmap(map);
10959 : }
10960 : }
10961 : }
10962 3406 : }
10963 :
10964 : /*
10965 : * addFkRecurseReferencing
10966 : * Recursive helper for the referencing side of foreign key creation,
10967 : * which creates the check triggers and recurses
10968 : *
10969 : * If the referencing relation is a plain relation, create the necessary check
10970 : * triggers that implement the constraint, and set up for Phase 3 constraint
10971 : * verification. If the referencing relation is a partitioned table, then
10972 : * we create a pg_constraint row for it and recurse on this routine for each
10973 : * partition.
10974 : *
10975 : * We assume that the referenced relation is locked against concurrent
10976 : * deletions. If it's a partitioned relation, every partition must be so
10977 : * locked.
10978 : *
10979 : * wqueue: the ALTER TABLE work queue; NULL when not running as part
10980 : * of an ALTER TABLE sequence.
10981 : * fkconstraint: the constraint being added
10982 : * rel: the referencing relation; might be a partition, if recursing
10983 : * pkrel: the root referenced relation
10984 : * indexOid: the OID of the index (on pkrel) implementing this constraint
10985 : * parentConstr: the OID of the parent constraint (there is always one)
10986 : * numfks: the number of columns in the foreign key
10987 : * pkattnum: the attnum array of referenced attributes
10988 : * fkattnum: the attnum array of referencing attributes
10989 : * pf/pp/ffeqoperators: OID array of operators between columns
10990 : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
10991 : * (...) clause
10992 : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10993 : * NULL/DEFAULT clause
10994 : * old_check_ok: true if this constraint replaces an existing one that
10995 : * was already validated (thus this one doesn't need validation)
10996 : * lockmode: the lockmode to acquire on partitions when recursing
10997 : * parentInsTrigger and parentUpdTrigger: when being recursively called on
10998 : * a partition, the OIDs of the parent check triggers for INSERT and
10999 : * UPDATE respectively.
11000 : * with_period: true if this is a temporal FK
11001 : */
11002 : static void
11003 2944 : addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
11004 : Relation pkrel, Oid indexOid, Oid parentConstr,
11005 : int numfks, int16 *pkattnum, int16 *fkattnum,
11006 : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
11007 : int numfkdelsetcols, int16 *fkdelsetcols,
11008 : bool old_check_ok, LOCKMODE lockmode,
11009 : Oid parentInsTrigger, Oid parentUpdTrigger,
11010 : bool with_period)
11011 : {
11012 2944 : Oid insertTriggerOid = InvalidOid,
11013 2944 : updateTriggerOid = InvalidOid;
11014 :
11015 : Assert(OidIsValid(parentConstr));
11016 : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11017 : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11018 :
11019 2944 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11020 0 : ereport(ERROR,
11021 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11022 : errmsg("foreign key constraints are not supported on foreign tables")));
11023 :
11024 : /*
11025 : * Add check triggers if the constraint is ENFORCED, and if needed,
11026 : * schedule them to be checked in Phase 3.
11027 : *
11028 : * If the relation is partitioned, drill down to do it to its partitions.
11029 : */
11030 2944 : if (fkconstraint->is_enforced)
11031 2902 : createForeignKeyCheckTriggers(RelationGetRelid(rel),
11032 : RelationGetRelid(pkrel),
11033 : fkconstraint,
11034 : parentConstr,
11035 : indexOid,
11036 : parentInsTrigger, parentUpdTrigger,
11037 : &insertTriggerOid, &updateTriggerOid);
11038 :
11039 2944 : if (rel->rd_rel->relkind == RELKIND_RELATION)
11040 : {
11041 : /*
11042 : * Tell Phase 3 to check that the constraint is satisfied by existing
11043 : * rows. We can skip this during table creation, when constraint is
11044 : * specified as NOT ENFORCED, or when requested explicitly by
11045 : * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
11046 : * recreating a constraint following a SET DATA TYPE operation that
11047 : * did not impugn its validity.
11048 : */
11049 2444 : if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
11050 836 : fkconstraint->is_enforced)
11051 : {
11052 : NewConstraint *newcon;
11053 : AlteredTableInfo *tab;
11054 :
11055 836 : tab = ATGetQueueEntry(wqueue, rel);
11056 :
11057 836 : newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
11058 836 : newcon->name = get_constraint_name(parentConstr);
11059 836 : newcon->contype = CONSTR_FOREIGN;
11060 836 : newcon->refrelid = RelationGetRelid(pkrel);
11061 836 : newcon->refindid = indexOid;
11062 836 : newcon->conid = parentConstr;
11063 836 : newcon->conwithperiod = fkconstraint->fk_with_period;
11064 836 : newcon->qual = (Node *) fkconstraint;
11065 :
11066 836 : tab->constraints = lappend(tab->constraints, newcon);
11067 : }
11068 : }
11069 500 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11070 : {
11071 500 : PartitionDesc pd = RelationGetPartitionDesc(rel, true);
11072 : Relation trigrel;
11073 :
11074 : /*
11075 : * Triggers of the foreign keys will be manipulated a bunch of times
11076 : * in the loop below. To avoid repeatedly opening/closing the trigger
11077 : * catalog relation, we open it here and pass it to the subroutines
11078 : * called below.
11079 : */
11080 500 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11081 :
11082 : /*
11083 : * Recurse to take appropriate action on each partition; either we
11084 : * find an existing constraint to reparent to ours, or we create a new
11085 : * one.
11086 : */
11087 930 : for (int i = 0; i < pd->nparts; i++)
11088 : {
11089 436 : Relation partition = table_open(pd->oids[i], lockmode);
11090 : List *partFKs;
11091 : AttrMap *attmap;
11092 : AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
11093 : bool attached;
11094 : ObjectAddress address;
11095 :
11096 436 : CheckAlterTableIsSafe(partition);
11097 :
11098 430 : attmap = build_attrmap_by_name(RelationGetDescr(partition),
11099 : RelationGetDescr(rel),
11100 : false);
11101 1106 : for (int j = 0; j < numfks; j++)
11102 676 : mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
11103 :
11104 : /* Check whether an existing constraint can be repurposed */
11105 430 : partFKs = copyObject(RelationGetFKeyList(partition));
11106 430 : attached = false;
11107 884 : foreach_node(ForeignKeyCacheInfo, fk, partFKs)
11108 : {
11109 36 : if (tryAttachPartitionForeignKey(wqueue,
11110 : fk,
11111 : partition,
11112 : parentConstr,
11113 : numfks,
11114 : mapped_fkattnum,
11115 : pkattnum,
11116 : pfeqoperators,
11117 : insertTriggerOid,
11118 : updateTriggerOid,
11119 : trigrel))
11120 : {
11121 12 : attached = true;
11122 12 : break;
11123 : }
11124 : }
11125 430 : if (attached)
11126 : {
11127 12 : table_close(partition, NoLock);
11128 12 : continue;
11129 : }
11130 :
11131 : /*
11132 : * No luck finding a good constraint to reuse; create our own.
11133 : */
11134 418 : address = addFkConstraint(addFkReferencingSide,
11135 : fkconstraint->conname, fkconstraint,
11136 : partition, pkrel, indexOid, parentConstr,
11137 : numfks, pkattnum,
11138 : mapped_fkattnum, pfeqoperators,
11139 : ppeqoperators, ffeqoperators,
11140 : numfkdelsetcols, fkdelsetcols, true,
11141 : with_period);
11142 :
11143 : /* call ourselves to finalize the creation and we're done */
11144 418 : addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
11145 : indexOid,
11146 : address.objectId,
11147 : numfks,
11148 : pkattnum,
11149 : mapped_fkattnum,
11150 : pfeqoperators,
11151 : ppeqoperators,
11152 : ffeqoperators,
11153 : numfkdelsetcols,
11154 : fkdelsetcols,
11155 : old_check_ok,
11156 : lockmode,
11157 : insertTriggerOid,
11158 : updateTriggerOid,
11159 : with_period);
11160 :
11161 418 : table_close(partition, NoLock);
11162 : }
11163 :
11164 494 : table_close(trigrel, RowExclusiveLock);
11165 : }
11166 2938 : }
11167 :
11168 : /*
11169 : * CloneForeignKeyConstraints
11170 : * Clone foreign keys from a partitioned table to a newly acquired
11171 : * partition.
11172 : *
11173 : * partitionRel is a partition of parentRel, so we can be certain that it has
11174 : * the same columns with the same datatypes. The columns may be in different
11175 : * order, though.
11176 : *
11177 : * wqueue must be passed to set up phase 3 constraint checking, unless the
11178 : * referencing-side partition is known to be empty (such as in CREATE TABLE /
11179 : * PARTITION OF).
11180 : */
11181 : static void
11182 9980 : CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
11183 : Relation partitionRel)
11184 : {
11185 : /* This only works for declarative partitioning */
11186 : Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
11187 :
11188 : /*
11189 : * First, clone constraints where the parent is on the referencing side.
11190 : */
11191 9980 : CloneFkReferencing(wqueue, parentRel, partitionRel);
11192 :
11193 : /*
11194 : * Clone constraints for which the parent is on the referenced side.
11195 : */
11196 9962 : CloneFkReferenced(parentRel, partitionRel);
11197 9962 : }
11198 :
11199 : /*
11200 : * CloneFkReferenced
11201 : * Subroutine for CloneForeignKeyConstraints
11202 : *
11203 : * Find all the FKs that have the parent relation on the referenced side;
11204 : * clone those constraints to the given partition. This is to be called
11205 : * when the partition is being created or attached.
11206 : *
11207 : * This recurses to partitions, if the relation being attached is partitioned.
11208 : * Recursion is done by calling addFkRecurseReferenced.
11209 : */
11210 : static void
11211 9962 : CloneFkReferenced(Relation parentRel, Relation partitionRel)
11212 : {
11213 : Relation pg_constraint;
11214 : AttrMap *attmap;
11215 : ListCell *cell;
11216 : SysScanDesc scan;
11217 : ScanKeyData key[2];
11218 : HeapTuple tuple;
11219 9962 : List *clone = NIL;
11220 : Relation trigrel;
11221 :
11222 : /*
11223 : * Search for any constraints where this partition's parent is in the
11224 : * referenced side. However, we must not clone any constraint whose
11225 : * parent constraint is also going to be cloned, to avoid duplicates. So
11226 : * do it in two steps: first construct the list of constraints to clone,
11227 : * then go over that list cloning those whose parents are not in the list.
11228 : * (We must not rely on the parent being seen first, since the catalog
11229 : * scan could return children first.)
11230 : */
11231 9962 : pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11232 9962 : ScanKeyInit(&key[0],
11233 : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
11234 : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
11235 9962 : ScanKeyInit(&key[1],
11236 : Anum_pg_constraint_contype, BTEqualStrategyNumber,
11237 : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
11238 : /* This is a seqscan, as we don't have a usable index ... */
11239 9962 : scan = systable_beginscan(pg_constraint, InvalidOid, true,
11240 : NULL, 2, key);
11241 10406 : while ((tuple = systable_getnext(scan)) != NULL)
11242 : {
11243 444 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11244 :
11245 444 : clone = lappend_oid(clone, constrForm->oid);
11246 : }
11247 9962 : systable_endscan(scan);
11248 9962 : table_close(pg_constraint, RowShareLock);
11249 :
11250 : /*
11251 : * Triggers of the foreign keys will be manipulated a bunch of times in
11252 : * the loop below. To avoid repeatedly opening/closing the trigger
11253 : * catalog relation, we open it here and pass it to the subroutines called
11254 : * below.
11255 : */
11256 9962 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11257 :
11258 9962 : attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
11259 : RelationGetDescr(parentRel),
11260 : false);
11261 10406 : foreach(cell, clone)
11262 : {
11263 444 : Oid constrOid = lfirst_oid(cell);
11264 : Form_pg_constraint constrForm;
11265 : Relation fkRel;
11266 : Oid indexOid;
11267 : Oid partIndexId;
11268 : int numfks;
11269 : AttrNumber conkey[INDEX_MAX_KEYS];
11270 : AttrNumber mapped_confkey[INDEX_MAX_KEYS];
11271 : AttrNumber confkey[INDEX_MAX_KEYS];
11272 : Oid conpfeqop[INDEX_MAX_KEYS];
11273 : Oid conppeqop[INDEX_MAX_KEYS];
11274 : Oid conffeqop[INDEX_MAX_KEYS];
11275 : int numfkdelsetcols;
11276 : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11277 : Constraint *fkconstraint;
11278 : ObjectAddress address;
11279 444 : Oid deleteTriggerOid = InvalidOid,
11280 444 : updateTriggerOid = InvalidOid;
11281 :
11282 444 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
11283 444 : if (!HeapTupleIsValid(tuple))
11284 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
11285 444 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11286 :
11287 : /*
11288 : * As explained above: don't try to clone a constraint for which we're
11289 : * going to clone the parent.
11290 : */
11291 444 : if (list_member_oid(clone, constrForm->conparentid))
11292 : {
11293 222 : ReleaseSysCache(tuple);
11294 222 : continue;
11295 : }
11296 :
11297 : /* We need the same lock level that CreateTrigger will acquire */
11298 222 : fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
11299 :
11300 222 : indexOid = constrForm->conindid;
11301 222 : DeconstructFkConstraintRow(tuple,
11302 : &numfks,
11303 : conkey,
11304 : confkey,
11305 : conpfeqop,
11306 : conppeqop,
11307 : conffeqop,
11308 : &numfkdelsetcols,
11309 : confdelsetcols);
11310 :
11311 486 : for (int i = 0; i < numfks; i++)
11312 264 : mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
11313 :
11314 222 : fkconstraint = makeNode(Constraint);
11315 222 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11316 222 : fkconstraint->conname = NameStr(constrForm->conname);
11317 222 : fkconstraint->deferrable = constrForm->condeferrable;
11318 222 : fkconstraint->initdeferred = constrForm->condeferred;
11319 222 : fkconstraint->location = -1;
11320 222 : fkconstraint->pktable = NULL;
11321 : /* ->fk_attrs determined below */
11322 222 : fkconstraint->pk_attrs = NIL;
11323 222 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11324 222 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11325 222 : fkconstraint->fk_del_action = constrForm->confdeltype;
11326 222 : fkconstraint->fk_del_set_cols = NIL;
11327 222 : fkconstraint->old_conpfeqop = NIL;
11328 222 : fkconstraint->old_pktable_oid = InvalidOid;
11329 222 : fkconstraint->is_enforced = constrForm->conenforced;
11330 222 : fkconstraint->skip_validation = false;
11331 222 : fkconstraint->initially_valid = constrForm->convalidated;
11332 :
11333 : /* set up colnames that are used to generate the constraint name */
11334 486 : for (int i = 0; i < numfks; i++)
11335 : {
11336 : Form_pg_attribute att;
11337 :
11338 264 : att = TupleDescAttr(RelationGetDescr(fkRel),
11339 264 : conkey[i] - 1);
11340 264 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11341 264 : makeString(NameStr(att->attname)));
11342 : }
11343 :
11344 : /*
11345 : * Add the new foreign key constraint pointing to the new partition.
11346 : * Because this new partition appears in the referenced side of the
11347 : * constraint, we don't need to set up for Phase 3 check.
11348 : */
11349 222 : partIndexId = index_get_partition(partitionRel, indexOid);
11350 222 : if (!OidIsValid(partIndexId))
11351 0 : elog(ERROR, "index for %u not found in partition %s",
11352 : indexOid, RelationGetRelationName(partitionRel));
11353 :
11354 : /*
11355 : * Get the "action" triggers belonging to the constraint to pass as
11356 : * parent OIDs for similar triggers that will be created on the
11357 : * partition in addFkRecurseReferenced().
11358 : */
11359 222 : if (constrForm->conenforced)
11360 222 : GetForeignKeyActionTriggers(trigrel, constrOid,
11361 : constrForm->confrelid, constrForm->conrelid,
11362 : &deleteTriggerOid, &updateTriggerOid);
11363 :
11364 : /* Add this constraint ... */
11365 222 : address = addFkConstraint(addFkReferencedSide,
11366 : fkconstraint->conname, fkconstraint, fkRel,
11367 : partitionRel, partIndexId, constrOid,
11368 : numfks, mapped_confkey,
11369 : conkey, conpfeqop, conppeqop, conffeqop,
11370 : numfkdelsetcols, confdelsetcols, false,
11371 222 : constrForm->conperiod);
11372 : /* ... and recurse */
11373 222 : addFkRecurseReferenced(fkconstraint,
11374 : fkRel,
11375 : partitionRel,
11376 : partIndexId,
11377 : address.objectId,
11378 : numfks,
11379 : mapped_confkey,
11380 : conkey,
11381 : conpfeqop,
11382 : conppeqop,
11383 : conffeqop,
11384 : numfkdelsetcols,
11385 : confdelsetcols,
11386 : true,
11387 : deleteTriggerOid,
11388 : updateTriggerOid,
11389 222 : constrForm->conperiod);
11390 :
11391 222 : table_close(fkRel, NoLock);
11392 222 : ReleaseSysCache(tuple);
11393 : }
11394 :
11395 9962 : table_close(trigrel, RowExclusiveLock);
11396 9962 : }
11397 :
11398 : /*
11399 : * CloneFkReferencing
11400 : * Subroutine for CloneForeignKeyConstraints
11401 : *
11402 : * For each FK constraint of the parent relation in the given list, find an
11403 : * equivalent constraint in its partition relation that can be reparented;
11404 : * if one cannot be found, create a new constraint in the partition as its
11405 : * child.
11406 : *
11407 : * If wqueue is given, it is used to set up phase-3 verification for each
11408 : * cloned constraint; omit it if such verification is not needed
11409 : * (example: the partition is being created anew).
11410 : */
11411 : static void
11412 9980 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
11413 : {
11414 : AttrMap *attmap;
11415 : List *partFKs;
11416 9980 : List *clone = NIL;
11417 : ListCell *cell;
11418 : Relation trigrel;
11419 :
11420 : /* obtain a list of constraints that we need to clone */
11421 11284 : foreach(cell, RelationGetFKeyList(parentRel))
11422 : {
11423 1310 : ForeignKeyCacheInfo *fk = lfirst(cell);
11424 :
11425 : /*
11426 : * Refuse to attach a table as partition that this partitioned table
11427 : * already has a foreign key to. This isn't useful schema, which is
11428 : * proven by the fact that there have been no user complaints that
11429 : * it's already impossible to achieve this in the opposite direction,
11430 : * i.e., creating a foreign key that references a partition. This
11431 : * restriction allows us to dodge some complexities around
11432 : * pg_constraint and pg_trigger row creations that would be needed
11433 : * during ATTACH/DETACH for this kind of relationship.
11434 : */
11435 1310 : if (fk->confrelid == RelationGetRelid(partRel))
11436 6 : ereport(ERROR,
11437 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11438 : errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
11439 : RelationGetRelationName(partRel),
11440 : get_constraint_name(fk->conoid))));
11441 :
11442 1304 : clone = lappend_oid(clone, fk->conoid);
11443 : }
11444 :
11445 : /*
11446 : * Silently do nothing if there's nothing to do. In particular, this
11447 : * avoids throwing a spurious error for foreign tables.
11448 : */
11449 9974 : if (clone == NIL)
11450 9430 : return;
11451 :
11452 544 : if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11453 0 : ereport(ERROR,
11454 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11455 : errmsg("foreign key constraints are not supported on foreign tables")));
11456 :
11457 : /*
11458 : * Triggers of the foreign keys will be manipulated a bunch of times in
11459 : * the loop below. To avoid repeatedly opening/closing the trigger
11460 : * catalog relation, we open it here and pass it to the subroutines called
11461 : * below.
11462 : */
11463 544 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11464 :
11465 : /*
11466 : * The constraint key may differ, if the columns in the partition are
11467 : * different. This map is used to convert them.
11468 : */
11469 544 : attmap = build_attrmap_by_name(RelationGetDescr(partRel),
11470 : RelationGetDescr(parentRel),
11471 : false);
11472 :
11473 544 : partFKs = copyObject(RelationGetFKeyList(partRel));
11474 :
11475 1836 : foreach(cell, clone)
11476 : {
11477 1304 : Oid parentConstrOid = lfirst_oid(cell);
11478 : Form_pg_constraint constrForm;
11479 : Relation pkrel;
11480 : HeapTuple tuple;
11481 : int numfks;
11482 : AttrNumber conkey[INDEX_MAX_KEYS];
11483 : AttrNumber mapped_conkey[INDEX_MAX_KEYS];
11484 : AttrNumber confkey[INDEX_MAX_KEYS];
11485 : Oid conpfeqop[INDEX_MAX_KEYS];
11486 : Oid conppeqop[INDEX_MAX_KEYS];
11487 : Oid conffeqop[INDEX_MAX_KEYS];
11488 : int numfkdelsetcols;
11489 : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11490 : Constraint *fkconstraint;
11491 : bool attached;
11492 : Oid indexOid;
11493 : ObjectAddress address;
11494 : ListCell *lc;
11495 1304 : Oid insertTriggerOid = InvalidOid,
11496 1304 : updateTriggerOid = InvalidOid;
11497 : bool with_period;
11498 :
11499 1304 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
11500 1304 : if (!HeapTupleIsValid(tuple))
11501 0 : elog(ERROR, "cache lookup failed for constraint %u",
11502 : parentConstrOid);
11503 1304 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11504 :
11505 : /* Don't clone constraints whose parents are being cloned */
11506 1304 : if (list_member_oid(clone, constrForm->conparentid))
11507 : {
11508 724 : ReleaseSysCache(tuple);
11509 874 : continue;
11510 : }
11511 :
11512 : /*
11513 : * Need to prevent concurrent deletions. If pkrel is a partitioned
11514 : * relation, that means to lock all partitions.
11515 : */
11516 580 : pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
11517 580 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11518 250 : (void) find_all_inheritors(RelationGetRelid(pkrel),
11519 : ShareRowExclusiveLock, NULL);
11520 :
11521 580 : DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
11522 : conpfeqop, conppeqop, conffeqop,
11523 : &numfkdelsetcols, confdelsetcols);
11524 1394 : for (int i = 0; i < numfks; i++)
11525 814 : mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
11526 :
11527 : /*
11528 : * Get the "check" triggers belonging to the constraint, if it is
11529 : * ENFORCED, to pass as parent OIDs for similar triggers that will be
11530 : * created on the partition in addFkRecurseReferencing(). They are
11531 : * also passed to tryAttachPartitionForeignKey() below to simply
11532 : * assign as parents to the partition's existing "check" triggers,
11533 : * that is, if the corresponding constraints is deemed attachable to
11534 : * the parent constraint.
11535 : */
11536 580 : if (constrForm->conenforced)
11537 568 : GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
11538 : constrForm->confrelid, constrForm->conrelid,
11539 : &insertTriggerOid, &updateTriggerOid);
11540 :
11541 : /*
11542 : * Before creating a new constraint, see whether any existing FKs are
11543 : * fit for the purpose. If one is, attach the parent constraint to
11544 : * it, and don't clone anything. This way we avoid the expensive
11545 : * verification step and don't end up with a duplicate FK, and we
11546 : * don't need to recurse to partitions for this constraint.
11547 : */
11548 580 : attached = false;
11549 670 : foreach(lc, partFKs)
11550 : {
11551 246 : ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
11552 :
11553 246 : if (tryAttachPartitionForeignKey(wqueue,
11554 : fk,
11555 : partRel,
11556 : parentConstrOid,
11557 : numfks,
11558 : mapped_conkey,
11559 : confkey,
11560 : conpfeqop,
11561 : insertTriggerOid,
11562 : updateTriggerOid,
11563 : trigrel))
11564 : {
11565 150 : attached = true;
11566 150 : table_close(pkrel, NoLock);
11567 150 : break;
11568 : }
11569 : }
11570 574 : if (attached)
11571 : {
11572 150 : ReleaseSysCache(tuple);
11573 150 : continue;
11574 : }
11575 :
11576 : /* No dice. Set up to create our own constraint */
11577 424 : fkconstraint = makeNode(Constraint);
11578 424 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11579 : /* ->conname determined below */
11580 424 : fkconstraint->deferrable = constrForm->condeferrable;
11581 424 : fkconstraint->initdeferred = constrForm->condeferred;
11582 424 : fkconstraint->location = -1;
11583 424 : fkconstraint->pktable = NULL;
11584 : /* ->fk_attrs determined below */
11585 424 : fkconstraint->pk_attrs = NIL;
11586 424 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11587 424 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11588 424 : fkconstraint->fk_del_action = constrForm->confdeltype;
11589 424 : fkconstraint->fk_del_set_cols = NIL;
11590 424 : fkconstraint->old_conpfeqop = NIL;
11591 424 : fkconstraint->old_pktable_oid = InvalidOid;
11592 424 : fkconstraint->is_enforced = constrForm->conenforced;
11593 424 : fkconstraint->skip_validation = false;
11594 424 : fkconstraint->initially_valid = constrForm->convalidated;
11595 968 : for (int i = 0; i < numfks; i++)
11596 : {
11597 : Form_pg_attribute att;
11598 :
11599 544 : att = TupleDescAttr(RelationGetDescr(partRel),
11600 544 : mapped_conkey[i] - 1);
11601 544 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11602 544 : makeString(NameStr(att->attname)));
11603 : }
11604 :
11605 424 : indexOid = constrForm->conindid;
11606 424 : with_period = constrForm->conperiod;
11607 :
11608 : /* Create the pg_constraint entry at this level */
11609 424 : address = addFkConstraint(addFkReferencingSide,
11610 424 : NameStr(constrForm->conname), fkconstraint,
11611 : partRel, pkrel, indexOid, parentConstrOid,
11612 : numfks, confkey,
11613 : mapped_conkey, conpfeqop,
11614 : conppeqop, conffeqop,
11615 : numfkdelsetcols, confdelsetcols,
11616 : false, with_period);
11617 :
11618 : /* Done with the cloned constraint's tuple */
11619 424 : ReleaseSysCache(tuple);
11620 :
11621 : /* Create the check triggers, and recurse to partitions, if any */
11622 424 : addFkRecurseReferencing(wqueue,
11623 : fkconstraint,
11624 : partRel,
11625 : pkrel,
11626 : indexOid,
11627 : address.objectId,
11628 : numfks,
11629 : confkey,
11630 : mapped_conkey,
11631 : conpfeqop,
11632 : conppeqop,
11633 : conffeqop,
11634 : numfkdelsetcols,
11635 : confdelsetcols,
11636 : false, /* no old check exists */
11637 : AccessExclusiveLock,
11638 : insertTriggerOid,
11639 : updateTriggerOid,
11640 : with_period);
11641 418 : table_close(pkrel, NoLock);
11642 : }
11643 :
11644 532 : table_close(trigrel, RowExclusiveLock);
11645 : }
11646 :
11647 : /*
11648 : * When the parent of a partition receives [the referencing side of] a foreign
11649 : * key, we must propagate that foreign key to the partition. However, the
11650 : * partition might already have an equivalent foreign key; this routine
11651 : * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
11652 : * by the other parameters. If they are equivalent, create the link between
11653 : * the two constraints and return true.
11654 : *
11655 : * If the given FK does not match the one defined by rest of the params,
11656 : * return false.
11657 : */
11658 : static bool
11659 282 : tryAttachPartitionForeignKey(List **wqueue,
11660 : ForeignKeyCacheInfo *fk,
11661 : Relation partition,
11662 : Oid parentConstrOid,
11663 : int numfks,
11664 : AttrNumber *mapped_conkey,
11665 : AttrNumber *confkey,
11666 : Oid *conpfeqop,
11667 : Oid parentInsTrigger,
11668 : Oid parentUpdTrigger,
11669 : Relation trigrel)
11670 : {
11671 : HeapTuple parentConstrTup;
11672 : Form_pg_constraint parentConstr;
11673 : HeapTuple partcontup;
11674 : Form_pg_constraint partConstr;
11675 :
11676 282 : parentConstrTup = SearchSysCache1(CONSTROID,
11677 : ObjectIdGetDatum(parentConstrOid));
11678 282 : if (!HeapTupleIsValid(parentConstrTup))
11679 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11680 282 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11681 :
11682 : /*
11683 : * Do some quick & easy initial checks. If any of these fail, we cannot
11684 : * use this constraint.
11685 : */
11686 282 : if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
11687 : {
11688 0 : ReleaseSysCache(parentConstrTup);
11689 0 : return false;
11690 : }
11691 786 : for (int i = 0; i < numfks; i++)
11692 : {
11693 504 : if (fk->conkey[i] != mapped_conkey[i] ||
11694 504 : fk->confkey[i] != confkey[i] ||
11695 504 : fk->conpfeqop[i] != conpfeqop[i])
11696 : {
11697 0 : ReleaseSysCache(parentConstrTup);
11698 0 : return false;
11699 : }
11700 : }
11701 :
11702 : /* Looks good so far; perform more extensive checks. */
11703 282 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
11704 282 : if (!HeapTupleIsValid(partcontup))
11705 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
11706 282 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11707 :
11708 : /*
11709 : * An error should be raised if the constraint enforceability is
11710 : * different. Returning false without raising an error, as we do for other
11711 : * attributes, could lead to a duplicate constraint with the same
11712 : * enforceability as the parent. While this may be acceptable, it may not
11713 : * be ideal. Therefore, it's better to raise an error and allow the user
11714 : * to correct the enforceability before proceeding.
11715 : */
11716 282 : if (partConstr->conenforced != parentConstr->conenforced)
11717 6 : ereport(ERROR,
11718 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
11719 : errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
11720 : NameStr(parentConstr->conname),
11721 : NameStr(partConstr->conname),
11722 : RelationGetRelationName(partition))));
11723 :
11724 276 : if (OidIsValid(partConstr->conparentid) ||
11725 240 : partConstr->condeferrable != parentConstr->condeferrable ||
11726 212 : partConstr->condeferred != parentConstr->condeferred ||
11727 212 : partConstr->confupdtype != parentConstr->confupdtype ||
11728 176 : partConstr->confdeltype != parentConstr->confdeltype ||
11729 176 : partConstr->confmatchtype != parentConstr->confmatchtype)
11730 : {
11731 114 : ReleaseSysCache(parentConstrTup);
11732 114 : ReleaseSysCache(partcontup);
11733 114 : return false;
11734 : }
11735 :
11736 162 : ReleaseSysCache(parentConstrTup);
11737 162 : ReleaseSysCache(partcontup);
11738 :
11739 : /* Looks good! Attach this constraint. */
11740 162 : AttachPartitionForeignKey(wqueue, partition, fk->conoid,
11741 : parentConstrOid, parentInsTrigger,
11742 : parentUpdTrigger, trigrel);
11743 :
11744 162 : return true;
11745 : }
11746 :
11747 : /*
11748 : * AttachPartitionForeignKey
11749 : *
11750 : * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
11751 : * attaching the constraint, removing redundant triggers and entries from
11752 : * pg_constraint, and setting the constraint's parent.
11753 : */
11754 : static void
11755 162 : AttachPartitionForeignKey(List **wqueue,
11756 : Relation partition,
11757 : Oid partConstrOid,
11758 : Oid parentConstrOid,
11759 : Oid parentInsTrigger,
11760 : Oid parentUpdTrigger,
11761 : Relation trigrel)
11762 : {
11763 : HeapTuple parentConstrTup;
11764 : Form_pg_constraint parentConstr;
11765 : HeapTuple partcontup;
11766 : Form_pg_constraint partConstr;
11767 : bool queueValidation;
11768 : Oid partConstrFrelid;
11769 : Oid partConstrRelid;
11770 : bool parentConstrIsEnforced;
11771 :
11772 : /* Fetch the parent constraint tuple */
11773 162 : parentConstrTup = SearchSysCache1(CONSTROID,
11774 : ObjectIdGetDatum(parentConstrOid));
11775 162 : if (!HeapTupleIsValid(parentConstrTup))
11776 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11777 162 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11778 162 : parentConstrIsEnforced = parentConstr->conenforced;
11779 :
11780 : /* Fetch the child constraint tuple */
11781 162 : partcontup = SearchSysCache1(CONSTROID,
11782 : ObjectIdGetDatum(partConstrOid));
11783 162 : if (!HeapTupleIsValid(partcontup))
11784 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11785 162 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11786 162 : partConstrFrelid = partConstr->confrelid;
11787 162 : partConstrRelid = partConstr->conrelid;
11788 :
11789 : /*
11790 : * If the referenced table is partitioned, then the partition we're
11791 : * attaching now has extra pg_constraint rows and action triggers that are
11792 : * no longer needed. Remove those.
11793 : */
11794 162 : if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
11795 : {
11796 36 : Relation pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11797 :
11798 36 : RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
11799 : partConstrRelid);
11800 :
11801 36 : table_close(pg_constraint, RowShareLock);
11802 : }
11803 :
11804 : /*
11805 : * Will we need to validate this constraint? A valid parent constraint
11806 : * implies that all child constraints have been validated, so if this one
11807 : * isn't, we must trigger phase 3 validation.
11808 : */
11809 162 : queueValidation = parentConstr->convalidated && !partConstr->convalidated;
11810 :
11811 162 : ReleaseSysCache(partcontup);
11812 162 : ReleaseSysCache(parentConstrTup);
11813 :
11814 : /*
11815 : * The action triggers in the new partition become redundant -- the parent
11816 : * table already has equivalent ones, and those will be able to reach the
11817 : * partition. Remove the ones in the partition. We identify them because
11818 : * they have our constraint OID, as well as being on the referenced rel.
11819 : */
11820 162 : DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
11821 : partConstrRelid);
11822 :
11823 162 : ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
11824 : RelationGetRelid(partition));
11825 :
11826 : /*
11827 : * Like the constraint, attach partition's "check" triggers to the
11828 : * corresponding parent triggers if the constraint is ENFORCED. NOT
11829 : * ENFORCED constraints do not have these triggers.
11830 : */
11831 162 : if (parentConstrIsEnforced)
11832 : {
11833 : Oid insertTriggerOid,
11834 : updateTriggerOid;
11835 :
11836 150 : GetForeignKeyCheckTriggers(trigrel,
11837 : partConstrOid, partConstrFrelid, partConstrRelid,
11838 : &insertTriggerOid, &updateTriggerOid);
11839 : Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
11840 150 : TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
11841 : RelationGetRelid(partition));
11842 : Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
11843 150 : TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
11844 : RelationGetRelid(partition));
11845 : }
11846 :
11847 : /*
11848 : * We updated this pg_constraint row above to set its parent; validating
11849 : * it will cause its convalidated flag to change, so we need CCI here. In
11850 : * addition, we need it unconditionally for the rare case where the parent
11851 : * table has *two* identical constraints; when reaching this function for
11852 : * the second one, we must have made our changes visible, otherwise we
11853 : * would try to attach both to this one.
11854 : */
11855 162 : CommandCounterIncrement();
11856 :
11857 : /* If validation is needed, put it in the queue now. */
11858 162 : if (queueValidation)
11859 : {
11860 : Relation conrel;
11861 : Oid confrelid;
11862 :
11863 18 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
11864 :
11865 18 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
11866 18 : if (!HeapTupleIsValid(partcontup))
11867 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11868 :
11869 18 : confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
11870 :
11871 : /* Use the same lock as for AT_ValidateConstraint */
11872 18 : QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
11873 : partcontup, ShareUpdateExclusiveLock);
11874 18 : ReleaseSysCache(partcontup);
11875 18 : table_close(conrel, RowExclusiveLock);
11876 : }
11877 162 : }
11878 :
11879 : /*
11880 : * RemoveInheritedConstraint
11881 : *
11882 : * Removes the constraint and its associated trigger from the specified
11883 : * relation, which inherited the given constraint.
11884 : */
11885 : static void
11886 36 : RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
11887 : Oid conrelid)
11888 : {
11889 : ObjectAddresses *objs;
11890 : HeapTuple consttup;
11891 : ScanKeyData key;
11892 : SysScanDesc scan;
11893 : HeapTuple trigtup;
11894 :
11895 36 : ScanKeyInit(&key,
11896 : Anum_pg_constraint_conrelid,
11897 : BTEqualStrategyNumber, F_OIDEQ,
11898 : ObjectIdGetDatum(conrelid));
11899 :
11900 36 : scan = systable_beginscan(conrel,
11901 : ConstraintRelidTypidNameIndexId,
11902 : true, NULL, 1, &key);
11903 36 : objs = new_object_addresses();
11904 324 : while ((consttup = systable_getnext(scan)) != NULL)
11905 : {
11906 288 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
11907 :
11908 288 : if (conform->conparentid != conoid)
11909 210 : continue;
11910 : else
11911 : {
11912 : ObjectAddress addr;
11913 : SysScanDesc scan2;
11914 : ScanKeyData key2;
11915 : int n PG_USED_FOR_ASSERTS_ONLY;
11916 :
11917 78 : ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
11918 78 : add_exact_object_address(&addr, objs);
11919 :
11920 : /*
11921 : * First we must delete the dependency record that binds the
11922 : * constraint records together.
11923 : */
11924 78 : n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
11925 : conform->oid,
11926 : DEPENDENCY_INTERNAL,
11927 : ConstraintRelationId,
11928 : conoid);
11929 : Assert(n == 1); /* actually only one is expected */
11930 :
11931 : /*
11932 : * Now search for the triggers for this constraint and set them up
11933 : * for deletion too
11934 : */
11935 78 : ScanKeyInit(&key2,
11936 : Anum_pg_trigger_tgconstraint,
11937 : BTEqualStrategyNumber, F_OIDEQ,
11938 : ObjectIdGetDatum(conform->oid));
11939 78 : scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
11940 : true, NULL, 1, &key2);
11941 234 : while ((trigtup = systable_getnext(scan2)) != NULL)
11942 : {
11943 156 : ObjectAddressSet(addr, TriggerRelationId,
11944 : ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
11945 156 : add_exact_object_address(&addr, objs);
11946 : }
11947 78 : systable_endscan(scan2);
11948 : }
11949 : }
11950 : /* make the dependency deletions visible */
11951 36 : CommandCounterIncrement();
11952 36 : performMultipleDeletions(objs, DROP_RESTRICT,
11953 : PERFORM_DELETION_INTERNAL);
11954 36 : systable_endscan(scan);
11955 36 : }
11956 :
11957 : /*
11958 : * DropForeignKeyConstraintTriggers
11959 : *
11960 : * The subroutine for tryAttachPartitionForeignKey handles the deletion of
11961 : * action triggers for the foreign key constraint.
11962 : *
11963 : * If valid confrelid and conrelid values are not provided, the respective
11964 : * trigger check will be skipped, and the trigger will be considered for
11965 : * removal.
11966 : */
11967 : static void
11968 234 : DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
11969 : Oid conrelid)
11970 : {
11971 : ScanKeyData key;
11972 : SysScanDesc scan;
11973 : HeapTuple trigtup;
11974 :
11975 234 : ScanKeyInit(&key,
11976 : Anum_pg_trigger_tgconstraint,
11977 : BTEqualStrategyNumber, F_OIDEQ,
11978 : ObjectIdGetDatum(conoid));
11979 234 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
11980 : NULL, 1, &key);
11981 1014 : while ((trigtup = systable_getnext(scan)) != NULL)
11982 : {
11983 780 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
11984 : ObjectAddress trigger;
11985 :
11986 : /* Invalid if trigger is not for a referential integrity constraint */
11987 780 : if (!OidIsValid(trgform->tgconstrrelid))
11988 300 : continue;
11989 780 : if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
11990 300 : continue;
11991 480 : if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
11992 0 : continue;
11993 :
11994 : /* We should be dropping trigger related to foreign key constraint */
11995 : Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
11996 : trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
11997 : trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
11998 : trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
11999 : trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
12000 : trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
12001 : trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
12002 : trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
12003 : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
12004 : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
12005 : trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
12006 : trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
12007 :
12008 : /*
12009 : * The constraint is originally set up to contain this trigger as an
12010 : * implementation object, so there's a dependency record that links
12011 : * the two; however, since the trigger is no longer needed, we remove
12012 : * the dependency link in order to be able to drop the trigger while
12013 : * keeping the constraint intact.
12014 : */
12015 480 : deleteDependencyRecordsFor(TriggerRelationId,
12016 : trgform->oid,
12017 : false);
12018 : /* make dependency deletion visible to performDeletion */
12019 480 : CommandCounterIncrement();
12020 480 : ObjectAddressSet(trigger, TriggerRelationId,
12021 : trgform->oid);
12022 480 : performDeletion(&trigger, DROP_RESTRICT, 0);
12023 : /* make trigger drop visible, in case the loop iterates */
12024 480 : CommandCounterIncrement();
12025 : }
12026 :
12027 234 : systable_endscan(scan);
12028 234 : }
12029 :
12030 : /*
12031 : * GetForeignKeyActionTriggers
12032 : * Returns delete and update "action" triggers of the given relation
12033 : * belonging to the given constraint
12034 : */
12035 : static void
12036 222 : GetForeignKeyActionTriggers(Relation trigrel,
12037 : Oid conoid, Oid confrelid, Oid conrelid,
12038 : Oid *deleteTriggerOid,
12039 : Oid *updateTriggerOid)
12040 : {
12041 : ScanKeyData key;
12042 : SysScanDesc scan;
12043 : HeapTuple trigtup;
12044 :
12045 222 : *deleteTriggerOid = *updateTriggerOid = InvalidOid;
12046 222 : ScanKeyInit(&key,
12047 : Anum_pg_trigger_tgconstraint,
12048 : BTEqualStrategyNumber, F_OIDEQ,
12049 : ObjectIdGetDatum(conoid));
12050 :
12051 222 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12052 : NULL, 1, &key);
12053 454 : while ((trigtup = systable_getnext(scan)) != NULL)
12054 : {
12055 454 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12056 :
12057 454 : if (trgform->tgconstrrelid != conrelid)
12058 10 : continue;
12059 444 : if (trgform->tgrelid != confrelid)
12060 0 : continue;
12061 : /* Only ever look at "action" triggers on the PK side. */
12062 444 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
12063 0 : continue;
12064 444 : if (TRIGGER_FOR_DELETE(trgform->tgtype))
12065 : {
12066 : Assert(*deleteTriggerOid == InvalidOid);
12067 222 : *deleteTriggerOid = trgform->oid;
12068 : }
12069 222 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12070 : {
12071 : Assert(*updateTriggerOid == InvalidOid);
12072 222 : *updateTriggerOid = trgform->oid;
12073 : }
12074 : #ifndef USE_ASSERT_CHECKING
12075 : /* In an assert-enabled build, continue looking to find duplicates */
12076 444 : if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
12077 222 : break;
12078 : #endif
12079 : }
12080 :
12081 222 : if (!OidIsValid(*deleteTriggerOid))
12082 0 : elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
12083 : conoid);
12084 222 : if (!OidIsValid(*updateTriggerOid))
12085 0 : elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
12086 : conoid);
12087 :
12088 222 : systable_endscan(scan);
12089 222 : }
12090 :
12091 : /*
12092 : * GetForeignKeyCheckTriggers
12093 : * Returns insert and update "check" triggers of the given relation
12094 : * belonging to the given constraint
12095 : */
12096 : static void
12097 820 : GetForeignKeyCheckTriggers(Relation trigrel,
12098 : Oid conoid, Oid confrelid, Oid conrelid,
12099 : Oid *insertTriggerOid,
12100 : Oid *updateTriggerOid)
12101 : {
12102 : ScanKeyData key;
12103 : SysScanDesc scan;
12104 : HeapTuple trigtup;
12105 :
12106 820 : *insertTriggerOid = *updateTriggerOid = InvalidOid;
12107 820 : ScanKeyInit(&key,
12108 : Anum_pg_trigger_tgconstraint,
12109 : BTEqualStrategyNumber, F_OIDEQ,
12110 : ObjectIdGetDatum(conoid));
12111 :
12112 820 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12113 : NULL, 1, &key);
12114 2626 : while ((trigtup = systable_getnext(scan)) != NULL)
12115 : {
12116 2626 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12117 :
12118 2626 : if (trgform->tgconstrrelid != confrelid)
12119 878 : continue;
12120 1748 : if (trgform->tgrelid != conrelid)
12121 0 : continue;
12122 : /* Only ever look at "check" triggers on the FK side. */
12123 1748 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
12124 108 : continue;
12125 1640 : if (TRIGGER_FOR_INSERT(trgform->tgtype))
12126 : {
12127 : Assert(*insertTriggerOid == InvalidOid);
12128 820 : *insertTriggerOid = trgform->oid;
12129 : }
12130 820 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12131 : {
12132 : Assert(*updateTriggerOid == InvalidOid);
12133 820 : *updateTriggerOid = trgform->oid;
12134 : }
12135 : #ifndef USE_ASSERT_CHECKING
12136 : /* In an assert-enabled build, continue looking to find duplicates. */
12137 1640 : if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
12138 820 : break;
12139 : #endif
12140 : }
12141 :
12142 820 : if (!OidIsValid(*insertTriggerOid))
12143 0 : elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
12144 : conoid);
12145 820 : if (!OidIsValid(*updateTriggerOid))
12146 0 : elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
12147 : conoid);
12148 :
12149 820 : systable_endscan(scan);
12150 820 : }
12151 :
12152 : /*
12153 : * ALTER TABLE ALTER CONSTRAINT
12154 : *
12155 : * Update the attributes of a constraint.
12156 : *
12157 : * Currently only works for Foreign Key and not null constraints.
12158 : *
12159 : * If the constraint is modified, returns its address; otherwise, return
12160 : * InvalidObjectAddress.
12161 : */
12162 : static ObjectAddress
12163 288 : ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
12164 : bool recurse, LOCKMODE lockmode)
12165 : {
12166 : Relation conrel;
12167 : Relation tgrel;
12168 : SysScanDesc scan;
12169 : ScanKeyData skey[3];
12170 : HeapTuple contuple;
12171 : Form_pg_constraint currcon;
12172 : ObjectAddress address;
12173 :
12174 : /*
12175 : * Disallow altering ONLY a partitioned table, as it would make no sense.
12176 : * This is okay for legacy inheritance.
12177 : */
12178 288 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
12179 0 : ereport(ERROR,
12180 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12181 : errmsg("constraint must be altered in child tables too"),
12182 : errhint("Do not specify the ONLY keyword."));
12183 :
12184 :
12185 288 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12186 288 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
12187 :
12188 : /*
12189 : * Find and check the target constraint
12190 : */
12191 288 : ScanKeyInit(&skey[0],
12192 : Anum_pg_constraint_conrelid,
12193 : BTEqualStrategyNumber, F_OIDEQ,
12194 : ObjectIdGetDatum(RelationGetRelid(rel)));
12195 288 : ScanKeyInit(&skey[1],
12196 : Anum_pg_constraint_contypid,
12197 : BTEqualStrategyNumber, F_OIDEQ,
12198 : ObjectIdGetDatum(InvalidOid));
12199 288 : ScanKeyInit(&skey[2],
12200 : Anum_pg_constraint_conname,
12201 : BTEqualStrategyNumber, F_NAMEEQ,
12202 288 : CStringGetDatum(cmdcon->conname));
12203 288 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12204 : true, NULL, 3, skey);
12205 :
12206 : /* There can be at most one matching row */
12207 288 : if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
12208 6 : ereport(ERROR,
12209 : (errcode(ERRCODE_UNDEFINED_OBJECT),
12210 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12211 : cmdcon->conname, RelationGetRelationName(rel))));
12212 :
12213 282 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12214 282 : if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
12215 0 : ereport(ERROR,
12216 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12217 : errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
12218 : cmdcon->conname, RelationGetRelationName(rel))));
12219 282 : if (cmdcon->alterEnforceability && currcon->contype != CONSTRAINT_FOREIGN)
12220 12 : ereport(ERROR,
12221 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12222 : errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
12223 : cmdcon->conname, RelationGetRelationName(rel))));
12224 270 : if (cmdcon->alterInheritability &&
12225 90 : currcon->contype != CONSTRAINT_NOTNULL)
12226 24 : ereport(ERROR,
12227 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
12228 : errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
12229 : cmdcon->conname, RelationGetRelationName(rel)));
12230 :
12231 : /* Refuse to modify inheritability of inherited constraints */
12232 246 : if (cmdcon->alterInheritability &&
12233 66 : cmdcon->noinherit && currcon->coninhcount > 0)
12234 6 : ereport(ERROR,
12235 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12236 : errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
12237 : NameStr(currcon->conname),
12238 : RelationGetRelationName(rel)));
12239 :
12240 : /*
12241 : * If it's not the topmost constraint, raise an error.
12242 : *
12243 : * Altering a non-topmost constraint leaves some triggers untouched, since
12244 : * they are not directly connected to this constraint; also, pg_dump would
12245 : * ignore the deferrability status of the individual constraint, since it
12246 : * only dumps topmost constraints. Avoid these problems by refusing this
12247 : * operation and telling the user to alter the parent constraint instead.
12248 : */
12249 240 : if (OidIsValid(currcon->conparentid))
12250 : {
12251 : HeapTuple tp;
12252 12 : Oid parent = currcon->conparentid;
12253 12 : char *ancestorname = NULL;
12254 12 : char *ancestortable = NULL;
12255 :
12256 : /* Loop to find the topmost constraint */
12257 24 : while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
12258 : {
12259 24 : Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
12260 :
12261 : /* If no parent, this is the constraint we want */
12262 24 : if (!OidIsValid(contup->conparentid))
12263 : {
12264 12 : ancestorname = pstrdup(NameStr(contup->conname));
12265 12 : ancestortable = get_rel_name(contup->conrelid);
12266 12 : ReleaseSysCache(tp);
12267 12 : break;
12268 : }
12269 :
12270 12 : parent = contup->conparentid;
12271 12 : ReleaseSysCache(tp);
12272 : }
12273 :
12274 12 : ereport(ERROR,
12275 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12276 : errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
12277 : cmdcon->conname, RelationGetRelationName(rel)),
12278 : ancestorname && ancestortable ?
12279 : errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
12280 : cmdcon->conname, ancestorname, ancestortable) : 0,
12281 : errhint("You may alter the constraint it derives from instead.")));
12282 : }
12283 :
12284 228 : address = InvalidObjectAddress;
12285 :
12286 : /*
12287 : * Do the actual catalog work, and recurse if necessary.
12288 : */
12289 228 : if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
12290 : contuple, recurse, lockmode))
12291 216 : ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
12292 :
12293 222 : systable_endscan(scan);
12294 :
12295 222 : table_close(tgrel, RowExclusiveLock);
12296 222 : table_close(conrel, RowExclusiveLock);
12297 :
12298 222 : return address;
12299 : }
12300 :
12301 : /*
12302 : * A subroutine of ATExecAlterConstraint that calls the respective routines for
12303 : * altering constraint's enforceability, deferrability or inheritability.
12304 : */
12305 : static bool
12306 228 : ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
12307 : Relation conrel, Relation tgrel, Relation rel,
12308 : HeapTuple contuple, bool recurse,
12309 : LOCKMODE lockmode)
12310 : {
12311 : Form_pg_constraint currcon;
12312 228 : bool changed = false;
12313 228 : List *otherrelids = NIL;
12314 :
12315 228 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12316 :
12317 : /*
12318 : * Do the catalog work for the enforceability or deferrability change,
12319 : * recurse if necessary.
12320 : *
12321 : * Note that even if deferrability is requested to be altered along with
12322 : * enforceability, we don't need to explicitly update multiple entries in
12323 : * pg_trigger related to deferrability.
12324 : *
12325 : * Modifying enforceability involves either creating or dropping the
12326 : * trigger, during which the deferrability setting will be adjusted
12327 : * automatically.
12328 : */
12329 300 : if (cmdcon->alterEnforceability &&
12330 72 : ATExecAlterConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
12331 : currcon->conrelid, currcon->confrelid,
12332 : contuple, lockmode, InvalidOid,
12333 : InvalidOid, InvalidOid, InvalidOid))
12334 66 : changed = true;
12335 :
12336 258 : else if (cmdcon->alterDeferrability &&
12337 96 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
12338 : contuple, recurse, &otherrelids,
12339 : lockmode))
12340 : {
12341 : /*
12342 : * AlterConstrUpdateConstraintEntry already invalidated relcache for
12343 : * the relations having the constraint itself; here we also invalidate
12344 : * for relations that have any triggers that are part of the
12345 : * constraint.
12346 : */
12347 306 : foreach_oid(relid, otherrelids)
12348 114 : CacheInvalidateRelcacheByRelid(relid);
12349 :
12350 96 : changed = true;
12351 : }
12352 :
12353 : /*
12354 : * Do the catalog work for the inheritability change.
12355 : */
12356 282 : if (cmdcon->alterInheritability &&
12357 60 : ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
12358 : lockmode))
12359 54 : changed = true;
12360 :
12361 222 : return changed;
12362 : }
12363 :
12364 : /*
12365 : * Returns true if the constraint's enforceability is altered.
12366 : *
12367 : * Depending on whether the constraint is being set to ENFORCED or NOT
12368 : * ENFORCED, it creates or drops the trigger accordingly.
12369 : *
12370 : * Note that we must recurse even when trying to change a constraint to not
12371 : * enforced if it is already not enforced, in case descendant constraints
12372 : * might be enforced and need to be changed to not enforced. Conversely, we
12373 : * should do nothing if a constraint is being set to enforced and is already
12374 : * enforced, as descendant constraints cannot be different in that case.
12375 : */
12376 : static bool
12377 168 : ATExecAlterConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12378 : Relation conrel, Relation tgrel,
12379 : Oid fkrelid, Oid pkrelid,
12380 : HeapTuple contuple, LOCKMODE lockmode,
12381 : Oid ReferencedParentDelTrigger,
12382 : Oid ReferencedParentUpdTrigger,
12383 : Oid ReferencingParentInsTrigger,
12384 : Oid ReferencingParentUpdTrigger)
12385 : {
12386 : Form_pg_constraint currcon;
12387 : Oid conoid;
12388 : Relation rel;
12389 168 : bool changed = false;
12390 :
12391 : /* Since this function recurses, it could be driven to stack overflow */
12392 168 : check_stack_depth();
12393 :
12394 : Assert(cmdcon->alterEnforceability);
12395 :
12396 168 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12397 168 : conoid = currcon->oid;
12398 :
12399 : /* Should be foreign key constraint */
12400 : Assert(currcon->contype == CONSTRAINT_FOREIGN);
12401 :
12402 168 : rel = table_open(currcon->conrelid, lockmode);
12403 :
12404 168 : if (currcon->conenforced != cmdcon->is_enforced)
12405 : {
12406 162 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12407 162 : changed = true;
12408 : }
12409 :
12410 : /* Drop triggers */
12411 168 : if (!cmdcon->is_enforced)
12412 : {
12413 : /*
12414 : * When setting a constraint to NOT ENFORCED, the constraint triggers
12415 : * need to be dropped. Therefore, we must process the child relations
12416 : * first, followed by the parent, to account for dependencies.
12417 : */
12418 126 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12419 54 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12420 18 : AlterConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12421 : fkrelid, pkrelid, contuple,
12422 : lockmode, InvalidOid, InvalidOid,
12423 : InvalidOid, InvalidOid);
12424 :
12425 : /* Drop all the triggers */
12426 72 : DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
12427 : }
12428 96 : else if (changed) /* Create triggers */
12429 : {
12430 96 : Oid ReferencedDelTriggerOid = InvalidOid,
12431 96 : ReferencedUpdTriggerOid = InvalidOid,
12432 96 : ReferencingInsTriggerOid = InvalidOid,
12433 96 : ReferencingUpdTriggerOid = InvalidOid;
12434 :
12435 : /* Prepare the minimal information required for trigger creation. */
12436 96 : Constraint *fkconstraint = makeNode(Constraint);
12437 :
12438 96 : fkconstraint->conname = pstrdup(NameStr(currcon->conname));
12439 96 : fkconstraint->fk_matchtype = currcon->confmatchtype;
12440 96 : fkconstraint->fk_upd_action = currcon->confupdtype;
12441 96 : fkconstraint->fk_del_action = currcon->confdeltype;
12442 :
12443 : /* Create referenced triggers */
12444 96 : if (currcon->conrelid == fkrelid)
12445 54 : createForeignKeyActionTriggers(currcon->conrelid,
12446 : currcon->confrelid,
12447 : fkconstraint,
12448 : conoid,
12449 : currcon->conindid,
12450 : ReferencedParentDelTrigger,
12451 : ReferencedParentUpdTrigger,
12452 : &ReferencedDelTriggerOid,
12453 : &ReferencedUpdTriggerOid);
12454 :
12455 : /* Create referencing triggers */
12456 96 : if (currcon->confrelid == pkrelid)
12457 84 : createForeignKeyCheckTriggers(currcon->conrelid,
12458 : pkrelid,
12459 : fkconstraint,
12460 : conoid,
12461 : currcon->conindid,
12462 : ReferencingParentInsTrigger,
12463 : ReferencingParentUpdTrigger,
12464 : &ReferencingInsTriggerOid,
12465 : &ReferencingUpdTriggerOid);
12466 :
12467 : /*
12468 : * Tell Phase 3 to check that the constraint is satisfied by existing
12469 : * rows. Only applies to leaf partitions, and (for constraints that
12470 : * reference a partitioned table) only if this is not one of the
12471 : * pg_constraint rows that exist solely to support action triggers.
12472 : */
12473 96 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12474 78 : currcon->confrelid == pkrelid)
12475 : {
12476 : AlteredTableInfo *tab;
12477 : NewConstraint *newcon;
12478 :
12479 66 : newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
12480 66 : newcon->name = fkconstraint->conname;
12481 66 : newcon->contype = CONSTR_FOREIGN;
12482 66 : newcon->refrelid = currcon->confrelid;
12483 66 : newcon->refindid = currcon->conindid;
12484 66 : newcon->conid = currcon->oid;
12485 66 : newcon->qual = (Node *) fkconstraint;
12486 :
12487 : /* Find or create work queue entry for this table */
12488 66 : tab = ATGetQueueEntry(wqueue, rel);
12489 66 : tab->constraints = lappend(tab->constraints, newcon);
12490 : }
12491 :
12492 : /*
12493 : * If the table at either end of the constraint is partitioned, we
12494 : * need to recurse and create triggers for each constraint that is a
12495 : * child of this one.
12496 : */
12497 174 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12498 78 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12499 24 : AlterConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12500 : fkrelid, pkrelid, contuple,
12501 : lockmode, ReferencedDelTriggerOid,
12502 : ReferencedUpdTriggerOid,
12503 : ReferencingInsTriggerOid,
12504 : ReferencingUpdTriggerOid);
12505 : }
12506 :
12507 168 : table_close(rel, NoLock);
12508 :
12509 168 : return changed;
12510 : }
12511 :
12512 : /*
12513 : * Returns true if the constraint's deferrability is altered.
12514 : *
12515 : * *otherrelids is appended OIDs of relations containing affected triggers.
12516 : *
12517 : * Note that we must recurse even when the values are correct, in case
12518 : * indirect descendants have had their constraints altered locally.
12519 : * (This could be avoided if we forbade altering constraints in partitions
12520 : * but existing releases don't do that.)
12521 : */
12522 : static bool
12523 162 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
12524 : Relation conrel, Relation tgrel, Relation rel,
12525 : HeapTuple contuple, bool recurse,
12526 : List **otherrelids, LOCKMODE lockmode)
12527 : {
12528 : Form_pg_constraint currcon;
12529 : Oid refrelid;
12530 162 : bool changed = false;
12531 :
12532 : /* since this function recurses, it could be driven to stack overflow */
12533 162 : check_stack_depth();
12534 :
12535 : Assert(cmdcon->alterDeferrability);
12536 :
12537 162 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12538 162 : refrelid = currcon->confrelid;
12539 :
12540 : /* Should be foreign key constraint */
12541 : Assert(currcon->contype == CONSTRAINT_FOREIGN);
12542 :
12543 : /*
12544 : * If called to modify a constraint that's already in the desired state,
12545 : * silently do nothing.
12546 : */
12547 162 : if (currcon->condeferrable != cmdcon->deferrable ||
12548 6 : currcon->condeferred != cmdcon->initdeferred)
12549 : {
12550 162 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12551 162 : changed = true;
12552 :
12553 : /*
12554 : * Now we need to update the multiple entries in pg_trigger that
12555 : * implement the constraint.
12556 : */
12557 162 : AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
12558 162 : cmdcon->deferrable,
12559 162 : cmdcon->initdeferred, otherrelids);
12560 : }
12561 :
12562 : /*
12563 : * If the table at either end of the constraint is partitioned, we need to
12564 : * handle every constraint that is a child of this one.
12565 : */
12566 162 : if (recurse && changed &&
12567 300 : (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12568 138 : get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
12569 42 : AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
12570 : contuple, recurse, otherrelids,
12571 : lockmode);
12572 :
12573 162 : return changed;
12574 : }
12575 :
12576 : /*
12577 : * Returns true if the constraint's inheritability is altered.
12578 : */
12579 : static bool
12580 60 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
12581 : Relation conrel, Relation rel,
12582 : HeapTuple contuple, LOCKMODE lockmode)
12583 : {
12584 : Form_pg_constraint currcon;
12585 : AttrNumber colNum;
12586 : char *colName;
12587 : List *children;
12588 :
12589 : Assert(cmdcon->alterInheritability);
12590 :
12591 60 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12592 :
12593 : /* The current implementation only works for NOT NULL constraints */
12594 : Assert(currcon->contype == CONSTRAINT_NOTNULL);
12595 :
12596 : /*
12597 : * If called to modify a constraint that's already in the desired state,
12598 : * silently do nothing.
12599 : */
12600 60 : if (cmdcon->noinherit == currcon->connoinherit)
12601 0 : return false;
12602 :
12603 60 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12604 60 : CommandCounterIncrement();
12605 :
12606 : /* Fetch the column number and name */
12607 60 : colNum = extractNotNullColumn(contuple);
12608 60 : colName = get_attname(currcon->conrelid, colNum, false);
12609 :
12610 : /*
12611 : * Propagate the change to children. For this subcommand type we don't
12612 : * recursively affect children, just the immediate level.
12613 : */
12614 60 : children = find_inheritance_children(RelationGetRelid(rel),
12615 : lockmode);
12616 192 : foreach_oid(childoid, children)
12617 : {
12618 : ObjectAddress addr;
12619 :
12620 84 : if (cmdcon->noinherit)
12621 : {
12622 : HeapTuple childtup;
12623 : Form_pg_constraint childcon;
12624 :
12625 30 : childtup = findNotNullConstraint(childoid, colName);
12626 30 : if (!childtup)
12627 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
12628 : colName, childoid);
12629 30 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
12630 : Assert(childcon->coninhcount > 0);
12631 30 : childcon->coninhcount--;
12632 30 : childcon->conislocal = true;
12633 30 : CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
12634 30 : heap_freetuple(childtup);
12635 : }
12636 : else
12637 : {
12638 54 : Relation childrel = table_open(childoid, NoLock);
12639 :
12640 54 : addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
12641 : colName, true, true, lockmode);
12642 48 : if (OidIsValid(addr.objectId))
12643 48 : CommandCounterIncrement();
12644 48 : table_close(childrel, NoLock);
12645 : }
12646 : }
12647 :
12648 54 : return true;
12649 : }
12650 :
12651 : /*
12652 : * A subroutine of ATExecAlterConstrDeferrability that updated constraint
12653 : * trigger's deferrability.
12654 : *
12655 : * The arguments to this function have the same meaning as the arguments to
12656 : * ATExecAlterConstrDeferrability.
12657 : */
12658 : static void
12659 162 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
12660 : bool deferrable, bool initdeferred,
12661 : List **otherrelids)
12662 : {
12663 : HeapTuple tgtuple;
12664 : ScanKeyData tgkey;
12665 : SysScanDesc tgscan;
12666 :
12667 162 : ScanKeyInit(&tgkey,
12668 : Anum_pg_trigger_tgconstraint,
12669 : BTEqualStrategyNumber, F_OIDEQ,
12670 : ObjectIdGetDatum(conoid));
12671 162 : tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
12672 : NULL, 1, &tgkey);
12673 630 : while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
12674 : {
12675 468 : Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
12676 : Form_pg_trigger copy_tg;
12677 : HeapTuple tgCopyTuple;
12678 :
12679 : /*
12680 : * Remember OIDs of other relation(s) involved in FK constraint.
12681 : * (Note: it's likely that we could skip forcing a relcache inval for
12682 : * other rels that don't have a trigger whose properties change, but
12683 : * let's be conservative.)
12684 : */
12685 468 : if (tgform->tgrelid != RelationGetRelid(rel))
12686 228 : *otherrelids = list_append_unique_oid(*otherrelids,
12687 : tgform->tgrelid);
12688 :
12689 : /*
12690 : * Update enable status and deferrability of RI_FKey_noaction_del,
12691 : * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
12692 : * triggers, but not others; see createForeignKeyActionTriggers and
12693 : * CreateFKCheckTrigger.
12694 : */
12695 468 : if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
12696 372 : tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
12697 258 : tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
12698 138 : tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
12699 18 : continue;
12700 :
12701 450 : tgCopyTuple = heap_copytuple(tgtuple);
12702 450 : copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
12703 :
12704 450 : copy_tg->tgdeferrable = deferrable;
12705 450 : copy_tg->tginitdeferred = initdeferred;
12706 450 : CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
12707 :
12708 450 : InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
12709 :
12710 450 : heap_freetuple(tgCopyTuple);
12711 : }
12712 :
12713 162 : systable_endscan(tgscan);
12714 162 : }
12715 :
12716 : /*
12717 : * Invokes ATExecAlterConstrEnforceability for each constraint that is a child of
12718 : * the specified constraint.
12719 : *
12720 : * Note that this doesn't handle recursion the normal way, viz. by scanning the
12721 : * list of child relations and recursing; instead it uses the conparentid
12722 : * relationships. This may need to be reconsidered.
12723 : *
12724 : * The arguments to this function have the same meaning as the arguments to
12725 : * ATExecAlterConstrEnforceability.
12726 : */
12727 : static void
12728 42 : AlterConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12729 : Relation conrel, Relation tgrel,
12730 : Oid fkrelid, Oid pkrelid,
12731 : HeapTuple contuple, LOCKMODE lockmode,
12732 : Oid ReferencedParentDelTrigger,
12733 : Oid ReferencedParentUpdTrigger,
12734 : Oid ReferencingParentInsTrigger,
12735 : Oid ReferencingParentUpdTrigger)
12736 : {
12737 : Form_pg_constraint currcon;
12738 : Oid conoid;
12739 : ScanKeyData pkey;
12740 : SysScanDesc pscan;
12741 : HeapTuple childtup;
12742 :
12743 42 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12744 42 : conoid = currcon->oid;
12745 :
12746 42 : ScanKeyInit(&pkey,
12747 : Anum_pg_constraint_conparentid,
12748 : BTEqualStrategyNumber, F_OIDEQ,
12749 : ObjectIdGetDatum(conoid));
12750 :
12751 42 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
12752 : true, NULL, 1, &pkey);
12753 :
12754 138 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
12755 96 : ATExecAlterConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
12756 : pkrelid, childtup, lockmode,
12757 : ReferencedParentDelTrigger,
12758 : ReferencedParentUpdTrigger,
12759 : ReferencingParentInsTrigger,
12760 : ReferencingParentUpdTrigger);
12761 :
12762 42 : systable_endscan(pscan);
12763 42 : }
12764 :
12765 : /*
12766 : * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
12767 : * the specified constraint.
12768 : *
12769 : * Note that this doesn't handle recursion the normal way, viz. by scanning the
12770 : * list of child relations and recursing; instead it uses the conparentid
12771 : * relationships. This may need to be reconsidered.
12772 : *
12773 : * The arguments to this function have the same meaning as the arguments to
12774 : * ATExecAlterConstrDeferrability.
12775 : */
12776 : static void
12777 42 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12778 : Relation conrel, Relation tgrel, Relation rel,
12779 : HeapTuple contuple, bool recurse,
12780 : List **otherrelids, LOCKMODE lockmode)
12781 : {
12782 : Form_pg_constraint currcon;
12783 : Oid conoid;
12784 : ScanKeyData pkey;
12785 : SysScanDesc pscan;
12786 : HeapTuple childtup;
12787 :
12788 42 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12789 42 : conoid = currcon->oid;
12790 :
12791 42 : ScanKeyInit(&pkey,
12792 : Anum_pg_constraint_conparentid,
12793 : BTEqualStrategyNumber, F_OIDEQ,
12794 : ObjectIdGetDatum(conoid));
12795 :
12796 42 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
12797 : true, NULL, 1, &pkey);
12798 :
12799 108 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
12800 : {
12801 66 : Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
12802 : Relation childrel;
12803 :
12804 66 : childrel = table_open(childcon->conrelid, lockmode);
12805 :
12806 66 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
12807 : childtup, recurse, otherrelids, lockmode);
12808 66 : table_close(childrel, NoLock);
12809 : }
12810 :
12811 42 : systable_endscan(pscan);
12812 42 : }
12813 :
12814 : /*
12815 : * Update the constraint entry for the given ATAlterConstraint command, and
12816 : * invoke the appropriate hooks.
12817 : */
12818 : static void
12819 384 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
12820 : HeapTuple contuple)
12821 : {
12822 : HeapTuple copyTuple;
12823 : Form_pg_constraint copy_con;
12824 :
12825 : Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
12826 : cmdcon->alterInheritability);
12827 :
12828 384 : copyTuple = heap_copytuple(contuple);
12829 384 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
12830 :
12831 384 : if (cmdcon->alterEnforceability)
12832 : {
12833 162 : copy_con->conenforced = cmdcon->is_enforced;
12834 :
12835 : /*
12836 : * NB: The convalidated status is irrelevant when the constraint is
12837 : * set to NOT ENFORCED, but for consistency, it should still be set
12838 : * appropriately. Similarly, if the constraint is later changed to
12839 : * ENFORCED, validation will be performed during phase 3, so it makes
12840 : * sense to mark it as valid in that case.
12841 : */
12842 162 : copy_con->convalidated = cmdcon->is_enforced;
12843 : }
12844 384 : if (cmdcon->alterDeferrability)
12845 : {
12846 168 : copy_con->condeferrable = cmdcon->deferrable;
12847 168 : copy_con->condeferred = cmdcon->initdeferred;
12848 : }
12849 384 : if (cmdcon->alterInheritability)
12850 60 : copy_con->connoinherit = cmdcon->noinherit;
12851 :
12852 384 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
12853 384 : InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
12854 :
12855 : /* Make new constraint flags visible to others */
12856 384 : CacheInvalidateRelcacheByRelid(copy_con->conrelid);
12857 :
12858 384 : heap_freetuple(copyTuple);
12859 384 : }
12860 :
12861 : /*
12862 : * ALTER TABLE VALIDATE CONSTRAINT
12863 : *
12864 : * XXX The reason we handle recursion here rather than at Phase 1 is because
12865 : * there's no good way to skip recursing when handling foreign keys: there is
12866 : * no need to lock children in that case, yet we wouldn't be able to avoid
12867 : * doing so at that level.
12868 : *
12869 : * Return value is the address of the validated constraint. If the constraint
12870 : * was already validated, InvalidObjectAddress is returned.
12871 : */
12872 : static ObjectAddress
12873 584 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
12874 : bool recurse, bool recursing, LOCKMODE lockmode)
12875 : {
12876 : Relation conrel;
12877 : SysScanDesc scan;
12878 : ScanKeyData skey[3];
12879 : HeapTuple tuple;
12880 : Form_pg_constraint con;
12881 : ObjectAddress address;
12882 :
12883 584 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12884 :
12885 : /*
12886 : * Find and check the target constraint
12887 : */
12888 584 : ScanKeyInit(&skey[0],
12889 : Anum_pg_constraint_conrelid,
12890 : BTEqualStrategyNumber, F_OIDEQ,
12891 : ObjectIdGetDatum(RelationGetRelid(rel)));
12892 584 : ScanKeyInit(&skey[1],
12893 : Anum_pg_constraint_contypid,
12894 : BTEqualStrategyNumber, F_OIDEQ,
12895 : ObjectIdGetDatum(InvalidOid));
12896 584 : ScanKeyInit(&skey[2],
12897 : Anum_pg_constraint_conname,
12898 : BTEqualStrategyNumber, F_NAMEEQ,
12899 : CStringGetDatum(constrName));
12900 584 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12901 : true, NULL, 3, skey);
12902 :
12903 : /* There can be at most one matching row */
12904 584 : if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
12905 0 : ereport(ERROR,
12906 : (errcode(ERRCODE_UNDEFINED_OBJECT),
12907 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12908 : constrName, RelationGetRelationName(rel))));
12909 :
12910 584 : con = (Form_pg_constraint) GETSTRUCT(tuple);
12911 584 : if (con->contype != CONSTRAINT_FOREIGN &&
12912 256 : con->contype != CONSTRAINT_CHECK &&
12913 112 : con->contype != CONSTRAINT_NOTNULL)
12914 0 : ereport(ERROR,
12915 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
12916 : errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
12917 : constrName, RelationGetRelationName(rel)),
12918 : errdetail("This operation is not supported for this type of constraint."));
12919 :
12920 584 : if (!con->conenforced)
12921 6 : ereport(ERROR,
12922 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12923 : errmsg("cannot validate NOT ENFORCED constraint")));
12924 :
12925 578 : if (!con->convalidated)
12926 : {
12927 560 : if (con->contype == CONSTRAINT_FOREIGN)
12928 : {
12929 322 : QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
12930 : tuple, lockmode);
12931 : }
12932 238 : else if (con->contype == CONSTRAINT_CHECK)
12933 : {
12934 126 : QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
12935 : tuple, recurse, recursing, lockmode);
12936 : }
12937 112 : else if (con->contype == CONSTRAINT_NOTNULL)
12938 : {
12939 112 : QueueNNConstraintValidation(wqueue, conrel, rel,
12940 : tuple, recurse, recursing, lockmode);
12941 : }
12942 :
12943 560 : ObjectAddressSet(address, ConstraintRelationId, con->oid);
12944 : }
12945 : else
12946 18 : address = InvalidObjectAddress; /* already validated */
12947 :
12948 578 : systable_endscan(scan);
12949 :
12950 578 : table_close(conrel, RowExclusiveLock);
12951 :
12952 578 : return address;
12953 : }
12954 :
12955 : /*
12956 : * QueueFKConstraintValidation
12957 : *
12958 : * Add an entry to the wqueue to validate the given foreign key constraint in
12959 : * Phase 3 and update the convalidated field in the pg_constraint catalog
12960 : * for the specified relation and all its children.
12961 : */
12962 : static void
12963 394 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
12964 : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
12965 : {
12966 : Form_pg_constraint con;
12967 : AlteredTableInfo *tab;
12968 : HeapTuple copyTuple;
12969 : Form_pg_constraint copy_con;
12970 :
12971 394 : con = (Form_pg_constraint) GETSTRUCT(contuple);
12972 : Assert(con->contype == CONSTRAINT_FOREIGN);
12973 : Assert(!con->convalidated);
12974 :
12975 : /*
12976 : * Add the validation to phase 3's queue; not needed for partitioned
12977 : * tables themselves, only for their partitions.
12978 : *
12979 : * When the referenced table (pkrelid) is partitioned, the referencing
12980 : * table (fkrel) has one pg_constraint row pointing to each partition
12981 : * thereof. These rows are there only to support action triggers and no
12982 : * table scan is needed, therefore skip this for them as well.
12983 : */
12984 394 : if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
12985 346 : con->confrelid == pkrelid)
12986 : {
12987 : NewConstraint *newcon;
12988 : Constraint *fkconstraint;
12989 :
12990 : /* Queue validation for phase 3 */
12991 334 : fkconstraint = makeNode(Constraint);
12992 : /* for now this is all we need */
12993 334 : fkconstraint->conname = pstrdup(NameStr(con->conname));
12994 :
12995 334 : newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
12996 334 : newcon->name = fkconstraint->conname;
12997 334 : newcon->contype = CONSTR_FOREIGN;
12998 334 : newcon->refrelid = con->confrelid;
12999 334 : newcon->refindid = con->conindid;
13000 334 : newcon->conid = con->oid;
13001 334 : newcon->qual = (Node *) fkconstraint;
13002 :
13003 : /* Find or create work queue entry for this table */
13004 334 : tab = ATGetQueueEntry(wqueue, fkrel);
13005 334 : tab->constraints = lappend(tab->constraints, newcon);
13006 : }
13007 :
13008 : /*
13009 : * If the table at either end of the constraint is partitioned, we need to
13010 : * recurse and handle every unvalidate constraint that is a child of this
13011 : * constraint.
13012 : */
13013 740 : if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13014 346 : get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
13015 : {
13016 : ScanKeyData pkey;
13017 : SysScanDesc pscan;
13018 : HeapTuple childtup;
13019 :
13020 72 : ScanKeyInit(&pkey,
13021 : Anum_pg_constraint_conparentid,
13022 : BTEqualStrategyNumber, F_OIDEQ,
13023 : ObjectIdGetDatum(con->oid));
13024 :
13025 72 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13026 : true, NULL, 1, &pkey);
13027 :
13028 144 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13029 : {
13030 : Form_pg_constraint childcon;
13031 : Relation childrel;
13032 :
13033 72 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13034 :
13035 : /*
13036 : * If the child constraint has already been validated, no further
13037 : * action is required for it or its descendants, as they are all
13038 : * valid.
13039 : */
13040 72 : if (childcon->convalidated)
13041 18 : continue;
13042 :
13043 54 : childrel = table_open(childcon->conrelid, lockmode);
13044 :
13045 : /*
13046 : * NB: Note that pkrelid should be passed as-is during recursion,
13047 : * as it is required to identify the root referenced table.
13048 : */
13049 54 : QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
13050 : childtup, lockmode);
13051 54 : table_close(childrel, NoLock);
13052 : }
13053 :
13054 72 : systable_endscan(pscan);
13055 : }
13056 :
13057 : /*
13058 : * Now mark the pg_constraint row as validated (even if we didn't check,
13059 : * notably the ones for partitions on the referenced side).
13060 : *
13061 : * We rely on transaction abort to roll back this change if phase 3
13062 : * ultimately finds violating rows. This is a bit ugly.
13063 : */
13064 394 : copyTuple = heap_copytuple(contuple);
13065 394 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13066 394 : copy_con->convalidated = true;
13067 394 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13068 :
13069 394 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13070 :
13071 394 : heap_freetuple(copyTuple);
13072 394 : }
13073 :
13074 : /*
13075 : * QueueCheckConstraintValidation
13076 : *
13077 : * Add an entry to the wqueue to validate the given check constraint in Phase 3
13078 : * and update the convalidated field in the pg_constraint catalog for the
13079 : * specified relation and all its inheriting children.
13080 : */
13081 : static void
13082 126 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13083 : char *constrName, HeapTuple contuple,
13084 : bool recurse, bool recursing, LOCKMODE lockmode)
13085 : {
13086 : Form_pg_constraint con;
13087 : AlteredTableInfo *tab;
13088 : HeapTuple copyTuple;
13089 : Form_pg_constraint copy_con;
13090 :
13091 126 : List *children = NIL;
13092 : ListCell *child;
13093 : NewConstraint *newcon;
13094 : Datum val;
13095 : char *conbin;
13096 :
13097 126 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13098 : Assert(con->contype == CONSTRAINT_CHECK);
13099 :
13100 : /*
13101 : * If we're recursing, the parent has already done this, so skip it. Also,
13102 : * if the constraint is a NO INHERIT constraint, we shouldn't try to look
13103 : * for it in the children.
13104 : */
13105 126 : if (!recursing && !con->connoinherit)
13106 72 : children = find_all_inheritors(RelationGetRelid(rel),
13107 : lockmode, NULL);
13108 :
13109 : /*
13110 : * For CHECK constraints, we must ensure that we only mark the constraint
13111 : * as validated on the parent if it's already validated on the children.
13112 : *
13113 : * We recurse before validating on the parent, to reduce risk of
13114 : * deadlocks.
13115 : */
13116 246 : foreach(child, children)
13117 : {
13118 120 : Oid childoid = lfirst_oid(child);
13119 : Relation childrel;
13120 :
13121 120 : if (childoid == RelationGetRelid(rel))
13122 72 : continue;
13123 :
13124 : /*
13125 : * If we are told not to recurse, there had better not be any child
13126 : * tables, because we can't mark the constraint on the parent valid
13127 : * unless it is valid for all child tables.
13128 : */
13129 48 : if (!recurse)
13130 0 : ereport(ERROR,
13131 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13132 : errmsg("constraint must be validated on child tables too")));
13133 :
13134 : /* find_all_inheritors already got lock */
13135 48 : childrel = table_open(childoid, NoLock);
13136 :
13137 48 : ATExecValidateConstraint(wqueue, childrel, constrName, false,
13138 : true, lockmode);
13139 48 : table_close(childrel, NoLock);
13140 : }
13141 :
13142 : /* Queue validation for phase 3 */
13143 126 : newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
13144 126 : newcon->name = constrName;
13145 126 : newcon->contype = CONSTR_CHECK;
13146 126 : newcon->refrelid = InvalidOid;
13147 126 : newcon->refindid = InvalidOid;
13148 126 : newcon->conid = con->oid;
13149 :
13150 126 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
13151 : Anum_pg_constraint_conbin);
13152 126 : conbin = TextDatumGetCString(val);
13153 126 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
13154 :
13155 : /* Find or create work queue entry for this table */
13156 126 : tab = ATGetQueueEntry(wqueue, rel);
13157 126 : tab->constraints = lappend(tab->constraints, newcon);
13158 :
13159 : /*
13160 : * Invalidate relcache so that others see the new validated constraint.
13161 : */
13162 126 : CacheInvalidateRelcache(rel);
13163 :
13164 : /*
13165 : * Now update the catalog, while we have the door open.
13166 : */
13167 126 : copyTuple = heap_copytuple(contuple);
13168 126 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13169 126 : copy_con->convalidated = true;
13170 126 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13171 :
13172 126 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13173 :
13174 126 : heap_freetuple(copyTuple);
13175 126 : }
13176 :
13177 : /*
13178 : * QueueNNConstraintValidation
13179 : *
13180 : * Add an entry to the wqueue to validate the given not-null constraint in
13181 : * Phase 3 and update the convalidated field in the pg_constraint catalog for
13182 : * the specified relation and all its inheriting children.
13183 : */
13184 : static void
13185 112 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13186 : HeapTuple contuple, bool recurse, bool recursing,
13187 : LOCKMODE lockmode)
13188 : {
13189 : Form_pg_constraint con;
13190 : AlteredTableInfo *tab;
13191 : HeapTuple copyTuple;
13192 : Form_pg_constraint copy_con;
13193 112 : List *children = NIL;
13194 : AttrNumber attnum;
13195 : char *colname;
13196 :
13197 112 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13198 : Assert(con->contype == CONSTRAINT_NOTNULL);
13199 :
13200 112 : attnum = extractNotNullColumn(contuple);
13201 :
13202 : /*
13203 : * If we're recursing, we've already done this for parent, so skip it.
13204 : * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
13205 : * look for it in the children.
13206 : *
13207 : * We recurse before validating on the parent, to reduce risk of
13208 : * deadlocks.
13209 : */
13210 112 : if (!recursing && !con->connoinherit)
13211 76 : children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
13212 :
13213 112 : colname = get_attname(RelationGetRelid(rel), attnum, false);
13214 378 : foreach_oid(childoid, children)
13215 : {
13216 : Relation childrel;
13217 : HeapTuple contup;
13218 : Form_pg_constraint childcon;
13219 : char *conname;
13220 :
13221 154 : if (childoid == RelationGetRelid(rel))
13222 76 : continue;
13223 :
13224 : /*
13225 : * If we are told not to recurse, there had better not be any child
13226 : * tables, because we can't mark the constraint on the parent valid
13227 : * unless it is valid for all child tables.
13228 : */
13229 78 : if (!recurse)
13230 0 : ereport(ERROR,
13231 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13232 : errmsg("constraint must be validated on child tables too"));
13233 :
13234 : /*
13235 : * The column on child might have a different attnum, so search by
13236 : * column name.
13237 : */
13238 78 : contup = findNotNullConstraint(childoid, colname);
13239 78 : if (!contup)
13240 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
13241 : colname, get_rel_name(childoid));
13242 78 : childcon = (Form_pg_constraint) GETSTRUCT(contup);
13243 78 : if (childcon->convalidated)
13244 42 : continue;
13245 :
13246 : /* find_all_inheritors already got lock */
13247 36 : childrel = table_open(childoid, NoLock);
13248 36 : conname = pstrdup(NameStr(childcon->conname));
13249 :
13250 : /* XXX improve ATExecValidateConstraint API to avoid double search */
13251 36 : ATExecValidateConstraint(wqueue, childrel, conname,
13252 : false, true, lockmode);
13253 36 : table_close(childrel, NoLock);
13254 : }
13255 :
13256 : /* Set attnotnull appropriately without queueing another validation */
13257 112 : set_attnotnull(NULL, rel, attnum, true, false);
13258 :
13259 112 : tab = ATGetQueueEntry(wqueue, rel);
13260 112 : tab->verify_new_notnull = true;
13261 :
13262 : /*
13263 : * Invalidate relcache so that others see the new validated constraint.
13264 : */
13265 112 : CacheInvalidateRelcache(rel);
13266 :
13267 : /*
13268 : * Now update the catalogs, while we have the door open.
13269 : */
13270 112 : copyTuple = heap_copytuple(contuple);
13271 112 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13272 112 : copy_con->convalidated = true;
13273 112 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13274 :
13275 112 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13276 :
13277 112 : heap_freetuple(copyTuple);
13278 112 : }
13279 :
13280 : /*
13281 : * transformColumnNameList - transform list of column names
13282 : *
13283 : * Lookup each name and return its attnum and, optionally, type and collation
13284 : * OIDs
13285 : *
13286 : * Note: the name of this function suggests that it's general-purpose,
13287 : * but actually it's only used to look up names appearing in foreign-key
13288 : * clauses. The error messages would need work to use it in other cases,
13289 : * and perhaps the validity checks as well.
13290 : */
13291 : static int
13292 6592 : transformColumnNameList(Oid relId, List *colList,
13293 : int16 *attnums, Oid *atttypids, Oid *attcollids)
13294 : {
13295 : ListCell *l;
13296 : int attnum;
13297 :
13298 6592 : attnum = 0;
13299 12068 : foreach(l, colList)
13300 : {
13301 5542 : char *attname = strVal(lfirst(l));
13302 : HeapTuple atttuple;
13303 : Form_pg_attribute attform;
13304 :
13305 5542 : atttuple = SearchSysCacheAttName(relId, attname);
13306 5542 : if (!HeapTupleIsValid(atttuple))
13307 54 : ereport(ERROR,
13308 : (errcode(ERRCODE_UNDEFINED_COLUMN),
13309 : errmsg("column \"%s\" referenced in foreign key constraint does not exist",
13310 : attname)));
13311 5488 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
13312 5488 : if (attform->attnum < 0)
13313 12 : ereport(ERROR,
13314 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13315 : errmsg("system columns cannot be used in foreign keys")));
13316 5476 : if (attnum >= INDEX_MAX_KEYS)
13317 0 : ereport(ERROR,
13318 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
13319 : errmsg("cannot have more than %d keys in a foreign key",
13320 : INDEX_MAX_KEYS)));
13321 5476 : attnums[attnum] = attform->attnum;
13322 5476 : if (atttypids != NULL)
13323 5440 : atttypids[attnum] = attform->atttypid;
13324 5476 : if (attcollids != NULL)
13325 5440 : attcollids[attnum] = attform->attcollation;
13326 5476 : ReleaseSysCache(atttuple);
13327 5476 : attnum++;
13328 : }
13329 :
13330 6526 : return attnum;
13331 : }
13332 :
13333 : /*
13334 : * transformFkeyGetPrimaryKey -
13335 : *
13336 : * Look up the names, attnums, types, and collations of the primary key attributes
13337 : * for the pkrel. Also return the index OID and index opclasses of the
13338 : * index supporting the primary key. Also return whether the index has
13339 : * WITHOUT OVERLAPS.
13340 : *
13341 : * All parameters except pkrel are output parameters. Also, the function
13342 : * return value is the number of attributes in the primary key.
13343 : *
13344 : * Used when the column list in the REFERENCES specification is omitted.
13345 : */
13346 : static int
13347 1196 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
13348 : List **attnamelist,
13349 : int16 *attnums, Oid *atttypids, Oid *attcollids,
13350 : Oid *opclasses, bool *pk_has_without_overlaps)
13351 : {
13352 : List *indexoidlist;
13353 : ListCell *indexoidscan;
13354 1196 : HeapTuple indexTuple = NULL;
13355 1196 : Form_pg_index indexStruct = NULL;
13356 : Datum indclassDatum;
13357 : oidvector *indclass;
13358 : int i;
13359 :
13360 : /*
13361 : * Get the list of index OIDs for the table from the relcache, and look up
13362 : * each one in the pg_index syscache until we find one marked primary key
13363 : * (hopefully there isn't more than one such). Insist it's valid, too.
13364 : */
13365 1196 : *indexOid = InvalidOid;
13366 :
13367 1196 : indexoidlist = RelationGetIndexList(pkrel);
13368 :
13369 1202 : foreach(indexoidscan, indexoidlist)
13370 : {
13371 1202 : Oid indexoid = lfirst_oid(indexoidscan);
13372 :
13373 1202 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13374 1202 : if (!HeapTupleIsValid(indexTuple))
13375 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
13376 1202 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13377 1202 : if (indexStruct->indisprimary && indexStruct->indisvalid)
13378 : {
13379 : /*
13380 : * Refuse to use a deferrable primary key. This is per SQL spec,
13381 : * and there would be a lot of interesting semantic problems if we
13382 : * tried to allow it.
13383 : */
13384 1196 : if (!indexStruct->indimmediate)
13385 0 : ereport(ERROR,
13386 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13387 : errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
13388 : RelationGetRelationName(pkrel))));
13389 :
13390 1196 : *indexOid = indexoid;
13391 1196 : break;
13392 : }
13393 6 : ReleaseSysCache(indexTuple);
13394 : }
13395 :
13396 1196 : list_free(indexoidlist);
13397 :
13398 : /*
13399 : * Check that we found it
13400 : */
13401 1196 : if (!OidIsValid(*indexOid))
13402 0 : ereport(ERROR,
13403 : (errcode(ERRCODE_UNDEFINED_OBJECT),
13404 : errmsg("there is no primary key for referenced table \"%s\"",
13405 : RelationGetRelationName(pkrel))));
13406 :
13407 : /* Must get indclass the hard way */
13408 1196 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13409 : Anum_pg_index_indclass);
13410 1196 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
13411 :
13412 : /*
13413 : * Now build the list of PK attributes from the indkey definition (we
13414 : * assume a primary key cannot have expressional elements)
13415 : */
13416 1196 : *attnamelist = NIL;
13417 2834 : for (i = 0; i < indexStruct->indnkeyatts; i++)
13418 : {
13419 1638 : int pkattno = indexStruct->indkey.values[i];
13420 :
13421 1638 : attnums[i] = pkattno;
13422 1638 : atttypids[i] = attnumTypeId(pkrel, pkattno);
13423 1638 : attcollids[i] = attnumCollationId(pkrel, pkattno);
13424 1638 : opclasses[i] = indclass->values[i];
13425 1638 : *attnamelist = lappend(*attnamelist,
13426 1638 : makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
13427 : }
13428 :
13429 1196 : *pk_has_without_overlaps = indexStruct->indisexclusion;
13430 :
13431 1196 : ReleaseSysCache(indexTuple);
13432 :
13433 1196 : return i;
13434 : }
13435 :
13436 : /*
13437 : * transformFkeyCheckAttrs -
13438 : *
13439 : * Validate that the 'attnums' columns in the 'pkrel' relation are valid to
13440 : * reference as part of a foreign key constraint.
13441 : *
13442 : * Returns the OID of the unique index supporting the constraint and
13443 : * populates the caller-provided 'opclasses' array with the opclasses
13444 : * associated with the index columns. Also sets whether the index
13445 : * uses WITHOUT OVERLAPS.
13446 : *
13447 : * Raises an ERROR on validation failure.
13448 : */
13449 : static Oid
13450 1320 : transformFkeyCheckAttrs(Relation pkrel,
13451 : int numattrs, int16 *attnums,
13452 : bool with_period, Oid *opclasses,
13453 : bool *pk_has_without_overlaps)
13454 : {
13455 1320 : Oid indexoid = InvalidOid;
13456 1320 : bool found = false;
13457 1320 : bool found_deferrable = false;
13458 : List *indexoidlist;
13459 : ListCell *indexoidscan;
13460 : int i,
13461 : j;
13462 :
13463 : /*
13464 : * Reject duplicate appearances of columns in the referenced-columns list.
13465 : * Such a case is forbidden by the SQL standard, and even if we thought it
13466 : * useful to allow it, there would be ambiguity about how to match the
13467 : * list to unique indexes (in particular, it'd be unclear which index
13468 : * opclass goes with which FK column).
13469 : */
13470 3092 : for (i = 0; i < numattrs; i++)
13471 : {
13472 2346 : for (j = i + 1; j < numattrs; j++)
13473 : {
13474 574 : if (attnums[i] == attnums[j])
13475 24 : ereport(ERROR,
13476 : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
13477 : errmsg("foreign key referenced-columns list must not contain duplicates")));
13478 : }
13479 : }
13480 :
13481 : /*
13482 : * Get the list of index OIDs for the table from the relcache, and look up
13483 : * each one in the pg_index syscache, and match unique indexes to the list
13484 : * of attnums we are given.
13485 : */
13486 1296 : indexoidlist = RelationGetIndexList(pkrel);
13487 :
13488 1478 : foreach(indexoidscan, indexoidlist)
13489 : {
13490 : HeapTuple indexTuple;
13491 : Form_pg_index indexStruct;
13492 :
13493 1466 : indexoid = lfirst_oid(indexoidscan);
13494 1466 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13495 1466 : if (!HeapTupleIsValid(indexTuple))
13496 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
13497 1466 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13498 :
13499 : /*
13500 : * Must have the right number of columns; must be unique (or if
13501 : * temporal then exclusion instead) and not a partial index; forget it
13502 : * if there are any expressions, too. Invalid indexes are out as well.
13503 : */
13504 2824 : if (indexStruct->indnkeyatts == numattrs &&
13505 1358 : (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
13506 2684 : indexStruct->indisvalid &&
13507 2684 : heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
13508 1342 : heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
13509 : {
13510 : Datum indclassDatum;
13511 : oidvector *indclass;
13512 :
13513 : /* Must get indclass the hard way */
13514 1342 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13515 : Anum_pg_index_indclass);
13516 1342 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
13517 :
13518 : /*
13519 : * The given attnum list may match the index columns in any order.
13520 : * Check for a match, and extract the appropriate opclasses while
13521 : * we're at it.
13522 : *
13523 : * We know that attnums[] is duplicate-free per the test at the
13524 : * start of this function, and we checked above that the number of
13525 : * index columns agrees, so if we find a match for each attnums[]
13526 : * entry then we must have a one-to-one match in some order.
13527 : */
13528 3102 : for (i = 0; i < numattrs; i++)
13529 : {
13530 1818 : found = false;
13531 2426 : for (j = 0; j < numattrs; j++)
13532 : {
13533 2368 : if (attnums[i] == indexStruct->indkey.values[j])
13534 : {
13535 1760 : opclasses[i] = indclass->values[j];
13536 1760 : found = true;
13537 1760 : break;
13538 : }
13539 : }
13540 1818 : if (!found)
13541 58 : break;
13542 : }
13543 : /* The last attribute in the index must be the PERIOD FK part */
13544 1342 : if (found && with_period)
13545 : {
13546 128 : int16 periodattnum = attnums[numattrs - 1];
13547 :
13548 128 : found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
13549 : }
13550 :
13551 : /*
13552 : * Refuse to use a deferrable unique/primary key. This is per SQL
13553 : * spec, and there would be a lot of interesting semantic problems
13554 : * if we tried to allow it.
13555 : */
13556 1342 : if (found && !indexStruct->indimmediate)
13557 : {
13558 : /*
13559 : * Remember that we found an otherwise matching index, so that
13560 : * we can generate a more appropriate error message.
13561 : */
13562 0 : found_deferrable = true;
13563 0 : found = false;
13564 : }
13565 :
13566 : /* We need to know whether the index has WITHOUT OVERLAPS */
13567 1342 : if (found)
13568 1284 : *pk_has_without_overlaps = indexStruct->indisexclusion;
13569 : }
13570 1466 : ReleaseSysCache(indexTuple);
13571 1466 : if (found)
13572 1284 : break;
13573 : }
13574 :
13575 1296 : if (!found)
13576 : {
13577 12 : if (found_deferrable)
13578 0 : ereport(ERROR,
13579 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13580 : errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
13581 : RelationGetRelationName(pkrel))));
13582 : else
13583 12 : ereport(ERROR,
13584 : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
13585 : errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
13586 : RelationGetRelationName(pkrel))));
13587 : }
13588 :
13589 1284 : list_free(indexoidlist);
13590 :
13591 1284 : return indexoid;
13592 : }
13593 :
13594 : /*
13595 : * findFkeyCast -
13596 : *
13597 : * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
13598 : * Caller has equal regard for binary coercibility and for an exact match.
13599 : */
13600 : static CoercionPathType
13601 12 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
13602 : {
13603 : CoercionPathType ret;
13604 :
13605 12 : if (targetTypeId == sourceTypeId)
13606 : {
13607 12 : ret = COERCION_PATH_RELABELTYPE;
13608 12 : *funcid = InvalidOid;
13609 : }
13610 : else
13611 : {
13612 0 : ret = find_coercion_pathway(targetTypeId, sourceTypeId,
13613 : COERCION_IMPLICIT, funcid);
13614 0 : if (ret == COERCION_PATH_NONE)
13615 : /* A previously-relied-upon cast is now gone. */
13616 0 : elog(ERROR, "could not find cast from %u to %u",
13617 : sourceTypeId, targetTypeId);
13618 : }
13619 :
13620 12 : return ret;
13621 : }
13622 :
13623 : /*
13624 : * Permissions checks on the referenced table for ADD FOREIGN KEY
13625 : *
13626 : * Note: we have already checked that the user owns the referencing table,
13627 : * else we'd have failed much earlier; no additional checks are needed for it.
13628 : */
13629 : static void
13630 2444 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
13631 : {
13632 2444 : Oid roleid = GetUserId();
13633 : AclResult aclresult;
13634 : int i;
13635 :
13636 : /* Okay if we have relation-level REFERENCES permission */
13637 2444 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
13638 : ACL_REFERENCES);
13639 2444 : if (aclresult == ACLCHECK_OK)
13640 2444 : return;
13641 : /* Else we must have REFERENCES on each column */
13642 0 : for (i = 0; i < natts; i++)
13643 : {
13644 0 : aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
13645 : roleid, ACL_REFERENCES);
13646 0 : if (aclresult != ACLCHECK_OK)
13647 0 : aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
13648 0 : RelationGetRelationName(rel));
13649 : }
13650 : }
13651 :
13652 : /*
13653 : * Scan the existing rows in a table to verify they meet a proposed FK
13654 : * constraint.
13655 : *
13656 : * Caller must have opened and locked both relations appropriately.
13657 : */
13658 : static void
13659 1230 : validateForeignKeyConstraint(char *conname,
13660 : Relation rel,
13661 : Relation pkrel,
13662 : Oid pkindOid,
13663 : Oid constraintOid,
13664 : bool hasperiod)
13665 : {
13666 : TupleTableSlot *slot;
13667 : TableScanDesc scan;
13668 1230 : Trigger trig = {0};
13669 : Snapshot snapshot;
13670 : MemoryContext oldcxt;
13671 : MemoryContext perTupCxt;
13672 :
13673 1230 : ereport(DEBUG1,
13674 : (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
13675 :
13676 : /*
13677 : * Build a trigger call structure; we'll need it either way.
13678 : */
13679 1230 : trig.tgoid = InvalidOid;
13680 1230 : trig.tgname = conname;
13681 1230 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
13682 1230 : trig.tgisinternal = true;
13683 1230 : trig.tgconstrrelid = RelationGetRelid(pkrel);
13684 1230 : trig.tgconstrindid = pkindOid;
13685 1230 : trig.tgconstraint = constraintOid;
13686 1230 : trig.tgdeferrable = false;
13687 1230 : trig.tginitdeferred = false;
13688 : /* we needn't fill in remaining fields */
13689 :
13690 : /*
13691 : * See if we can do it with a single LEFT JOIN query. A false result
13692 : * indicates we must proceed with the fire-the-trigger method. We can't do
13693 : * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
13694 : * left joins.
13695 : */
13696 1230 : if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
13697 1042 : return;
13698 :
13699 : /*
13700 : * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
13701 : * if that tuple had just been inserted. If any of those fail, it should
13702 : * ereport(ERROR) and that's that.
13703 : */
13704 114 : snapshot = RegisterSnapshot(GetLatestSnapshot());
13705 114 : slot = table_slot_create(rel, NULL);
13706 114 : scan = table_beginscan(rel, snapshot, 0, NULL);
13707 :
13708 114 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
13709 : "validateForeignKeyConstraint",
13710 : ALLOCSET_SMALL_SIZES);
13711 114 : oldcxt = MemoryContextSwitchTo(perTupCxt);
13712 :
13713 200 : while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
13714 : {
13715 104 : LOCAL_FCINFO(fcinfo, 0);
13716 104 : TriggerData trigdata = {0};
13717 :
13718 104 : CHECK_FOR_INTERRUPTS();
13719 :
13720 : /*
13721 : * Make a call to the trigger function
13722 : *
13723 : * No parameters are passed, but we do set a context
13724 : */
13725 520 : MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
13726 :
13727 : /*
13728 : * We assume RI_FKey_check_ins won't look at flinfo...
13729 : */
13730 104 : trigdata.type = T_TriggerData;
13731 104 : trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
13732 104 : trigdata.tg_relation = rel;
13733 104 : trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
13734 104 : trigdata.tg_trigslot = slot;
13735 104 : trigdata.tg_trigger = &trig;
13736 :
13737 104 : fcinfo->context = (Node *) &trigdata;
13738 :
13739 104 : RI_FKey_check_ins(fcinfo);
13740 :
13741 86 : MemoryContextReset(perTupCxt);
13742 : }
13743 :
13744 96 : MemoryContextSwitchTo(oldcxt);
13745 96 : MemoryContextDelete(perTupCxt);
13746 96 : table_endscan(scan);
13747 96 : UnregisterSnapshot(snapshot);
13748 96 : ExecDropSingleTupleTableSlot(slot);
13749 : }
13750 :
13751 : /*
13752 : * CreateFKCheckTrigger
13753 : * Creates the insert (on_insert=true) or update "check" trigger that
13754 : * implements a given foreign key
13755 : *
13756 : * Returns the OID of the so created trigger.
13757 : */
13758 : static Oid
13759 5972 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
13760 : Oid constraintOid, Oid indexOid, Oid parentTrigOid,
13761 : bool on_insert)
13762 : {
13763 : ObjectAddress trigAddress;
13764 : CreateTrigStmt *fk_trigger;
13765 :
13766 : /*
13767 : * Note: for a self-referential FK (referencing and referenced tables are
13768 : * the same), it is important that the ON UPDATE action fires before the
13769 : * CHECK action, since both triggers will fire on the same row during an
13770 : * UPDATE event; otherwise the CHECK trigger will be checking a non-final
13771 : * state of the row. Triggers fire in name order, so we ensure this by
13772 : * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
13773 : * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
13774 : */
13775 5972 : fk_trigger = makeNode(CreateTrigStmt);
13776 5972 : fk_trigger->replace = false;
13777 5972 : fk_trigger->isconstraint = true;
13778 5972 : fk_trigger->trigname = "RI_ConstraintTrigger_c";
13779 5972 : fk_trigger->relation = NULL;
13780 :
13781 : /* Either ON INSERT or ON UPDATE */
13782 5972 : if (on_insert)
13783 : {
13784 2986 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
13785 2986 : fk_trigger->events = TRIGGER_TYPE_INSERT;
13786 : }
13787 : else
13788 : {
13789 2986 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
13790 2986 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
13791 : }
13792 :
13793 5972 : fk_trigger->args = NIL;
13794 5972 : fk_trigger->row = true;
13795 5972 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
13796 5972 : fk_trigger->columns = NIL;
13797 5972 : fk_trigger->whenClause = NULL;
13798 5972 : fk_trigger->transitionRels = NIL;
13799 5972 : fk_trigger->deferrable = fkconstraint->deferrable;
13800 5972 : fk_trigger->initdeferred = fkconstraint->initdeferred;
13801 5972 : fk_trigger->constrrel = NULL;
13802 :
13803 5972 : trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
13804 : constraintOid, indexOid, InvalidOid,
13805 : parentTrigOid, NULL, true, false);
13806 :
13807 : /* Make changes-so-far visible */
13808 5972 : CommandCounterIncrement();
13809 :
13810 5972 : return trigAddress.objectId;
13811 : }
13812 :
13813 : /*
13814 : * createForeignKeyActionTriggers
13815 : * Create the referenced-side "action" triggers that implement a foreign
13816 : * key.
13817 : *
13818 : * Returns the OIDs of the so created triggers in *deleteTrigOid and
13819 : * *updateTrigOid.
13820 : */
13821 : static void
13822 3412 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
13823 : Oid constraintOid, Oid indexOid,
13824 : Oid parentDelTrigger, Oid parentUpdTrigger,
13825 : Oid *deleteTrigOid, Oid *updateTrigOid)
13826 : {
13827 : CreateTrigStmt *fk_trigger;
13828 : ObjectAddress trigAddress;
13829 :
13830 : /*
13831 : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
13832 : * DELETE action on the referenced table.
13833 : */
13834 3412 : fk_trigger = makeNode(CreateTrigStmt);
13835 3412 : fk_trigger->replace = false;
13836 3412 : fk_trigger->isconstraint = true;
13837 3412 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
13838 3412 : fk_trigger->relation = NULL;
13839 3412 : fk_trigger->args = NIL;
13840 3412 : fk_trigger->row = true;
13841 3412 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
13842 3412 : fk_trigger->events = TRIGGER_TYPE_DELETE;
13843 3412 : fk_trigger->columns = NIL;
13844 3412 : fk_trigger->whenClause = NULL;
13845 3412 : fk_trigger->transitionRels = NIL;
13846 3412 : fk_trigger->constrrel = NULL;
13847 :
13848 3412 : switch (fkconstraint->fk_del_action)
13849 : {
13850 2778 : case FKCONSTR_ACTION_NOACTION:
13851 2778 : fk_trigger->deferrable = fkconstraint->deferrable;
13852 2778 : fk_trigger->initdeferred = fkconstraint->initdeferred;
13853 2778 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
13854 2778 : break;
13855 30 : case FKCONSTR_ACTION_RESTRICT:
13856 30 : fk_trigger->deferrable = false;
13857 30 : fk_trigger->initdeferred = false;
13858 30 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
13859 30 : break;
13860 446 : case FKCONSTR_ACTION_CASCADE:
13861 446 : fk_trigger->deferrable = false;
13862 446 : fk_trigger->initdeferred = false;
13863 446 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
13864 446 : break;
13865 98 : case FKCONSTR_ACTION_SETNULL:
13866 98 : fk_trigger->deferrable = false;
13867 98 : fk_trigger->initdeferred = false;
13868 98 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
13869 98 : break;
13870 60 : case FKCONSTR_ACTION_SETDEFAULT:
13871 60 : fk_trigger->deferrable = false;
13872 60 : fk_trigger->initdeferred = false;
13873 60 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
13874 60 : break;
13875 0 : default:
13876 0 : elog(ERROR, "unrecognized FK action type: %d",
13877 : (int) fkconstraint->fk_del_action);
13878 : break;
13879 : }
13880 :
13881 3412 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
13882 : constraintOid, indexOid, InvalidOid,
13883 : parentDelTrigger, NULL, true, false);
13884 3412 : if (deleteTrigOid)
13885 3412 : *deleteTrigOid = trigAddress.objectId;
13886 :
13887 : /* Make changes-so-far visible */
13888 3412 : CommandCounterIncrement();
13889 :
13890 : /*
13891 : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
13892 : * UPDATE action on the referenced table.
13893 : */
13894 3412 : fk_trigger = makeNode(CreateTrigStmt);
13895 3412 : fk_trigger->replace = false;
13896 3412 : fk_trigger->isconstraint = true;
13897 3412 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
13898 3412 : fk_trigger->relation = NULL;
13899 3412 : fk_trigger->args = NIL;
13900 3412 : fk_trigger->row = true;
13901 3412 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
13902 3412 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
13903 3412 : fk_trigger->columns = NIL;
13904 3412 : fk_trigger->whenClause = NULL;
13905 3412 : fk_trigger->transitionRels = NIL;
13906 3412 : fk_trigger->constrrel = NULL;
13907 :
13908 3412 : switch (fkconstraint->fk_upd_action)
13909 : {
13910 2970 : case FKCONSTR_ACTION_NOACTION:
13911 2970 : fk_trigger->deferrable = fkconstraint->deferrable;
13912 2970 : fk_trigger->initdeferred = fkconstraint->initdeferred;
13913 2970 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
13914 2970 : break;
13915 36 : case FKCONSTR_ACTION_RESTRICT:
13916 36 : fk_trigger->deferrable = false;
13917 36 : fk_trigger->initdeferred = false;
13918 36 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
13919 36 : break;
13920 300 : case FKCONSTR_ACTION_CASCADE:
13921 300 : fk_trigger->deferrable = false;
13922 300 : fk_trigger->initdeferred = false;
13923 300 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
13924 300 : break;
13925 64 : case FKCONSTR_ACTION_SETNULL:
13926 64 : fk_trigger->deferrable = false;
13927 64 : fk_trigger->initdeferred = false;
13928 64 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
13929 64 : break;
13930 42 : case FKCONSTR_ACTION_SETDEFAULT:
13931 42 : fk_trigger->deferrable = false;
13932 42 : fk_trigger->initdeferred = false;
13933 42 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
13934 42 : break;
13935 0 : default:
13936 0 : elog(ERROR, "unrecognized FK action type: %d",
13937 : (int) fkconstraint->fk_upd_action);
13938 : break;
13939 : }
13940 :
13941 3412 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
13942 : constraintOid, indexOid, InvalidOid,
13943 : parentUpdTrigger, NULL, true, false);
13944 3412 : if (updateTrigOid)
13945 3412 : *updateTrigOid = trigAddress.objectId;
13946 3412 : }
13947 :
13948 : /*
13949 : * createForeignKeyCheckTriggers
13950 : * Create the referencing-side "check" triggers that implement a foreign
13951 : * key.
13952 : *
13953 : * Returns the OIDs of the so created triggers in *insertTrigOid and
13954 : * *updateTrigOid.
13955 : */
13956 : static void
13957 2986 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
13958 : Constraint *fkconstraint, Oid constraintOid,
13959 : Oid indexOid,
13960 : Oid parentInsTrigger, Oid parentUpdTrigger,
13961 : Oid *insertTrigOid, Oid *updateTrigOid)
13962 : {
13963 2986 : *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
13964 : constraintOid, indexOid,
13965 : parentInsTrigger, true);
13966 2986 : *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
13967 : constraintOid, indexOid,
13968 : parentUpdTrigger, false);
13969 2986 : }
13970 :
13971 : /*
13972 : * ALTER TABLE DROP CONSTRAINT
13973 : *
13974 : * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
13975 : */
13976 : static void
13977 792 : ATExecDropConstraint(Relation rel, const char *constrName,
13978 : DropBehavior behavior, bool recurse,
13979 : bool missing_ok, LOCKMODE lockmode)
13980 : {
13981 : Relation conrel;
13982 : SysScanDesc scan;
13983 : ScanKeyData skey[3];
13984 : HeapTuple tuple;
13985 792 : bool found = false;
13986 :
13987 792 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
13988 :
13989 : /*
13990 : * Find and drop the target constraint
13991 : */
13992 792 : ScanKeyInit(&skey[0],
13993 : Anum_pg_constraint_conrelid,
13994 : BTEqualStrategyNumber, F_OIDEQ,
13995 : ObjectIdGetDatum(RelationGetRelid(rel)));
13996 792 : ScanKeyInit(&skey[1],
13997 : Anum_pg_constraint_contypid,
13998 : BTEqualStrategyNumber, F_OIDEQ,
13999 : ObjectIdGetDatum(InvalidOid));
14000 792 : ScanKeyInit(&skey[2],
14001 : Anum_pg_constraint_conname,
14002 : BTEqualStrategyNumber, F_NAMEEQ,
14003 : CStringGetDatum(constrName));
14004 792 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14005 : true, NULL, 3, skey);
14006 :
14007 : /* There can be at most one matching row */
14008 792 : if (HeapTupleIsValid(tuple = systable_getnext(scan)))
14009 : {
14010 756 : dropconstraint_internal(rel, tuple, behavior, recurse, false,
14011 : missing_ok, lockmode);
14012 570 : found = true;
14013 : }
14014 :
14015 606 : systable_endscan(scan);
14016 :
14017 606 : if (!found)
14018 : {
14019 36 : if (!missing_ok)
14020 24 : ereport(ERROR,
14021 : errcode(ERRCODE_UNDEFINED_OBJECT),
14022 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14023 : constrName, RelationGetRelationName(rel)));
14024 : else
14025 12 : ereport(NOTICE,
14026 : errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
14027 : constrName, RelationGetRelationName(rel)));
14028 : }
14029 :
14030 582 : table_close(conrel, RowExclusiveLock);
14031 582 : }
14032 :
14033 : /*
14034 : * Remove a constraint, using its pg_constraint tuple
14035 : *
14036 : * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
14037 : * DROP NOT NULL.
14038 : *
14039 : * Returns the address of the constraint being removed.
14040 : */
14041 : static ObjectAddress
14042 1186 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
14043 : bool recurse, bool recursing, bool missing_ok,
14044 : LOCKMODE lockmode)
14045 : {
14046 : Relation conrel;
14047 : Form_pg_constraint con;
14048 : ObjectAddress conobj;
14049 : List *children;
14050 1186 : bool is_no_inherit_constraint = false;
14051 : char *constrName;
14052 1186 : char *colname = NULL;
14053 :
14054 : /* Guard against stack overflow due to overly deep inheritance tree. */
14055 1186 : check_stack_depth();
14056 :
14057 : /* At top level, permission check was done in ATPrepCmd, else do it */
14058 1186 : if (recursing)
14059 210 : ATSimplePermissions(AT_DropConstraint, rel,
14060 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
14061 :
14062 1180 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14063 :
14064 1180 : con = (Form_pg_constraint) GETSTRUCT(constraintTup);
14065 1180 : constrName = NameStr(con->conname);
14066 :
14067 : /* Don't allow drop of inherited constraints */
14068 1180 : if (con->coninhcount > 0 && !recursing)
14069 156 : ereport(ERROR,
14070 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14071 : errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
14072 : constrName, RelationGetRelationName(rel))));
14073 :
14074 : /*
14075 : * Reset pg_constraint.attnotnull, if this is a not-null constraint.
14076 : *
14077 : * While doing that, we're in a good position to disallow dropping a not-
14078 : * null constraint underneath a primary key, a replica identity index, or
14079 : * a generated identity column.
14080 : */
14081 1024 : if (con->contype == CONSTRAINT_NOTNULL)
14082 : {
14083 314 : Relation attrel = table_open(AttributeRelationId, RowExclusiveLock);
14084 314 : AttrNumber attnum = extractNotNullColumn(constraintTup);
14085 : Bitmapset *pkattrs;
14086 : Bitmapset *irattrs;
14087 : HeapTuple atttup;
14088 : Form_pg_attribute attForm;
14089 :
14090 : /* save column name for recursion step */
14091 314 : colname = get_attname(RelationGetRelid(rel), attnum, false);
14092 :
14093 : /*
14094 : * Disallow if it's in the primary key. For partitioned tables we
14095 : * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
14096 : * return NULL if the primary key is invalid; but we still need to
14097 : * protect not-null constraints under such a constraint, so check the
14098 : * slow way.
14099 : */
14100 314 : pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
14101 :
14102 314 : if (pkattrs == NULL &&
14103 278 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14104 : {
14105 18 : Oid pkindex = RelationGetPrimaryKeyIndex(rel, true);
14106 :
14107 18 : if (OidIsValid(pkindex))
14108 : {
14109 0 : Relation pk = relation_open(pkindex, AccessShareLock);
14110 :
14111 0 : pkattrs = NULL;
14112 0 : for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
14113 0 : pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
14114 :
14115 0 : relation_close(pk, AccessShareLock);
14116 : }
14117 : }
14118 :
14119 350 : if (pkattrs &&
14120 36 : bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
14121 24 : ereport(ERROR,
14122 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14123 : errmsg("column \"%s\" is in a primary key",
14124 : get_attname(RelationGetRelid(rel), attnum, false)));
14125 :
14126 : /* Disallow if it's in the replica identity */
14127 290 : irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
14128 290 : if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
14129 12 : ereport(ERROR,
14130 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14131 : errmsg("column \"%s\" is in index used as replica identity",
14132 : get_attname(RelationGetRelid(rel), attnum, false)));
14133 :
14134 : /* Disallow if it's a GENERATED AS IDENTITY column */
14135 278 : atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
14136 278 : if (!HeapTupleIsValid(atttup))
14137 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
14138 : attnum, RelationGetRelid(rel));
14139 278 : attForm = (Form_pg_attribute) GETSTRUCT(atttup);
14140 278 : if (attForm->attidentity != '\0')
14141 0 : ereport(ERROR,
14142 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14143 : errmsg("column \"%s\" of relation \"%s\" is an identity column",
14144 : get_attname(RelationGetRelid(rel), attnum,
14145 : false),
14146 : RelationGetRelationName(rel)));
14147 :
14148 : /* All good -- reset attnotnull if needed */
14149 278 : if (attForm->attnotnull)
14150 : {
14151 278 : attForm->attnotnull = false;
14152 278 : CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
14153 : }
14154 :
14155 278 : table_close(attrel, RowExclusiveLock);
14156 : }
14157 :
14158 988 : is_no_inherit_constraint = con->connoinherit;
14159 :
14160 : /*
14161 : * If it's a foreign-key constraint, we'd better lock the referenced table
14162 : * and check that that's not in use, just as we've already done for the
14163 : * constrained table (else we might, eg, be dropping a trigger that has
14164 : * unfired events). But we can/must skip that in the self-referential
14165 : * case.
14166 : */
14167 988 : if (con->contype == CONSTRAINT_FOREIGN &&
14168 168 : con->confrelid != RelationGetRelid(rel))
14169 : {
14170 : Relation frel;
14171 :
14172 : /* Must match lock taken by RemoveTriggerById: */
14173 168 : frel = table_open(con->confrelid, AccessExclusiveLock);
14174 168 : CheckAlterTableIsSafe(frel);
14175 162 : table_close(frel, NoLock);
14176 : }
14177 :
14178 : /*
14179 : * Perform the actual constraint deletion
14180 : */
14181 982 : ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
14182 982 : performDeletion(&conobj, behavior, 0);
14183 :
14184 : /*
14185 : * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
14186 : * are dropped via the dependency mechanism, so we're done here.
14187 : */
14188 946 : if (con->contype != CONSTRAINT_CHECK &&
14189 628 : con->contype != CONSTRAINT_NOTNULL &&
14190 350 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14191 : {
14192 78 : table_close(conrel, RowExclusiveLock);
14193 78 : return conobj;
14194 : }
14195 :
14196 : /*
14197 : * Propagate to children as appropriate. Unlike most other ALTER
14198 : * routines, we have to do this one level of recursion at a time; we can't
14199 : * use find_all_inheritors to do it in one pass.
14200 : */
14201 868 : if (!is_no_inherit_constraint)
14202 584 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
14203 : else
14204 284 : children = NIL;
14205 :
14206 2108 : foreach_oid(childrelid, children)
14207 : {
14208 : Relation childrel;
14209 : HeapTuple tuple;
14210 : Form_pg_constraint childcon;
14211 :
14212 : /* find_inheritance_children already got lock */
14213 384 : childrel = table_open(childrelid, NoLock);
14214 384 : CheckAlterTableIsSafe(childrel);
14215 :
14216 : /*
14217 : * We search for not-null constraints by column name, and others by
14218 : * constraint name.
14219 : */
14220 384 : if (con->contype == CONSTRAINT_NOTNULL)
14221 : {
14222 148 : tuple = findNotNullConstraint(childrelid, colname);
14223 148 : if (!HeapTupleIsValid(tuple))
14224 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
14225 : colname, RelationGetRelid(childrel));
14226 : }
14227 : else
14228 : {
14229 : SysScanDesc scan;
14230 : ScanKeyData skey[3];
14231 :
14232 236 : ScanKeyInit(&skey[0],
14233 : Anum_pg_constraint_conrelid,
14234 : BTEqualStrategyNumber, F_OIDEQ,
14235 : ObjectIdGetDatum(childrelid));
14236 236 : ScanKeyInit(&skey[1],
14237 : Anum_pg_constraint_contypid,
14238 : BTEqualStrategyNumber, F_OIDEQ,
14239 : ObjectIdGetDatum(InvalidOid));
14240 236 : ScanKeyInit(&skey[2],
14241 : Anum_pg_constraint_conname,
14242 : BTEqualStrategyNumber, F_NAMEEQ,
14243 : CStringGetDatum(constrName));
14244 236 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14245 : true, NULL, 3, skey);
14246 : /* There can only be one, so no need to loop */
14247 236 : tuple = systable_getnext(scan);
14248 236 : if (!HeapTupleIsValid(tuple))
14249 0 : ereport(ERROR,
14250 : (errcode(ERRCODE_UNDEFINED_OBJECT),
14251 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14252 : constrName,
14253 : RelationGetRelationName(childrel))));
14254 236 : tuple = heap_copytuple(tuple);
14255 236 : systable_endscan(scan);
14256 : }
14257 :
14258 384 : childcon = (Form_pg_constraint) GETSTRUCT(tuple);
14259 :
14260 : /* Right now only CHECK and not-null constraints can be inherited */
14261 384 : if (childcon->contype != CONSTRAINT_CHECK &&
14262 148 : childcon->contype != CONSTRAINT_NOTNULL)
14263 0 : elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
14264 :
14265 384 : if (childcon->coninhcount <= 0) /* shouldn't happen */
14266 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
14267 : childrelid, NameStr(childcon->conname));
14268 :
14269 384 : if (recurse)
14270 : {
14271 : /*
14272 : * If the child constraint has other definition sources, just
14273 : * decrement its inheritance count; if not, recurse to delete it.
14274 : */
14275 282 : if (childcon->coninhcount == 1 && !childcon->conislocal)
14276 : {
14277 : /* Time to delete this child constraint, too */
14278 210 : dropconstraint_internal(childrel, tuple, behavior,
14279 : recurse, true, missing_ok,
14280 : lockmode);
14281 : }
14282 : else
14283 : {
14284 : /* Child constraint must survive my deletion */
14285 72 : childcon->coninhcount--;
14286 72 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14287 :
14288 : /* Make update visible */
14289 72 : CommandCounterIncrement();
14290 : }
14291 : }
14292 : else
14293 : {
14294 : /*
14295 : * If we were told to drop ONLY in this table (no recursion) and
14296 : * there are no further parents for this constraint, we need to
14297 : * mark the inheritors' constraints as locally defined rather than
14298 : * inherited.
14299 : */
14300 102 : childcon->coninhcount--;
14301 102 : if (childcon->coninhcount == 0)
14302 102 : childcon->conislocal = true;
14303 :
14304 102 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14305 :
14306 : /* Make update visible */
14307 102 : CommandCounterIncrement();
14308 : }
14309 :
14310 378 : heap_freetuple(tuple);
14311 :
14312 378 : table_close(childrel, NoLock);
14313 : }
14314 :
14315 862 : table_close(conrel, RowExclusiveLock);
14316 :
14317 862 : return conobj;
14318 : }
14319 :
14320 : /*
14321 : * ALTER COLUMN TYPE
14322 : *
14323 : * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
14324 : * TYPE during phase 1 --- the AlterTableCmd passed in here is already
14325 : * transformed (and must be, because we rely on some transformed fields).
14326 : *
14327 : * The point of this is that the execution of all ALTER COLUMN TYPEs for a
14328 : * table will be done "in parallel" during phase 3, so all the USING
14329 : * expressions should be parsed assuming the original column types. Also,
14330 : * this allows a USING expression to refer to a field that will be dropped.
14331 : *
14332 : * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
14333 : * the first two execution steps in phase 2; they must not see the effects
14334 : * of any other subcommand types, since the USING expressions are parsed
14335 : * against the unmodified table's state.
14336 : */
14337 : static void
14338 1300 : ATPrepAlterColumnType(List **wqueue,
14339 : AlteredTableInfo *tab, Relation rel,
14340 : bool recurse, bool recursing,
14341 : AlterTableCmd *cmd, LOCKMODE lockmode,
14342 : AlterTableUtilityContext *context)
14343 : {
14344 1300 : char *colName = cmd->name;
14345 1300 : ColumnDef *def = (ColumnDef *) cmd->def;
14346 1300 : TypeName *typeName = def->typeName;
14347 1300 : Node *transform = def->cooked_default;
14348 : HeapTuple tuple;
14349 : Form_pg_attribute attTup;
14350 : AttrNumber attnum;
14351 : Oid targettype;
14352 : int32 targettypmod;
14353 : Oid targetcollid;
14354 : NewColumnValue *newval;
14355 1300 : ParseState *pstate = make_parsestate(NULL);
14356 : AclResult aclresult;
14357 : bool is_expr;
14358 :
14359 1300 : pstate->p_sourcetext = context->queryString;
14360 :
14361 1300 : if (rel->rd_rel->reloftype && !recursing)
14362 6 : ereport(ERROR,
14363 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14364 : errmsg("cannot alter column type of typed table"),
14365 : parser_errposition(pstate, def->location)));
14366 :
14367 : /* lookup the attribute so we can check inheritance status */
14368 1294 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
14369 1294 : if (!HeapTupleIsValid(tuple))
14370 0 : ereport(ERROR,
14371 : (errcode(ERRCODE_UNDEFINED_COLUMN),
14372 : errmsg("column \"%s\" of relation \"%s\" does not exist",
14373 : colName, RelationGetRelationName(rel)),
14374 : parser_errposition(pstate, def->location)));
14375 1294 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
14376 1294 : attnum = attTup->attnum;
14377 :
14378 : /* Can't alter a system attribute */
14379 1294 : if (attnum <= 0)
14380 6 : ereport(ERROR,
14381 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14382 : errmsg("cannot alter system column \"%s\"", colName),
14383 : parser_errposition(pstate, def->location)));
14384 :
14385 : /*
14386 : * Cannot specify USING when altering type of a generated column, because
14387 : * that would violate the generation expression.
14388 : */
14389 1288 : if (attTup->attgenerated && def->cooked_default)
14390 12 : ereport(ERROR,
14391 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
14392 : errmsg("cannot specify USING when altering type of generated column"),
14393 : errdetail("Column \"%s\" is a generated column.", colName),
14394 : parser_errposition(pstate, def->location)));
14395 :
14396 : /*
14397 : * Don't alter inherited columns. At outer level, there had better not be
14398 : * any inherited definition; when recursing, we assume this was checked at
14399 : * the parent level (see below).
14400 : */
14401 1276 : if (attTup->attinhcount > 0 && !recursing)
14402 6 : ereport(ERROR,
14403 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14404 : errmsg("cannot alter inherited column \"%s\"", colName),
14405 : parser_errposition(pstate, def->location)));
14406 :
14407 : /* Don't alter columns used in the partition key */
14408 1270 : if (has_partition_attrs(rel,
14409 : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
14410 : &is_expr))
14411 18 : ereport(ERROR,
14412 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14413 : errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
14414 : colName, RelationGetRelationName(rel)),
14415 : parser_errposition(pstate, def->location)));
14416 :
14417 : /* Look up the target type */
14418 1252 : typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
14419 :
14420 1246 : aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
14421 1246 : if (aclresult != ACLCHECK_OK)
14422 12 : aclcheck_error_type(aclresult, targettype);
14423 :
14424 : /* And the collation */
14425 1234 : targetcollid = GetColumnDefCollation(pstate, def, targettype);
14426 :
14427 : /* make sure datatype is legal for a column */
14428 2456 : CheckAttributeType(colName, targettype, targetcollid,
14429 1228 : list_make1_oid(rel->rd_rel->reltype),
14430 1228 : (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
14431 :
14432 1216 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14433 : {
14434 : /* do nothing */
14435 : }
14436 1180 : else if (tab->relkind == RELKIND_RELATION ||
14437 202 : tab->relkind == RELKIND_PARTITIONED_TABLE)
14438 : {
14439 : /*
14440 : * Set up an expression to transform the old data value to the new
14441 : * type. If a USING option was given, use the expression as
14442 : * transformed by transformAlterTableStmt, else just take the old
14443 : * value and try to coerce it. We do this first so that type
14444 : * incompatibility can be detected before we waste effort, and because
14445 : * we need the expression to be parsed against the original table row
14446 : * type.
14447 : */
14448 1044 : if (!transform)
14449 : {
14450 816 : transform = (Node *) makeVar(1, attnum,
14451 : attTup->atttypid, attTup->atttypmod,
14452 : attTup->attcollation,
14453 : 0);
14454 : }
14455 :
14456 1044 : transform = coerce_to_target_type(pstate,
14457 : transform, exprType(transform),
14458 : targettype, targettypmod,
14459 : COERCION_ASSIGNMENT,
14460 : COERCE_IMPLICIT_CAST,
14461 : -1);
14462 1044 : if (transform == NULL)
14463 : {
14464 : /* error text depends on whether USING was specified or not */
14465 24 : if (def->cooked_default != NULL)
14466 6 : ereport(ERROR,
14467 : (errcode(ERRCODE_DATATYPE_MISMATCH),
14468 : errmsg("result of USING clause for column \"%s\""
14469 : " cannot be cast automatically to type %s",
14470 : colName, format_type_be(targettype)),
14471 : errhint("You might need to add an explicit cast.")));
14472 : else
14473 18 : ereport(ERROR,
14474 : (errcode(ERRCODE_DATATYPE_MISMATCH),
14475 : errmsg("column \"%s\" cannot be cast automatically to type %s",
14476 : colName, format_type_be(targettype)),
14477 : !attTup->attgenerated ?
14478 : /* translator: USING is SQL, don't translate it */
14479 : errhint("You might need to specify \"USING %s::%s\".",
14480 : quote_identifier(colName),
14481 : format_type_with_typemod(targettype,
14482 : targettypmod)) : 0));
14483 : }
14484 :
14485 : /* Fix collations after all else */
14486 1020 : assign_expr_collations(pstate, transform);
14487 :
14488 : /* Expand virtual generated columns in the expr. */
14489 1020 : transform = expand_generated_columns_in_expr(transform, rel, 1);
14490 :
14491 : /* Plan the expr now so we can accurately assess the need to rewrite. */
14492 1020 : transform = (Node *) expression_planner((Expr *) transform);
14493 :
14494 : /*
14495 : * Add a work queue item to make ATRewriteTable update the column
14496 : * contents.
14497 : */
14498 1020 : newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
14499 1020 : newval->attnum = attnum;
14500 1020 : newval->expr = (Expr *) transform;
14501 1020 : newval->is_generated = false;
14502 :
14503 1020 : tab->newvals = lappend(tab->newvals, newval);
14504 1020 : if (ATColumnChangeRequiresRewrite(transform, attnum))
14505 824 : tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
14506 : }
14507 136 : else if (transform)
14508 12 : ereport(ERROR,
14509 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14510 : errmsg("\"%s\" is not a table",
14511 : RelationGetRelationName(rel))));
14512 :
14513 1180 : if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14514 : {
14515 : /*
14516 : * For relations or columns without storage, do this check now.
14517 : * Regular tables will check it later when the table is being
14518 : * rewritten.
14519 : */
14520 226 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
14521 : }
14522 :
14523 1132 : ReleaseSysCache(tuple);
14524 :
14525 : /*
14526 : * Recurse manually by queueing a new command for each child, if
14527 : * necessary. We cannot apply ATSimpleRecursion here because we need to
14528 : * remap attribute numbers in the USING expression, if any.
14529 : *
14530 : * If we are told not to recurse, there had better not be any child
14531 : * tables; else the alter would put them out of step.
14532 : */
14533 1132 : if (recurse)
14534 : {
14535 874 : Oid relid = RelationGetRelid(rel);
14536 : List *child_oids,
14537 : *child_numparents;
14538 : ListCell *lo,
14539 : *li;
14540 :
14541 874 : child_oids = find_all_inheritors(relid, lockmode,
14542 : &child_numparents);
14543 :
14544 : /*
14545 : * find_all_inheritors does the recursive search of the inheritance
14546 : * hierarchy, so all we have to do is process all of the relids in the
14547 : * list that it returns.
14548 : */
14549 1956 : forboth(lo, child_oids, li, child_numparents)
14550 : {
14551 1106 : Oid childrelid = lfirst_oid(lo);
14552 1106 : int numparents = lfirst_int(li);
14553 : Relation childrel;
14554 : HeapTuple childtuple;
14555 : Form_pg_attribute childattTup;
14556 :
14557 1106 : if (childrelid == relid)
14558 874 : continue;
14559 :
14560 : /* find_all_inheritors already got lock */
14561 232 : childrel = relation_open(childrelid, NoLock);
14562 232 : CheckAlterTableIsSafe(childrel);
14563 :
14564 : /*
14565 : * Verify that the child doesn't have any inherited definitions of
14566 : * this column that came from outside this inheritance hierarchy.
14567 : * (renameatt makes a similar test, though in a different way
14568 : * because of its different recursion mechanism.)
14569 : */
14570 232 : childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
14571 : colName);
14572 232 : if (!HeapTupleIsValid(childtuple))
14573 0 : ereport(ERROR,
14574 : (errcode(ERRCODE_UNDEFINED_COLUMN),
14575 : errmsg("column \"%s\" of relation \"%s\" does not exist",
14576 : colName, RelationGetRelationName(childrel))));
14577 232 : childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
14578 :
14579 232 : if (childattTup->attinhcount > numparents)
14580 6 : ereport(ERROR,
14581 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14582 : errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
14583 : colName, RelationGetRelationName(childrel))));
14584 :
14585 226 : ReleaseSysCache(childtuple);
14586 :
14587 : /*
14588 : * Remap the attribute numbers. If no USING expression was
14589 : * specified, there is no need for this step.
14590 : */
14591 226 : if (def->cooked_default)
14592 : {
14593 : AttrMap *attmap;
14594 : bool found_whole_row;
14595 :
14596 : /* create a copy to scribble on */
14597 78 : cmd = copyObject(cmd);
14598 :
14599 78 : attmap = build_attrmap_by_name(RelationGetDescr(childrel),
14600 : RelationGetDescr(rel),
14601 : false);
14602 156 : ((ColumnDef *) cmd->def)->cooked_default =
14603 78 : map_variable_attnos(def->cooked_default,
14604 : 1, 0,
14605 : attmap,
14606 : InvalidOid, &found_whole_row);
14607 78 : if (found_whole_row)
14608 6 : ereport(ERROR,
14609 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14610 : errmsg("cannot convert whole-row table reference"),
14611 : errdetail("USING expression contains a whole-row table reference.")));
14612 72 : pfree(attmap);
14613 : }
14614 220 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
14615 208 : relation_close(childrel, NoLock);
14616 : }
14617 : }
14618 308 : else if (!recursing &&
14619 50 : find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
14620 0 : ereport(ERROR,
14621 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14622 : errmsg("type of inherited column \"%s\" must be changed in child tables too",
14623 : colName)));
14624 :
14625 1108 : if (tab->relkind == RELKIND_COMPOSITE_TYPE)
14626 50 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
14627 1102 : }
14628 :
14629 : /*
14630 : * When the data type of a column is changed, a rewrite might not be required
14631 : * if the new type is sufficiently identical to the old one, and the USING
14632 : * clause isn't trying to insert some other value. It's safe to skip the
14633 : * rewrite in these cases:
14634 : *
14635 : * - the old type is binary coercible to the new type
14636 : * - the new type is an unconstrained domain over the old type
14637 : * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
14638 : *
14639 : * In the case of a constrained domain, we could get by with scanning the
14640 : * table and checking the constraint rather than actually rewriting it, but we
14641 : * don't currently try to do that.
14642 : */
14643 : static bool
14644 1020 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
14645 : {
14646 : Assert(expr != NULL);
14647 :
14648 : for (;;)
14649 : {
14650 : /* only one varno, so no need to check that */
14651 1138 : if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
14652 196 : return false;
14653 942 : else if (IsA(expr, RelabelType))
14654 106 : expr = (Node *) ((RelabelType *) expr)->arg;
14655 836 : else if (IsA(expr, CoerceToDomain))
14656 : {
14657 0 : CoerceToDomain *d = (CoerceToDomain *) expr;
14658 :
14659 0 : if (DomainHasConstraints(d->resulttype))
14660 0 : return true;
14661 0 : expr = (Node *) d->arg;
14662 : }
14663 836 : else if (IsA(expr, FuncExpr))
14664 : {
14665 630 : FuncExpr *f = (FuncExpr *) expr;
14666 :
14667 630 : switch (f->funcid)
14668 : {
14669 18 : case F_TIMESTAMPTZ_TIMESTAMP:
14670 : case F_TIMESTAMP_TIMESTAMPTZ:
14671 18 : if (TimestampTimestampTzRequiresRewrite())
14672 6 : return true;
14673 : else
14674 12 : expr = linitial(f->args);
14675 12 : break;
14676 612 : default:
14677 612 : return true;
14678 : }
14679 : }
14680 : else
14681 206 : return true;
14682 : }
14683 : }
14684 :
14685 : /*
14686 : * ALTER COLUMN .. SET DATA TYPE
14687 : *
14688 : * Return the address of the modified column.
14689 : */
14690 : static ObjectAddress
14691 1066 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
14692 : AlterTableCmd *cmd, LOCKMODE lockmode)
14693 : {
14694 1066 : char *colName = cmd->name;
14695 1066 : ColumnDef *def = (ColumnDef *) cmd->def;
14696 1066 : TypeName *typeName = def->typeName;
14697 : HeapTuple heapTup;
14698 : Form_pg_attribute attTup,
14699 : attOldTup;
14700 : AttrNumber attnum;
14701 : HeapTuple typeTuple;
14702 : Form_pg_type tform;
14703 : Oid targettype;
14704 : int32 targettypmod;
14705 : Oid targetcollid;
14706 : Node *defaultexpr;
14707 : Relation attrelation;
14708 : Relation depRel;
14709 : ScanKeyData key[3];
14710 : SysScanDesc scan;
14711 : HeapTuple depTup;
14712 : ObjectAddress address;
14713 :
14714 : /*
14715 : * Clear all the missing values if we're rewriting the table, since this
14716 : * renders them pointless.
14717 : */
14718 1066 : if (tab->rewrite)
14719 : {
14720 : Relation newrel;
14721 :
14722 764 : newrel = table_open(RelationGetRelid(rel), NoLock);
14723 764 : RelationClearMissing(newrel);
14724 764 : relation_close(newrel, NoLock);
14725 : /* make sure we don't conflict with later attribute modifications */
14726 764 : CommandCounterIncrement();
14727 : }
14728 :
14729 1066 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
14730 :
14731 : /* Look up the target column */
14732 1066 : heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
14733 1066 : if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
14734 0 : ereport(ERROR,
14735 : (errcode(ERRCODE_UNDEFINED_COLUMN),
14736 : errmsg("column \"%s\" of relation \"%s\" does not exist",
14737 : colName, RelationGetRelationName(rel))));
14738 1066 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
14739 1066 : attnum = attTup->attnum;
14740 1066 : attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
14741 :
14742 : /* Check for multiple ALTER TYPE on same column --- can't cope */
14743 1066 : if (attTup->atttypid != attOldTup->atttypid ||
14744 1066 : attTup->atttypmod != attOldTup->atttypmod)
14745 0 : ereport(ERROR,
14746 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14747 : errmsg("cannot alter type of column \"%s\" twice",
14748 : colName)));
14749 :
14750 : /* Look up the target type (should not fail, since prep found it) */
14751 1066 : typeTuple = typenameType(NULL, typeName, &targettypmod);
14752 1066 : tform = (Form_pg_type) GETSTRUCT(typeTuple);
14753 1066 : targettype = tform->oid;
14754 : /* And the collation */
14755 1066 : targetcollid = GetColumnDefCollation(NULL, def, targettype);
14756 :
14757 : /*
14758 : * If there is a default expression for the column, get it and ensure we
14759 : * can coerce it to the new datatype. (We must do this before changing
14760 : * the column type, because build_column_default itself will try to
14761 : * coerce, and will not issue the error message we want if it fails.)
14762 : *
14763 : * We remove any implicit coercion steps at the top level of the old
14764 : * default expression; this has been agreed to satisfy the principle of
14765 : * least surprise. (The conversion to the new column type should act like
14766 : * it started from what the user sees as the stored expression, and the
14767 : * implicit coercions aren't going to be shown.)
14768 : */
14769 1066 : if (attTup->atthasdef)
14770 : {
14771 92 : defaultexpr = build_column_default(rel, attnum);
14772 : Assert(defaultexpr);
14773 92 : defaultexpr = strip_implicit_coercions(defaultexpr);
14774 92 : defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
14775 : defaultexpr, exprType(defaultexpr),
14776 : targettype, targettypmod,
14777 : COERCION_ASSIGNMENT,
14778 : COERCE_IMPLICIT_CAST,
14779 : -1);
14780 92 : if (defaultexpr == NULL)
14781 : {
14782 6 : if (attTup->attgenerated)
14783 0 : ereport(ERROR,
14784 : (errcode(ERRCODE_DATATYPE_MISMATCH),
14785 : errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
14786 : colName, format_type_be(targettype))));
14787 : else
14788 6 : ereport(ERROR,
14789 : (errcode(ERRCODE_DATATYPE_MISMATCH),
14790 : errmsg("default for column \"%s\" cannot be cast automatically to type %s",
14791 : colName, format_type_be(targettype))));
14792 : }
14793 : }
14794 : else
14795 974 : defaultexpr = NULL;
14796 :
14797 : /*
14798 : * Find everything that depends on the column (constraints, indexes, etc),
14799 : * and record enough information to let us recreate the objects.
14800 : *
14801 : * The actual recreation does not happen here, but only after we have
14802 : * performed all the individual ALTER TYPE operations. We have to save
14803 : * the info before executing ALTER TYPE, though, else the deparser will
14804 : * get confused.
14805 : */
14806 1060 : RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
14807 :
14808 : /*
14809 : * Now scan for dependencies of this column on other things. The only
14810 : * things we should find are the dependency on the column datatype and
14811 : * possibly a collation dependency. Those can be removed.
14812 : */
14813 1024 : depRel = table_open(DependRelationId, RowExclusiveLock);
14814 :
14815 1024 : ScanKeyInit(&key[0],
14816 : Anum_pg_depend_classid,
14817 : BTEqualStrategyNumber, F_OIDEQ,
14818 : ObjectIdGetDatum(RelationRelationId));
14819 1024 : ScanKeyInit(&key[1],
14820 : Anum_pg_depend_objid,
14821 : BTEqualStrategyNumber, F_OIDEQ,
14822 : ObjectIdGetDatum(RelationGetRelid(rel)));
14823 1024 : ScanKeyInit(&key[2],
14824 : Anum_pg_depend_objsubid,
14825 : BTEqualStrategyNumber, F_INT4EQ,
14826 : Int32GetDatum((int32) attnum));
14827 :
14828 1024 : scan = systable_beginscan(depRel, DependDependerIndexId, true,
14829 : NULL, 3, key);
14830 :
14831 1028 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
14832 : {
14833 4 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
14834 : ObjectAddress foundObject;
14835 :
14836 4 : foundObject.classId = foundDep->refclassid;
14837 4 : foundObject.objectId = foundDep->refobjid;
14838 4 : foundObject.objectSubId = foundDep->refobjsubid;
14839 :
14840 4 : if (foundDep->deptype != DEPENDENCY_NORMAL)
14841 0 : elog(ERROR, "found unexpected dependency type '%c'",
14842 : foundDep->deptype);
14843 4 : if (!(foundDep->refclassid == TypeRelationId &&
14844 4 : foundDep->refobjid == attTup->atttypid) &&
14845 0 : !(foundDep->refclassid == CollationRelationId &&
14846 0 : foundDep->refobjid == attTup->attcollation))
14847 0 : elog(ERROR, "found unexpected dependency for column: %s",
14848 : getObjectDescription(&foundObject, false));
14849 :
14850 4 : CatalogTupleDelete(depRel, &depTup->t_self);
14851 : }
14852 :
14853 1024 : systable_endscan(scan);
14854 :
14855 1024 : table_close(depRel, RowExclusiveLock);
14856 :
14857 : /*
14858 : * Here we go --- change the recorded column type and collation. (Note
14859 : * heapTup is a copy of the syscache entry, so okay to scribble on.) First
14860 : * fix up the missing value if any.
14861 : */
14862 1024 : if (attTup->atthasmissing)
14863 : {
14864 : Datum missingval;
14865 : bool missingNull;
14866 :
14867 : /* if rewrite is true the missing value should already be cleared */
14868 : Assert(tab->rewrite == 0);
14869 :
14870 : /* Get the missing value datum */
14871 6 : missingval = heap_getattr(heapTup,
14872 : Anum_pg_attribute_attmissingval,
14873 : attrelation->rd_att,
14874 : &missingNull);
14875 :
14876 : /* if it's a null array there is nothing to do */
14877 :
14878 6 : if (!missingNull)
14879 : {
14880 : /*
14881 : * Get the datum out of the array and repack it in a new array
14882 : * built with the new type data. We assume that since the table
14883 : * doesn't need rewriting, the actual Datum doesn't need to be
14884 : * changed, only the array metadata.
14885 : */
14886 :
14887 6 : int one = 1;
14888 : bool isNull;
14889 6 : Datum valuesAtt[Natts_pg_attribute] = {0};
14890 6 : bool nullsAtt[Natts_pg_attribute] = {0};
14891 6 : bool replacesAtt[Natts_pg_attribute] = {0};
14892 : HeapTuple newTup;
14893 :
14894 12 : missingval = array_get_element(missingval,
14895 : 1,
14896 : &one,
14897 : 0,
14898 6 : attTup->attlen,
14899 6 : attTup->attbyval,
14900 6 : attTup->attalign,
14901 : &isNull);
14902 6 : missingval = PointerGetDatum(construct_array(&missingval,
14903 : 1,
14904 : targettype,
14905 6 : tform->typlen,
14906 6 : tform->typbyval,
14907 6 : tform->typalign));
14908 :
14909 6 : valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
14910 6 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
14911 6 : nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
14912 :
14913 6 : newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
14914 : valuesAtt, nullsAtt, replacesAtt);
14915 6 : heap_freetuple(heapTup);
14916 6 : heapTup = newTup;
14917 6 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
14918 : }
14919 : }
14920 :
14921 1024 : attTup->atttypid = targettype;
14922 1024 : attTup->atttypmod = targettypmod;
14923 1024 : attTup->attcollation = targetcollid;
14924 1024 : if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
14925 0 : ereport(ERROR,
14926 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
14927 : errmsg("too many array dimensions"));
14928 1024 : attTup->attndims = list_length(typeName->arrayBounds);
14929 1024 : attTup->attlen = tform->typlen;
14930 1024 : attTup->attbyval = tform->typbyval;
14931 1024 : attTup->attalign = tform->typalign;
14932 1024 : attTup->attstorage = tform->typstorage;
14933 1024 : attTup->attcompression = InvalidCompressionMethod;
14934 :
14935 1024 : ReleaseSysCache(typeTuple);
14936 :
14937 1024 : CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
14938 :
14939 1024 : table_close(attrelation, RowExclusiveLock);
14940 :
14941 : /* Install dependencies on new datatype and collation */
14942 1024 : add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
14943 1024 : add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
14944 :
14945 : /*
14946 : * Drop any pg_statistic entry for the column, since it's now wrong type
14947 : */
14948 1024 : RemoveStatistics(RelationGetRelid(rel), attnum);
14949 :
14950 1024 : InvokeObjectPostAlterHook(RelationRelationId,
14951 : RelationGetRelid(rel), attnum);
14952 :
14953 : /*
14954 : * Update the default, if present, by brute force --- remove and re-add
14955 : * the default. Probably unsafe to take shortcuts, since the new version
14956 : * may well have additional dependencies. (It's okay to do this now,
14957 : * rather than after other ALTER TYPE commands, since the default won't
14958 : * depend on other column types.)
14959 : */
14960 1024 : if (defaultexpr)
14961 : {
14962 : /*
14963 : * If it's a GENERATED default, drop its dependency records, in
14964 : * particular its INTERNAL dependency on the column, which would
14965 : * otherwise cause dependency.c to refuse to perform the deletion.
14966 : */
14967 86 : if (attTup->attgenerated)
14968 : {
14969 36 : Oid attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
14970 :
14971 36 : if (!OidIsValid(attrdefoid))
14972 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
14973 : RelationGetRelid(rel), attnum);
14974 36 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
14975 : }
14976 :
14977 : /*
14978 : * Make updates-so-far visible, particularly the new pg_attribute row
14979 : * which will be updated again.
14980 : */
14981 86 : CommandCounterIncrement();
14982 :
14983 : /*
14984 : * We use RESTRICT here for safety, but at present we do not expect
14985 : * anything to depend on the default.
14986 : */
14987 86 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
14988 : true);
14989 :
14990 86 : (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
14991 : }
14992 :
14993 1024 : ObjectAddressSubSet(address, RelationRelationId,
14994 : RelationGetRelid(rel), attnum);
14995 :
14996 : /* Cleanup */
14997 1024 : heap_freetuple(heapTup);
14998 :
14999 1024 : return address;
15000 : }
15001 :
15002 : /*
15003 : * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
15004 : * that depends on the column (constraints, indexes, etc), and record enough
15005 : * information to let us recreate the objects.
15006 : */
15007 : static void
15008 1138 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
15009 : Relation rel, AttrNumber attnum, const char *colName)
15010 : {
15011 : Relation depRel;
15012 : ScanKeyData key[3];
15013 : SysScanDesc scan;
15014 : HeapTuple depTup;
15015 :
15016 : Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
15017 :
15018 1138 : depRel = table_open(DependRelationId, RowExclusiveLock);
15019 :
15020 1138 : ScanKeyInit(&key[0],
15021 : Anum_pg_depend_refclassid,
15022 : BTEqualStrategyNumber, F_OIDEQ,
15023 : ObjectIdGetDatum(RelationRelationId));
15024 1138 : ScanKeyInit(&key[1],
15025 : Anum_pg_depend_refobjid,
15026 : BTEqualStrategyNumber, F_OIDEQ,
15027 : ObjectIdGetDatum(RelationGetRelid(rel)));
15028 1138 : ScanKeyInit(&key[2],
15029 : Anum_pg_depend_refobjsubid,
15030 : BTEqualStrategyNumber, F_INT4EQ,
15031 : Int32GetDatum((int32) attnum));
15032 :
15033 1138 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15034 : NULL, 3, key);
15035 :
15036 2270 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15037 : {
15038 1168 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15039 : ObjectAddress foundObject;
15040 :
15041 1168 : foundObject.classId = foundDep->classid;
15042 1168 : foundObject.objectId = foundDep->objid;
15043 1168 : foundObject.objectSubId = foundDep->objsubid;
15044 :
15045 1168 : switch (foundObject.classId)
15046 : {
15047 274 : case RelationRelationId:
15048 : {
15049 274 : char relKind = get_rel_relkind(foundObject.objectId);
15050 :
15051 274 : if (relKind == RELKIND_INDEX ||
15052 : relKind == RELKIND_PARTITIONED_INDEX)
15053 : {
15054 : Assert(foundObject.objectSubId == 0);
15055 236 : RememberIndexForRebuilding(foundObject.objectId, tab);
15056 : }
15057 38 : else if (relKind == RELKIND_SEQUENCE)
15058 : {
15059 : /*
15060 : * This must be a SERIAL column's sequence. We need
15061 : * not do anything to it.
15062 : */
15063 : Assert(foundObject.objectSubId == 0);
15064 : }
15065 : else
15066 : {
15067 : /* Not expecting any other direct dependencies... */
15068 0 : elog(ERROR, "unexpected object depending on column: %s",
15069 : getObjectDescription(&foundObject, false));
15070 : }
15071 274 : break;
15072 : }
15073 :
15074 680 : case ConstraintRelationId:
15075 : Assert(foundObject.objectSubId == 0);
15076 680 : RememberConstraintForRebuilding(foundObject.objectId, tab);
15077 680 : break;
15078 :
15079 0 : case ProcedureRelationId:
15080 :
15081 : /*
15082 : * A new-style SQL function can depend on a column, if that
15083 : * column is referenced in the parsed function body. Ideally
15084 : * we'd automatically update the function by deparsing and
15085 : * reparsing it, but that's risky and might well fail anyhow.
15086 : * FIXME someday.
15087 : *
15088 : * This is only a problem for AT_AlterColumnType, not
15089 : * AT_SetExpression.
15090 : */
15091 0 : if (subtype == AT_AlterColumnType)
15092 0 : ereport(ERROR,
15093 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15094 : errmsg("cannot alter type of a column used by a function or procedure"),
15095 : errdetail("%s depends on column \"%s\"",
15096 : getObjectDescription(&foundObject, false),
15097 : colName)));
15098 0 : break;
15099 :
15100 12 : case RewriteRelationId:
15101 :
15102 : /*
15103 : * View/rule bodies have pretty much the same issues as
15104 : * function bodies. FIXME someday.
15105 : */
15106 12 : if (subtype == AT_AlterColumnType)
15107 12 : ereport(ERROR,
15108 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15109 : errmsg("cannot alter type of a column used by a view or rule"),
15110 : errdetail("%s depends on column \"%s\"",
15111 : getObjectDescription(&foundObject, false),
15112 : colName)));
15113 0 : break;
15114 :
15115 0 : case TriggerRelationId:
15116 :
15117 : /*
15118 : * A trigger can depend on a column because the column is
15119 : * specified as an update target, or because the column is
15120 : * used in the trigger's WHEN condition. The first case would
15121 : * not require any extra work, but the second case would
15122 : * require updating the WHEN expression, which has the same
15123 : * issues as above. Since we can't easily tell which case
15124 : * applies, we punt for both. FIXME someday.
15125 : */
15126 0 : if (subtype == AT_AlterColumnType)
15127 0 : ereport(ERROR,
15128 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15129 : errmsg("cannot alter type of a column used in a trigger definition"),
15130 : errdetail("%s depends on column \"%s\"",
15131 : getObjectDescription(&foundObject, false),
15132 : colName)));
15133 0 : break;
15134 :
15135 0 : case PolicyRelationId:
15136 :
15137 : /*
15138 : * A policy can depend on a column because the column is
15139 : * specified in the policy's USING or WITH CHECK qual
15140 : * expressions. It might be possible to rewrite and recheck
15141 : * the policy expression, but punt for now. It's certainly
15142 : * easy enough to remove and recreate the policy; still, FIXME
15143 : * someday.
15144 : */
15145 0 : if (subtype == AT_AlterColumnType)
15146 0 : ereport(ERROR,
15147 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15148 : errmsg("cannot alter type of a column used in a policy definition"),
15149 : errdetail("%s depends on column \"%s\"",
15150 : getObjectDescription(&foundObject, false),
15151 : colName)));
15152 0 : break;
15153 :
15154 188 : case AttrDefaultRelationId:
15155 : {
15156 188 : ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
15157 :
15158 188 : if (col.objectId == RelationGetRelid(rel) &&
15159 188 : col.objectSubId == attnum)
15160 : {
15161 : /*
15162 : * Ignore the column's own default expression. The
15163 : * caller deals with it.
15164 : */
15165 : }
15166 : else
15167 : {
15168 : /*
15169 : * This must be a reference from the expression of a
15170 : * generated column elsewhere in the same table.
15171 : * Changing the type/generated expression of a column
15172 : * that is used by a generated column is not allowed
15173 : * by SQL standard, so just punt for now. It might be
15174 : * doable with some thinking and effort.
15175 : */
15176 24 : if (subtype == AT_AlterColumnType)
15177 24 : ereport(ERROR,
15178 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15179 : errmsg("cannot alter type of a column used by a generated column"),
15180 : errdetail("Column \"%s\" is used by generated column \"%s\".",
15181 : colName,
15182 : get_attname(col.objectId,
15183 : col.objectSubId,
15184 : false))));
15185 : }
15186 164 : break;
15187 : }
15188 :
15189 14 : case StatisticExtRelationId:
15190 :
15191 : /*
15192 : * Give the extended-stats machinery a chance to fix anything
15193 : * that this column type change would break.
15194 : */
15195 14 : RememberStatisticsForRebuilding(foundObject.objectId, tab);
15196 14 : break;
15197 :
15198 0 : case PublicationRelRelationId:
15199 :
15200 : /*
15201 : * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
15202 : * clause. Same issues as above. FIXME someday.
15203 : */
15204 0 : if (subtype == AT_AlterColumnType)
15205 0 : ereport(ERROR,
15206 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15207 : errmsg("cannot alter type of a column used by a publication WHERE clause"),
15208 : errdetail("%s depends on column \"%s\"",
15209 : getObjectDescription(&foundObject, false),
15210 : colName)));
15211 0 : break;
15212 :
15213 0 : default:
15214 :
15215 : /*
15216 : * We don't expect any other sorts of objects to depend on a
15217 : * column.
15218 : */
15219 0 : elog(ERROR, "unexpected object depending on column: %s",
15220 : getObjectDescription(&foundObject, false));
15221 : break;
15222 : }
15223 : }
15224 :
15225 1102 : systable_endscan(scan);
15226 1102 : table_close(depRel, NoLock);
15227 1102 : }
15228 :
15229 : /*
15230 : * Subroutine for ATExecAlterColumnType: remember that a replica identity
15231 : * needs to be reset.
15232 : */
15233 : static void
15234 444 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
15235 : {
15236 444 : if (!get_index_isreplident(indoid))
15237 426 : return;
15238 :
15239 18 : if (tab->replicaIdentityIndex)
15240 0 : elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
15241 :
15242 18 : tab->replicaIdentityIndex = get_rel_name(indoid);
15243 : }
15244 :
15245 : /*
15246 : * Subroutine for ATExecAlterColumnType: remember any clustered index.
15247 : */
15248 : static void
15249 444 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
15250 : {
15251 444 : if (!get_index_isclustered(indoid))
15252 426 : return;
15253 :
15254 18 : if (tab->clusterOnIndex)
15255 0 : elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
15256 :
15257 18 : tab->clusterOnIndex = get_rel_name(indoid);
15258 : }
15259 :
15260 : /*
15261 : * Subroutine for ATExecAlterColumnType: remember that a constraint needs
15262 : * to be rebuilt (which we might already know).
15263 : */
15264 : static void
15265 692 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
15266 : {
15267 : /*
15268 : * This de-duplication check is critical for two independent reasons: we
15269 : * mustn't try to recreate the same constraint twice, and if a constraint
15270 : * depends on more than one column whose type is to be altered, we must
15271 : * capture its definition string before applying any of the column type
15272 : * changes. ruleutils.c will get confused if we ask again later.
15273 : */
15274 692 : if (!list_member_oid(tab->changedConstraintOids, conoid))
15275 : {
15276 : /* OK, capture the constraint's existing definition string */
15277 602 : char *defstring = pg_get_constraintdef_command(conoid);
15278 : Oid indoid;
15279 :
15280 : /*
15281 : * It is critical to create not-null constraints ahead of primary key
15282 : * indexes; otherwise, the not-null constraint would be created by the
15283 : * primary key, and the constraint name would be wrong.
15284 : */
15285 602 : if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
15286 : {
15287 198 : tab->changedConstraintOids = lcons_oid(conoid,
15288 : tab->changedConstraintOids);
15289 198 : tab->changedConstraintDefs = lcons(defstring,
15290 : tab->changedConstraintDefs);
15291 : }
15292 : else
15293 : {
15294 :
15295 404 : tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
15296 : conoid);
15297 404 : tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
15298 : defstring);
15299 : }
15300 :
15301 : /*
15302 : * For the index of a constraint, if any, remember if it is used for
15303 : * the table's replica identity or if it is a clustered index, so that
15304 : * ATPostAlterTypeCleanup() can queue up commands necessary to restore
15305 : * those properties.
15306 : */
15307 602 : indoid = get_constraint_index(conoid);
15308 602 : if (OidIsValid(indoid))
15309 : {
15310 228 : RememberReplicaIdentityForRebuilding(indoid, tab);
15311 228 : RememberClusterOnForRebuilding(indoid, tab);
15312 : }
15313 : }
15314 692 : }
15315 :
15316 : /*
15317 : * Subroutine for ATExecAlterColumnType: remember that an index needs
15318 : * to be rebuilt (which we might already know).
15319 : */
15320 : static void
15321 236 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
15322 : {
15323 : /*
15324 : * This de-duplication check is critical for two independent reasons: we
15325 : * mustn't try to recreate the same index twice, and if an index depends
15326 : * on more than one column whose type is to be altered, we must capture
15327 : * its definition string before applying any of the column type changes.
15328 : * ruleutils.c will get confused if we ask again later.
15329 : */
15330 236 : if (!list_member_oid(tab->changedIndexOids, indoid))
15331 : {
15332 : /*
15333 : * Before adding it as an index-to-rebuild, we'd better see if it
15334 : * belongs to a constraint, and if so rebuild the constraint instead.
15335 : * Typically this check fails, because constraint indexes normally
15336 : * have only dependencies on their constraint. But it's possible for
15337 : * such an index to also have direct dependencies on table columns,
15338 : * for example with a partial exclusion constraint.
15339 : */
15340 228 : Oid conoid = get_index_constraint(indoid);
15341 :
15342 228 : if (OidIsValid(conoid))
15343 : {
15344 12 : RememberConstraintForRebuilding(conoid, tab);
15345 : }
15346 : else
15347 : {
15348 : /* OK, capture the index's existing definition string */
15349 216 : char *defstring = pg_get_indexdef_string(indoid);
15350 :
15351 216 : tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
15352 : indoid);
15353 216 : tab->changedIndexDefs = lappend(tab->changedIndexDefs,
15354 : defstring);
15355 :
15356 : /*
15357 : * Remember if this index is used for the table's replica identity
15358 : * or if it is a clustered index, so that ATPostAlterTypeCleanup()
15359 : * can queue up commands necessary to restore those properties.
15360 : */
15361 216 : RememberReplicaIdentityForRebuilding(indoid, tab);
15362 216 : RememberClusterOnForRebuilding(indoid, tab);
15363 : }
15364 : }
15365 236 : }
15366 :
15367 : /*
15368 : * Subroutine for ATExecAlterColumnType: remember that a statistics object
15369 : * needs to be rebuilt (which we might already know).
15370 : */
15371 : static void
15372 14 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
15373 : {
15374 : /*
15375 : * This de-duplication check is critical for two independent reasons: we
15376 : * mustn't try to recreate the same statistics object twice, and if the
15377 : * statistics object depends on more than one column whose type is to be
15378 : * altered, we must capture its definition string before applying any of
15379 : * the type changes. ruleutils.c will get confused if we ask again later.
15380 : */
15381 14 : if (!list_member_oid(tab->changedStatisticsOids, stxoid))
15382 : {
15383 : /* OK, capture the statistics object's existing definition string */
15384 14 : char *defstring = pg_get_statisticsobjdef_string(stxoid);
15385 :
15386 14 : tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
15387 : stxoid);
15388 14 : tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
15389 : defstring);
15390 : }
15391 14 : }
15392 :
15393 : /*
15394 : * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
15395 : * operations for a particular relation. We have to drop and recreate all the
15396 : * indexes and constraints that depend on the altered columns. We do the
15397 : * actual dropping here, but re-creation is managed by adding work queue
15398 : * entries to do those steps later.
15399 : */
15400 : static void
15401 1132 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
15402 : {
15403 : ObjectAddress obj;
15404 : ObjectAddresses *objects;
15405 : ListCell *def_item;
15406 : ListCell *oid_item;
15407 :
15408 : /*
15409 : * Collect all the constraints and indexes to drop so we can process them
15410 : * in a single call. That way we don't have to worry about dependencies
15411 : * among them.
15412 : */
15413 1132 : objects = new_object_addresses();
15414 :
15415 : /*
15416 : * Re-parse the index and constraint definitions, and attach them to the
15417 : * appropriate work queue entries. We do this before dropping because in
15418 : * the case of a constraint on another table, we might not yet have
15419 : * exclusive lock on the table the constraint is attached to, and we need
15420 : * to get that before reparsing/dropping. (That's possible at least for
15421 : * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
15422 : * requires a dependency on the target table's composite type in the other
15423 : * table's constraint expressions.)
15424 : *
15425 : * We can't rely on the output of deparsing to tell us which relation to
15426 : * operate on, because concurrent activity might have made the name
15427 : * resolve differently. Instead, we've got to use the OID of the
15428 : * constraint or index we're processing to figure out which relation to
15429 : * operate on.
15430 : */
15431 1734 : forboth(oid_item, tab->changedConstraintOids,
15432 : def_item, tab->changedConstraintDefs)
15433 : {
15434 602 : Oid oldId = lfirst_oid(oid_item);
15435 : HeapTuple tup;
15436 : Form_pg_constraint con;
15437 : Oid relid;
15438 : Oid confrelid;
15439 : bool conislocal;
15440 :
15441 602 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
15442 602 : if (!HeapTupleIsValid(tup)) /* should not happen */
15443 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
15444 602 : con = (Form_pg_constraint) GETSTRUCT(tup);
15445 602 : if (OidIsValid(con->conrelid))
15446 588 : relid = con->conrelid;
15447 : else
15448 : {
15449 : /* must be a domain constraint */
15450 14 : relid = get_typ_typrelid(getBaseType(con->contypid));
15451 14 : if (!OidIsValid(relid))
15452 0 : elog(ERROR, "could not identify relation associated with constraint %u", oldId);
15453 : }
15454 602 : confrelid = con->confrelid;
15455 602 : conislocal = con->conislocal;
15456 602 : ReleaseSysCache(tup);
15457 :
15458 602 : ObjectAddressSet(obj, ConstraintRelationId, oldId);
15459 602 : add_exact_object_address(&obj, objects);
15460 :
15461 : /*
15462 : * If the constraint is inherited (only), we don't want to inject a
15463 : * new definition here; it'll get recreated when
15464 : * ATAddCheckNNConstraint recurses from adding the parent table's
15465 : * constraint. But we had to carry the info this far so that we can
15466 : * drop the constraint below.
15467 : */
15468 602 : if (!conislocal)
15469 28 : continue;
15470 :
15471 : /*
15472 : * When rebuilding another table's constraint that references the
15473 : * table we're modifying, we might not yet have any lock on the other
15474 : * table, so get one now. We'll need AccessExclusiveLock for the DROP
15475 : * CONSTRAINT step, so there's no value in asking for anything weaker.
15476 : */
15477 574 : if (relid != tab->relid)
15478 42 : LockRelationOid(relid, AccessExclusiveLock);
15479 :
15480 574 : ATPostAlterTypeParse(oldId, relid, confrelid,
15481 574 : (char *) lfirst(def_item),
15482 574 : wqueue, lockmode, tab->rewrite);
15483 : }
15484 1348 : forboth(oid_item, tab->changedIndexOids,
15485 : def_item, tab->changedIndexDefs)
15486 : {
15487 216 : Oid oldId = lfirst_oid(oid_item);
15488 : Oid relid;
15489 :
15490 216 : relid = IndexGetRelation(oldId, false);
15491 216 : ATPostAlterTypeParse(oldId, relid, InvalidOid,
15492 216 : (char *) lfirst(def_item),
15493 216 : wqueue, lockmode, tab->rewrite);
15494 :
15495 216 : ObjectAddressSet(obj, RelationRelationId, oldId);
15496 216 : add_exact_object_address(&obj, objects);
15497 : }
15498 :
15499 : /* add dependencies for new statistics */
15500 1146 : forboth(oid_item, tab->changedStatisticsOids,
15501 : def_item, tab->changedStatisticsDefs)
15502 : {
15503 14 : Oid oldId = lfirst_oid(oid_item);
15504 : Oid relid;
15505 :
15506 14 : relid = StatisticsGetRelation(oldId, false);
15507 14 : ATPostAlterTypeParse(oldId, relid, InvalidOid,
15508 14 : (char *) lfirst(def_item),
15509 14 : wqueue, lockmode, tab->rewrite);
15510 :
15511 14 : ObjectAddressSet(obj, StatisticExtRelationId, oldId);
15512 14 : add_exact_object_address(&obj, objects);
15513 : }
15514 :
15515 : /*
15516 : * Queue up command to restore replica identity index marking
15517 : */
15518 1132 : if (tab->replicaIdentityIndex)
15519 : {
15520 18 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
15521 18 : ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
15522 :
15523 18 : subcmd->identity_type = REPLICA_IDENTITY_INDEX;
15524 18 : subcmd->name = tab->replicaIdentityIndex;
15525 18 : cmd->subtype = AT_ReplicaIdentity;
15526 18 : cmd->def = (Node *) subcmd;
15527 :
15528 : /* do it after indexes and constraints */
15529 18 : tab->subcmds[AT_PASS_OLD_CONSTR] =
15530 18 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15531 : }
15532 :
15533 : /*
15534 : * Queue up command to restore marking of index used for cluster.
15535 : */
15536 1132 : if (tab->clusterOnIndex)
15537 : {
15538 18 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
15539 :
15540 18 : cmd->subtype = AT_ClusterOn;
15541 18 : cmd->name = tab->clusterOnIndex;
15542 :
15543 : /* do it after indexes and constraints */
15544 18 : tab->subcmds[AT_PASS_OLD_CONSTR] =
15545 18 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15546 : }
15547 :
15548 : /*
15549 : * It should be okay to use DROP_RESTRICT here, since nothing else should
15550 : * be depending on these objects.
15551 : */
15552 1132 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
15553 :
15554 1132 : free_object_addresses(objects);
15555 :
15556 : /*
15557 : * The objects will get recreated during subsequent passes over the work
15558 : * queue.
15559 : */
15560 1132 : }
15561 :
15562 : /*
15563 : * Parse the previously-saved definition string for a constraint, index or
15564 : * statistics object against the newly-established column data type(s), and
15565 : * queue up the resulting command parsetrees for execution.
15566 : *
15567 : * This might fail if, for example, you have a WHERE clause that uses an
15568 : * operator that's not available for the new column type.
15569 : */
15570 : static void
15571 804 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
15572 : List **wqueue, LOCKMODE lockmode, bool rewrite)
15573 : {
15574 : List *raw_parsetree_list;
15575 : List *querytree_list;
15576 : ListCell *list_item;
15577 : Relation rel;
15578 :
15579 : /*
15580 : * We expect that we will get only ALTER TABLE and CREATE INDEX
15581 : * statements. Hence, there is no need to pass them through
15582 : * parse_analyze_*() or the rewriter, but instead we need to pass them
15583 : * through parse_utilcmd.c to make them ready for execution.
15584 : */
15585 804 : raw_parsetree_list = raw_parser(cmd, RAW_PARSE_DEFAULT);
15586 804 : querytree_list = NIL;
15587 1608 : foreach(list_item, raw_parsetree_list)
15588 : {
15589 804 : RawStmt *rs = lfirst_node(RawStmt, list_item);
15590 804 : Node *stmt = rs->stmt;
15591 :
15592 804 : if (IsA(stmt, IndexStmt))
15593 216 : querytree_list = lappend(querytree_list,
15594 216 : transformIndexStmt(oldRelId,
15595 : (IndexStmt *) stmt,
15596 : cmd));
15597 588 : else if (IsA(stmt, AlterTableStmt))
15598 : {
15599 : List *beforeStmts;
15600 : List *afterStmts;
15601 :
15602 560 : stmt = (Node *) transformAlterTableStmt(oldRelId,
15603 : (AlterTableStmt *) stmt,
15604 : cmd,
15605 : &beforeStmts,
15606 : &afterStmts);
15607 560 : querytree_list = list_concat(querytree_list, beforeStmts);
15608 560 : querytree_list = lappend(querytree_list, stmt);
15609 560 : querytree_list = list_concat(querytree_list, afterStmts);
15610 : }
15611 28 : else if (IsA(stmt, CreateStatsStmt))
15612 14 : querytree_list = lappend(querytree_list,
15613 14 : transformStatsStmt(oldRelId,
15614 : (CreateStatsStmt *) stmt,
15615 : cmd));
15616 : else
15617 14 : querytree_list = lappend(querytree_list, stmt);
15618 : }
15619 :
15620 : /* Caller should already have acquired whatever lock we need. */
15621 804 : rel = relation_open(oldRelId, NoLock);
15622 :
15623 : /*
15624 : * Attach each generated command to the proper place in the work queue.
15625 : * Note this could result in creation of entirely new work-queue entries.
15626 : *
15627 : * Also note that we have to tweak the command subtypes, because it turns
15628 : * out that re-creation of indexes and constraints has to act a bit
15629 : * differently from initial creation.
15630 : */
15631 1608 : foreach(list_item, querytree_list)
15632 : {
15633 804 : Node *stm = (Node *) lfirst(list_item);
15634 : AlteredTableInfo *tab;
15635 :
15636 804 : tab = ATGetQueueEntry(wqueue, rel);
15637 :
15638 804 : if (IsA(stm, IndexStmt))
15639 : {
15640 216 : IndexStmt *stmt = (IndexStmt *) stm;
15641 : AlterTableCmd *newcmd;
15642 :
15643 216 : if (!rewrite)
15644 56 : TryReuseIndex(oldId, stmt);
15645 216 : stmt->reset_default_tblspc = true;
15646 : /* keep the index's comment */
15647 216 : stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
15648 :
15649 216 : newcmd = makeNode(AlterTableCmd);
15650 216 : newcmd->subtype = AT_ReAddIndex;
15651 216 : newcmd->def = (Node *) stmt;
15652 216 : tab->subcmds[AT_PASS_OLD_INDEX] =
15653 216 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
15654 : }
15655 588 : else if (IsA(stm, AlterTableStmt))
15656 : {
15657 560 : AlterTableStmt *stmt = (AlterTableStmt *) stm;
15658 : ListCell *lcmd;
15659 :
15660 1120 : foreach(lcmd, stmt->cmds)
15661 : {
15662 560 : AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
15663 :
15664 560 : if (cmd->subtype == AT_AddIndex)
15665 : {
15666 : IndexStmt *indstmt;
15667 : Oid indoid;
15668 :
15669 228 : indstmt = castNode(IndexStmt, cmd->def);
15670 228 : indoid = get_constraint_index(oldId);
15671 :
15672 228 : if (!rewrite)
15673 48 : TryReuseIndex(indoid, indstmt);
15674 : /* keep any comment on the index */
15675 228 : indstmt->idxcomment = GetComment(indoid,
15676 : RelationRelationId, 0);
15677 228 : indstmt->reset_default_tblspc = true;
15678 :
15679 228 : cmd->subtype = AT_ReAddIndex;
15680 228 : tab->subcmds[AT_PASS_OLD_INDEX] =
15681 228 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
15682 :
15683 : /* recreate any comment on the constraint */
15684 228 : RebuildConstraintComment(tab,
15685 : AT_PASS_OLD_INDEX,
15686 : oldId,
15687 : rel,
15688 : NIL,
15689 228 : indstmt->idxname);
15690 : }
15691 332 : else if (cmd->subtype == AT_AddConstraint)
15692 : {
15693 332 : Constraint *con = castNode(Constraint, cmd->def);
15694 :
15695 332 : con->old_pktable_oid = refRelId;
15696 : /* rewriting neither side of a FK */
15697 332 : if (con->contype == CONSTR_FOREIGN &&
15698 72 : !rewrite && tab->rewrite == 0)
15699 6 : TryReuseForeignKey(oldId, con);
15700 332 : con->reset_default_tblspc = true;
15701 332 : cmd->subtype = AT_ReAddConstraint;
15702 332 : tab->subcmds[AT_PASS_OLD_CONSTR] =
15703 332 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15704 :
15705 : /*
15706 : * Recreate any comment on the constraint. If we have
15707 : * recreated a primary key, then transformTableConstraint
15708 : * has added an unnamed not-null constraint here; skip
15709 : * this in that case.
15710 : */
15711 332 : if (con->conname)
15712 332 : RebuildConstraintComment(tab,
15713 : AT_PASS_OLD_CONSTR,
15714 : oldId,
15715 : rel,
15716 : NIL,
15717 332 : con->conname);
15718 : else
15719 : Assert(con->contype == CONSTR_NOTNULL);
15720 : }
15721 : else
15722 0 : elog(ERROR, "unexpected statement subtype: %d",
15723 : (int) cmd->subtype);
15724 : }
15725 : }
15726 28 : else if (IsA(stm, AlterDomainStmt))
15727 : {
15728 14 : AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
15729 :
15730 14 : if (stmt->subtype == 'C') /* ADD CONSTRAINT */
15731 : {
15732 14 : Constraint *con = castNode(Constraint, stmt->def);
15733 14 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
15734 :
15735 14 : cmd->subtype = AT_ReAddDomainConstraint;
15736 14 : cmd->def = (Node *) stmt;
15737 14 : tab->subcmds[AT_PASS_OLD_CONSTR] =
15738 14 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15739 :
15740 : /* recreate any comment on the constraint */
15741 14 : RebuildConstraintComment(tab,
15742 : AT_PASS_OLD_CONSTR,
15743 : oldId,
15744 : NULL,
15745 : stmt->typeName,
15746 14 : con->conname);
15747 : }
15748 : else
15749 0 : elog(ERROR, "unexpected statement subtype: %d",
15750 : (int) stmt->subtype);
15751 : }
15752 14 : else if (IsA(stm, CreateStatsStmt))
15753 : {
15754 14 : CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
15755 : AlterTableCmd *newcmd;
15756 :
15757 : /* keep the statistics object's comment */
15758 14 : stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
15759 :
15760 14 : newcmd = makeNode(AlterTableCmd);
15761 14 : newcmd->subtype = AT_ReAddStatistics;
15762 14 : newcmd->def = (Node *) stmt;
15763 14 : tab->subcmds[AT_PASS_MISC] =
15764 14 : lappend(tab->subcmds[AT_PASS_MISC], newcmd);
15765 : }
15766 : else
15767 0 : elog(ERROR, "unexpected statement type: %d",
15768 : (int) nodeTag(stm));
15769 : }
15770 :
15771 804 : relation_close(rel, NoLock);
15772 804 : }
15773 :
15774 : /*
15775 : * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
15776 : * for a table or domain constraint that is being rebuilt.
15777 : *
15778 : * objid is the OID of the constraint.
15779 : * Pass "rel" for a table constraint, or "domname" (domain's qualified name
15780 : * as a string list) for a domain constraint.
15781 : * (We could dig that info, as well as the conname, out of the pg_constraint
15782 : * entry; but callers already have them so might as well pass them.)
15783 : */
15784 : static void
15785 574 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
15786 : Relation rel, List *domname,
15787 : const char *conname)
15788 : {
15789 : CommentStmt *cmd;
15790 : char *comment_str;
15791 : AlterTableCmd *newcmd;
15792 :
15793 : /* Look for comment for object wanted, and leave if none */
15794 574 : comment_str = GetComment(objid, ConstraintRelationId, 0);
15795 574 : if (comment_str == NULL)
15796 484 : return;
15797 :
15798 : /* Build CommentStmt node, copying all input data for safety */
15799 90 : cmd = makeNode(CommentStmt);
15800 90 : if (rel)
15801 : {
15802 78 : cmd->objtype = OBJECT_TABCONSTRAINT;
15803 78 : cmd->object = (Node *)
15804 78 : list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
15805 : makeString(pstrdup(RelationGetRelationName(rel))),
15806 : makeString(pstrdup(conname)));
15807 : }
15808 : else
15809 : {
15810 12 : cmd->objtype = OBJECT_DOMCONSTRAINT;
15811 12 : cmd->object = (Node *)
15812 12 : list_make2(makeTypeNameFromNameList(copyObject(domname)),
15813 : makeString(pstrdup(conname)));
15814 : }
15815 90 : cmd->comment = comment_str;
15816 :
15817 : /* Append it to list of commands */
15818 90 : newcmd = makeNode(AlterTableCmd);
15819 90 : newcmd->subtype = AT_ReAddComment;
15820 90 : newcmd->def = (Node *) cmd;
15821 90 : tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
15822 : }
15823 :
15824 : /*
15825 : * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
15826 : * for the real analysis, then mutates the IndexStmt based on that verdict.
15827 : */
15828 : static void
15829 104 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
15830 : {
15831 104 : if (CheckIndexCompatible(oldId,
15832 104 : stmt->accessMethod,
15833 104 : stmt->indexParams,
15834 104 : stmt->excludeOpNames,
15835 104 : stmt->iswithoutoverlaps))
15836 : {
15837 104 : Relation irel = index_open(oldId, NoLock);
15838 :
15839 : /* If it's a partitioned index, there is no storage to share. */
15840 104 : if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
15841 : {
15842 74 : stmt->oldNumber = irel->rd_locator.relNumber;
15843 74 : stmt->oldCreateSubid = irel->rd_createSubid;
15844 74 : stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
15845 : }
15846 104 : index_close(irel, NoLock);
15847 : }
15848 104 : }
15849 :
15850 : /*
15851 : * Subroutine for ATPostAlterTypeParse().
15852 : *
15853 : * Stash the old P-F equality operator into the Constraint node, for possible
15854 : * use by ATAddForeignKeyConstraint() in determining whether revalidation of
15855 : * this constraint can be skipped.
15856 : */
15857 : static void
15858 6 : TryReuseForeignKey(Oid oldId, Constraint *con)
15859 : {
15860 : HeapTuple tup;
15861 : Datum adatum;
15862 : ArrayType *arr;
15863 : Oid *rawarr;
15864 : int numkeys;
15865 : int i;
15866 :
15867 : Assert(con->contype == CONSTR_FOREIGN);
15868 : Assert(con->old_conpfeqop == NIL); /* already prepared this node */
15869 :
15870 6 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
15871 6 : if (!HeapTupleIsValid(tup)) /* should not happen */
15872 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
15873 :
15874 6 : adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
15875 : Anum_pg_constraint_conpfeqop);
15876 6 : arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
15877 6 : numkeys = ARR_DIMS(arr)[0];
15878 : /* test follows the one in ri_FetchConstraintInfo() */
15879 6 : if (ARR_NDIM(arr) != 1 ||
15880 6 : ARR_HASNULL(arr) ||
15881 6 : ARR_ELEMTYPE(arr) != OIDOID)
15882 0 : elog(ERROR, "conpfeqop is not a 1-D Oid array");
15883 6 : rawarr = (Oid *) ARR_DATA_PTR(arr);
15884 :
15885 : /* stash a List of the operator Oids in our Constraint node */
15886 12 : for (i = 0; i < numkeys; i++)
15887 6 : con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
15888 :
15889 6 : ReleaseSysCache(tup);
15890 6 : }
15891 :
15892 : /*
15893 : * ALTER COLUMN .. OPTIONS ( ... )
15894 : *
15895 : * Returns the address of the modified column
15896 : */
15897 : static ObjectAddress
15898 172 : ATExecAlterColumnGenericOptions(Relation rel,
15899 : const char *colName,
15900 : List *options,
15901 : LOCKMODE lockmode)
15902 : {
15903 : Relation ftrel;
15904 : Relation attrel;
15905 : ForeignServer *server;
15906 : ForeignDataWrapper *fdw;
15907 : HeapTuple tuple;
15908 : HeapTuple newtuple;
15909 : bool isnull;
15910 : Datum repl_val[Natts_pg_attribute];
15911 : bool repl_null[Natts_pg_attribute];
15912 : bool repl_repl[Natts_pg_attribute];
15913 : Datum datum;
15914 : Form_pg_foreign_table fttableform;
15915 : Form_pg_attribute atttableform;
15916 : AttrNumber attnum;
15917 : ObjectAddress address;
15918 :
15919 172 : if (options == NIL)
15920 0 : return InvalidObjectAddress;
15921 :
15922 : /* First, determine FDW validator associated to the foreign table. */
15923 172 : ftrel = table_open(ForeignTableRelationId, AccessShareLock);
15924 172 : tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
15925 172 : if (!HeapTupleIsValid(tuple))
15926 0 : ereport(ERROR,
15927 : (errcode(ERRCODE_UNDEFINED_OBJECT),
15928 : errmsg("foreign table \"%s\" does not exist",
15929 : RelationGetRelationName(rel))));
15930 172 : fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
15931 172 : server = GetForeignServer(fttableform->ftserver);
15932 172 : fdw = GetForeignDataWrapper(server->fdwid);
15933 :
15934 172 : table_close(ftrel, AccessShareLock);
15935 172 : ReleaseSysCache(tuple);
15936 :
15937 172 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
15938 172 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
15939 172 : if (!HeapTupleIsValid(tuple))
15940 0 : ereport(ERROR,
15941 : (errcode(ERRCODE_UNDEFINED_COLUMN),
15942 : errmsg("column \"%s\" of relation \"%s\" does not exist",
15943 : colName, RelationGetRelationName(rel))));
15944 :
15945 : /* Prevent them from altering a system attribute */
15946 172 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
15947 172 : attnum = atttableform->attnum;
15948 172 : if (attnum <= 0)
15949 6 : ereport(ERROR,
15950 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15951 : errmsg("cannot alter system column \"%s\"", colName)));
15952 :
15953 :
15954 : /* Initialize buffers for new tuple values */
15955 166 : memset(repl_val, 0, sizeof(repl_val));
15956 166 : memset(repl_null, false, sizeof(repl_null));
15957 166 : memset(repl_repl, false, sizeof(repl_repl));
15958 :
15959 : /* Extract the current options */
15960 166 : datum = SysCacheGetAttr(ATTNAME,
15961 : tuple,
15962 : Anum_pg_attribute_attfdwoptions,
15963 : &isnull);
15964 166 : if (isnull)
15965 156 : datum = PointerGetDatum(NULL);
15966 :
15967 : /* Transform the options */
15968 166 : datum = transformGenericOptions(AttributeRelationId,
15969 : datum,
15970 : options,
15971 : fdw->fdwvalidator);
15972 :
15973 166 : if (PointerIsValid(DatumGetPointer(datum)))
15974 166 : repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
15975 : else
15976 0 : repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
15977 :
15978 166 : repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
15979 :
15980 : /* Everything looks good - update the tuple */
15981 :
15982 166 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
15983 : repl_val, repl_null, repl_repl);
15984 :
15985 166 : CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
15986 :
15987 166 : InvokeObjectPostAlterHook(RelationRelationId,
15988 : RelationGetRelid(rel),
15989 : atttableform->attnum);
15990 166 : ObjectAddressSubSet(address, RelationRelationId,
15991 : RelationGetRelid(rel), attnum);
15992 :
15993 166 : ReleaseSysCache(tuple);
15994 :
15995 166 : table_close(attrel, RowExclusiveLock);
15996 :
15997 166 : heap_freetuple(newtuple);
15998 :
15999 166 : return address;
16000 : }
16001 :
16002 : /*
16003 : * ALTER TABLE OWNER
16004 : *
16005 : * recursing is true if we are recursing from a table to its indexes,
16006 : * sequences, or toast table. We don't allow the ownership of those things to
16007 : * be changed separately from the parent table. Also, we can skip permission
16008 : * checks (this is necessary not just an optimization, else we'd fail to
16009 : * handle toast tables properly).
16010 : *
16011 : * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
16012 : * free-standing composite type.
16013 : */
16014 : void
16015 3812 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
16016 : {
16017 : Relation target_rel;
16018 : Relation class_rel;
16019 : HeapTuple tuple;
16020 : Form_pg_class tuple_class;
16021 :
16022 : /*
16023 : * Get exclusive lock till end of transaction on the target table. Use
16024 : * relation_open so that we can work on indexes and sequences.
16025 : */
16026 3812 : target_rel = relation_open(relationOid, lockmode);
16027 :
16028 : /* Get its pg_class tuple, too */
16029 3812 : class_rel = table_open(RelationRelationId, RowExclusiveLock);
16030 :
16031 3812 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16032 3812 : if (!HeapTupleIsValid(tuple))
16033 0 : elog(ERROR, "cache lookup failed for relation %u", relationOid);
16034 3812 : tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16035 :
16036 : /* Can we change the ownership of this tuple? */
16037 3812 : switch (tuple_class->relkind)
16038 : {
16039 3466 : case RELKIND_RELATION:
16040 : case RELKIND_VIEW:
16041 : case RELKIND_MATVIEW:
16042 : case RELKIND_FOREIGN_TABLE:
16043 : case RELKIND_PARTITIONED_TABLE:
16044 : /* ok to change owner */
16045 3466 : break;
16046 96 : case RELKIND_INDEX:
16047 96 : if (!recursing)
16048 : {
16049 : /*
16050 : * Because ALTER INDEX OWNER used to be allowed, and in fact
16051 : * is generated by old versions of pg_dump, we give a warning
16052 : * and do nothing rather than erroring out. Also, to avoid
16053 : * unnecessary chatter while restoring those old dumps, say
16054 : * nothing at all if the command would be a no-op anyway.
16055 : */
16056 0 : if (tuple_class->relowner != newOwnerId)
16057 0 : ereport(WARNING,
16058 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16059 : errmsg("cannot change owner of index \"%s\"",
16060 : NameStr(tuple_class->relname)),
16061 : errhint("Change the ownership of the index's table instead.")));
16062 : /* quick hack to exit via the no-op path */
16063 0 : newOwnerId = tuple_class->relowner;
16064 : }
16065 96 : break;
16066 20 : case RELKIND_PARTITIONED_INDEX:
16067 20 : if (recursing)
16068 20 : break;
16069 0 : ereport(ERROR,
16070 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16071 : errmsg("cannot change owner of index \"%s\"",
16072 : NameStr(tuple_class->relname)),
16073 : errhint("Change the ownership of the index's table instead.")));
16074 : break;
16075 180 : case RELKIND_SEQUENCE:
16076 180 : if (!recursing &&
16077 132 : tuple_class->relowner != newOwnerId)
16078 : {
16079 : /* if it's an owned sequence, disallow changing it by itself */
16080 : Oid tableId;
16081 : int32 colId;
16082 :
16083 0 : if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16084 0 : sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16085 0 : ereport(ERROR,
16086 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16087 : errmsg("cannot change owner of sequence \"%s\"",
16088 : NameStr(tuple_class->relname)),
16089 : errdetail("Sequence \"%s\" is linked to table \"%s\".",
16090 : NameStr(tuple_class->relname),
16091 : get_rel_name(tableId))));
16092 : }
16093 180 : break;
16094 8 : case RELKIND_COMPOSITE_TYPE:
16095 8 : if (recursing)
16096 8 : break;
16097 0 : ereport(ERROR,
16098 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16099 : errmsg("\"%s\" is a composite type",
16100 : NameStr(tuple_class->relname)),
16101 : /* translator: %s is an SQL ALTER command */
16102 : errhint("Use %s instead.",
16103 : "ALTER TYPE")));
16104 : break;
16105 42 : case RELKIND_TOASTVALUE:
16106 42 : if (recursing)
16107 42 : break;
16108 : /* FALL THRU */
16109 : default:
16110 0 : ereport(ERROR,
16111 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16112 : errmsg("cannot change owner of relation \"%s\"",
16113 : NameStr(tuple_class->relname)),
16114 : errdetail_relkind_not_supported(tuple_class->relkind)));
16115 : }
16116 :
16117 : /*
16118 : * If the new owner is the same as the existing owner, consider the
16119 : * command to have succeeded. This is for dump restoration purposes.
16120 : */
16121 3812 : if (tuple_class->relowner != newOwnerId)
16122 : {
16123 : Datum repl_val[Natts_pg_class];
16124 : bool repl_null[Natts_pg_class];
16125 : bool repl_repl[Natts_pg_class];
16126 : Acl *newAcl;
16127 : Datum aclDatum;
16128 : bool isNull;
16129 : HeapTuple newtuple;
16130 :
16131 : /* skip permission checks when recursing to index or toast table */
16132 500 : if (!recursing)
16133 : {
16134 : /* Superusers can always do it */
16135 282 : if (!superuser())
16136 : {
16137 42 : Oid namespaceOid = tuple_class->relnamespace;
16138 : AclResult aclresult;
16139 :
16140 : /* Otherwise, must be owner of the existing object */
16141 42 : if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16142 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
16143 0 : RelationGetRelationName(target_rel));
16144 :
16145 : /* Must be able to become new owner */
16146 42 : check_can_set_role(GetUserId(), newOwnerId);
16147 :
16148 : /* New owner must have CREATE privilege on namespace */
16149 30 : aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16150 : ACL_CREATE);
16151 30 : if (aclresult != ACLCHECK_OK)
16152 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
16153 0 : get_namespace_name(namespaceOid));
16154 : }
16155 : }
16156 :
16157 488 : memset(repl_null, false, sizeof(repl_null));
16158 488 : memset(repl_repl, false, sizeof(repl_repl));
16159 :
16160 488 : repl_repl[Anum_pg_class_relowner - 1] = true;
16161 488 : repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16162 :
16163 : /*
16164 : * Determine the modified ACL for the new owner. This is only
16165 : * necessary when the ACL is non-null.
16166 : */
16167 488 : aclDatum = SysCacheGetAttr(RELOID, tuple,
16168 : Anum_pg_class_relacl,
16169 : &isNull);
16170 488 : if (!isNull)
16171 : {
16172 46 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
16173 : tuple_class->relowner, newOwnerId);
16174 46 : repl_repl[Anum_pg_class_relacl - 1] = true;
16175 46 : repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16176 : }
16177 :
16178 488 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16179 :
16180 488 : CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16181 :
16182 488 : heap_freetuple(newtuple);
16183 :
16184 : /*
16185 : * We must similarly update any per-column ACLs to reflect the new
16186 : * owner; for neatness reasons that's split out as a subroutine.
16187 : */
16188 488 : change_owner_fix_column_acls(relationOid,
16189 : tuple_class->relowner,
16190 : newOwnerId);
16191 :
16192 : /*
16193 : * Update owner dependency reference, if any. A composite type has
16194 : * none, because it's tracked for the pg_type entry instead of here;
16195 : * indexes and TOAST tables don't have their own entries either.
16196 : */
16197 488 : if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16198 480 : tuple_class->relkind != RELKIND_INDEX &&
16199 384 : tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16200 364 : tuple_class->relkind != RELKIND_TOASTVALUE)
16201 322 : changeDependencyOnOwner(RelationRelationId, relationOid,
16202 : newOwnerId);
16203 :
16204 : /*
16205 : * Also change the ownership of the table's row type, if it has one
16206 : */
16207 488 : if (OidIsValid(tuple_class->reltype))
16208 296 : AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16209 :
16210 : /*
16211 : * If we are operating on a table or materialized view, also change
16212 : * the ownership of any indexes and sequences that belong to the
16213 : * relation, as well as its toast table (if it has one).
16214 : */
16215 488 : if (tuple_class->relkind == RELKIND_RELATION ||
16216 262 : tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16217 224 : tuple_class->relkind == RELKIND_MATVIEW ||
16218 224 : tuple_class->relkind == RELKIND_TOASTVALUE)
16219 : {
16220 : List *index_oid_list;
16221 : ListCell *i;
16222 :
16223 : /* Find all the indexes belonging to this relation */
16224 306 : index_oid_list = RelationGetIndexList(target_rel);
16225 :
16226 : /* For each index, recursively change its ownership */
16227 422 : foreach(i, index_oid_list)
16228 116 : ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16229 :
16230 306 : list_free(index_oid_list);
16231 : }
16232 :
16233 : /* If it has a toast table, recurse to change its ownership */
16234 488 : if (tuple_class->reltoastrelid != InvalidOid)
16235 42 : ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16236 : true, lockmode);
16237 :
16238 : /* If it has dependent sequences, recurse to change them too */
16239 488 : change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16240 : }
16241 :
16242 3800 : InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16243 :
16244 3800 : ReleaseSysCache(tuple);
16245 3800 : table_close(class_rel, RowExclusiveLock);
16246 3800 : relation_close(target_rel, NoLock);
16247 3800 : }
16248 :
16249 : /*
16250 : * change_owner_fix_column_acls
16251 : *
16252 : * Helper function for ATExecChangeOwner. Scan the columns of the table
16253 : * and fix any non-null column ACLs to reflect the new owner.
16254 : */
16255 : static void
16256 488 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
16257 : {
16258 : Relation attRelation;
16259 : SysScanDesc scan;
16260 : ScanKeyData key[1];
16261 : HeapTuple attributeTuple;
16262 :
16263 488 : attRelation = table_open(AttributeRelationId, RowExclusiveLock);
16264 488 : ScanKeyInit(&key[0],
16265 : Anum_pg_attribute_attrelid,
16266 : BTEqualStrategyNumber, F_OIDEQ,
16267 : ObjectIdGetDatum(relationOid));
16268 488 : scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
16269 : true, NULL, 1, key);
16270 3386 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
16271 : {
16272 2898 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
16273 : Datum repl_val[Natts_pg_attribute];
16274 : bool repl_null[Natts_pg_attribute];
16275 : bool repl_repl[Natts_pg_attribute];
16276 : Acl *newAcl;
16277 : Datum aclDatum;
16278 : bool isNull;
16279 : HeapTuple newtuple;
16280 :
16281 : /* Ignore dropped columns */
16282 2898 : if (att->attisdropped)
16283 2896 : continue;
16284 :
16285 2898 : aclDatum = heap_getattr(attributeTuple,
16286 : Anum_pg_attribute_attacl,
16287 : RelationGetDescr(attRelation),
16288 : &isNull);
16289 : /* Null ACLs do not require changes */
16290 2898 : if (isNull)
16291 2896 : continue;
16292 :
16293 2 : memset(repl_null, false, sizeof(repl_null));
16294 2 : memset(repl_repl, false, sizeof(repl_repl));
16295 :
16296 2 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
16297 : oldOwnerId, newOwnerId);
16298 2 : repl_repl[Anum_pg_attribute_attacl - 1] = true;
16299 2 : repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
16300 :
16301 2 : newtuple = heap_modify_tuple(attributeTuple,
16302 : RelationGetDescr(attRelation),
16303 : repl_val, repl_null, repl_repl);
16304 :
16305 2 : CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
16306 :
16307 2 : heap_freetuple(newtuple);
16308 : }
16309 488 : systable_endscan(scan);
16310 488 : table_close(attRelation, RowExclusiveLock);
16311 488 : }
16312 :
16313 : /*
16314 : * change_owner_recurse_to_sequences
16315 : *
16316 : * Helper function for ATExecChangeOwner. Examines pg_depend searching
16317 : * for sequences that are dependent on serial columns, and changes their
16318 : * ownership.
16319 : */
16320 : static void
16321 488 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
16322 : {
16323 : Relation depRel;
16324 : SysScanDesc scan;
16325 : ScanKeyData key[2];
16326 : HeapTuple tup;
16327 :
16328 : /*
16329 : * SERIAL sequences are those having an auto dependency on one of the
16330 : * table's columns (we don't care *which* column, exactly).
16331 : */
16332 488 : depRel = table_open(DependRelationId, AccessShareLock);
16333 :
16334 488 : ScanKeyInit(&key[0],
16335 : Anum_pg_depend_refclassid,
16336 : BTEqualStrategyNumber, F_OIDEQ,
16337 : ObjectIdGetDatum(RelationRelationId));
16338 488 : ScanKeyInit(&key[1],
16339 : Anum_pg_depend_refobjid,
16340 : BTEqualStrategyNumber, F_OIDEQ,
16341 : ObjectIdGetDatum(relationOid));
16342 : /* we leave refobjsubid unspecified */
16343 :
16344 488 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
16345 : NULL, 2, key);
16346 :
16347 1378 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
16348 : {
16349 890 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
16350 : Relation seqRel;
16351 :
16352 : /* skip dependencies other than auto dependencies on columns */
16353 890 : if (depForm->refobjsubid == 0 ||
16354 352 : depForm->classid != RelationRelationId ||
16355 142 : depForm->objsubid != 0 ||
16356 142 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
16357 748 : continue;
16358 :
16359 : /* Use relation_open just in case it's an index */
16360 142 : seqRel = relation_open(depForm->objid, lockmode);
16361 :
16362 : /* skip non-sequence relations */
16363 142 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
16364 : {
16365 : /* No need to keep the lock */
16366 116 : relation_close(seqRel, lockmode);
16367 116 : continue;
16368 : }
16369 :
16370 : /* We don't need to close the sequence while we alter it. */
16371 26 : ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
16372 :
16373 : /* Now we can close it. Keep the lock till end of transaction. */
16374 26 : relation_close(seqRel, NoLock);
16375 : }
16376 :
16377 488 : systable_endscan(scan);
16378 :
16379 488 : relation_close(depRel, AccessShareLock);
16380 488 : }
16381 :
16382 : /*
16383 : * ALTER TABLE CLUSTER ON
16384 : *
16385 : * The only thing we have to do is to change the indisclustered bits.
16386 : *
16387 : * Return the address of the new clustering index.
16388 : */
16389 : static ObjectAddress
16390 64 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
16391 : {
16392 : Oid indexOid;
16393 : ObjectAddress address;
16394 :
16395 64 : indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
16396 :
16397 64 : if (!OidIsValid(indexOid))
16398 0 : ereport(ERROR,
16399 : (errcode(ERRCODE_UNDEFINED_OBJECT),
16400 : errmsg("index \"%s\" for table \"%s\" does not exist",
16401 : indexName, RelationGetRelationName(rel))));
16402 :
16403 : /* Check index is valid to cluster on */
16404 64 : check_index_is_clusterable(rel, indexOid, lockmode);
16405 :
16406 : /* And do the work */
16407 64 : mark_index_clustered(rel, indexOid, false);
16408 :
16409 58 : ObjectAddressSet(address,
16410 : RelationRelationId, indexOid);
16411 :
16412 58 : return address;
16413 : }
16414 :
16415 : /*
16416 : * ALTER TABLE SET WITHOUT CLUSTER
16417 : *
16418 : * We have to find any indexes on the table that have indisclustered bit
16419 : * set and turn it off.
16420 : */
16421 : static void
16422 18 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
16423 : {
16424 18 : mark_index_clustered(rel, InvalidOid, false);
16425 12 : }
16426 :
16427 : /*
16428 : * Preparation phase for SET ACCESS METHOD
16429 : *
16430 : * Check that the access method exists and determine whether a change is
16431 : * actually needed.
16432 : */
16433 : static void
16434 110 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
16435 : {
16436 : Oid amoid;
16437 :
16438 : /*
16439 : * Look up the access method name and check that it differs from the
16440 : * table's current AM. If DEFAULT was specified for a partitioned table
16441 : * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
16442 : */
16443 110 : if (amname != NULL)
16444 74 : amoid = get_table_am_oid(amname, false);
16445 36 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
16446 18 : amoid = InvalidOid;
16447 : else
16448 18 : amoid = get_table_am_oid(default_table_access_method, false);
16449 :
16450 : /* if it's a match, phase 3 doesn't need to do anything */
16451 110 : if (rel->rd_rel->relam == amoid)
16452 12 : return;
16453 :
16454 : /* Save info for Phase 3 to do the real work */
16455 98 : tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
16456 98 : tab->newAccessMethod = amoid;
16457 98 : tab->chgAccessMethod = true;
16458 : }
16459 :
16460 : /*
16461 : * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
16462 : * storage that have an interest in preserving AM.
16463 : *
16464 : * Since these have no storage, setting the access method is a catalog only
16465 : * operation.
16466 : */
16467 : static void
16468 44 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
16469 : {
16470 : Relation pg_class;
16471 : Oid oldAccessMethodId;
16472 : HeapTuple tuple;
16473 : Form_pg_class rd_rel;
16474 44 : Oid reloid = RelationGetRelid(rel);
16475 :
16476 : /*
16477 : * Shouldn't be called on relations having storage; these are processed in
16478 : * phase 3.
16479 : */
16480 : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
16481 :
16482 : /* Get a modifiable copy of the relation's pg_class row. */
16483 44 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
16484 :
16485 44 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
16486 44 : if (!HeapTupleIsValid(tuple))
16487 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
16488 44 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
16489 :
16490 : /* Update the pg_class row. */
16491 44 : oldAccessMethodId = rd_rel->relam;
16492 44 : rd_rel->relam = newAccessMethodId;
16493 :
16494 : /* Leave if no update required */
16495 44 : if (rd_rel->relam == oldAccessMethodId)
16496 : {
16497 0 : heap_freetuple(tuple);
16498 0 : table_close(pg_class, RowExclusiveLock);
16499 0 : return;
16500 : }
16501 :
16502 44 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
16503 :
16504 : /*
16505 : * Update the dependency on the new access method. No dependency is added
16506 : * if the new access method is InvalidOid (default case). Be very careful
16507 : * that this has to compare the previous value stored in pg_class with the
16508 : * new one.
16509 : */
16510 44 : if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
16511 20 : {
16512 : ObjectAddress relobj,
16513 : referenced;
16514 :
16515 : /*
16516 : * New access method is defined and there was no dependency
16517 : * previously, so record a new one.
16518 : */
16519 20 : ObjectAddressSet(relobj, RelationRelationId, reloid);
16520 20 : ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
16521 20 : recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
16522 : }
16523 24 : else if (OidIsValid(oldAccessMethodId) &&
16524 24 : !OidIsValid(rd_rel->relam))
16525 : {
16526 : /*
16527 : * There was an access method defined, and no new one, so just remove
16528 : * the existing dependency.
16529 : */
16530 12 : deleteDependencyRecordsForClass(RelationRelationId, reloid,
16531 : AccessMethodRelationId,
16532 : DEPENDENCY_NORMAL);
16533 : }
16534 : else
16535 : {
16536 : Assert(OidIsValid(oldAccessMethodId) &&
16537 : OidIsValid(rd_rel->relam));
16538 :
16539 : /* Both are valid, so update the dependency */
16540 12 : changeDependencyFor(RelationRelationId, reloid,
16541 : AccessMethodRelationId,
16542 : oldAccessMethodId, rd_rel->relam);
16543 : }
16544 :
16545 : /* make the relam and dependency changes visible */
16546 44 : CommandCounterIncrement();
16547 :
16548 44 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16549 :
16550 44 : heap_freetuple(tuple);
16551 44 : table_close(pg_class, RowExclusiveLock);
16552 : }
16553 :
16554 : /*
16555 : * ALTER TABLE SET TABLESPACE
16556 : */
16557 : static void
16558 158 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
16559 : {
16560 : Oid tablespaceId;
16561 :
16562 : /* Check that the tablespace exists */
16563 158 : tablespaceId = get_tablespace_oid(tablespacename, false);
16564 :
16565 : /* Check permissions except when moving to database's default */
16566 158 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
16567 : {
16568 : AclResult aclresult;
16569 :
16570 66 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
16571 66 : if (aclresult != ACLCHECK_OK)
16572 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
16573 : }
16574 :
16575 : /* Save info for Phase 3 to do the real work */
16576 158 : if (OidIsValid(tab->newTableSpace))
16577 0 : ereport(ERROR,
16578 : (errcode(ERRCODE_SYNTAX_ERROR),
16579 : errmsg("cannot have multiple SET TABLESPACE subcommands")));
16580 :
16581 158 : tab->newTableSpace = tablespaceId;
16582 158 : }
16583 :
16584 : /*
16585 : * Set, reset, or replace reloptions.
16586 : */
16587 : static void
16588 958 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
16589 : LOCKMODE lockmode)
16590 : {
16591 : Oid relid;
16592 : Relation pgclass;
16593 : HeapTuple tuple;
16594 : HeapTuple newtuple;
16595 : Datum datum;
16596 : Datum newOptions;
16597 : Datum repl_val[Natts_pg_class];
16598 : bool repl_null[Natts_pg_class];
16599 : bool repl_repl[Natts_pg_class];
16600 958 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
16601 :
16602 958 : if (defList == NIL && operation != AT_ReplaceRelOptions)
16603 0 : return; /* nothing to do */
16604 :
16605 958 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
16606 :
16607 : /* Fetch heap tuple */
16608 958 : relid = RelationGetRelid(rel);
16609 958 : tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
16610 958 : if (!HeapTupleIsValid(tuple))
16611 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
16612 :
16613 958 : if (operation == AT_ReplaceRelOptions)
16614 : {
16615 : /*
16616 : * If we're supposed to replace the reloptions list, we just pretend
16617 : * there were none before.
16618 : */
16619 198 : datum = (Datum) 0;
16620 : }
16621 : else
16622 : {
16623 : bool isnull;
16624 :
16625 : /* Get the old reloptions */
16626 760 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
16627 : &isnull);
16628 760 : if (isnull)
16629 472 : datum = (Datum) 0;
16630 : }
16631 :
16632 : /* Generate new proposed reloptions (text array) */
16633 958 : newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
16634 : operation == AT_ResetRelOptions);
16635 :
16636 : /* Validate */
16637 952 : switch (rel->rd_rel->relkind)
16638 : {
16639 530 : case RELKIND_RELATION:
16640 : case RELKIND_MATVIEW:
16641 530 : (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
16642 530 : break;
16643 6 : case RELKIND_PARTITIONED_TABLE:
16644 6 : (void) partitioned_table_reloptions(newOptions, true);
16645 0 : break;
16646 300 : case RELKIND_VIEW:
16647 300 : (void) view_reloptions(newOptions, true);
16648 282 : break;
16649 116 : case RELKIND_INDEX:
16650 : case RELKIND_PARTITIONED_INDEX:
16651 116 : (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
16652 94 : break;
16653 0 : case RELKIND_TOASTVALUE:
16654 : /* fall through to error -- shouldn't ever get here */
16655 : default:
16656 0 : ereport(ERROR,
16657 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16658 : errmsg("cannot set options for relation \"%s\"",
16659 : RelationGetRelationName(rel)),
16660 : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
16661 : break;
16662 : }
16663 :
16664 : /* Special-case validation of view options */
16665 906 : if (rel->rd_rel->relkind == RELKIND_VIEW)
16666 : {
16667 282 : Query *view_query = get_view_query(rel);
16668 282 : List *view_options = untransformRelOptions(newOptions);
16669 : ListCell *cell;
16670 282 : bool check_option = false;
16671 :
16672 384 : foreach(cell, view_options)
16673 : {
16674 102 : DefElem *defel = (DefElem *) lfirst(cell);
16675 :
16676 102 : if (strcmp(defel->defname, "check_option") == 0)
16677 24 : check_option = true;
16678 : }
16679 :
16680 : /*
16681 : * If the check option is specified, look to see if the view is
16682 : * actually auto-updatable or not.
16683 : */
16684 282 : if (check_option)
16685 : {
16686 : const char *view_updatable_error =
16687 24 : view_query_is_auto_updatable(view_query, true);
16688 :
16689 24 : if (view_updatable_error)
16690 0 : ereport(ERROR,
16691 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16692 : errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
16693 : errhint("%s", _(view_updatable_error))));
16694 : }
16695 : }
16696 :
16697 : /*
16698 : * All we need do here is update the pg_class row; the new options will be
16699 : * propagated into relcaches during post-commit cache inval.
16700 : */
16701 906 : memset(repl_val, 0, sizeof(repl_val));
16702 906 : memset(repl_null, false, sizeof(repl_null));
16703 906 : memset(repl_repl, false, sizeof(repl_repl));
16704 :
16705 906 : if (newOptions != (Datum) 0)
16706 608 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
16707 : else
16708 298 : repl_null[Anum_pg_class_reloptions - 1] = true;
16709 :
16710 906 : repl_repl[Anum_pg_class_reloptions - 1] = true;
16711 :
16712 906 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
16713 : repl_val, repl_null, repl_repl);
16714 :
16715 906 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
16716 906 : UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
16717 :
16718 906 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16719 :
16720 906 : heap_freetuple(newtuple);
16721 :
16722 906 : ReleaseSysCache(tuple);
16723 :
16724 : /* repeat the whole exercise for the toast table, if there's one */
16725 906 : if (OidIsValid(rel->rd_rel->reltoastrelid))
16726 : {
16727 : Relation toastrel;
16728 262 : Oid toastid = rel->rd_rel->reltoastrelid;
16729 :
16730 262 : toastrel = table_open(toastid, lockmode);
16731 :
16732 : /* Fetch heap tuple */
16733 262 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
16734 262 : if (!HeapTupleIsValid(tuple))
16735 0 : elog(ERROR, "cache lookup failed for relation %u", toastid);
16736 :
16737 262 : if (operation == AT_ReplaceRelOptions)
16738 : {
16739 : /*
16740 : * If we're supposed to replace the reloptions list, we just
16741 : * pretend there were none before.
16742 : */
16743 0 : datum = (Datum) 0;
16744 : }
16745 : else
16746 : {
16747 : bool isnull;
16748 :
16749 : /* Get the old reloptions */
16750 262 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
16751 : &isnull);
16752 262 : if (isnull)
16753 226 : datum = (Datum) 0;
16754 : }
16755 :
16756 262 : newOptions = transformRelOptions(datum, defList, "toast", validnsps,
16757 : false, operation == AT_ResetRelOptions);
16758 :
16759 262 : (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
16760 :
16761 262 : memset(repl_val, 0, sizeof(repl_val));
16762 262 : memset(repl_null, false, sizeof(repl_null));
16763 262 : memset(repl_repl, false, sizeof(repl_repl));
16764 :
16765 262 : if (newOptions != (Datum) 0)
16766 42 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
16767 : else
16768 220 : repl_null[Anum_pg_class_reloptions - 1] = true;
16769 :
16770 262 : repl_repl[Anum_pg_class_reloptions - 1] = true;
16771 :
16772 262 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
16773 : repl_val, repl_null, repl_repl);
16774 :
16775 262 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
16776 :
16777 262 : InvokeObjectPostAlterHookArg(RelationRelationId,
16778 : RelationGetRelid(toastrel), 0,
16779 : InvalidOid, true);
16780 :
16781 262 : heap_freetuple(newtuple);
16782 :
16783 262 : ReleaseSysCache(tuple);
16784 :
16785 262 : table_close(toastrel, NoLock);
16786 : }
16787 :
16788 906 : table_close(pgclass, RowExclusiveLock);
16789 : }
16790 :
16791 : /*
16792 : * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
16793 : * rewriting to be done, so we just want to copy the data as fast as possible.
16794 : */
16795 : static void
16796 162 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
16797 : {
16798 : Relation rel;
16799 : Oid reltoastrelid;
16800 : RelFileNumber newrelfilenumber;
16801 : RelFileLocator newrlocator;
16802 162 : List *reltoastidxids = NIL;
16803 : ListCell *lc;
16804 :
16805 : /*
16806 : * Need lock here in case we are recursing to toast table or index
16807 : */
16808 162 : rel = relation_open(tableOid, lockmode);
16809 :
16810 : /* Check first if relation can be moved to new tablespace */
16811 162 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
16812 : {
16813 2 : InvokeObjectPostAlterHook(RelationRelationId,
16814 : RelationGetRelid(rel), 0);
16815 2 : relation_close(rel, NoLock);
16816 2 : return;
16817 : }
16818 :
16819 160 : reltoastrelid = rel->rd_rel->reltoastrelid;
16820 : /* Fetch the list of indexes on toast relation if necessary */
16821 160 : if (OidIsValid(reltoastrelid))
16822 : {
16823 20 : Relation toastRel = relation_open(reltoastrelid, lockmode);
16824 :
16825 20 : reltoastidxids = RelationGetIndexList(toastRel);
16826 20 : relation_close(toastRel, lockmode);
16827 : }
16828 :
16829 : /*
16830 : * Relfilenumbers are not unique in databases across tablespaces, so we
16831 : * need to allocate a new one in the new tablespace.
16832 : */
16833 160 : newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
16834 160 : rel->rd_rel->relpersistence);
16835 :
16836 : /* Open old and new relation */
16837 160 : newrlocator = rel->rd_locator;
16838 160 : newrlocator.relNumber = newrelfilenumber;
16839 160 : newrlocator.spcOid = newTableSpace;
16840 :
16841 : /* hand off to AM to actually create new rel storage and copy the data */
16842 160 : if (rel->rd_rel->relkind == RELKIND_INDEX)
16843 : {
16844 62 : index_copy_data(rel, newrlocator);
16845 : }
16846 : else
16847 : {
16848 : Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
16849 98 : table_relation_copy_data(rel, &newrlocator);
16850 : }
16851 :
16852 : /*
16853 : * Update the pg_class row.
16854 : *
16855 : * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
16856 : * executed on pg_class or its indexes (the above copy wouldn't contain
16857 : * the updated pg_class entry), but that's forbidden with
16858 : * CheckRelationTableSpaceMove().
16859 : */
16860 160 : SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
16861 :
16862 160 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16863 :
16864 160 : RelationAssumeNewRelfilelocator(rel);
16865 :
16866 160 : relation_close(rel, NoLock);
16867 :
16868 : /* Make sure the reltablespace change is visible */
16869 160 : CommandCounterIncrement();
16870 :
16871 : /* Move associated toast relation and/or indexes, too */
16872 160 : if (OidIsValid(reltoastrelid))
16873 20 : ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
16874 180 : foreach(lc, reltoastidxids)
16875 20 : ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
16876 :
16877 : /* Clean up */
16878 160 : list_free(reltoastidxids);
16879 : }
16880 :
16881 : /*
16882 : * Special handling of ALTER TABLE SET TABLESPACE for relations with no
16883 : * storage that have an interest in preserving tablespace.
16884 : *
16885 : * Since these have no storage the tablespace can be updated with a simple
16886 : * metadata only operation to update the tablespace.
16887 : */
16888 : static void
16889 36 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
16890 : {
16891 : /*
16892 : * Shouldn't be called on relations having storage; these are processed in
16893 : * phase 3.
16894 : */
16895 : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
16896 :
16897 : /* check if relation can be moved to its new tablespace */
16898 36 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
16899 : {
16900 0 : InvokeObjectPostAlterHook(RelationRelationId,
16901 : RelationGetRelid(rel),
16902 : 0);
16903 0 : return;
16904 : }
16905 :
16906 : /* Update can be done, so change reltablespace */
16907 30 : SetRelationTableSpace(rel, newTableSpace, InvalidOid);
16908 :
16909 30 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16910 :
16911 : /* Make sure the reltablespace change is visible */
16912 30 : CommandCounterIncrement();
16913 : }
16914 :
16915 : /*
16916 : * Alter Table ALL ... SET TABLESPACE
16917 : *
16918 : * Allows a user to move all objects of some type in a given tablespace in the
16919 : * current database to another tablespace. Objects can be chosen based on the
16920 : * owner of the object also, to allow users to move only their objects.
16921 : * The user must have CREATE rights on the new tablespace, as usual. The main
16922 : * permissions handling is done by the lower-level table move function.
16923 : *
16924 : * All to-be-moved objects are locked first. If NOWAIT is specified and the
16925 : * lock can't be acquired then we ereport(ERROR).
16926 : */
16927 : Oid
16928 30 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
16929 : {
16930 30 : List *relations = NIL;
16931 : ListCell *l;
16932 : ScanKeyData key[1];
16933 : Relation rel;
16934 : TableScanDesc scan;
16935 : HeapTuple tuple;
16936 : Oid orig_tablespaceoid;
16937 : Oid new_tablespaceoid;
16938 30 : List *role_oids = roleSpecsToIds(stmt->roles);
16939 :
16940 : /* Ensure we were not asked to move something we can't */
16941 30 : if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
16942 12 : stmt->objtype != OBJECT_MATVIEW)
16943 0 : ereport(ERROR,
16944 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
16945 : errmsg("only tables, indexes, and materialized views exist in tablespaces")));
16946 :
16947 : /* Get the orig and new tablespace OIDs */
16948 30 : orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
16949 30 : new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
16950 :
16951 : /* Can't move shared relations in to or out of pg_global */
16952 : /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
16953 30 : if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
16954 : new_tablespaceoid == GLOBALTABLESPACE_OID)
16955 0 : ereport(ERROR,
16956 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
16957 : errmsg("cannot move relations in to or out of pg_global tablespace")));
16958 :
16959 : /*
16960 : * Must have CREATE rights on the new tablespace, unless it is the
16961 : * database default tablespace (which all users implicitly have CREATE
16962 : * rights on).
16963 : */
16964 30 : if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
16965 : {
16966 : AclResult aclresult;
16967 :
16968 0 : aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
16969 : ACL_CREATE);
16970 0 : if (aclresult != ACLCHECK_OK)
16971 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
16972 0 : get_tablespace_name(new_tablespaceoid));
16973 : }
16974 :
16975 : /*
16976 : * Now that the checks are done, check if we should set either to
16977 : * InvalidOid because it is our database's default tablespace.
16978 : */
16979 30 : if (orig_tablespaceoid == MyDatabaseTableSpace)
16980 0 : orig_tablespaceoid = InvalidOid;
16981 :
16982 30 : if (new_tablespaceoid == MyDatabaseTableSpace)
16983 30 : new_tablespaceoid = InvalidOid;
16984 :
16985 : /* no-op */
16986 30 : if (orig_tablespaceoid == new_tablespaceoid)
16987 0 : return new_tablespaceoid;
16988 :
16989 : /*
16990 : * Walk the list of objects in the tablespace and move them. This will
16991 : * only find objects in our database, of course.
16992 : */
16993 30 : ScanKeyInit(&key[0],
16994 : Anum_pg_class_reltablespace,
16995 : BTEqualStrategyNumber, F_OIDEQ,
16996 : ObjectIdGetDatum(orig_tablespaceoid));
16997 :
16998 30 : rel = table_open(RelationRelationId, AccessShareLock);
16999 30 : scan = table_beginscan_catalog(rel, 1, key);
17000 132 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17001 : {
17002 102 : Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
17003 102 : Oid relOid = relForm->oid;
17004 :
17005 : /*
17006 : * Do not move objects in pg_catalog as part of this, if an admin
17007 : * really wishes to do so, they can issue the individual ALTER
17008 : * commands directly.
17009 : *
17010 : * Also, explicitly avoid any shared tables, temp tables, or TOAST
17011 : * (TOAST will be moved with the main table).
17012 : */
17013 102 : if (IsCatalogNamespace(relForm->relnamespace) ||
17014 204 : relForm->relisshared ||
17015 204 : isAnyTempNamespace(relForm->relnamespace) ||
17016 102 : IsToastNamespace(relForm->relnamespace))
17017 0 : continue;
17018 :
17019 : /* Only move the object type requested */
17020 102 : if ((stmt->objtype == OBJECT_TABLE &&
17021 60 : relForm->relkind != RELKIND_RELATION &&
17022 36 : relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17023 66 : (stmt->objtype == OBJECT_INDEX &&
17024 36 : relForm->relkind != RELKIND_INDEX &&
17025 6 : relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17026 60 : (stmt->objtype == OBJECT_MATVIEW &&
17027 6 : relForm->relkind != RELKIND_MATVIEW))
17028 42 : continue;
17029 :
17030 : /* Check if we are only moving objects owned by certain roles */
17031 60 : if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17032 0 : continue;
17033 :
17034 : /*
17035 : * Handle permissions-checking here since we are locking the tables
17036 : * and also to avoid doing a bunch of work only to fail part-way. Note
17037 : * that permissions will also be checked by AlterTableInternal().
17038 : *
17039 : * Caller must be considered an owner on the table to move it.
17040 : */
17041 60 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17042 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
17043 0 : NameStr(relForm->relname));
17044 :
17045 60 : if (stmt->nowait &&
17046 0 : !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
17047 0 : ereport(ERROR,
17048 : (errcode(ERRCODE_OBJECT_IN_USE),
17049 : errmsg("aborting because lock on relation \"%s.%s\" is not available",
17050 : get_namespace_name(relForm->relnamespace),
17051 : NameStr(relForm->relname))));
17052 : else
17053 60 : LockRelationOid(relOid, AccessExclusiveLock);
17054 :
17055 : /* Add to our list of objects to move */
17056 60 : relations = lappend_oid(relations, relOid);
17057 : }
17058 :
17059 30 : table_endscan(scan);
17060 30 : table_close(rel, AccessShareLock);
17061 :
17062 30 : if (relations == NIL)
17063 12 : ereport(NOTICE,
17064 : (errcode(ERRCODE_NO_DATA_FOUND),
17065 : errmsg("no matching relations in tablespace \"%s\" found",
17066 : orig_tablespaceoid == InvalidOid ? "(database default)" :
17067 : get_tablespace_name(orig_tablespaceoid))));
17068 :
17069 : /* Everything is locked, loop through and move all of the relations. */
17070 90 : foreach(l, relations)
17071 : {
17072 60 : List *cmds = NIL;
17073 60 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
17074 :
17075 60 : cmd->subtype = AT_SetTableSpace;
17076 60 : cmd->name = stmt->new_tablespacename;
17077 :
17078 60 : cmds = lappend(cmds, cmd);
17079 :
17080 60 : EventTriggerAlterTableStart((Node *) stmt);
17081 : /* OID is set by AlterTableInternal */
17082 60 : AlterTableInternal(lfirst_oid(l), cmds, false);
17083 60 : EventTriggerAlterTableEnd();
17084 : }
17085 :
17086 30 : return new_tablespaceoid;
17087 : }
17088 :
17089 : static void
17090 62 : index_copy_data(Relation rel, RelFileLocator newrlocator)
17091 : {
17092 : SMgrRelation dstrel;
17093 :
17094 : /*
17095 : * Since we copy the file directly without looking at the shared buffers,
17096 : * we'd better first flush out any pages of the source relation that are
17097 : * in shared buffers. We assume no new changes will be made while we are
17098 : * holding exclusive lock on the rel.
17099 : */
17100 62 : FlushRelationBuffers(rel);
17101 :
17102 : /*
17103 : * Create and copy all forks of the relation, and schedule unlinking of
17104 : * old physical files.
17105 : *
17106 : * NOTE: any conflict in relfilenumber value will be caught in
17107 : * RelationCreateStorage().
17108 : */
17109 62 : dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
17110 :
17111 : /* copy main fork */
17112 62 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
17113 62 : rel->rd_rel->relpersistence);
17114 :
17115 : /* copy those extra forks that exist */
17116 62 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
17117 248 : forkNum <= MAX_FORKNUM; forkNum++)
17118 : {
17119 186 : if (smgrexists(RelationGetSmgr(rel), forkNum))
17120 : {
17121 0 : smgrcreate(dstrel, forkNum, false);
17122 :
17123 : /*
17124 : * WAL log creation if the relation is persistent, or this is the
17125 : * init fork of an unlogged relation.
17126 : */
17127 0 : if (RelationIsPermanent(rel) ||
17128 0 : (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
17129 : forkNum == INIT_FORKNUM))
17130 0 : log_smgrcreate(&newrlocator, forkNum);
17131 0 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
17132 0 : rel->rd_rel->relpersistence);
17133 : }
17134 : }
17135 :
17136 : /* drop old relation, and close new one */
17137 62 : RelationDropStorage(rel);
17138 62 : smgrclose(dstrel);
17139 62 : }
17140 :
17141 : /*
17142 : * ALTER TABLE ENABLE/DISABLE TRIGGER
17143 : *
17144 : * We just pass this off to trigger.c.
17145 : */
17146 : static void
17147 346 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
17148 : char fires_when, bool skip_system, bool recurse,
17149 : LOCKMODE lockmode)
17150 : {
17151 346 : EnableDisableTrigger(rel, trigname, InvalidOid,
17152 : fires_when, skip_system, recurse,
17153 : lockmode);
17154 :
17155 346 : InvokeObjectPostAlterHook(RelationRelationId,
17156 : RelationGetRelid(rel), 0);
17157 346 : }
17158 :
17159 : /*
17160 : * ALTER TABLE ENABLE/DISABLE RULE
17161 : *
17162 : * We just pass this off to rewriteDefine.c.
17163 : */
17164 : static void
17165 52 : ATExecEnableDisableRule(Relation rel, const char *rulename,
17166 : char fires_when, LOCKMODE lockmode)
17167 : {
17168 52 : EnableDisableRule(rel, rulename, fires_when);
17169 :
17170 52 : InvokeObjectPostAlterHook(RelationRelationId,
17171 : RelationGetRelid(rel), 0);
17172 52 : }
17173 :
17174 : /*
17175 : * ALTER TABLE INHERIT
17176 : *
17177 : * Add a parent to the child's parents. This verifies that all the columns and
17178 : * check constraints of the parent appear in the child and that they have the
17179 : * same data types and expressions.
17180 : */
17181 : static void
17182 444 : ATPrepAddInherit(Relation child_rel)
17183 : {
17184 444 : if (child_rel->rd_rel->reloftype)
17185 6 : ereport(ERROR,
17186 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17187 : errmsg("cannot change inheritance of typed table")));
17188 :
17189 438 : if (child_rel->rd_rel->relispartition)
17190 6 : ereport(ERROR,
17191 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17192 : errmsg("cannot change inheritance of a partition")));
17193 :
17194 432 : if (child_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17195 6 : ereport(ERROR,
17196 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17197 : errmsg("cannot change inheritance of partitioned table")));
17198 426 : }
17199 :
17200 : /*
17201 : * Return the address of the new parent relation.
17202 : */
17203 : static ObjectAddress
17204 426 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
17205 : {
17206 : Relation parent_rel;
17207 : List *children;
17208 : ObjectAddress address;
17209 : const char *trigger_name;
17210 :
17211 : /*
17212 : * A self-exclusive lock is needed here. See the similar case in
17213 : * MergeAttributes() for a full explanation.
17214 : */
17215 426 : parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
17216 :
17217 : /*
17218 : * Must be owner of both parent and child -- child was checked by
17219 : * ATSimplePermissions call in ATPrepCmd
17220 : */
17221 426 : ATSimplePermissions(AT_AddInherit, parent_rel,
17222 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
17223 :
17224 : /* Permanent rels cannot inherit from temporary ones */
17225 426 : if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17226 6 : child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
17227 0 : ereport(ERROR,
17228 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17229 : errmsg("cannot inherit from temporary relation \"%s\"",
17230 : RelationGetRelationName(parent_rel))));
17231 :
17232 : /* If parent rel is temp, it must belong to this session */
17233 426 : if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17234 6 : !parent_rel->rd_islocaltemp)
17235 0 : ereport(ERROR,
17236 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17237 : errmsg("cannot inherit from temporary relation of another session")));
17238 :
17239 : /* Ditto for the child */
17240 426 : if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17241 6 : !child_rel->rd_islocaltemp)
17242 0 : ereport(ERROR,
17243 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17244 : errmsg("cannot inherit to temporary relation of another session")));
17245 :
17246 : /* Prevent partitioned tables from becoming inheritance parents */
17247 426 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17248 6 : ereport(ERROR,
17249 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17250 : errmsg("cannot inherit from partitioned table \"%s\"",
17251 : parent->relname)));
17252 :
17253 : /* Likewise for partitions */
17254 420 : if (parent_rel->rd_rel->relispartition)
17255 6 : ereport(ERROR,
17256 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17257 : errmsg("cannot inherit from a partition")));
17258 :
17259 : /*
17260 : * Prevent circularity by seeing if proposed parent inherits from child.
17261 : * (In particular, this disallows making a rel inherit from itself.)
17262 : *
17263 : * This is not completely bulletproof because of race conditions: in
17264 : * multi-level inheritance trees, someone else could concurrently be
17265 : * making another inheritance link that closes the loop but does not join
17266 : * either of the rels we have locked. Preventing that seems to require
17267 : * exclusive locks on the entire inheritance tree, which is a cure worse
17268 : * than the disease. find_all_inheritors() will cope with circularity
17269 : * anyway, so don't sweat it too much.
17270 : *
17271 : * We use weakest lock we can on child's children, namely AccessShareLock.
17272 : */
17273 414 : children = find_all_inheritors(RelationGetRelid(child_rel),
17274 : AccessShareLock, NULL);
17275 :
17276 414 : if (list_member_oid(children, RelationGetRelid(parent_rel)))
17277 12 : ereport(ERROR,
17278 : (errcode(ERRCODE_DUPLICATE_TABLE),
17279 : errmsg("circular inheritance not allowed"),
17280 : errdetail("\"%s\" is already a child of \"%s\".",
17281 : parent->relname,
17282 : RelationGetRelationName(child_rel))));
17283 :
17284 : /*
17285 : * If child_rel has row-level triggers with transition tables, we
17286 : * currently don't allow it to become an inheritance child. See also
17287 : * prohibitions in ATExecAttachPartition() and CreateTrigger().
17288 : */
17289 402 : trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
17290 402 : if (trigger_name != NULL)
17291 6 : ereport(ERROR,
17292 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17293 : errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
17294 : trigger_name, RelationGetRelationName(child_rel)),
17295 : errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
17296 :
17297 : /* OK to create inheritance */
17298 396 : CreateInheritance(child_rel, parent_rel, false);
17299 :
17300 306 : ObjectAddressSet(address, RelationRelationId,
17301 : RelationGetRelid(parent_rel));
17302 :
17303 : /* keep our lock on the parent relation until commit */
17304 306 : table_close(parent_rel, NoLock);
17305 :
17306 306 : return address;
17307 : }
17308 :
17309 : /*
17310 : * CreateInheritance
17311 : * Catalog manipulation portion of creating inheritance between a child
17312 : * table and a parent table.
17313 : *
17314 : * Common to ATExecAddInherit() and ATExecAttachPartition().
17315 : */
17316 : static void
17317 3036 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
17318 : {
17319 : Relation catalogRelation;
17320 : SysScanDesc scan;
17321 : ScanKeyData key;
17322 : HeapTuple inheritsTuple;
17323 : int32 inhseqno;
17324 :
17325 : /* Note: get RowExclusiveLock because we will write pg_inherits below. */
17326 3036 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
17327 :
17328 : /*
17329 : * Check for duplicates in the list of parents, and determine the highest
17330 : * inhseqno already present; we'll use the next one for the new parent.
17331 : * Also, if proposed child is a partition, it cannot already be
17332 : * inheriting.
17333 : *
17334 : * Note: we do not reject the case where the child already inherits from
17335 : * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
17336 : */
17337 3036 : ScanKeyInit(&key,
17338 : Anum_pg_inherits_inhrelid,
17339 : BTEqualStrategyNumber, F_OIDEQ,
17340 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
17341 3036 : scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
17342 : true, NULL, 1, &key);
17343 :
17344 : /* inhseqno sequences start at 1 */
17345 3036 : inhseqno = 0;
17346 3104 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
17347 : {
17348 74 : Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
17349 :
17350 74 : if (inh->inhparent == RelationGetRelid(parent_rel))
17351 6 : ereport(ERROR,
17352 : (errcode(ERRCODE_DUPLICATE_TABLE),
17353 : errmsg("relation \"%s\" would be inherited from more than once",
17354 : RelationGetRelationName(parent_rel))));
17355 :
17356 68 : if (inh->inhseqno > inhseqno)
17357 68 : inhseqno = inh->inhseqno;
17358 : }
17359 3030 : systable_endscan(scan);
17360 :
17361 : /* Match up the columns and bump attinhcount as needed */
17362 3030 : MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
17363 :
17364 : /* Match up the constraints and bump coninhcount as needed */
17365 2898 : MergeConstraintsIntoExisting(child_rel, parent_rel);
17366 :
17367 : /*
17368 : * OK, it looks valid. Make the catalog entries that show inheritance.
17369 : */
17370 2838 : StoreCatalogInheritance1(RelationGetRelid(child_rel),
17371 : RelationGetRelid(parent_rel),
17372 : inhseqno + 1,
17373 : catalogRelation,
17374 2838 : parent_rel->rd_rel->relkind ==
17375 : RELKIND_PARTITIONED_TABLE);
17376 :
17377 : /* Now we're done with pg_inherits */
17378 2838 : table_close(catalogRelation, RowExclusiveLock);
17379 2838 : }
17380 :
17381 : /*
17382 : * Obtain the source-text form of the constraint expression for a check
17383 : * constraint, given its pg_constraint tuple
17384 : */
17385 : static char *
17386 188 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
17387 : {
17388 : Form_pg_constraint con;
17389 : bool isnull;
17390 : Datum attr;
17391 : Datum expr;
17392 :
17393 188 : con = (Form_pg_constraint) GETSTRUCT(contup);
17394 188 : attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
17395 188 : if (isnull)
17396 0 : elog(ERROR, "null conbin for constraint %u", con->oid);
17397 :
17398 188 : expr = DirectFunctionCall2(pg_get_expr, attr,
17399 : ObjectIdGetDatum(con->conrelid));
17400 188 : return TextDatumGetCString(expr);
17401 : }
17402 :
17403 : /*
17404 : * Determine whether two check constraints are functionally equivalent
17405 : *
17406 : * The test we apply is to see whether they reverse-compile to the same
17407 : * source string. This insulates us from issues like whether attributes
17408 : * have the same physical column numbers in parent and child relations.
17409 : *
17410 : * Note that we ignore enforceability as there are cases where constraints
17411 : * with differing enforceability are allowed.
17412 : */
17413 : static bool
17414 94 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
17415 : {
17416 94 : Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
17417 94 : Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
17418 :
17419 94 : if (acon->condeferrable != bcon->condeferrable ||
17420 94 : acon->condeferred != bcon->condeferred ||
17421 94 : strcmp(decompile_conbin(a, tupleDesc),
17422 94 : decompile_conbin(b, tupleDesc)) != 0)
17423 6 : return false;
17424 : else
17425 88 : return true;
17426 : }
17427 :
17428 : /*
17429 : * Check columns in child table match up with columns in parent, and increment
17430 : * their attinhcount.
17431 : *
17432 : * Called by CreateInheritance
17433 : *
17434 : * Currently all parent columns must be found in child. Missing columns are an
17435 : * error. One day we might consider creating new columns like CREATE TABLE
17436 : * does. However, that is widely unpopular --- in the common use case of
17437 : * partitioned tables it's a foot-gun.
17438 : *
17439 : * The data type must match exactly. If the parent column is NOT NULL then
17440 : * the child must be as well. Defaults are not compared, however.
17441 : */
17442 : static void
17443 3030 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
17444 : {
17445 : Relation attrrel;
17446 : TupleDesc parent_desc;
17447 :
17448 3030 : attrrel = table_open(AttributeRelationId, RowExclusiveLock);
17449 3030 : parent_desc = RelationGetDescr(parent_rel);
17450 :
17451 9736 : for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
17452 : {
17453 6838 : Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
17454 6838 : char *parent_attname = NameStr(parent_att->attname);
17455 : HeapTuple tuple;
17456 :
17457 : /* Ignore dropped columns in the parent. */
17458 6838 : if (parent_att->attisdropped)
17459 296 : continue;
17460 :
17461 : /* Find same column in child (matching on column name). */
17462 6542 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
17463 6542 : if (HeapTupleIsValid(tuple))
17464 : {
17465 6530 : Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
17466 :
17467 6530 : if (parent_att->atttypid != child_att->atttypid ||
17468 6524 : parent_att->atttypmod != child_att->atttypmod)
17469 12 : ereport(ERROR,
17470 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17471 : errmsg("child table \"%s\" has different type for column \"%s\"",
17472 : RelationGetRelationName(child_rel), parent_attname)));
17473 :
17474 6518 : if (parent_att->attcollation != child_att->attcollation)
17475 6 : ereport(ERROR,
17476 : (errcode(ERRCODE_COLLATION_MISMATCH),
17477 : errmsg("child table \"%s\" has different collation for column \"%s\"",
17478 : RelationGetRelationName(child_rel), parent_attname)));
17479 :
17480 : /*
17481 : * If the parent has a not-null constraint that's not NO INHERIT,
17482 : * make sure the child has one too.
17483 : *
17484 : * Other constraints are checked elsewhere.
17485 : */
17486 6512 : if (parent_att->attnotnull && !child_att->attnotnull)
17487 : {
17488 : HeapTuple contup;
17489 :
17490 48 : contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
17491 48 : parent_att->attnum);
17492 48 : if (HeapTupleIsValid(contup) &&
17493 48 : !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
17494 30 : ereport(ERROR,
17495 : errcode(ERRCODE_DATATYPE_MISMATCH),
17496 : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
17497 : parent_attname, RelationGetRelationName(child_rel)));
17498 : }
17499 :
17500 : /*
17501 : * Child column must be generated if and only if parent column is.
17502 : */
17503 6482 : if (parent_att->attgenerated && !child_att->attgenerated)
17504 36 : ereport(ERROR,
17505 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17506 : errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
17507 6446 : if (child_att->attgenerated && !parent_att->attgenerated)
17508 24 : ereport(ERROR,
17509 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17510 : errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
17511 :
17512 6422 : if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
17513 12 : ereport(ERROR,
17514 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17515 : errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
17516 : errdetail("Parent column is %s, child column is %s.",
17517 : parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
17518 : child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
17519 :
17520 : /*
17521 : * Regular inheritance children are independent enough not to
17522 : * inherit identity columns. But partitions are integral part of
17523 : * a partitioned table and inherit identity column.
17524 : */
17525 6410 : if (ispartition)
17526 5716 : child_att->attidentity = parent_att->attidentity;
17527 :
17528 : /*
17529 : * OK, bump the child column's inheritance count. (If we fail
17530 : * later on, this change will just roll back.)
17531 : */
17532 6410 : if (pg_add_s16_overflow(child_att->attinhcount, 1,
17533 : &child_att->attinhcount))
17534 0 : ereport(ERROR,
17535 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
17536 : errmsg("too many inheritance parents"));
17537 :
17538 : /*
17539 : * In case of partitions, we must enforce that value of attislocal
17540 : * is same in all partitions. (Note: there are only inherited
17541 : * attributes in partitions)
17542 : */
17543 6410 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17544 : {
17545 : Assert(child_att->attinhcount == 1);
17546 5716 : child_att->attislocal = false;
17547 : }
17548 :
17549 6410 : CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
17550 6410 : heap_freetuple(tuple);
17551 : }
17552 : else
17553 : {
17554 12 : ereport(ERROR,
17555 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17556 : errmsg("child table is missing column \"%s\"", parent_attname)));
17557 : }
17558 : }
17559 :
17560 2898 : table_close(attrrel, RowExclusiveLock);
17561 2898 : }
17562 :
17563 : /*
17564 : * Check constraints in child table match up with constraints in parent,
17565 : * and increment their coninhcount.
17566 : *
17567 : * Constraints that are marked ONLY in the parent are ignored.
17568 : *
17569 : * Called by CreateInheritance
17570 : *
17571 : * Currently all constraints in parent must be present in the child. One day we
17572 : * may consider adding new constraints like CREATE TABLE does.
17573 : *
17574 : * XXX This is O(N^2) which may be an issue with tables with hundreds of
17575 : * constraints. As long as tables have more like 10 constraints it shouldn't be
17576 : * a problem though. Even 100 constraints ought not be the end of the world.
17577 : *
17578 : * XXX See MergeWithExistingConstraint too if you change this code.
17579 : */
17580 : static void
17581 2898 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
17582 : {
17583 : Relation constraintrel;
17584 : SysScanDesc parent_scan;
17585 : ScanKeyData parent_key;
17586 : HeapTuple parent_tuple;
17587 2898 : Oid parent_relid = RelationGetRelid(parent_rel);
17588 : AttrMap *attmap;
17589 :
17590 2898 : constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
17591 :
17592 : /* Outer loop scans through the parent's constraint definitions */
17593 2898 : ScanKeyInit(&parent_key,
17594 : Anum_pg_constraint_conrelid,
17595 : BTEqualStrategyNumber, F_OIDEQ,
17596 : ObjectIdGetDatum(parent_relid));
17597 2898 : parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
17598 : true, NULL, 1, &parent_key);
17599 :
17600 2898 : attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
17601 : RelationGetDescr(child_rel),
17602 : true);
17603 :
17604 4968 : while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
17605 : {
17606 2130 : Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
17607 : SysScanDesc child_scan;
17608 : ScanKeyData child_key;
17609 : HeapTuple child_tuple;
17610 : AttrNumber parent_attno;
17611 2130 : bool found = false;
17612 :
17613 2130 : if (parent_con->contype != CONSTRAINT_CHECK &&
17614 1992 : parent_con->contype != CONSTRAINT_NOTNULL)
17615 994 : continue;
17616 :
17617 : /* if the parent's constraint is marked NO INHERIT, it's not inherited */
17618 1180 : if (parent_con->connoinherit)
17619 44 : continue;
17620 :
17621 1136 : if (parent_con->contype == CONSTRAINT_NOTNULL)
17622 1018 : parent_attno = extractNotNullColumn(parent_tuple);
17623 : else
17624 118 : parent_attno = InvalidAttrNumber;
17625 :
17626 : /* Search for a child constraint matching this one */
17627 1136 : ScanKeyInit(&child_key,
17628 : Anum_pg_constraint_conrelid,
17629 : BTEqualStrategyNumber, F_OIDEQ,
17630 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
17631 1136 : child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
17632 : true, NULL, 1, &child_key);
17633 :
17634 1734 : while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
17635 : {
17636 1710 : Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
17637 : HeapTuple child_copy;
17638 :
17639 1710 : if (child_con->contype != parent_con->contype)
17640 284 : continue;
17641 :
17642 : /*
17643 : * CHECK constraint are matched by constraint name, NOT NULL ones
17644 : * by attribute number.
17645 : */
17646 1426 : if (child_con->contype == CONSTRAINT_CHECK)
17647 : {
17648 154 : if (strcmp(NameStr(parent_con->conname),
17649 124 : NameStr(child_con->conname)) != 0)
17650 30 : continue;
17651 : }
17652 1302 : else if (child_con->contype == CONSTRAINT_NOTNULL)
17653 : {
17654 : Form_pg_attribute parent_attr;
17655 : Form_pg_attribute child_attr;
17656 : AttrNumber child_attno;
17657 :
17658 1302 : parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
17659 1302 : child_attno = extractNotNullColumn(child_tuple);
17660 1302 : if (parent_attno != attmap->attnums[child_attno - 1])
17661 284 : continue;
17662 :
17663 1018 : child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
17664 : /* there shouldn't be constraints on dropped columns */
17665 1018 : if (parent_attr->attisdropped || child_attr->attisdropped)
17666 0 : elog(ERROR, "found not-null constraint on dropped columns");
17667 : }
17668 :
17669 1112 : if (child_con->contype == CONSTRAINT_CHECK &&
17670 94 : !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
17671 6 : ereport(ERROR,
17672 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17673 : errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
17674 : RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
17675 :
17676 : /*
17677 : * If the child constraint is "no inherit" then cannot merge
17678 : */
17679 1106 : if (child_con->connoinherit)
17680 12 : ereport(ERROR,
17681 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
17682 : errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
17683 : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
17684 :
17685 : /*
17686 : * If the child constraint is "not valid" then cannot merge with a
17687 : * valid parent constraint
17688 : */
17689 1094 : if (parent_con->convalidated && child_con->conenforced &&
17690 1040 : !child_con->convalidated)
17691 12 : ereport(ERROR,
17692 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
17693 : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
17694 : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
17695 :
17696 : /*
17697 : * A NOT ENFORCED child constraint cannot be merged with an
17698 : * ENFORCED parent constraint. However, the reverse is allowed,
17699 : * where the child constraint is ENFORCED.
17700 : */
17701 1082 : if (parent_con->conenforced && !child_con->conenforced)
17702 6 : ereport(ERROR,
17703 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
17704 : errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
17705 : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
17706 :
17707 : /*
17708 : * OK, bump the child constraint's inheritance count. (If we fail
17709 : * later on, this change will just roll back.)
17710 : */
17711 1076 : child_copy = heap_copytuple(child_tuple);
17712 1076 : child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
17713 :
17714 1076 : if (pg_add_s16_overflow(child_con->coninhcount, 1,
17715 : &child_con->coninhcount))
17716 0 : ereport(ERROR,
17717 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
17718 : errmsg("too many inheritance parents"));
17719 :
17720 : /*
17721 : * In case of partitions, an inherited constraint must be
17722 : * inherited only once since it cannot have multiple parents and
17723 : * it is never considered local.
17724 : */
17725 1076 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17726 : {
17727 : Assert(child_con->coninhcount == 1);
17728 928 : child_con->conislocal = false;
17729 : }
17730 :
17731 1076 : CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
17732 1076 : heap_freetuple(child_copy);
17733 :
17734 1076 : found = true;
17735 1076 : break;
17736 : }
17737 :
17738 1100 : systable_endscan(child_scan);
17739 :
17740 1100 : if (!found)
17741 : {
17742 24 : if (parent_con->contype == CONSTRAINT_NOTNULL)
17743 0 : ereport(ERROR,
17744 : errcode(ERRCODE_DATATYPE_MISMATCH),
17745 : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
17746 : get_attname(parent_relid,
17747 : extractNotNullColumn(parent_tuple),
17748 : false),
17749 : RelationGetRelationName(child_rel)));
17750 :
17751 24 : ereport(ERROR,
17752 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17753 : errmsg("child table is missing constraint \"%s\"",
17754 : NameStr(parent_con->conname))));
17755 : }
17756 : }
17757 :
17758 2838 : systable_endscan(parent_scan);
17759 2838 : table_close(constraintrel, RowExclusiveLock);
17760 2838 : }
17761 :
17762 : /*
17763 : * ALTER TABLE NO INHERIT
17764 : *
17765 : * Return value is the address of the relation that is no longer parent.
17766 : */
17767 : static ObjectAddress
17768 86 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
17769 : {
17770 : ObjectAddress address;
17771 : Relation parent_rel;
17772 :
17773 86 : if (rel->rd_rel->relispartition)
17774 0 : ereport(ERROR,
17775 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17776 : errmsg("cannot change inheritance of a partition")));
17777 :
17778 : /*
17779 : * AccessShareLock on the parent is probably enough, seeing that DROP
17780 : * TABLE doesn't lock parent tables at all. We need some lock since we'll
17781 : * be inspecting the parent's schema.
17782 : */
17783 86 : parent_rel = table_openrv(parent, AccessShareLock);
17784 :
17785 : /*
17786 : * We don't bother to check ownership of the parent table --- ownership of
17787 : * the child is presumed enough rights.
17788 : */
17789 :
17790 : /* Off to RemoveInheritance() where most of the work happens */
17791 86 : RemoveInheritance(rel, parent_rel, false);
17792 :
17793 80 : ObjectAddressSet(address, RelationRelationId,
17794 : RelationGetRelid(parent_rel));
17795 :
17796 : /* keep our lock on the parent relation until commit */
17797 80 : table_close(parent_rel, NoLock);
17798 :
17799 80 : return address;
17800 : }
17801 :
17802 : /*
17803 : * MarkInheritDetached
17804 : *
17805 : * Set inhdetachpending for a partition, for ATExecDetachPartition
17806 : * in concurrent mode. While at it, verify that no other partition is
17807 : * already pending detach.
17808 : */
17809 : static void
17810 146 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
17811 : {
17812 : Relation catalogRelation;
17813 : SysScanDesc scan;
17814 : ScanKeyData key;
17815 : HeapTuple inheritsTuple;
17816 146 : bool found = false;
17817 :
17818 : Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
17819 :
17820 : /*
17821 : * Find pg_inherits entries by inhparent. (We need to scan them all in
17822 : * order to verify that no other partition is pending detach.)
17823 : */
17824 146 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
17825 146 : ScanKeyInit(&key,
17826 : Anum_pg_inherits_inhparent,
17827 : BTEqualStrategyNumber, F_OIDEQ,
17828 : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
17829 146 : scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
17830 : true, NULL, 1, &key);
17831 :
17832 576 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
17833 : {
17834 : Form_pg_inherits inhForm;
17835 :
17836 286 : inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
17837 286 : if (inhForm->inhdetachpending)
17838 2 : ereport(ERROR,
17839 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
17840 : errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
17841 : get_rel_name(inhForm->inhrelid),
17842 : get_namespace_name(parent_rel->rd_rel->relnamespace),
17843 : RelationGetRelationName(parent_rel)),
17844 : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
17845 :
17846 284 : if (inhForm->inhrelid == RelationGetRelid(child_rel))
17847 : {
17848 : HeapTuple newtup;
17849 :
17850 144 : newtup = heap_copytuple(inheritsTuple);
17851 144 : ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
17852 :
17853 144 : CatalogTupleUpdate(catalogRelation,
17854 : &inheritsTuple->t_self,
17855 : newtup);
17856 144 : found = true;
17857 144 : heap_freetuple(newtup);
17858 : /* keep looking, to ensure we catch others pending detach */
17859 : }
17860 : }
17861 :
17862 : /* Done */
17863 144 : systable_endscan(scan);
17864 144 : table_close(catalogRelation, RowExclusiveLock);
17865 :
17866 144 : if (!found)
17867 0 : ereport(ERROR,
17868 : (errcode(ERRCODE_UNDEFINED_TABLE),
17869 : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
17870 : RelationGetRelationName(child_rel),
17871 : RelationGetRelationName(parent_rel))));
17872 144 : }
17873 :
17874 : /*
17875 : * RemoveInheritance
17876 : *
17877 : * Drop a parent from the child's parents. This just adjusts the attinhcount
17878 : * and attislocal of the columns and removes the pg_inherit and pg_depend
17879 : * entries. expect_detached is passed down to DeleteInheritsTuple, q.v..
17880 : *
17881 : * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
17882 : * up attislocal stays true, which means if a child is ever removed from a
17883 : * parent then its columns will never be automatically dropped which may
17884 : * surprise. But at least we'll never surprise by dropping columns someone
17885 : * isn't expecting to be dropped which would actually mean data loss.
17886 : *
17887 : * coninhcount and conislocal for inherited constraints are adjusted in
17888 : * exactly the same way.
17889 : *
17890 : * Common to ATExecDropInherit() and ATExecDetachPartition().
17891 : */
17892 : static void
17893 590 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
17894 : {
17895 : Relation catalogRelation;
17896 : SysScanDesc scan;
17897 : ScanKeyData key[3];
17898 : HeapTuple attributeTuple,
17899 : constraintTuple;
17900 : AttrMap *attmap;
17901 : List *connames;
17902 : List *nncolumns;
17903 : bool found;
17904 : bool is_partitioning;
17905 :
17906 590 : is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
17907 :
17908 590 : found = DeleteInheritsTuple(RelationGetRelid(child_rel),
17909 : RelationGetRelid(parent_rel),
17910 : expect_detached,
17911 590 : RelationGetRelationName(child_rel));
17912 590 : if (!found)
17913 : {
17914 24 : if (is_partitioning)
17915 18 : ereport(ERROR,
17916 : (errcode(ERRCODE_UNDEFINED_TABLE),
17917 : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
17918 : RelationGetRelationName(child_rel),
17919 : RelationGetRelationName(parent_rel))));
17920 : else
17921 6 : ereport(ERROR,
17922 : (errcode(ERRCODE_UNDEFINED_TABLE),
17923 : errmsg("relation \"%s\" is not a parent of relation \"%s\"",
17924 : RelationGetRelationName(parent_rel),
17925 : RelationGetRelationName(child_rel))));
17926 : }
17927 :
17928 : /*
17929 : * Search through child columns looking for ones matching parent rel
17930 : */
17931 566 : catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
17932 566 : ScanKeyInit(&key[0],
17933 : Anum_pg_attribute_attrelid,
17934 : BTEqualStrategyNumber, F_OIDEQ,
17935 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
17936 566 : scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
17937 : true, NULL, 1, key);
17938 5054 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
17939 : {
17940 4488 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
17941 :
17942 : /* Ignore if dropped or not inherited */
17943 4488 : if (att->attisdropped)
17944 6 : continue;
17945 4482 : if (att->attinhcount <= 0)
17946 3426 : continue;
17947 :
17948 1056 : if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
17949 1056 : NameStr(att->attname)))
17950 : {
17951 : /* Decrement inhcount and possibly set islocal to true */
17952 1002 : HeapTuple copyTuple = heap_copytuple(attributeTuple);
17953 1002 : Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
17954 :
17955 1002 : copy_att->attinhcount--;
17956 1002 : if (copy_att->attinhcount == 0)
17957 972 : copy_att->attislocal = true;
17958 :
17959 1002 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
17960 1002 : heap_freetuple(copyTuple);
17961 : }
17962 : }
17963 566 : systable_endscan(scan);
17964 566 : table_close(catalogRelation, RowExclusiveLock);
17965 :
17966 : /*
17967 : * Likewise, find inherited check and not-null constraints and disinherit
17968 : * them. To do this, we first need a list of the names of the parent's
17969 : * check constraints. (We cheat a bit by only checking for name matches,
17970 : * assuming that the expressions will match.)
17971 : *
17972 : * For NOT NULL columns, we store column numbers to match, mapping them in
17973 : * to the child rel's attribute numbers.
17974 : */
17975 566 : attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
17976 : RelationGetDescr(parent_rel),
17977 : false);
17978 :
17979 566 : catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
17980 566 : ScanKeyInit(&key[0],
17981 : Anum_pg_constraint_conrelid,
17982 : BTEqualStrategyNumber, F_OIDEQ,
17983 : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
17984 566 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
17985 : true, NULL, 1, key);
17986 :
17987 566 : connames = NIL;
17988 566 : nncolumns = NIL;
17989 :
17990 1220 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
17991 : {
17992 654 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
17993 :
17994 654 : if (con->connoinherit)
17995 110 : continue;
17996 :
17997 544 : if (con->contype == CONSTRAINT_CHECK)
17998 12 : connames = lappend(connames, pstrdup(NameStr(con->conname)));
17999 544 : if (con->contype == CONSTRAINT_NOTNULL)
18000 : {
18001 208 : AttrNumber parent_attno = extractNotNullColumn(constraintTuple);
18002 :
18003 208 : nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
18004 : }
18005 : }
18006 :
18007 566 : systable_endscan(scan);
18008 :
18009 : /* Now scan the child's constraints to find matches */
18010 566 : ScanKeyInit(&key[0],
18011 : Anum_pg_constraint_conrelid,
18012 : BTEqualStrategyNumber, F_OIDEQ,
18013 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18014 566 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18015 : true, NULL, 1, key);
18016 :
18017 1320 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18018 : {
18019 754 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18020 754 : bool match = false;
18021 :
18022 : /*
18023 : * Match CHECK constraints by name, not-null constraints by column
18024 : * number, and ignore all others.
18025 : */
18026 754 : if (con->contype == CONSTRAINT_CHECK)
18027 : {
18028 350 : foreach_ptr(char, chkname, connames)
18029 : {
18030 18 : if (con->contype == CONSTRAINT_CHECK &&
18031 18 : strcmp(NameStr(con->conname), chkname) == 0)
18032 : {
18033 12 : match = true;
18034 12 : connames = foreach_delete_current(connames, chkname);
18035 12 : break;
18036 : }
18037 : }
18038 : }
18039 582 : else if (con->contype == CONSTRAINT_NOTNULL)
18040 : {
18041 268 : AttrNumber child_attno = extractNotNullColumn(constraintTuple);
18042 :
18043 542 : foreach_int(prevattno, nncolumns)
18044 : {
18045 214 : if (prevattno == child_attno)
18046 : {
18047 208 : match = true;
18048 208 : nncolumns = foreach_delete_current(nncolumns, prevattno);
18049 208 : break;
18050 : }
18051 : }
18052 : }
18053 : else
18054 314 : continue;
18055 :
18056 440 : if (match)
18057 : {
18058 : /* Decrement inhcount and possibly set islocal to true */
18059 220 : HeapTuple copyTuple = heap_copytuple(constraintTuple);
18060 220 : Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
18061 :
18062 220 : if (copy_con->coninhcount <= 0) /* shouldn't happen */
18063 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
18064 : RelationGetRelid(child_rel), NameStr(copy_con->conname));
18065 :
18066 220 : copy_con->coninhcount--;
18067 220 : if (copy_con->coninhcount == 0)
18068 202 : copy_con->conislocal = true;
18069 :
18070 220 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18071 220 : heap_freetuple(copyTuple);
18072 : }
18073 : }
18074 :
18075 : /* We should have matched all constraints */
18076 566 : if (connames != NIL || nncolumns != NIL)
18077 0 : elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
18078 : list_length(connames) + list_length(nncolumns),
18079 : RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
18080 :
18081 566 : systable_endscan(scan);
18082 566 : table_close(catalogRelation, RowExclusiveLock);
18083 :
18084 566 : drop_parent_dependency(RelationGetRelid(child_rel),
18085 : RelationRelationId,
18086 : RelationGetRelid(parent_rel),
18087 : child_dependency_type(is_partitioning));
18088 :
18089 : /*
18090 : * Post alter hook of this inherits. Since object_access_hook doesn't take
18091 : * multiple object identifiers, we relay oid of parent relation using
18092 : * auxiliary_id argument.
18093 : */
18094 566 : InvokeObjectPostAlterHookArg(InheritsRelationId,
18095 : RelationGetRelid(child_rel), 0,
18096 : RelationGetRelid(parent_rel), false);
18097 566 : }
18098 :
18099 : /*
18100 : * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
18101 : * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
18102 : * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
18103 : * be TypeRelationId). There's no convenient way to do this, so go trawling
18104 : * through pg_depend.
18105 : */
18106 : static void
18107 578 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
18108 : DependencyType deptype)
18109 : {
18110 : Relation catalogRelation;
18111 : SysScanDesc scan;
18112 : ScanKeyData key[3];
18113 : HeapTuple depTuple;
18114 :
18115 578 : catalogRelation = table_open(DependRelationId, RowExclusiveLock);
18116 :
18117 578 : ScanKeyInit(&key[0],
18118 : Anum_pg_depend_classid,
18119 : BTEqualStrategyNumber, F_OIDEQ,
18120 : ObjectIdGetDatum(RelationRelationId));
18121 578 : ScanKeyInit(&key[1],
18122 : Anum_pg_depend_objid,
18123 : BTEqualStrategyNumber, F_OIDEQ,
18124 : ObjectIdGetDatum(relid));
18125 578 : ScanKeyInit(&key[2],
18126 : Anum_pg_depend_objsubid,
18127 : BTEqualStrategyNumber, F_INT4EQ,
18128 : Int32GetDatum(0));
18129 :
18130 578 : scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
18131 : NULL, 3, key);
18132 :
18133 1794 : while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
18134 : {
18135 1216 : Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
18136 :
18137 1216 : if (dep->refclassid == refclassid &&
18138 620 : dep->refobjid == refobjid &&
18139 578 : dep->refobjsubid == 0 &&
18140 578 : dep->deptype == deptype)
18141 578 : CatalogTupleDelete(catalogRelation, &depTuple->t_self);
18142 : }
18143 :
18144 578 : systable_endscan(scan);
18145 578 : table_close(catalogRelation, RowExclusiveLock);
18146 578 : }
18147 :
18148 : /*
18149 : * ALTER TABLE OF
18150 : *
18151 : * Attach a table to a composite type, as though it had been created with CREATE
18152 : * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
18153 : * subject table must not have inheritance parents. These restrictions ensure
18154 : * that you cannot create a configuration impossible with CREATE TABLE OF alone.
18155 : *
18156 : * The address of the type is returned.
18157 : */
18158 : static ObjectAddress
18159 66 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
18160 : {
18161 66 : Oid relid = RelationGetRelid(rel);
18162 : Type typetuple;
18163 : Form_pg_type typeform;
18164 : Oid typeid;
18165 : Relation inheritsRelation,
18166 : relationRelation;
18167 : SysScanDesc scan;
18168 : ScanKeyData key;
18169 : AttrNumber table_attno,
18170 : type_attno;
18171 : TupleDesc typeTupleDesc,
18172 : tableTupleDesc;
18173 : ObjectAddress tableobj,
18174 : typeobj;
18175 : HeapTuple classtuple;
18176 :
18177 : /* Validate the type. */
18178 66 : typetuple = typenameType(NULL, ofTypename, NULL);
18179 66 : check_of_type(typetuple);
18180 66 : typeform = (Form_pg_type) GETSTRUCT(typetuple);
18181 66 : typeid = typeform->oid;
18182 :
18183 : /* Fail if the table has any inheritance parents. */
18184 66 : inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
18185 66 : ScanKeyInit(&key,
18186 : Anum_pg_inherits_inhrelid,
18187 : BTEqualStrategyNumber, F_OIDEQ,
18188 : ObjectIdGetDatum(relid));
18189 66 : scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
18190 : true, NULL, 1, &key);
18191 66 : if (HeapTupleIsValid(systable_getnext(scan)))
18192 6 : ereport(ERROR,
18193 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18194 : errmsg("typed tables cannot inherit")));
18195 60 : systable_endscan(scan);
18196 60 : table_close(inheritsRelation, AccessShareLock);
18197 :
18198 : /*
18199 : * Check the tuple descriptors for compatibility. Unlike inheritance, we
18200 : * require that the order also match. However, attnotnull need not match.
18201 : */
18202 60 : typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
18203 60 : tableTupleDesc = RelationGetDescr(rel);
18204 60 : table_attno = 1;
18205 190 : for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
18206 : {
18207 : Form_pg_attribute type_attr,
18208 : table_attr;
18209 : const char *type_attname,
18210 : *table_attname;
18211 :
18212 : /* Get the next non-dropped type attribute. */
18213 154 : type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
18214 154 : if (type_attr->attisdropped)
18215 44 : continue;
18216 110 : type_attname = NameStr(type_attr->attname);
18217 :
18218 : /* Get the next non-dropped table attribute. */
18219 : do
18220 : {
18221 122 : if (table_attno > tableTupleDesc->natts)
18222 6 : ereport(ERROR,
18223 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18224 : errmsg("table is missing column \"%s\"",
18225 : type_attname)));
18226 116 : table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
18227 116 : table_attno++;
18228 116 : } while (table_attr->attisdropped);
18229 104 : table_attname = NameStr(table_attr->attname);
18230 :
18231 : /* Compare name. */
18232 104 : if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
18233 6 : ereport(ERROR,
18234 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18235 : errmsg("table has column \"%s\" where type requires \"%s\"",
18236 : table_attname, type_attname)));
18237 :
18238 : /* Compare type. */
18239 98 : if (table_attr->atttypid != type_attr->atttypid ||
18240 92 : table_attr->atttypmod != type_attr->atttypmod ||
18241 86 : table_attr->attcollation != type_attr->attcollation)
18242 12 : ereport(ERROR,
18243 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18244 : errmsg("table \"%s\" has different type for column \"%s\"",
18245 : RelationGetRelationName(rel), type_attname)));
18246 : }
18247 36 : ReleaseTupleDesc(typeTupleDesc);
18248 :
18249 : /* Any remaining columns at the end of the table had better be dropped. */
18250 36 : for (; table_attno <= tableTupleDesc->natts; table_attno++)
18251 : {
18252 6 : Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
18253 : table_attno - 1);
18254 :
18255 6 : if (!table_attr->attisdropped)
18256 6 : ereport(ERROR,
18257 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18258 : errmsg("table has extra column \"%s\"",
18259 : NameStr(table_attr->attname))));
18260 : }
18261 :
18262 : /* If the table was already typed, drop the existing dependency. */
18263 30 : if (rel->rd_rel->reloftype)
18264 6 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
18265 : DEPENDENCY_NORMAL);
18266 :
18267 : /* Record a dependency on the new type. */
18268 30 : tableobj.classId = RelationRelationId;
18269 30 : tableobj.objectId = relid;
18270 30 : tableobj.objectSubId = 0;
18271 30 : typeobj.classId = TypeRelationId;
18272 30 : typeobj.objectId = typeid;
18273 30 : typeobj.objectSubId = 0;
18274 30 : recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
18275 :
18276 : /* Update pg_class.reloftype */
18277 30 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
18278 30 : classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18279 30 : if (!HeapTupleIsValid(classtuple))
18280 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18281 30 : ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
18282 30 : CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
18283 :
18284 30 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
18285 :
18286 30 : heap_freetuple(classtuple);
18287 30 : table_close(relationRelation, RowExclusiveLock);
18288 :
18289 30 : ReleaseSysCache(typetuple);
18290 :
18291 30 : return typeobj;
18292 : }
18293 :
18294 : /*
18295 : * ALTER TABLE NOT OF
18296 : *
18297 : * Detach a typed table from its originating type. Just clear reloftype and
18298 : * remove the dependency.
18299 : */
18300 : static void
18301 6 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
18302 : {
18303 6 : Oid relid = RelationGetRelid(rel);
18304 : Relation relationRelation;
18305 : HeapTuple tuple;
18306 :
18307 6 : if (!OidIsValid(rel->rd_rel->reloftype))
18308 0 : ereport(ERROR,
18309 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18310 : errmsg("\"%s\" is not a typed table",
18311 : RelationGetRelationName(rel))));
18312 :
18313 : /*
18314 : * We don't bother to check ownership of the type --- ownership of the
18315 : * table is presumed enough rights. No lock required on the type, either.
18316 : */
18317 :
18318 6 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
18319 : DEPENDENCY_NORMAL);
18320 :
18321 : /* Clear pg_class.reloftype */
18322 6 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
18323 6 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18324 6 : if (!HeapTupleIsValid(tuple))
18325 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18326 6 : ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
18327 6 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
18328 :
18329 6 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
18330 :
18331 6 : heap_freetuple(tuple);
18332 6 : table_close(relationRelation, RowExclusiveLock);
18333 6 : }
18334 :
18335 : /*
18336 : * relation_mark_replica_identity: Update a table's replica identity
18337 : *
18338 : * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
18339 : * index. Otherwise, it must be InvalidOid.
18340 : *
18341 : * Caller had better hold an exclusive lock on the relation, as the results
18342 : * of running two of these concurrently wouldn't be pretty.
18343 : */
18344 : static void
18345 460 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
18346 : bool is_internal)
18347 : {
18348 : Relation pg_index;
18349 : Relation pg_class;
18350 : HeapTuple pg_class_tuple;
18351 : HeapTuple pg_index_tuple;
18352 : Form_pg_class pg_class_form;
18353 : Form_pg_index pg_index_form;
18354 : ListCell *index;
18355 :
18356 : /*
18357 : * Check whether relreplident has changed, and update it if so.
18358 : */
18359 460 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
18360 460 : pg_class_tuple = SearchSysCacheCopy1(RELOID,
18361 : ObjectIdGetDatum(RelationGetRelid(rel)));
18362 460 : if (!HeapTupleIsValid(pg_class_tuple))
18363 0 : elog(ERROR, "cache lookup failed for relation \"%s\"",
18364 : RelationGetRelationName(rel));
18365 460 : pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
18366 460 : if (pg_class_form->relreplident != ri_type)
18367 : {
18368 410 : pg_class_form->relreplident = ri_type;
18369 410 : CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
18370 : }
18371 460 : table_close(pg_class, RowExclusiveLock);
18372 460 : heap_freetuple(pg_class_tuple);
18373 :
18374 : /*
18375 : * Update the per-index indisreplident flags correctly.
18376 : */
18377 460 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
18378 1180 : foreach(index, RelationGetIndexList(rel))
18379 : {
18380 720 : Oid thisIndexOid = lfirst_oid(index);
18381 720 : bool dirty = false;
18382 :
18383 720 : pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
18384 : ObjectIdGetDatum(thisIndexOid));
18385 720 : if (!HeapTupleIsValid(pg_index_tuple))
18386 0 : elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
18387 720 : pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
18388 :
18389 720 : if (thisIndexOid == indexOid)
18390 : {
18391 : /* Set the bit if not already set. */
18392 240 : if (!pg_index_form->indisreplident)
18393 : {
18394 222 : dirty = true;
18395 222 : pg_index_form->indisreplident = true;
18396 : }
18397 : }
18398 : else
18399 : {
18400 : /* Unset the bit if set. */
18401 480 : if (pg_index_form->indisreplident)
18402 : {
18403 52 : dirty = true;
18404 52 : pg_index_form->indisreplident = false;
18405 : }
18406 : }
18407 :
18408 720 : if (dirty)
18409 : {
18410 274 : CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
18411 274 : InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
18412 : InvalidOid, is_internal);
18413 :
18414 : /*
18415 : * Invalidate the relcache for the table, so that after we commit
18416 : * all sessions will refresh the table's replica identity index
18417 : * before attempting any UPDATE or DELETE on the table. (If we
18418 : * changed the table's pg_class row above, then a relcache inval
18419 : * is already queued due to that; but we might not have.)
18420 : */
18421 274 : CacheInvalidateRelcache(rel);
18422 : }
18423 720 : heap_freetuple(pg_index_tuple);
18424 : }
18425 :
18426 460 : table_close(pg_index, RowExclusiveLock);
18427 460 : }
18428 :
18429 : /*
18430 : * ALTER TABLE <name> REPLICA IDENTITY ...
18431 : */
18432 : static void
18433 508 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
18434 : {
18435 : Oid indexOid;
18436 : Relation indexRel;
18437 : int key;
18438 :
18439 508 : if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
18440 : {
18441 6 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18442 6 : return;
18443 : }
18444 502 : else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
18445 : {
18446 166 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18447 166 : return;
18448 : }
18449 336 : else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
18450 : {
18451 48 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18452 48 : return;
18453 : }
18454 288 : else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
18455 : {
18456 : /* fallthrough */ ;
18457 : }
18458 : else
18459 0 : elog(ERROR, "unexpected identity type %u", stmt->identity_type);
18460 :
18461 : /* Check that the index exists */
18462 288 : indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
18463 288 : if (!OidIsValid(indexOid))
18464 0 : ereport(ERROR,
18465 : (errcode(ERRCODE_UNDEFINED_OBJECT),
18466 : errmsg("index \"%s\" for table \"%s\" does not exist",
18467 : stmt->name, RelationGetRelationName(rel))));
18468 :
18469 288 : indexRel = index_open(indexOid, ShareLock);
18470 :
18471 : /* Check that the index is on the relation we're altering. */
18472 288 : if (indexRel->rd_index == NULL ||
18473 288 : indexRel->rd_index->indrelid != RelationGetRelid(rel))
18474 6 : ereport(ERROR,
18475 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18476 : errmsg("\"%s\" is not an index for table \"%s\"",
18477 : RelationGetRelationName(indexRel),
18478 : RelationGetRelationName(rel))));
18479 :
18480 : /*
18481 : * The AM must support uniqueness, and the index must in fact be unique.
18482 : * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
18483 : * exclusion), we can use that too.
18484 : */
18485 282 : if ((!indexRel->rd_indam->amcanunique ||
18486 262 : !indexRel->rd_index->indisunique) &&
18487 26 : !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
18488 12 : ereport(ERROR,
18489 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18490 : errmsg("cannot use non-unique index \"%s\" as replica identity",
18491 : RelationGetRelationName(indexRel))));
18492 : /* Deferred indexes are not guaranteed to be always unique. */
18493 270 : if (!indexRel->rd_index->indimmediate)
18494 12 : ereport(ERROR,
18495 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18496 : errmsg("cannot use non-immediate index \"%s\" as replica identity",
18497 : RelationGetRelationName(indexRel))));
18498 : /* Expression indexes aren't supported. */
18499 258 : if (RelationGetIndexExpressions(indexRel) != NIL)
18500 6 : ereport(ERROR,
18501 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18502 : errmsg("cannot use expression index \"%s\" as replica identity",
18503 : RelationGetRelationName(indexRel))));
18504 : /* Predicate indexes aren't supported. */
18505 252 : if (RelationGetIndexPredicate(indexRel) != NIL)
18506 6 : ereport(ERROR,
18507 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18508 : errmsg("cannot use partial index \"%s\" as replica identity",
18509 : RelationGetRelationName(indexRel))));
18510 :
18511 : /* Check index for nullable columns. */
18512 552 : for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
18513 : {
18514 312 : int16 attno = indexRel->rd_index->indkey.values[key];
18515 : Form_pg_attribute attr;
18516 :
18517 : /*
18518 : * Reject any other system columns. (Going forward, we'll disallow
18519 : * indexes containing such columns in the first place, but they might
18520 : * exist in older branches.)
18521 : */
18522 312 : if (attno <= 0)
18523 0 : ereport(ERROR,
18524 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
18525 : errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
18526 : RelationGetRelationName(indexRel), attno)));
18527 :
18528 312 : attr = TupleDescAttr(rel->rd_att, attno - 1);
18529 312 : if (!attr->attnotnull)
18530 6 : ereport(ERROR,
18531 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18532 : errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
18533 : RelationGetRelationName(indexRel),
18534 : NameStr(attr->attname))));
18535 : }
18536 :
18537 : /* This index is suitable for use as a replica identity. Mark it. */
18538 240 : relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
18539 :
18540 240 : index_close(indexRel, NoLock);
18541 : }
18542 :
18543 : /*
18544 : * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
18545 : */
18546 : static void
18547 318 : ATExecSetRowSecurity(Relation rel, bool rls)
18548 : {
18549 : Relation pg_class;
18550 : Oid relid;
18551 : HeapTuple tuple;
18552 :
18553 318 : relid = RelationGetRelid(rel);
18554 :
18555 : /* Pull the record for this relation and update it */
18556 318 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
18557 :
18558 318 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18559 :
18560 318 : if (!HeapTupleIsValid(tuple))
18561 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18562 :
18563 318 : ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
18564 318 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
18565 :
18566 318 : InvokeObjectPostAlterHook(RelationRelationId,
18567 : RelationGetRelid(rel), 0);
18568 :
18569 318 : table_close(pg_class, RowExclusiveLock);
18570 318 : heap_freetuple(tuple);
18571 318 : }
18572 :
18573 : /*
18574 : * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
18575 : */
18576 : static void
18577 134 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
18578 : {
18579 : Relation pg_class;
18580 : Oid relid;
18581 : HeapTuple tuple;
18582 :
18583 134 : relid = RelationGetRelid(rel);
18584 :
18585 134 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
18586 :
18587 134 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18588 :
18589 134 : if (!HeapTupleIsValid(tuple))
18590 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18591 :
18592 134 : ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
18593 134 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
18594 :
18595 134 : InvokeObjectPostAlterHook(RelationRelationId,
18596 : RelationGetRelid(rel), 0);
18597 :
18598 134 : table_close(pg_class, RowExclusiveLock);
18599 134 : heap_freetuple(tuple);
18600 134 : }
18601 :
18602 : /*
18603 : * ALTER FOREIGN TABLE <name> OPTIONS (...)
18604 : */
18605 : static void
18606 58 : ATExecGenericOptions(Relation rel, List *options)
18607 : {
18608 : Relation ftrel;
18609 : ForeignServer *server;
18610 : ForeignDataWrapper *fdw;
18611 : HeapTuple tuple;
18612 : bool isnull;
18613 : Datum repl_val[Natts_pg_foreign_table];
18614 : bool repl_null[Natts_pg_foreign_table];
18615 : bool repl_repl[Natts_pg_foreign_table];
18616 : Datum datum;
18617 : Form_pg_foreign_table tableform;
18618 :
18619 58 : if (options == NIL)
18620 0 : return;
18621 :
18622 58 : ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
18623 :
18624 58 : tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
18625 : ObjectIdGetDatum(rel->rd_id));
18626 58 : if (!HeapTupleIsValid(tuple))
18627 0 : ereport(ERROR,
18628 : (errcode(ERRCODE_UNDEFINED_OBJECT),
18629 : errmsg("foreign table \"%s\" does not exist",
18630 : RelationGetRelationName(rel))));
18631 58 : tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
18632 58 : server = GetForeignServer(tableform->ftserver);
18633 58 : fdw = GetForeignDataWrapper(server->fdwid);
18634 :
18635 58 : memset(repl_val, 0, sizeof(repl_val));
18636 58 : memset(repl_null, false, sizeof(repl_null));
18637 58 : memset(repl_repl, false, sizeof(repl_repl));
18638 :
18639 : /* Extract the current options */
18640 58 : datum = SysCacheGetAttr(FOREIGNTABLEREL,
18641 : tuple,
18642 : Anum_pg_foreign_table_ftoptions,
18643 : &isnull);
18644 58 : if (isnull)
18645 4 : datum = PointerGetDatum(NULL);
18646 :
18647 : /* Transform the options */
18648 58 : datum = transformGenericOptions(ForeignTableRelationId,
18649 : datum,
18650 : options,
18651 : fdw->fdwvalidator);
18652 :
18653 56 : if (PointerIsValid(DatumGetPointer(datum)))
18654 56 : repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
18655 : else
18656 0 : repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
18657 :
18658 56 : repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
18659 :
18660 : /* Everything looks good - update the tuple */
18661 :
18662 56 : tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
18663 : repl_val, repl_null, repl_repl);
18664 :
18665 56 : CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
18666 :
18667 : /*
18668 : * Invalidate relcache so that all sessions will refresh any cached plans
18669 : * that might depend on the old options.
18670 : */
18671 56 : CacheInvalidateRelcache(rel);
18672 :
18673 56 : InvokeObjectPostAlterHook(ForeignTableRelationId,
18674 : RelationGetRelid(rel), 0);
18675 :
18676 56 : table_close(ftrel, RowExclusiveLock);
18677 :
18678 56 : heap_freetuple(tuple);
18679 : }
18680 :
18681 : /*
18682 : * ALTER TABLE ALTER COLUMN SET COMPRESSION
18683 : *
18684 : * Return value is the address of the modified column
18685 : */
18686 : static ObjectAddress
18687 90 : ATExecSetCompression(Relation rel,
18688 : const char *column,
18689 : Node *newValue,
18690 : LOCKMODE lockmode)
18691 : {
18692 : Relation attrel;
18693 : HeapTuple tuple;
18694 : Form_pg_attribute atttableform;
18695 : AttrNumber attnum;
18696 : char *compression;
18697 : char cmethod;
18698 : ObjectAddress address;
18699 :
18700 90 : compression = strVal(newValue);
18701 :
18702 90 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
18703 :
18704 : /* copy the cache entry so we can scribble on it below */
18705 90 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
18706 90 : if (!HeapTupleIsValid(tuple))
18707 0 : ereport(ERROR,
18708 : (errcode(ERRCODE_UNDEFINED_COLUMN),
18709 : errmsg("column \"%s\" of relation \"%s\" does not exist",
18710 : column, RelationGetRelationName(rel))));
18711 :
18712 : /* prevent them from altering a system attribute */
18713 90 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
18714 90 : attnum = atttableform->attnum;
18715 90 : if (attnum <= 0)
18716 0 : ereport(ERROR,
18717 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18718 : errmsg("cannot alter system column \"%s\"", column)));
18719 :
18720 : /*
18721 : * Check that column type is compressible, then get the attribute
18722 : * compression method code
18723 : */
18724 90 : cmethod = GetAttributeCompression(atttableform->atttypid, compression);
18725 :
18726 : /* update pg_attribute entry */
18727 84 : atttableform->attcompression = cmethod;
18728 84 : CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
18729 :
18730 84 : InvokeObjectPostAlterHook(RelationRelationId,
18731 : RelationGetRelid(rel),
18732 : attnum);
18733 :
18734 : /*
18735 : * Apply the change to indexes as well (only for simple index columns,
18736 : * matching behavior of index.c ConstructTupleDescriptor()).
18737 : */
18738 84 : SetIndexStorageProperties(rel, attrel, attnum,
18739 : false, 0,
18740 : true, cmethod,
18741 : lockmode);
18742 :
18743 84 : heap_freetuple(tuple);
18744 :
18745 84 : table_close(attrel, RowExclusiveLock);
18746 :
18747 : /* make changes visible */
18748 84 : CommandCounterIncrement();
18749 :
18750 84 : ObjectAddressSubSet(address, RelationRelationId,
18751 : RelationGetRelid(rel), attnum);
18752 84 : return address;
18753 : }
18754 :
18755 :
18756 : /*
18757 : * Preparation phase for SET LOGGED/UNLOGGED
18758 : *
18759 : * This verifies that we're not trying to change a temp table. Also,
18760 : * existing foreign key constraints are checked to avoid ending up with
18761 : * permanent tables referencing unlogged tables.
18762 : */
18763 : static void
18764 100 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
18765 : {
18766 : Relation pg_constraint;
18767 : HeapTuple tuple;
18768 : SysScanDesc scan;
18769 : ScanKeyData skey[1];
18770 :
18771 : /*
18772 : * Disallow changing status for a temp table. Also verify whether we can
18773 : * get away with doing nothing; in such cases we don't need to run the
18774 : * checks below, either.
18775 : */
18776 100 : switch (rel->rd_rel->relpersistence)
18777 : {
18778 0 : case RELPERSISTENCE_TEMP:
18779 0 : ereport(ERROR,
18780 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
18781 : errmsg("cannot change logged status of table \"%s\" because it is temporary",
18782 : RelationGetRelationName(rel)),
18783 : errtable(rel)));
18784 : break;
18785 56 : case RELPERSISTENCE_PERMANENT:
18786 56 : if (toLogged)
18787 : /* nothing to do */
18788 12 : return;
18789 50 : break;
18790 44 : case RELPERSISTENCE_UNLOGGED:
18791 44 : if (!toLogged)
18792 : /* nothing to do */
18793 6 : return;
18794 38 : break;
18795 : }
18796 :
18797 : /*
18798 : * Check that the table is not part of any publication when changing to
18799 : * UNLOGGED, as UNLOGGED tables can't be published.
18800 : */
18801 138 : if (!toLogged &&
18802 50 : GetRelationPublications(RelationGetRelid(rel)) != NIL)
18803 0 : ereport(ERROR,
18804 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
18805 : errmsg("cannot change table \"%s\" to unlogged because it is part of a publication",
18806 : RelationGetRelationName(rel)),
18807 : errdetail("Unlogged relations cannot be replicated.")));
18808 :
18809 : /*
18810 : * Check existing foreign key constraints to preserve the invariant that
18811 : * permanent tables cannot reference unlogged ones. Self-referencing
18812 : * foreign keys can safely be ignored.
18813 : */
18814 88 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
18815 :
18816 : /*
18817 : * Scan conrelid if changing to permanent, else confrelid. This also
18818 : * determines whether a useful index exists.
18819 : */
18820 88 : ScanKeyInit(&skey[0],
18821 : toLogged ? Anum_pg_constraint_conrelid :
18822 : Anum_pg_constraint_confrelid,
18823 : BTEqualStrategyNumber, F_OIDEQ,
18824 : ObjectIdGetDatum(RelationGetRelid(rel)));
18825 88 : scan = systable_beginscan(pg_constraint,
18826 : toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
18827 : true, NULL, 1, skey);
18828 :
18829 142 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
18830 : {
18831 66 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
18832 :
18833 66 : if (con->contype == CONSTRAINT_FOREIGN)
18834 : {
18835 : Oid foreignrelid;
18836 : Relation foreignrel;
18837 :
18838 : /* the opposite end of what we used as scankey */
18839 30 : foreignrelid = toLogged ? con->confrelid : con->conrelid;
18840 :
18841 : /* ignore if self-referencing */
18842 30 : if (RelationGetRelid(rel) == foreignrelid)
18843 12 : continue;
18844 :
18845 18 : foreignrel = relation_open(foreignrelid, AccessShareLock);
18846 :
18847 18 : if (toLogged)
18848 : {
18849 6 : if (!RelationIsPermanent(foreignrel))
18850 6 : ereport(ERROR,
18851 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
18852 : errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
18853 : RelationGetRelationName(rel),
18854 : RelationGetRelationName(foreignrel)),
18855 : errtableconstraint(rel, NameStr(con->conname))));
18856 : }
18857 : else
18858 : {
18859 12 : if (RelationIsPermanent(foreignrel))
18860 6 : ereport(ERROR,
18861 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
18862 : errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
18863 : RelationGetRelationName(rel),
18864 : RelationGetRelationName(foreignrel)),
18865 : errtableconstraint(rel, NameStr(con->conname))));
18866 : }
18867 :
18868 6 : relation_close(foreignrel, AccessShareLock);
18869 : }
18870 : }
18871 :
18872 76 : systable_endscan(scan);
18873 :
18874 76 : table_close(pg_constraint, AccessShareLock);
18875 :
18876 : /* force rewrite if necessary; see comment in ATRewriteTables */
18877 76 : tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
18878 76 : if (toLogged)
18879 32 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
18880 : else
18881 44 : tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
18882 76 : tab->chgPersistence = true;
18883 : }
18884 :
18885 : /*
18886 : * Execute ALTER TABLE SET SCHEMA
18887 : */
18888 : ObjectAddress
18889 104 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
18890 : {
18891 : Relation rel;
18892 : Oid relid;
18893 : Oid oldNspOid;
18894 : Oid nspOid;
18895 : RangeVar *newrv;
18896 : ObjectAddresses *objsMoved;
18897 : ObjectAddress myself;
18898 :
18899 104 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
18900 104 : stmt->missing_ok ? RVR_MISSING_OK : 0,
18901 : RangeVarCallbackForAlterRelation,
18902 : stmt);
18903 :
18904 102 : if (!OidIsValid(relid))
18905 : {
18906 12 : ereport(NOTICE,
18907 : (errmsg("relation \"%s\" does not exist, skipping",
18908 : stmt->relation->relname)));
18909 12 : return InvalidObjectAddress;
18910 : }
18911 :
18912 90 : rel = relation_open(relid, NoLock);
18913 :
18914 90 : oldNspOid = RelationGetNamespace(rel);
18915 :
18916 : /* If it's an owned sequence, disallow moving it by itself. */
18917 90 : if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
18918 : {
18919 : Oid tableId;
18920 : int32 colId;
18921 :
18922 10 : if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
18923 2 : sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
18924 6 : ereport(ERROR,
18925 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18926 : errmsg("cannot move an owned sequence into another schema"),
18927 : errdetail("Sequence \"%s\" is linked to table \"%s\".",
18928 : RelationGetRelationName(rel),
18929 : get_rel_name(tableId))));
18930 : }
18931 :
18932 : /* Get and lock schema OID and check its permissions. */
18933 84 : newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
18934 84 : nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
18935 :
18936 : /* common checks on switching namespaces */
18937 84 : CheckSetNamespace(oldNspOid, nspOid);
18938 :
18939 84 : objsMoved = new_object_addresses();
18940 84 : AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
18941 84 : free_object_addresses(objsMoved);
18942 :
18943 84 : ObjectAddressSet(myself, RelationRelationId, relid);
18944 :
18945 84 : if (oldschema)
18946 84 : *oldschema = oldNspOid;
18947 :
18948 : /* close rel, but keep lock until commit */
18949 84 : relation_close(rel, NoLock);
18950 :
18951 84 : return myself;
18952 : }
18953 :
18954 : /*
18955 : * The guts of relocating a table or materialized view to another namespace:
18956 : * besides moving the relation itself, its dependent objects are relocated to
18957 : * the new schema.
18958 : */
18959 : void
18960 86 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
18961 : ObjectAddresses *objsMoved)
18962 : {
18963 : Relation classRel;
18964 :
18965 : Assert(objsMoved != NULL);
18966 :
18967 : /* OK, modify the pg_class row and pg_depend entry */
18968 86 : classRel = table_open(RelationRelationId, RowExclusiveLock);
18969 :
18970 86 : AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
18971 : nspOid, true, objsMoved);
18972 :
18973 : /* Fix the table's row type too, if it has one */
18974 86 : if (OidIsValid(rel->rd_rel->reltype))
18975 84 : AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
18976 : false, /* isImplicitArray */
18977 : false, /* ignoreDependent */
18978 : false, /* errorOnTableType */
18979 : objsMoved);
18980 :
18981 : /* Fix other dependent stuff */
18982 86 : AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
18983 86 : AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
18984 : objsMoved, AccessExclusiveLock);
18985 86 : AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
18986 : false, objsMoved);
18987 :
18988 86 : table_close(classRel, RowExclusiveLock);
18989 86 : }
18990 :
18991 : /*
18992 : * The guts of relocating a relation to another namespace: fix the pg_class
18993 : * entry, and the pg_depend entry if any. Caller must already have
18994 : * opened and write-locked pg_class.
18995 : */
18996 : void
18997 188 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
18998 : Oid oldNspOid, Oid newNspOid,
18999 : bool hasDependEntry,
19000 : ObjectAddresses *objsMoved)
19001 : {
19002 : HeapTuple classTup;
19003 : Form_pg_class classForm;
19004 : ObjectAddress thisobj;
19005 188 : bool already_done = false;
19006 :
19007 : /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19008 188 : classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
19009 188 : if (!HeapTupleIsValid(classTup))
19010 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
19011 188 : classForm = (Form_pg_class) GETSTRUCT(classTup);
19012 :
19013 : Assert(classForm->relnamespace == oldNspOid);
19014 :
19015 188 : thisobj.classId = RelationRelationId;
19016 188 : thisobj.objectId = relOid;
19017 188 : thisobj.objectSubId = 0;
19018 :
19019 : /*
19020 : * If the object has already been moved, don't move it again. If it's
19021 : * already in the right place, don't move it, but still fire the object
19022 : * access hook.
19023 : */
19024 188 : already_done = object_address_present(&thisobj, objsMoved);
19025 188 : if (!already_done && oldNspOid != newNspOid)
19026 146 : {
19027 146 : ItemPointerData otid = classTup->t_self;
19028 :
19029 : /* check for duplicate name (more friendly than unique-index failure) */
19030 146 : if (get_relname_relid(NameStr(classForm->relname),
19031 : newNspOid) != InvalidOid)
19032 0 : ereport(ERROR,
19033 : (errcode(ERRCODE_DUPLICATE_TABLE),
19034 : errmsg("relation \"%s\" already exists in schema \"%s\"",
19035 : NameStr(classForm->relname),
19036 : get_namespace_name(newNspOid))));
19037 :
19038 : /* classTup is a copy, so OK to scribble on */
19039 146 : classForm->relnamespace = newNspOid;
19040 :
19041 146 : CatalogTupleUpdate(classRel, &otid, classTup);
19042 146 : UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19043 :
19044 :
19045 : /* Update dependency on schema if caller said so */
19046 250 : if (hasDependEntry &&
19047 104 : changeDependencyFor(RelationRelationId,
19048 : relOid,
19049 : NamespaceRelationId,
19050 : oldNspOid,
19051 : newNspOid) != 1)
19052 0 : elog(ERROR, "could not change schema dependency for relation \"%s\"",
19053 : NameStr(classForm->relname));
19054 : }
19055 : else
19056 42 : UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19057 188 : if (!already_done)
19058 : {
19059 188 : add_exact_object_address(&thisobj, objsMoved);
19060 :
19061 188 : InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19062 : }
19063 :
19064 188 : heap_freetuple(classTup);
19065 188 : }
19066 :
19067 : /*
19068 : * Move all indexes for the specified relation to another namespace.
19069 : *
19070 : * Note: we assume adequate permission checking was done by the caller,
19071 : * and that the caller has a suitable lock on the owning relation.
19072 : */
19073 : static void
19074 86 : AlterIndexNamespaces(Relation classRel, Relation rel,
19075 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
19076 : {
19077 : List *indexList;
19078 : ListCell *l;
19079 :
19080 86 : indexList = RelationGetIndexList(rel);
19081 :
19082 132 : foreach(l, indexList)
19083 : {
19084 46 : Oid indexOid = lfirst_oid(l);
19085 : ObjectAddress thisobj;
19086 :
19087 46 : thisobj.classId = RelationRelationId;
19088 46 : thisobj.objectId = indexOid;
19089 46 : thisobj.objectSubId = 0;
19090 :
19091 : /*
19092 : * Note: currently, the index will not have its own dependency on the
19093 : * namespace, so we don't need to do changeDependencyFor(). There's no
19094 : * row type in pg_type, either.
19095 : *
19096 : * XXX this objsMoved test may be pointless -- surely we have a single
19097 : * dependency link from a relation to each index?
19098 : */
19099 46 : if (!object_address_present(&thisobj, objsMoved))
19100 : {
19101 46 : AlterRelationNamespaceInternal(classRel, indexOid,
19102 : oldNspOid, newNspOid,
19103 : false, objsMoved);
19104 46 : add_exact_object_address(&thisobj, objsMoved);
19105 : }
19106 : }
19107 :
19108 86 : list_free(indexList);
19109 86 : }
19110 :
19111 : /*
19112 : * Move all identity and SERIAL-column sequences of the specified relation to another
19113 : * namespace.
19114 : *
19115 : * Note: we assume adequate permission checking was done by the caller,
19116 : * and that the caller has a suitable lock on the owning relation.
19117 : */
19118 : static void
19119 86 : AlterSeqNamespaces(Relation classRel, Relation rel,
19120 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
19121 : LOCKMODE lockmode)
19122 : {
19123 : Relation depRel;
19124 : SysScanDesc scan;
19125 : ScanKeyData key[2];
19126 : HeapTuple tup;
19127 :
19128 : /*
19129 : * SERIAL sequences are those having an auto dependency on one of the
19130 : * table's columns (we don't care *which* column, exactly).
19131 : */
19132 86 : depRel = table_open(DependRelationId, AccessShareLock);
19133 :
19134 86 : ScanKeyInit(&key[0],
19135 : Anum_pg_depend_refclassid,
19136 : BTEqualStrategyNumber, F_OIDEQ,
19137 : ObjectIdGetDatum(RelationRelationId));
19138 86 : ScanKeyInit(&key[1],
19139 : Anum_pg_depend_refobjid,
19140 : BTEqualStrategyNumber, F_OIDEQ,
19141 : ObjectIdGetDatum(RelationGetRelid(rel)));
19142 : /* we leave refobjsubid unspecified */
19143 :
19144 86 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
19145 : NULL, 2, key);
19146 :
19147 616 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
19148 : {
19149 530 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
19150 : Relation seqRel;
19151 :
19152 : /* skip dependencies other than auto dependencies on columns */
19153 530 : if (depForm->refobjsubid == 0 ||
19154 382 : depForm->classid != RelationRelationId ||
19155 42 : depForm->objsubid != 0 ||
19156 42 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
19157 488 : continue;
19158 :
19159 : /* Use relation_open just in case it's an index */
19160 42 : seqRel = relation_open(depForm->objid, lockmode);
19161 :
19162 : /* skip non-sequence relations */
19163 42 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
19164 : {
19165 : /* No need to keep the lock */
19166 0 : relation_close(seqRel, lockmode);
19167 0 : continue;
19168 : }
19169 :
19170 : /* Fix the pg_class and pg_depend entries */
19171 42 : AlterRelationNamespaceInternal(classRel, depForm->objid,
19172 : oldNspOid, newNspOid,
19173 : true, objsMoved);
19174 :
19175 : /*
19176 : * Sequences used to have entries in pg_type, but no longer do. If we
19177 : * ever re-instate that, we'll need to move the pg_type entry to the
19178 : * new namespace, too (using AlterTypeNamespaceInternal).
19179 : */
19180 : Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
19181 :
19182 : /* Now we can close it. Keep the lock till end of transaction. */
19183 42 : relation_close(seqRel, NoLock);
19184 : }
19185 :
19186 86 : systable_endscan(scan);
19187 :
19188 86 : relation_close(depRel, AccessShareLock);
19189 86 : }
19190 :
19191 :
19192 : /*
19193 : * This code supports
19194 : * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
19195 : *
19196 : * Because we only support this for TEMP tables, it's sufficient to remember
19197 : * the state in a backend-local data structure.
19198 : */
19199 :
19200 : /*
19201 : * Register a newly-created relation's ON COMMIT action.
19202 : */
19203 : void
19204 176 : register_on_commit_action(Oid relid, OnCommitAction action)
19205 : {
19206 : OnCommitItem *oc;
19207 : MemoryContext oldcxt;
19208 :
19209 : /*
19210 : * We needn't bother registering the relation unless there is an ON COMMIT
19211 : * action we need to take.
19212 : */
19213 176 : if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19214 24 : return;
19215 :
19216 152 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
19217 :
19218 152 : oc = (OnCommitItem *) palloc(sizeof(OnCommitItem));
19219 152 : oc->relid = relid;
19220 152 : oc->oncommit = action;
19221 152 : oc->creating_subid = GetCurrentSubTransactionId();
19222 152 : oc->deleting_subid = InvalidSubTransactionId;
19223 :
19224 : /*
19225 : * We use lcons() here so that ON COMMIT actions are processed in reverse
19226 : * order of registration. That might not be essential but it seems
19227 : * reasonable.
19228 : */
19229 152 : on_commits = lcons(oc, on_commits);
19230 :
19231 152 : MemoryContextSwitchTo(oldcxt);
19232 : }
19233 :
19234 : /*
19235 : * Unregister any ON COMMIT action when a relation is deleted.
19236 : *
19237 : * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
19238 : */
19239 : void
19240 47870 : remove_on_commit_action(Oid relid)
19241 : {
19242 : ListCell *l;
19243 :
19244 48016 : foreach(l, on_commits)
19245 : {
19246 286 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19247 :
19248 286 : if (oc->relid == relid)
19249 : {
19250 140 : oc->deleting_subid = GetCurrentSubTransactionId();
19251 140 : break;
19252 : }
19253 : }
19254 47870 : }
19255 :
19256 : /*
19257 : * Perform ON COMMIT actions.
19258 : *
19259 : * This is invoked just before actually committing, since it's possible
19260 : * to encounter errors.
19261 : */
19262 : void
19263 978174 : PreCommit_on_commit_actions(void)
19264 : {
19265 : ListCell *l;
19266 978174 : List *oids_to_truncate = NIL;
19267 978174 : List *oids_to_drop = NIL;
19268 :
19269 978996 : foreach(l, on_commits)
19270 : {
19271 822 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19272 :
19273 : /* Ignore entry if already dropped in this xact */
19274 822 : if (oc->deleting_subid != InvalidSubTransactionId)
19275 74 : continue;
19276 :
19277 748 : switch (oc->oncommit)
19278 : {
19279 0 : case ONCOMMIT_NOOP:
19280 : case ONCOMMIT_PRESERVE_ROWS:
19281 : /* Do nothing (there shouldn't be such entries, actually) */
19282 0 : break;
19283 694 : case ONCOMMIT_DELETE_ROWS:
19284 :
19285 : /*
19286 : * If this transaction hasn't accessed any temporary
19287 : * relations, we can skip truncating ON COMMIT DELETE ROWS
19288 : * tables, as they must still be empty.
19289 : */
19290 694 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
19291 448 : oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
19292 694 : break;
19293 54 : case ONCOMMIT_DROP:
19294 54 : oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
19295 54 : break;
19296 : }
19297 : }
19298 :
19299 : /*
19300 : * Truncate relations before dropping so that all dependencies between
19301 : * relations are removed after they are worked on. Doing it like this
19302 : * might be a waste as it is possible that a relation being truncated will
19303 : * be dropped anyway due to its parent being dropped, but this makes the
19304 : * code more robust because of not having to re-check that the relation
19305 : * exists at truncation time.
19306 : */
19307 978174 : if (oids_to_truncate != NIL)
19308 382 : heap_truncate(oids_to_truncate);
19309 :
19310 978168 : if (oids_to_drop != NIL)
19311 : {
19312 48 : ObjectAddresses *targetObjects = new_object_addresses();
19313 :
19314 102 : foreach(l, oids_to_drop)
19315 : {
19316 : ObjectAddress object;
19317 :
19318 54 : object.classId = RelationRelationId;
19319 54 : object.objectId = lfirst_oid(l);
19320 54 : object.objectSubId = 0;
19321 :
19322 : Assert(!object_address_present(&object, targetObjects));
19323 :
19324 54 : add_exact_object_address(&object, targetObjects);
19325 : }
19326 :
19327 : /*
19328 : * Object deletion might involve toast table access (to clean up
19329 : * toasted catalog entries), so ensure we have a valid snapshot.
19330 : */
19331 48 : PushActiveSnapshot(GetTransactionSnapshot());
19332 :
19333 : /*
19334 : * Since this is an automatic drop, rather than one directly initiated
19335 : * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19336 : */
19337 48 : performMultipleDeletions(targetObjects, DROP_CASCADE,
19338 : PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
19339 :
19340 48 : PopActiveSnapshot();
19341 :
19342 : #ifdef USE_ASSERT_CHECKING
19343 :
19344 : /*
19345 : * Note that table deletion will call remove_on_commit_action, so the
19346 : * entry should get marked as deleted.
19347 : */
19348 : foreach(l, on_commits)
19349 : {
19350 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19351 :
19352 : if (oc->oncommit != ONCOMMIT_DROP)
19353 : continue;
19354 :
19355 : Assert(oc->deleting_subid != InvalidSubTransactionId);
19356 : }
19357 : #endif
19358 : }
19359 978168 : }
19360 :
19361 : /*
19362 : * Post-commit or post-abort cleanup for ON COMMIT management.
19363 : *
19364 : * All we do here is remove no-longer-needed OnCommitItem entries.
19365 : *
19366 : * During commit, remove entries that were deleted during this transaction;
19367 : * during abort, remove those created during this transaction.
19368 : */
19369 : void
19370 1026844 : AtEOXact_on_commit_actions(bool isCommit)
19371 : {
19372 : ListCell *cur_item;
19373 :
19374 1027696 : foreach(cur_item, on_commits)
19375 : {
19376 852 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19377 :
19378 954 : if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19379 102 : oc->creating_subid != InvalidSubTransactionId)
19380 : {
19381 : /* cur_item must be removed */
19382 152 : on_commits = foreach_delete_current(on_commits, cur_item);
19383 152 : pfree(oc);
19384 : }
19385 : else
19386 : {
19387 : /* cur_item must be preserved */
19388 700 : oc->creating_subid = InvalidSubTransactionId;
19389 700 : oc->deleting_subid = InvalidSubTransactionId;
19390 : }
19391 : }
19392 1026844 : }
19393 :
19394 : /*
19395 : * Post-subcommit or post-subabort cleanup for ON COMMIT management.
19396 : *
19397 : * During subabort, we can immediately remove entries created during this
19398 : * subtransaction. During subcommit, just relabel entries marked during
19399 : * this subtransaction as being the parent's responsibility.
19400 : */
19401 : void
19402 20030 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
19403 : SubTransactionId parentSubid)
19404 : {
19405 : ListCell *cur_item;
19406 :
19407 20030 : foreach(cur_item, on_commits)
19408 : {
19409 0 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19410 :
19411 0 : if (!isCommit && oc->creating_subid == mySubid)
19412 : {
19413 : /* cur_item must be removed */
19414 0 : on_commits = foreach_delete_current(on_commits, cur_item);
19415 0 : pfree(oc);
19416 : }
19417 : else
19418 : {
19419 : /* cur_item must be preserved */
19420 0 : if (oc->creating_subid == mySubid)
19421 0 : oc->creating_subid = parentSubid;
19422 0 : if (oc->deleting_subid == mySubid)
19423 0 : oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19424 : }
19425 : }
19426 20030 : }
19427 :
19428 : /*
19429 : * This is intended as a callback for RangeVarGetRelidExtended(). It allows
19430 : * the relation to be locked only if (1) it's a plain or partitioned table,
19431 : * materialized view, or TOAST table and (2) the current user is the owner (or
19432 : * the superuser) or has been granted MAINTAIN. This meets the
19433 : * permission-checking needs of CLUSTER, REINDEX TABLE, and REFRESH
19434 : * MATERIALIZED VIEW; we expose it here so that it can be used by all.
19435 : */
19436 : void
19437 1022 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
19438 : Oid relId, Oid oldRelId, void *arg)
19439 : {
19440 : char relkind;
19441 : AclResult aclresult;
19442 :
19443 : /* Nothing to do if the relation was not found. */
19444 1022 : if (!OidIsValid(relId))
19445 6 : return;
19446 :
19447 : /*
19448 : * If the relation does exist, check whether it's an index. But note that
19449 : * the relation might have been dropped between the time we did the name
19450 : * lookup and now. In that case, there's nothing to do.
19451 : */
19452 1016 : relkind = get_rel_relkind(relId);
19453 1016 : if (!relkind)
19454 0 : return;
19455 1016 : if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19456 140 : relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19457 28 : ereport(ERROR,
19458 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19459 : errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19460 :
19461 : /* Check permissions */
19462 988 : aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
19463 988 : if (aclresult != ACLCHECK_OK)
19464 30 : aclcheck_error(aclresult,
19465 30 : get_relkind_objtype(get_rel_relkind(relId)),
19466 30 : relation->relname);
19467 : }
19468 :
19469 : /*
19470 : * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
19471 : */
19472 : static void
19473 3442 : RangeVarCallbackForTruncate(const RangeVar *relation,
19474 : Oid relId, Oid oldRelId, void *arg)
19475 : {
19476 : HeapTuple tuple;
19477 :
19478 : /* Nothing to do if the relation was not found. */
19479 3442 : if (!OidIsValid(relId))
19480 0 : return;
19481 :
19482 3442 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19483 3442 : if (!HeapTupleIsValid(tuple)) /* should not happen */
19484 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
19485 :
19486 3442 : truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
19487 3436 : truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
19488 :
19489 3404 : ReleaseSysCache(tuple);
19490 : }
19491 :
19492 : /*
19493 : * Callback for RangeVarGetRelidExtended(). Checks that the current user is
19494 : * the owner of the relation, or superuser.
19495 : */
19496 : void
19497 16068 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
19498 : Oid relId, Oid oldRelId, void *arg)
19499 : {
19500 : HeapTuple tuple;
19501 :
19502 : /* Nothing to do if the relation was not found. */
19503 16068 : if (!OidIsValid(relId))
19504 12 : return;
19505 :
19506 16056 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19507 16056 : if (!HeapTupleIsValid(tuple)) /* should not happen */
19508 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
19509 :
19510 16056 : if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
19511 6 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
19512 6 : relation->relname);
19513 :
19514 31980 : if (!allowSystemTableMods &&
19515 15930 : IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19516 2 : ereport(ERROR,
19517 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19518 : errmsg("permission denied: \"%s\" is a system catalog",
19519 : relation->relname)));
19520 :
19521 16048 : ReleaseSysCache(tuple);
19522 : }
19523 :
19524 : /*
19525 : * Common RangeVarGetRelid callback for rename, set schema, and alter table
19526 : * processing.
19527 : */
19528 : static void
19529 36158 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
19530 : void *arg)
19531 : {
19532 36158 : Node *stmt = (Node *) arg;
19533 : ObjectType reltype;
19534 : HeapTuple tuple;
19535 : Form_pg_class classform;
19536 : AclResult aclresult;
19537 : char relkind;
19538 :
19539 36158 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
19540 36158 : if (!HeapTupleIsValid(tuple))
19541 218 : return; /* concurrently dropped */
19542 35940 : classform = (Form_pg_class) GETSTRUCT(tuple);
19543 35940 : relkind = classform->relkind;
19544 :
19545 : /* Must own relation. */
19546 35940 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
19547 60 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
19548 :
19549 : /* No system table modifications unless explicitly allowed. */
19550 35880 : if (!allowSystemTableMods && IsSystemClass(relid, classform))
19551 30 : ereport(ERROR,
19552 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19553 : errmsg("permission denied: \"%s\" is a system catalog",
19554 : rv->relname)));
19555 :
19556 : /*
19557 : * Extract the specified relation type from the statement parse tree.
19558 : *
19559 : * Also, for ALTER .. RENAME, check permissions: the user must (still)
19560 : * have CREATE rights on the containing namespace.
19561 : */
19562 35850 : if (IsA(stmt, RenameStmt))
19563 : {
19564 492 : aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
19565 : GetUserId(), ACL_CREATE);
19566 492 : if (aclresult != ACLCHECK_OK)
19567 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
19568 0 : get_namespace_name(classform->relnamespace));
19569 492 : reltype = ((RenameStmt *) stmt)->renameType;
19570 : }
19571 35358 : else if (IsA(stmt, AlterObjectSchemaStmt))
19572 90 : reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
19573 :
19574 35268 : else if (IsA(stmt, AlterTableStmt))
19575 35268 : reltype = ((AlterTableStmt *) stmt)->objtype;
19576 : else
19577 : {
19578 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
19579 : reltype = OBJECT_TABLE; /* placate compiler */
19580 : }
19581 :
19582 : /*
19583 : * For compatibility with prior releases, we allow ALTER TABLE to be used
19584 : * with most other types of relations (but not composite types). We allow
19585 : * similar flexibility for ALTER INDEX in the case of RENAME, but not
19586 : * otherwise. Otherwise, the user must select the correct form of the
19587 : * command for the relation at issue.
19588 : */
19589 35850 : if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
19590 0 : ereport(ERROR,
19591 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19592 : errmsg("\"%s\" is not a sequence", rv->relname)));
19593 :
19594 35850 : if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
19595 0 : ereport(ERROR,
19596 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19597 : errmsg("\"%s\" is not a view", rv->relname)));
19598 :
19599 35850 : if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
19600 0 : ereport(ERROR,
19601 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19602 : errmsg("\"%s\" is not a materialized view", rv->relname)));
19603 :
19604 35850 : if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
19605 0 : ereport(ERROR,
19606 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19607 : errmsg("\"%s\" is not a foreign table", rv->relname)));
19608 :
19609 35850 : if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
19610 0 : ereport(ERROR,
19611 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19612 : errmsg("\"%s\" is not a composite type", rv->relname)));
19613 :
19614 35850 : if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
19615 : relkind != RELKIND_PARTITIONED_INDEX
19616 34 : && !IsA(stmt, RenameStmt))
19617 6 : ereport(ERROR,
19618 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19619 : errmsg("\"%s\" is not an index", rv->relname)));
19620 :
19621 : /*
19622 : * Don't allow ALTER TABLE on composite types. We want people to use ALTER
19623 : * TYPE for that.
19624 : */
19625 35844 : if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
19626 0 : ereport(ERROR,
19627 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19628 : errmsg("\"%s\" is a composite type", rv->relname),
19629 : /* translator: %s is an SQL ALTER command */
19630 : errhint("Use %s instead.",
19631 : "ALTER TYPE")));
19632 :
19633 : /*
19634 : * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
19635 : * to a different schema, such as indexes and TOAST tables.
19636 : */
19637 35844 : if (IsA(stmt, AlterObjectSchemaStmt))
19638 : {
19639 90 : if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
19640 0 : ereport(ERROR,
19641 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19642 : errmsg("cannot change schema of index \"%s\"",
19643 : rv->relname),
19644 : errhint("Change the schema of the table instead.")));
19645 90 : else if (relkind == RELKIND_COMPOSITE_TYPE)
19646 0 : ereport(ERROR,
19647 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19648 : errmsg("cannot change schema of composite type \"%s\"",
19649 : rv->relname),
19650 : /* translator: %s is an SQL ALTER command */
19651 : errhint("Use %s instead.",
19652 : "ALTER TYPE")));
19653 90 : else if (relkind == RELKIND_TOASTVALUE)
19654 0 : ereport(ERROR,
19655 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19656 : errmsg("cannot change schema of TOAST table \"%s\"",
19657 : rv->relname),
19658 : errhint("Change the schema of the table instead.")));
19659 : }
19660 :
19661 35844 : ReleaseSysCache(tuple);
19662 : }
19663 :
19664 : /*
19665 : * Transform any expressions present in the partition key
19666 : *
19667 : * Returns a transformed PartitionSpec.
19668 : */
19669 : static PartitionSpec *
19670 5098 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
19671 : {
19672 : PartitionSpec *newspec;
19673 : ParseState *pstate;
19674 : ParseNamespaceItem *nsitem;
19675 : ListCell *l;
19676 :
19677 5098 : newspec = makeNode(PartitionSpec);
19678 :
19679 5098 : newspec->strategy = partspec->strategy;
19680 5098 : newspec->partParams = NIL;
19681 5098 : newspec->location = partspec->location;
19682 :
19683 : /* Check valid number of columns for strategy */
19684 7656 : if (partspec->strategy == PARTITION_STRATEGY_LIST &&
19685 2558 : list_length(partspec->partParams) != 1)
19686 6 : ereport(ERROR,
19687 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19688 : errmsg("cannot use \"list\" partition strategy with more than one column")));
19689 :
19690 : /*
19691 : * Create a dummy ParseState and insert the target relation as its sole
19692 : * rangetable entry. We need a ParseState for transformExpr.
19693 : */
19694 5092 : pstate = make_parsestate(NULL);
19695 5092 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
19696 : NULL, false, true);
19697 5092 : addNSItemToQuery(pstate, nsitem, true, true, true);
19698 :
19699 : /* take care of any partition expressions */
19700 10620 : foreach(l, partspec->partParams)
19701 : {
19702 5552 : PartitionElem *pelem = lfirst_node(PartitionElem, l);
19703 :
19704 5552 : if (pelem->expr)
19705 : {
19706 : /* Copy, to avoid scribbling on the input */
19707 320 : pelem = copyObject(pelem);
19708 :
19709 : /* Now do parse transformation of the expression */
19710 320 : pelem->expr = transformExpr(pstate, pelem->expr,
19711 : EXPR_KIND_PARTITION_EXPRESSION);
19712 :
19713 : /* we have to fix its collations too */
19714 296 : assign_expr_collations(pstate, pelem->expr);
19715 : }
19716 :
19717 5528 : newspec->partParams = lappend(newspec->partParams, pelem);
19718 : }
19719 :
19720 5068 : return newspec;
19721 : }
19722 :
19723 : /*
19724 : * Compute per-partition-column information from a list of PartitionElems.
19725 : * Expressions in the PartitionElems must be parse-analyzed already.
19726 : */
19727 : static void
19728 5068 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
19729 : List **partexprs, Oid *partopclass, Oid *partcollation,
19730 : PartitionStrategy strategy)
19731 : {
19732 : int attn;
19733 : ListCell *lc;
19734 : Oid am_oid;
19735 :
19736 5068 : attn = 0;
19737 10500 : foreach(lc, partParams)
19738 : {
19739 5528 : PartitionElem *pelem = lfirst_node(PartitionElem, lc);
19740 : Oid atttype;
19741 : Oid attcollation;
19742 :
19743 5528 : if (pelem->name != NULL)
19744 : {
19745 : /* Simple attribute reference */
19746 : HeapTuple atttuple;
19747 : Form_pg_attribute attform;
19748 :
19749 5232 : atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
19750 5232 : pelem->name);
19751 5232 : if (!HeapTupleIsValid(atttuple))
19752 12 : ereport(ERROR,
19753 : (errcode(ERRCODE_UNDEFINED_COLUMN),
19754 : errmsg("column \"%s\" named in partition key does not exist",
19755 : pelem->name),
19756 : parser_errposition(pstate, pelem->location)));
19757 5220 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
19758 :
19759 5220 : if (attform->attnum <= 0)
19760 6 : ereport(ERROR,
19761 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19762 : errmsg("cannot use system column \"%s\" in partition key",
19763 : pelem->name),
19764 : parser_errposition(pstate, pelem->location)));
19765 :
19766 : /*
19767 : * Stored generated columns cannot work: They are computed after
19768 : * BEFORE triggers, but partition routing is done before all
19769 : * triggers. Maybe virtual generated columns could be made to
19770 : * work, but then they would need to be handled as an expression
19771 : * below.
19772 : */
19773 5214 : if (attform->attgenerated)
19774 12 : ereport(ERROR,
19775 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19776 : errmsg("cannot use generated column in partition key"),
19777 : errdetail("Column \"%s\" is a generated column.",
19778 : pelem->name),
19779 : parser_errposition(pstate, pelem->location)));
19780 :
19781 5202 : partattrs[attn] = attform->attnum;
19782 5202 : atttype = attform->atttypid;
19783 5202 : attcollation = attform->attcollation;
19784 5202 : ReleaseSysCache(atttuple);
19785 : }
19786 : else
19787 : {
19788 : /* Expression */
19789 296 : Node *expr = pelem->expr;
19790 : char partattname[16];
19791 :
19792 : Assert(expr != NULL);
19793 296 : atttype = exprType(expr);
19794 296 : attcollation = exprCollation(expr);
19795 :
19796 : /*
19797 : * The expression must be of a storable type (e.g., not RECORD).
19798 : * The test is the same as for whether a table column is of a safe
19799 : * type (which is why we needn't check for the non-expression
19800 : * case).
19801 : */
19802 296 : snprintf(partattname, sizeof(partattname), "%d", attn + 1);
19803 296 : CheckAttributeType(partattname,
19804 : atttype, attcollation,
19805 : NIL, CHKATYPE_IS_PARTKEY);
19806 :
19807 : /*
19808 : * Strip any top-level COLLATE clause. This ensures that we treat
19809 : * "x COLLATE y" and "(x COLLATE y)" alike.
19810 : */
19811 284 : while (IsA(expr, CollateExpr))
19812 0 : expr = (Node *) ((CollateExpr *) expr)->arg;
19813 :
19814 284 : if (IsA(expr, Var) &&
19815 12 : ((Var *) expr)->varattno > 0)
19816 : {
19817 : /*
19818 : * User wrote "(column)" or "(column COLLATE something)".
19819 : * Treat it like simple attribute anyway.
19820 : */
19821 6 : partattrs[attn] = ((Var *) expr)->varattno;
19822 : }
19823 : else
19824 : {
19825 278 : Bitmapset *expr_attrs = NULL;
19826 : int i;
19827 :
19828 278 : partattrs[attn] = 0; /* marks the column as expression */
19829 278 : *partexprs = lappend(*partexprs, expr);
19830 :
19831 : /*
19832 : * transformPartitionSpec() should have already rejected
19833 : * subqueries, aggregates, window functions, and SRFs, based
19834 : * on the EXPR_KIND_ for partition expressions.
19835 : */
19836 :
19837 : /*
19838 : * Cannot allow system column references, since that would
19839 : * make partition routing impossible: their values won't be
19840 : * known yet when we need to do that.
19841 : */
19842 278 : pull_varattnos(expr, 1, &expr_attrs);
19843 2224 : for (i = FirstLowInvalidHeapAttributeNumber; i < 0; i++)
19844 : {
19845 1946 : if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
19846 : expr_attrs))
19847 0 : ereport(ERROR,
19848 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19849 : errmsg("partition key expressions cannot contain system column references")));
19850 : }
19851 :
19852 : /*
19853 : * Stored generated columns cannot work: They are computed
19854 : * after BEFORE triggers, but partition routing is done before
19855 : * all triggers. Virtual generated columns could probably
19856 : * work, but it would require more work elsewhere (for example
19857 : * SET EXPRESSION would need to check whether the column is
19858 : * used in partition keys). Seems safer to prohibit for now.
19859 : */
19860 278 : i = -1;
19861 612 : while ((i = bms_next_member(expr_attrs, i)) >= 0)
19862 : {
19863 346 : AttrNumber attno = i + FirstLowInvalidHeapAttributeNumber;
19864 :
19865 346 : if (attno > 0 &&
19866 340 : TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
19867 12 : ereport(ERROR,
19868 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19869 : errmsg("cannot use generated column in partition key"),
19870 : errdetail("Column \"%s\" is a generated column.",
19871 : get_attname(RelationGetRelid(rel), attno, false)),
19872 : parser_errposition(pstate, pelem->location)));
19873 : }
19874 :
19875 : /*
19876 : * Preprocess the expression before checking for mutability.
19877 : * This is essential for the reasons described in
19878 : * contain_mutable_functions_after_planning. However, we call
19879 : * expression_planner for ourselves rather than using that
19880 : * function, because if constant-folding reduces the
19881 : * expression to a constant, we'd like to know that so we can
19882 : * complain below.
19883 : *
19884 : * Like contain_mutable_functions_after_planning, assume that
19885 : * expression_planner won't scribble on its input, so this
19886 : * won't affect the partexprs entry we saved above.
19887 : */
19888 266 : expr = (Node *) expression_planner((Expr *) expr);
19889 :
19890 : /*
19891 : * Partition expressions cannot contain mutable functions,
19892 : * because a given row must always map to the same partition
19893 : * as long as there is no change in the partition boundary
19894 : * structure.
19895 : */
19896 266 : if (contain_mutable_functions(expr))
19897 6 : ereport(ERROR,
19898 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19899 : errmsg("functions in partition key expression must be marked IMMUTABLE")));
19900 :
19901 : /*
19902 : * While it is not exactly *wrong* for a partition expression
19903 : * to be a constant, it seems better to reject such keys.
19904 : */
19905 260 : if (IsA(expr, Const))
19906 12 : ereport(ERROR,
19907 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
19908 : errmsg("cannot use constant expression as partition key")));
19909 : }
19910 : }
19911 :
19912 : /*
19913 : * Apply collation override if any
19914 : */
19915 5456 : if (pelem->collation)
19916 54 : attcollation = get_collation_oid(pelem->collation, false);
19917 :
19918 : /*
19919 : * Check we have a collation iff it's a collatable type. The only
19920 : * expected failures here are (1) COLLATE applied to a noncollatable
19921 : * type, or (2) partition expression had an unresolved collation. But
19922 : * we might as well code this to be a complete consistency check.
19923 : */
19924 5456 : if (type_is_collatable(atttype))
19925 : {
19926 640 : if (!OidIsValid(attcollation))
19927 0 : ereport(ERROR,
19928 : (errcode(ERRCODE_INDETERMINATE_COLLATION),
19929 : errmsg("could not determine which collation to use for partition expression"),
19930 : errhint("Use the COLLATE clause to set the collation explicitly.")));
19931 : }
19932 : else
19933 : {
19934 4816 : if (OidIsValid(attcollation))
19935 0 : ereport(ERROR,
19936 : (errcode(ERRCODE_DATATYPE_MISMATCH),
19937 : errmsg("collations are not supported by type %s",
19938 : format_type_be(atttype))));
19939 : }
19940 :
19941 5456 : partcollation[attn] = attcollation;
19942 :
19943 : /*
19944 : * Identify the appropriate operator class. For list and range
19945 : * partitioning, we use a btree operator class; hash partitioning uses
19946 : * a hash operator class.
19947 : */
19948 5456 : if (strategy == PARTITION_STRATEGY_HASH)
19949 314 : am_oid = HASH_AM_OID;
19950 : else
19951 5142 : am_oid = BTREE_AM_OID;
19952 :
19953 5456 : if (!pelem->opclass)
19954 : {
19955 5324 : partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
19956 :
19957 5324 : if (!OidIsValid(partopclass[attn]))
19958 : {
19959 12 : if (strategy == PARTITION_STRATEGY_HASH)
19960 0 : ereport(ERROR,
19961 : (errcode(ERRCODE_UNDEFINED_OBJECT),
19962 : errmsg("data type %s has no default operator class for access method \"%s\"",
19963 : format_type_be(atttype), "hash"),
19964 : errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
19965 : else
19966 12 : ereport(ERROR,
19967 : (errcode(ERRCODE_UNDEFINED_OBJECT),
19968 : errmsg("data type %s has no default operator class for access method \"%s\"",
19969 : format_type_be(atttype), "btree"),
19970 : errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
19971 : }
19972 : }
19973 : else
19974 132 : partopclass[attn] = ResolveOpClass(pelem->opclass,
19975 : atttype,
19976 : am_oid == HASH_AM_OID ? "hash" : "btree",
19977 : am_oid);
19978 :
19979 5432 : attn++;
19980 : }
19981 4972 : }
19982 :
19983 : /*
19984 : * PartConstraintImpliedByRelConstraint
19985 : * Do scanrel's existing constraints imply the partition constraint?
19986 : *
19987 : * "Existing constraints" include its check constraints and column-level
19988 : * not-null constraints. partConstraint describes the partition constraint,
19989 : * in implicit-AND form.
19990 : */
19991 : bool
19992 3602 : PartConstraintImpliedByRelConstraint(Relation scanrel,
19993 : List *partConstraint)
19994 : {
19995 3602 : List *existConstraint = NIL;
19996 3602 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
19997 : int i;
19998 :
19999 3602 : if (constr && constr->has_not_null)
20000 : {
20001 956 : int natts = scanrel->rd_att->natts;
20002 :
20003 3038 : for (i = 1; i <= natts; i++)
20004 : {
20005 2082 : CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20006 :
20007 : /* invalid not-null constraint must be ignored here */
20008 2082 : if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20009 : {
20010 1274 : Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
20011 1274 : NullTest *ntest = makeNode(NullTest);
20012 :
20013 1274 : ntest->arg = (Expr *) makeVar(1,
20014 : i,
20015 : wholeatt->atttypid,
20016 : wholeatt->atttypmod,
20017 : wholeatt->attcollation,
20018 : 0);
20019 1274 : ntest->nulltesttype = IS_NOT_NULL;
20020 :
20021 : /*
20022 : * argisrow=false is correct even for a composite column,
20023 : * because attnotnull does not represent a SQL-spec IS NOT
20024 : * NULL test in such a case, just IS DISTINCT FROM NULL.
20025 : */
20026 1274 : ntest->argisrow = false;
20027 1274 : ntest->location = -1;
20028 1274 : existConstraint = lappend(existConstraint, ntest);
20029 : }
20030 : }
20031 : }
20032 :
20033 3602 : return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20034 : }
20035 :
20036 : /*
20037 : * ConstraintImpliedByRelConstraint
20038 : * Do scanrel's existing constraints imply the given constraint?
20039 : *
20040 : * testConstraint is the constraint to validate. provenConstraint is a
20041 : * caller-provided list of conditions which this function may assume
20042 : * to be true. Both provenConstraint and testConstraint must be in
20043 : * implicit-AND form, must only contain immutable clauses, and must
20044 : * contain only Vars with varno = 1.
20045 : */
20046 : bool
20047 4840 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
20048 : {
20049 4840 : List *existConstraint = list_copy(provenConstraint);
20050 4840 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20051 : int num_check,
20052 : i;
20053 :
20054 4840 : num_check = (constr != NULL) ? constr->num_check : 0;
20055 5360 : for (i = 0; i < num_check; i++)
20056 : {
20057 : Node *cexpr;
20058 :
20059 : /*
20060 : * If this constraint hasn't been fully validated yet, we must ignore
20061 : * it here.
20062 : */
20063 520 : if (!constr->check[i].ccvalid)
20064 6 : continue;
20065 :
20066 : /*
20067 : * NOT ENFORCED constraints are always marked as invalid, which should
20068 : * have been ignored.
20069 : */
20070 : Assert(constr->check[i].ccenforced);
20071 :
20072 514 : cexpr = stringToNode(constr->check[i].ccbin);
20073 :
20074 : /*
20075 : * Run each expression through const-simplification and
20076 : * canonicalization. It is necessary, because we will be comparing it
20077 : * to similarly-processed partition constraint expressions, and may
20078 : * fail to detect valid matches without this.
20079 : */
20080 514 : cexpr = eval_const_expressions(NULL, cexpr);
20081 514 : cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
20082 :
20083 514 : existConstraint = list_concat(existConstraint,
20084 514 : make_ands_implicit((Expr *) cexpr));
20085 : }
20086 :
20087 : /*
20088 : * Try to make the proof. Since we are comparing CHECK constraints, we
20089 : * need to use weak implication, i.e., we assume existConstraint is
20090 : * not-false and try to prove the same for testConstraint.
20091 : *
20092 : * Note that predicate_implied_by assumes its first argument is known
20093 : * immutable. That should always be true for both NOT NULL and partition
20094 : * constraints, so we don't test it here.
20095 : */
20096 4840 : return predicate_implied_by(testConstraint, existConstraint, true);
20097 : }
20098 :
20099 : /*
20100 : * QueuePartitionConstraintValidation
20101 : *
20102 : * Add an entry to wqueue to have the given partition constraint validated by
20103 : * Phase 3, for the given relation, and all its children.
20104 : *
20105 : * We first verify whether the given constraint is implied by pre-existing
20106 : * relation constraints; if it is, there's no need to scan the table to
20107 : * validate, so don't queue in that case.
20108 : */
20109 : static void
20110 2972 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
20111 : List *partConstraint,
20112 : bool validate_default)
20113 : {
20114 : /*
20115 : * Based on the table's existing constraints, determine whether or not we
20116 : * may skip scanning the table.
20117 : */
20118 2972 : if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
20119 : {
20120 92 : if (!validate_default)
20121 70 : ereport(DEBUG1,
20122 : (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
20123 : RelationGetRelationName(scanrel))));
20124 : else
20125 22 : ereport(DEBUG1,
20126 : (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
20127 : RelationGetRelationName(scanrel))));
20128 92 : return;
20129 : }
20130 :
20131 : /*
20132 : * Constraints proved insufficient. For plain relations, queue a
20133 : * validation item now; for partitioned tables, recurse to process each
20134 : * partition.
20135 : */
20136 2880 : if (scanrel->rd_rel->relkind == RELKIND_RELATION)
20137 : {
20138 : AlteredTableInfo *tab;
20139 :
20140 : /* Grab a work queue entry. */
20141 2420 : tab = ATGetQueueEntry(wqueue, scanrel);
20142 : Assert(tab->partition_constraint == NULL);
20143 2420 : tab->partition_constraint = (Expr *) linitial(partConstraint);
20144 2420 : tab->validate_default = validate_default;
20145 : }
20146 460 : else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20147 : {
20148 412 : PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
20149 : int i;
20150 :
20151 808 : for (i = 0; i < partdesc->nparts; i++)
20152 : {
20153 : Relation part_rel;
20154 : List *thisPartConstraint;
20155 :
20156 : /*
20157 : * This is the minimum lock we need to prevent deadlocks.
20158 : */
20159 396 : part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
20160 :
20161 : /*
20162 : * Adjust the constraint for scanrel so that it matches this
20163 : * partition's attribute numbers.
20164 : */
20165 : thisPartConstraint =
20166 396 : map_partition_varattnos(partConstraint, 1,
20167 : part_rel, scanrel);
20168 :
20169 396 : QueuePartitionConstraintValidation(wqueue, part_rel,
20170 : thisPartConstraint,
20171 : validate_default);
20172 396 : table_close(part_rel, NoLock); /* keep lock till commit */
20173 : }
20174 : }
20175 : }
20176 :
20177 : /*
20178 : * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
20179 : *
20180 : * Return the address of the newly attached partition.
20181 : */
20182 : static ObjectAddress
20183 2796 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
20184 : AlterTableUtilityContext *context)
20185 : {
20186 : Relation attachrel,
20187 : catalog;
20188 : List *attachrel_children;
20189 : List *partConstraint;
20190 : SysScanDesc scan;
20191 : ScanKeyData skey;
20192 : AttrNumber attno;
20193 : int natts;
20194 : TupleDesc tupleDesc;
20195 : ObjectAddress address;
20196 : const char *trigger_name;
20197 : Oid defaultPartOid;
20198 : List *partBoundConstraint;
20199 2796 : ParseState *pstate = make_parsestate(NULL);
20200 :
20201 2796 : pstate->p_sourcetext = context->queryString;
20202 :
20203 : /*
20204 : * We must lock the default partition if one exists, because attaching a
20205 : * new partition will change its partition constraint.
20206 : */
20207 : defaultPartOid =
20208 2796 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
20209 2796 : if (OidIsValid(defaultPartOid))
20210 184 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
20211 :
20212 2796 : attachrel = table_openrv(cmd->name, AccessExclusiveLock);
20213 :
20214 : /*
20215 : * XXX I think it'd be a good idea to grab locks on all tables referenced
20216 : * by FKs at this point also.
20217 : */
20218 :
20219 : /*
20220 : * Must be owner of both parent and source table -- parent was checked by
20221 : * ATSimplePermissions call in ATPrepCmd
20222 : */
20223 2790 : ATSimplePermissions(AT_AttachPartition, attachrel,
20224 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
20225 :
20226 : /* A partition can only have one parent */
20227 2784 : if (attachrel->rd_rel->relispartition)
20228 6 : ereport(ERROR,
20229 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20230 : errmsg("\"%s\" is already a partition",
20231 : RelationGetRelationName(attachrel))));
20232 :
20233 2778 : if (OidIsValid(attachrel->rd_rel->reloftype))
20234 6 : ereport(ERROR,
20235 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20236 : errmsg("cannot attach a typed table as partition")));
20237 :
20238 : /*
20239 : * Table being attached should not already be part of inheritance; either
20240 : * as a child table...
20241 : */
20242 2772 : catalog = table_open(InheritsRelationId, AccessShareLock);
20243 2772 : ScanKeyInit(&skey,
20244 : Anum_pg_inherits_inhrelid,
20245 : BTEqualStrategyNumber, F_OIDEQ,
20246 : ObjectIdGetDatum(RelationGetRelid(attachrel)));
20247 2772 : scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
20248 : NULL, 1, &skey);
20249 2772 : if (HeapTupleIsValid(systable_getnext(scan)))
20250 6 : ereport(ERROR,
20251 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20252 : errmsg("cannot attach inheritance child as partition")));
20253 2766 : systable_endscan(scan);
20254 :
20255 : /* ...or as a parent table (except the case when it is partitioned) */
20256 2766 : ScanKeyInit(&skey,
20257 : Anum_pg_inherits_inhparent,
20258 : BTEqualStrategyNumber, F_OIDEQ,
20259 : ObjectIdGetDatum(RelationGetRelid(attachrel)));
20260 2766 : scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
20261 : 1, &skey);
20262 2766 : if (HeapTupleIsValid(systable_getnext(scan)) &&
20263 264 : attachrel->rd_rel->relkind == RELKIND_RELATION)
20264 6 : ereport(ERROR,
20265 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20266 : errmsg("cannot attach inheritance parent as partition")));
20267 2760 : systable_endscan(scan);
20268 2760 : table_close(catalog, AccessShareLock);
20269 :
20270 : /*
20271 : * Prevent circularity by seeing if rel is a partition of attachrel. (In
20272 : * particular, this disallows making a rel a partition of itself.)
20273 : *
20274 : * We do that by checking if rel is a member of the list of attachrel's
20275 : * partitions provided the latter is partitioned at all. We want to avoid
20276 : * having to construct this list again, so we request the strongest lock
20277 : * on all partitions. We need the strongest lock, because we may decide
20278 : * to scan them if we find out that the table being attached (or its leaf
20279 : * partitions) may contain rows that violate the partition constraint. If
20280 : * the table has a constraint that would prevent such rows, which by
20281 : * definition is present in all the partitions, we need not scan the
20282 : * table, nor its partitions. But we cannot risk a deadlock by taking a
20283 : * weaker lock now and the stronger one only when needed.
20284 : */
20285 2760 : attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
20286 : AccessExclusiveLock, NULL);
20287 2760 : if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
20288 12 : ereport(ERROR,
20289 : (errcode(ERRCODE_DUPLICATE_TABLE),
20290 : errmsg("circular inheritance not allowed"),
20291 : errdetail("\"%s\" is already a child of \"%s\".",
20292 : RelationGetRelationName(rel),
20293 : RelationGetRelationName(attachrel))));
20294 :
20295 : /* If the parent is permanent, so must be all of its partitions. */
20296 2748 : if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
20297 2706 : attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
20298 6 : ereport(ERROR,
20299 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20300 : errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
20301 : RelationGetRelationName(rel))));
20302 :
20303 : /* Temp parent cannot have a partition that is itself not a temp */
20304 2742 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
20305 42 : attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
20306 18 : ereport(ERROR,
20307 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20308 : errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
20309 : RelationGetRelationName(rel))));
20310 :
20311 : /* If the parent is temp, it must belong to this session */
20312 2724 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
20313 24 : !rel->rd_islocaltemp)
20314 0 : ereport(ERROR,
20315 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20316 : errmsg("cannot attach as partition of temporary relation of another session")));
20317 :
20318 : /* Ditto for the partition */
20319 2724 : if (attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
20320 24 : !attachrel->rd_islocaltemp)
20321 0 : ereport(ERROR,
20322 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20323 : errmsg("cannot attach temporary relation of another session as partition")));
20324 :
20325 : /*
20326 : * Check if attachrel has any identity columns or any columns that aren't
20327 : * in the parent.
20328 : */
20329 2724 : tupleDesc = RelationGetDescr(attachrel);
20330 2724 : natts = tupleDesc->natts;
20331 9266 : for (attno = 1; attno <= natts; attno++)
20332 : {
20333 6584 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
20334 6584 : char *attributeName = NameStr(attribute->attname);
20335 :
20336 : /* Ignore dropped */
20337 6584 : if (attribute->attisdropped)
20338 580 : continue;
20339 :
20340 6004 : if (attribute->attidentity)
20341 24 : ereport(ERROR,
20342 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20343 : errmsg("table \"%s\" being attached contains an identity column \"%s\"",
20344 : RelationGetRelationName(attachrel), attributeName),
20345 : errdetail("The new partition may not contain an identity column."));
20346 :
20347 : /* Try to find the column in parent (matching on column name) */
20348 5980 : if (!SearchSysCacheExists2(ATTNAME,
20349 : ObjectIdGetDatum(RelationGetRelid(rel)),
20350 : CStringGetDatum(attributeName)))
20351 18 : ereport(ERROR,
20352 : (errcode(ERRCODE_DATATYPE_MISMATCH),
20353 : errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
20354 : RelationGetRelationName(attachrel), attributeName,
20355 : RelationGetRelationName(rel)),
20356 : errdetail("The new partition may contain only the columns present in parent.")));
20357 : }
20358 :
20359 : /*
20360 : * If child_rel has row-level triggers with transition tables, we
20361 : * currently don't allow it to become a partition. See also prohibitions
20362 : * in ATExecAddInherit() and CreateTrigger().
20363 : */
20364 2682 : trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
20365 2682 : if (trigger_name != NULL)
20366 6 : ereport(ERROR,
20367 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
20368 : errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
20369 : trigger_name, RelationGetRelationName(attachrel)),
20370 : errdetail("ROW triggers with transition tables are not supported on partitions.")));
20371 :
20372 : /*
20373 : * Check that the new partition's bound is valid and does not overlap any
20374 : * of existing partitions of the parent - note that it does not return on
20375 : * error.
20376 : */
20377 2676 : check_new_partition_bound(RelationGetRelationName(attachrel), rel,
20378 : cmd->bound, pstate);
20379 :
20380 : /* OK to create inheritance. Rest of the checks performed there */
20381 2640 : CreateInheritance(attachrel, rel, true);
20382 :
20383 : /* Update the pg_class entry. */
20384 2532 : StorePartitionBound(attachrel, rel, cmd->bound);
20385 :
20386 : /* Ensure there exists a correct set of indexes in the partition. */
20387 2532 : AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
20388 :
20389 : /* and triggers */
20390 2502 : CloneRowTriggersToPartition(rel, attachrel);
20391 :
20392 : /*
20393 : * Clone foreign key constraints. Callee is responsible for setting up
20394 : * for phase 3 constraint verification.
20395 : */
20396 2496 : CloneForeignKeyConstraints(wqueue, rel, attachrel);
20397 :
20398 : /*
20399 : * Generate partition constraint from the partition bound specification.
20400 : * If the parent itself is a partition, make sure to include its
20401 : * constraint as well.
20402 : */
20403 2478 : partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
20404 :
20405 : /*
20406 : * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
20407 : * since it's needed later to construct the constraint expression for
20408 : * validating against the default partition, if any.
20409 : */
20410 2478 : partConstraint = list_concat_copy(partBoundConstraint,
20411 2478 : RelationGetPartitionQual(rel));
20412 :
20413 : /* Skip validation if there are no constraints to validate. */
20414 2478 : if (partConstraint)
20415 : {
20416 : /*
20417 : * Run the partition quals through const-simplification similar to
20418 : * check constraints. We skip canonicalize_qual, though, because
20419 : * partition quals should be in canonical form already.
20420 : */
20421 : partConstraint =
20422 2428 : (List *) eval_const_expressions(NULL,
20423 : (Node *) partConstraint);
20424 :
20425 : /* XXX this sure looks wrong */
20426 2428 : partConstraint = list_make1(make_ands_explicit(partConstraint));
20427 :
20428 : /*
20429 : * Adjust the generated constraint to match this partition's attribute
20430 : * numbers.
20431 : */
20432 2428 : partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
20433 : rel);
20434 :
20435 : /* Validate partition constraints against the table being attached. */
20436 2428 : QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
20437 : false);
20438 : }
20439 :
20440 : /*
20441 : * If we're attaching a partition other than the default partition and a
20442 : * default one exists, then that partition's partition constraint changes,
20443 : * so add an entry to the work queue to validate it, too. (We must not do
20444 : * this when the partition being attached is the default one; we already
20445 : * did it above!)
20446 : */
20447 2478 : if (OidIsValid(defaultPartOid))
20448 : {
20449 : Relation defaultrel;
20450 : List *defPartConstraint;
20451 :
20452 : Assert(!cmd->bound->is_default);
20453 :
20454 : /* we already hold a lock on the default partition */
20455 148 : defaultrel = table_open(defaultPartOid, NoLock);
20456 : defPartConstraint =
20457 148 : get_proposed_default_constraint(partBoundConstraint);
20458 :
20459 : /*
20460 : * Map the Vars in the constraint expression from rel's attnos to
20461 : * defaultrel's.
20462 : */
20463 : defPartConstraint =
20464 148 : map_partition_varattnos(defPartConstraint,
20465 : 1, defaultrel, rel);
20466 148 : QueuePartitionConstraintValidation(wqueue, defaultrel,
20467 : defPartConstraint, true);
20468 :
20469 : /* keep our lock until commit. */
20470 148 : table_close(defaultrel, NoLock);
20471 : }
20472 :
20473 2478 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
20474 :
20475 : /*
20476 : * If the partition we just attached is partitioned itself, invalidate
20477 : * relcache for all descendent partitions too to ensure that their
20478 : * rd_partcheck expression trees are rebuilt; partitions already locked at
20479 : * the beginning of this function.
20480 : */
20481 2478 : if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20482 : {
20483 : ListCell *l;
20484 :
20485 1124 : foreach(l, attachrel_children)
20486 : {
20487 738 : CacheInvalidateRelcacheByRelid(lfirst_oid(l));
20488 : }
20489 : }
20490 :
20491 : /* keep our lock until commit */
20492 2478 : table_close(attachrel, NoLock);
20493 :
20494 2478 : return address;
20495 : }
20496 :
20497 : /*
20498 : * AttachPartitionEnsureIndexes
20499 : * subroutine for ATExecAttachPartition to create/match indexes
20500 : *
20501 : * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
20502 : * PARTITION: every partition must have an index attached to each index on the
20503 : * partitioned table.
20504 : */
20505 : static void
20506 2532 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
20507 : {
20508 : List *idxes;
20509 : List *attachRelIdxs;
20510 : Relation *attachrelIdxRels;
20511 : IndexInfo **attachInfos;
20512 : ListCell *cell;
20513 : MemoryContext cxt;
20514 : MemoryContext oldcxt;
20515 :
20516 2532 : cxt = AllocSetContextCreate(CurrentMemoryContext,
20517 : "AttachPartitionEnsureIndexes",
20518 : ALLOCSET_DEFAULT_SIZES);
20519 2532 : oldcxt = MemoryContextSwitchTo(cxt);
20520 :
20521 2532 : idxes = RelationGetIndexList(rel);
20522 2532 : attachRelIdxs = RelationGetIndexList(attachrel);
20523 2532 : attachrelIdxRels = palloc(sizeof(Relation) * list_length(attachRelIdxs));
20524 2532 : attachInfos = palloc(sizeof(IndexInfo *) * list_length(attachRelIdxs));
20525 :
20526 : /* Build arrays of all existing indexes and their IndexInfos */
20527 5446 : foreach_oid(cldIdxId, attachRelIdxs)
20528 : {
20529 382 : int i = foreach_current_index(cldIdxId);
20530 :
20531 382 : attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
20532 382 : attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
20533 : }
20534 :
20535 : /*
20536 : * If we're attaching a foreign table, we must fail if any of the indexes
20537 : * is a constraint index; otherwise, there's nothing to do here. Do this
20538 : * before starting work, to avoid wasting the effort of building a few
20539 : * non-unique indexes before coming across a unique one.
20540 : */
20541 2532 : if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
20542 : {
20543 86 : foreach(cell, idxes)
20544 : {
20545 36 : Oid idx = lfirst_oid(cell);
20546 36 : Relation idxRel = index_open(idx, AccessShareLock);
20547 :
20548 36 : if (idxRel->rd_index->indisunique ||
20549 24 : idxRel->rd_index->indisprimary)
20550 12 : ereport(ERROR,
20551 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20552 : errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
20553 : RelationGetRelationName(attachrel),
20554 : RelationGetRelationName(rel)),
20555 : errdetail("Partitioned table \"%s\" contains unique indexes.",
20556 : RelationGetRelationName(rel))));
20557 24 : index_close(idxRel, AccessShareLock);
20558 : }
20559 :
20560 50 : goto out;
20561 : }
20562 :
20563 : /*
20564 : * For each index on the partitioned table, find a matching one in the
20565 : * partition-to-be; if one is not found, create one.
20566 : */
20567 2902 : foreach(cell, idxes)
20568 : {
20569 450 : Oid idx = lfirst_oid(cell);
20570 450 : Relation idxRel = index_open(idx, AccessShareLock);
20571 : IndexInfo *info;
20572 : AttrMap *attmap;
20573 450 : bool found = false;
20574 : Oid constraintOid;
20575 :
20576 : /*
20577 : * Ignore indexes in the partitioned table other than partitioned
20578 : * indexes.
20579 : */
20580 450 : if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
20581 : {
20582 0 : index_close(idxRel, AccessShareLock);
20583 0 : continue;
20584 : }
20585 :
20586 : /* construct an indexinfo to compare existing indexes against */
20587 450 : info = BuildIndexInfo(idxRel);
20588 450 : attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
20589 : RelationGetDescr(rel),
20590 : false);
20591 450 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
20592 :
20593 : /*
20594 : * Scan the list of existing indexes in the partition-to-be, and mark
20595 : * the first matching, valid, unattached one we find, if any, as
20596 : * partition of the parent index. If we find one, we're done.
20597 : */
20598 510 : for (int i = 0; i < list_length(attachRelIdxs); i++)
20599 : {
20600 274 : Oid cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
20601 274 : Oid cldConstrOid = InvalidOid;
20602 :
20603 : /* does this index have a parent? if so, can't use it */
20604 274 : if (attachrelIdxRels[i]->rd_rel->relispartition)
20605 12 : continue;
20606 :
20607 : /* If this index is invalid, can't use it */
20608 262 : if (!attachrelIdxRels[i]->rd_index->indisvalid)
20609 6 : continue;
20610 :
20611 256 : if (CompareIndexInfo(attachInfos[i], info,
20612 256 : attachrelIdxRels[i]->rd_indcollation,
20613 256 : idxRel->rd_indcollation,
20614 256 : attachrelIdxRels[i]->rd_opfamily,
20615 256 : idxRel->rd_opfamily,
20616 : attmap))
20617 : {
20618 : /*
20619 : * If this index is being created in the parent because of a
20620 : * constraint, then the child needs to have a constraint also,
20621 : * so look for one. If there is no such constraint, this
20622 : * index is no good, so keep looking.
20623 : */
20624 220 : if (OidIsValid(constraintOid))
20625 : {
20626 : cldConstrOid =
20627 122 : get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
20628 : cldIdxId);
20629 : /* no dice */
20630 122 : if (!OidIsValid(cldConstrOid))
20631 6 : continue;
20632 :
20633 : /* Ensure they're both the same type of constraint */
20634 232 : if (get_constraint_type(constraintOid) !=
20635 116 : get_constraint_type(cldConstrOid))
20636 0 : continue;
20637 : }
20638 :
20639 : /* bingo. */
20640 214 : IndexSetParentIndex(attachrelIdxRels[i], idx);
20641 214 : if (OidIsValid(constraintOid))
20642 116 : ConstraintSetParentConstraint(cldConstrOid, constraintOid,
20643 : RelationGetRelid(attachrel));
20644 214 : found = true;
20645 :
20646 214 : CommandCounterIncrement();
20647 214 : break;
20648 : }
20649 : }
20650 :
20651 : /*
20652 : * If no suitable index was found in the partition-to-be, create one
20653 : * now. Note that if this is a PK, not-null constraints must already
20654 : * exist.
20655 : */
20656 450 : if (!found)
20657 : {
20658 : IndexStmt *stmt;
20659 : Oid conOid;
20660 :
20661 236 : stmt = generateClonedIndexStmt(NULL,
20662 : idxRel, attmap,
20663 : &conOid);
20664 236 : DefineIndex(RelationGetRelid(attachrel), stmt, InvalidOid,
20665 : RelationGetRelid(idxRel),
20666 : conOid,
20667 : -1,
20668 : true, false, false, false, false);
20669 : }
20670 :
20671 432 : index_close(idxRel, AccessShareLock);
20672 : }
20673 :
20674 2502 : out:
20675 : /* Clean up. */
20676 2872 : for (int i = 0; i < list_length(attachRelIdxs); i++)
20677 370 : index_close(attachrelIdxRels[i], AccessShareLock);
20678 2502 : MemoryContextSwitchTo(oldcxt);
20679 2502 : MemoryContextDelete(cxt);
20680 2502 : }
20681 :
20682 : /*
20683 : * CloneRowTriggersToPartition
20684 : * subroutine for ATExecAttachPartition/DefineRelation to create row
20685 : * triggers on partitions
20686 : */
20687 : static void
20688 2934 : CloneRowTriggersToPartition(Relation parent, Relation partition)
20689 : {
20690 : Relation pg_trigger;
20691 : ScanKeyData key;
20692 : SysScanDesc scan;
20693 : HeapTuple tuple;
20694 : MemoryContext perTupCxt;
20695 :
20696 2934 : ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
20697 : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
20698 2934 : pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
20699 2934 : scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
20700 : true, NULL, 1, &key);
20701 :
20702 2934 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
20703 : "clone trig", ALLOCSET_SMALL_SIZES);
20704 :
20705 4754 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
20706 : {
20707 1826 : Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
20708 : CreateTrigStmt *trigStmt;
20709 1826 : Node *qual = NULL;
20710 : Datum value;
20711 : bool isnull;
20712 1826 : List *cols = NIL;
20713 1826 : List *trigargs = NIL;
20714 : MemoryContext oldcxt;
20715 :
20716 : /*
20717 : * Ignore statement-level triggers; those are not cloned.
20718 : */
20719 1826 : if (!TRIGGER_FOR_ROW(trigForm->tgtype))
20720 1670 : continue;
20721 :
20722 : /*
20723 : * Don't clone internal triggers, because the constraint cloning code
20724 : * will.
20725 : */
20726 1826 : if (trigForm->tgisinternal)
20727 1670 : continue;
20728 :
20729 : /*
20730 : * Complain if we find an unexpected trigger type.
20731 : */
20732 156 : if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
20733 138 : !TRIGGER_FOR_AFTER(trigForm->tgtype))
20734 0 : elog(ERROR, "unexpected trigger \"%s\" found",
20735 : NameStr(trigForm->tgname));
20736 :
20737 : /* Use short-lived context for CREATE TRIGGER */
20738 156 : oldcxt = MemoryContextSwitchTo(perTupCxt);
20739 :
20740 : /*
20741 : * If there is a WHEN clause, generate a 'cooked' version of it that's
20742 : * appropriate for the partition.
20743 : */
20744 156 : value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
20745 : RelationGetDescr(pg_trigger), &isnull);
20746 156 : if (!isnull)
20747 : {
20748 6 : qual = stringToNode(TextDatumGetCString(value));
20749 6 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
20750 : partition, parent);
20751 6 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
20752 : partition, parent);
20753 : }
20754 :
20755 : /*
20756 : * If there is a column list, transform it to a list of column names.
20757 : * Note we don't need to map this list in any way ...
20758 : */
20759 156 : if (trigForm->tgattr.dim1 > 0)
20760 : {
20761 : int i;
20762 :
20763 12 : for (i = 0; i < trigForm->tgattr.dim1; i++)
20764 : {
20765 : Form_pg_attribute col;
20766 :
20767 6 : col = TupleDescAttr(parent->rd_att,
20768 6 : trigForm->tgattr.values[i] - 1);
20769 6 : cols = lappend(cols,
20770 6 : makeString(pstrdup(NameStr(col->attname))));
20771 : }
20772 : }
20773 :
20774 : /* Reconstruct trigger arguments list. */
20775 156 : if (trigForm->tgnargs > 0)
20776 : {
20777 : char *p;
20778 :
20779 12 : value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
20780 : RelationGetDescr(pg_trigger), &isnull);
20781 12 : if (isnull)
20782 0 : elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
20783 : NameStr(trigForm->tgname), RelationGetRelationName(partition));
20784 :
20785 12 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
20786 :
20787 36 : for (int i = 0; i < trigForm->tgnargs; i++)
20788 : {
20789 24 : trigargs = lappend(trigargs, makeString(pstrdup(p)));
20790 24 : p += strlen(p) + 1;
20791 : }
20792 : }
20793 :
20794 156 : trigStmt = makeNode(CreateTrigStmt);
20795 156 : trigStmt->replace = false;
20796 156 : trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
20797 156 : trigStmt->trigname = NameStr(trigForm->tgname);
20798 156 : trigStmt->relation = NULL;
20799 156 : trigStmt->funcname = NULL; /* passed separately */
20800 156 : trigStmt->args = trigargs;
20801 156 : trigStmt->row = true;
20802 156 : trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
20803 156 : trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
20804 156 : trigStmt->columns = cols;
20805 156 : trigStmt->whenClause = NULL; /* passed separately */
20806 156 : trigStmt->transitionRels = NIL; /* not supported at present */
20807 156 : trigStmt->deferrable = trigForm->tgdeferrable;
20808 156 : trigStmt->initdeferred = trigForm->tginitdeferred;
20809 156 : trigStmt->constrrel = NULL; /* passed separately */
20810 :
20811 156 : CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
20812 : trigForm->tgconstrrelid, InvalidOid, InvalidOid,
20813 : trigForm->tgfoid, trigForm->oid, qual,
20814 156 : false, true, trigForm->tgenabled);
20815 :
20816 150 : MemoryContextSwitchTo(oldcxt);
20817 150 : MemoryContextReset(perTupCxt);
20818 : }
20819 :
20820 2928 : MemoryContextDelete(perTupCxt);
20821 :
20822 2928 : systable_endscan(scan);
20823 2928 : table_close(pg_trigger, RowExclusiveLock);
20824 2928 : }
20825 :
20826 : /*
20827 : * ALTER TABLE DETACH PARTITION
20828 : *
20829 : * Return the address of the relation that is no longer a partition of rel.
20830 : *
20831 : * If concurrent mode is requested, we run in two transactions. A side-
20832 : * effect is that this command cannot run in a multi-part ALTER TABLE.
20833 : * Currently, that's enforced by the grammar.
20834 : *
20835 : * The strategy for concurrency is to first modify the partition's
20836 : * pg_inherit catalog row to make it visible to everyone that the
20837 : * partition is detached, lock the partition against writes, and commit
20838 : * the transaction; anyone who requests the partition descriptor from
20839 : * that point onwards has to ignore such a partition. In a second
20840 : * transaction, we wait until all transactions that could have seen the
20841 : * partition as attached are gone, then we remove the rest of partition
20842 : * metadata (pg_inherits and pg_class.relpartbounds).
20843 : */
20844 : static ObjectAddress
20845 570 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
20846 : RangeVar *name, bool concurrent)
20847 : {
20848 : Relation partRel;
20849 : ObjectAddress address;
20850 : Oid defaultPartOid;
20851 :
20852 : /*
20853 : * We must lock the default partition, because detaching this partition
20854 : * will change its partition constraint.
20855 : */
20856 : defaultPartOid =
20857 570 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
20858 570 : if (OidIsValid(defaultPartOid))
20859 : {
20860 : /*
20861 : * Concurrent detaching when a default partition exists is not
20862 : * supported. The main problem is that the default partition
20863 : * constraint would change. And there's a definitional problem: what
20864 : * should happen to the tuples that are being inserted that belong to
20865 : * the partition being detached? Putting them on the partition being
20866 : * detached would be wrong, since they'd become "lost" after the
20867 : * detaching completes but we cannot put them in the default partition
20868 : * either until we alter its partition constraint.
20869 : *
20870 : * I think we could solve this problem if we effected the constraint
20871 : * change before committing the first transaction. But the lock would
20872 : * have to remain AEL and it would cause concurrent query planning to
20873 : * be blocked, so changing it that way would be even worse.
20874 : */
20875 106 : if (concurrent)
20876 12 : ereport(ERROR,
20877 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20878 : errmsg("cannot detach partitions concurrently when a default partition exists")));
20879 94 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
20880 : }
20881 :
20882 : /*
20883 : * In concurrent mode, the partition is locked with share-update-exclusive
20884 : * in the first transaction. This allows concurrent transactions to be
20885 : * doing DML to the partition.
20886 : */
20887 558 : partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
20888 : AccessExclusiveLock);
20889 :
20890 : /*
20891 : * Check inheritance conditions and either delete the pg_inherits row (in
20892 : * non-concurrent mode) or just set the inhdetachpending flag.
20893 : */
20894 546 : if (!concurrent)
20895 400 : RemoveInheritance(partRel, rel, false);
20896 : else
20897 146 : MarkInheritDetached(partRel, rel);
20898 :
20899 : /*
20900 : * Ensure that foreign keys still hold after this detach. This keeps
20901 : * locks on the referencing tables, which prevents concurrent transactions
20902 : * from adding rows that we wouldn't see. For this to work in concurrent
20903 : * mode, it is critical that the partition appears as no longer attached
20904 : * for the RI queries as soon as the first transaction commits.
20905 : */
20906 526 : ATDetachCheckNoForeignKeyRefs(partRel);
20907 :
20908 : /*
20909 : * Concurrent mode has to work harder; first we add a new constraint to
20910 : * the partition that matches the partition constraint. Then we close our
20911 : * existing transaction, and in a new one wait for all processes to catch
20912 : * up on the catalog updates we've done so far; at that point we can
20913 : * complete the operation.
20914 : */
20915 492 : if (concurrent)
20916 : {
20917 : Oid partrelid,
20918 : parentrelid;
20919 : LOCKTAG tag;
20920 : char *parentrelname;
20921 : char *partrelname;
20922 :
20923 : /*
20924 : * Add a new constraint to the partition being detached, which
20925 : * supplants the partition constraint (unless there is one already).
20926 : */
20927 140 : DetachAddConstraintIfNeeded(wqueue, partRel);
20928 :
20929 : /*
20930 : * We're almost done now; the only traces that remain are the
20931 : * pg_inherits tuple and the partition's relpartbounds. Before we can
20932 : * remove those, we need to wait until all transactions that know that
20933 : * this is a partition are gone.
20934 : */
20935 :
20936 : /*
20937 : * Remember relation OIDs to re-acquire them later; and relation names
20938 : * too, for error messages if something is dropped in between.
20939 : */
20940 140 : partrelid = RelationGetRelid(partRel);
20941 140 : parentrelid = RelationGetRelid(rel);
20942 140 : parentrelname = MemoryContextStrdup(PortalContext,
20943 140 : RelationGetRelationName(rel));
20944 140 : partrelname = MemoryContextStrdup(PortalContext,
20945 140 : RelationGetRelationName(partRel));
20946 :
20947 : /* Invalidate relcache entries for the parent -- must be before close */
20948 140 : CacheInvalidateRelcache(rel);
20949 :
20950 140 : table_close(partRel, NoLock);
20951 140 : table_close(rel, NoLock);
20952 140 : tab->rel = NULL;
20953 :
20954 : /* Make updated catalog entry visible */
20955 140 : PopActiveSnapshot();
20956 140 : CommitTransactionCommand();
20957 :
20958 140 : StartTransactionCommand();
20959 :
20960 : /*
20961 : * Now wait. This ensures that all queries that were planned
20962 : * including the partition are finished before we remove the rest of
20963 : * catalog entries. We don't need or indeed want to acquire this
20964 : * lock, though -- that would block later queries.
20965 : *
20966 : * We don't need to concern ourselves with waiting for a lock on the
20967 : * partition itself, since we will acquire AccessExclusiveLock below.
20968 : */
20969 140 : SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
20970 140 : WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
20971 :
20972 : /*
20973 : * Now acquire locks in both relations again. Note they may have been
20974 : * removed in the meantime, so care is required.
20975 : */
20976 90 : rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
20977 90 : partRel = try_relation_open(partrelid, AccessExclusiveLock);
20978 :
20979 : /* If the relations aren't there, something bad happened; bail out */
20980 90 : if (rel == NULL)
20981 : {
20982 0 : if (partRel != NULL) /* shouldn't happen */
20983 0 : elog(WARNING, "dangling partition \"%s\" remains, can't fix",
20984 : partrelname);
20985 0 : ereport(ERROR,
20986 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20987 : errmsg("partitioned table \"%s\" was removed concurrently",
20988 : parentrelname)));
20989 : }
20990 90 : if (partRel == NULL)
20991 0 : ereport(ERROR,
20992 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20993 : errmsg("partition \"%s\" was removed concurrently", partrelname)));
20994 :
20995 90 : tab->rel = rel;
20996 : }
20997 :
20998 : /*
20999 : * Detaching the partition might involve TOAST table access, so ensure we
21000 : * have a valid snapshot.
21001 : */
21002 442 : PushActiveSnapshot(GetTransactionSnapshot());
21003 :
21004 : /* Do the final part of detaching */
21005 442 : DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
21006 :
21007 440 : PopActiveSnapshot();
21008 :
21009 440 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21010 :
21011 : /* keep our lock until commit */
21012 440 : table_close(partRel, NoLock);
21013 :
21014 440 : return address;
21015 : }
21016 :
21017 : /*
21018 : * Second part of ALTER TABLE .. DETACH.
21019 : *
21020 : * This is separate so that it can be run independently when the second
21021 : * transaction of the concurrent algorithm fails (crash or abort).
21022 : */
21023 : static void
21024 456 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
21025 : Oid defaultPartOid)
21026 : {
21027 : Relation classRel;
21028 : List *fks;
21029 : ListCell *cell;
21030 : List *indexes;
21031 : Datum new_val[Natts_pg_class];
21032 : bool new_null[Natts_pg_class],
21033 : new_repl[Natts_pg_class];
21034 : HeapTuple tuple,
21035 : newtuple;
21036 456 : Relation trigrel = NULL;
21037 456 : List *fkoids = NIL;
21038 :
21039 456 : if (concurrent)
21040 : {
21041 : /*
21042 : * We can remove the pg_inherits row now. (In the non-concurrent case,
21043 : * this was already done).
21044 : */
21045 104 : RemoveInheritance(partRel, rel, true);
21046 : }
21047 :
21048 : /* Drop any triggers that were cloned on creation/attach. */
21049 456 : DropClonedTriggersFromPartition(RelationGetRelid(partRel));
21050 :
21051 : /*
21052 : * Detach any foreign keys that are inherited. This includes creating
21053 : * additional action triggers.
21054 : */
21055 456 : fks = copyObject(RelationGetFKeyList(partRel));
21056 456 : if (fks != NIL)
21057 84 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
21058 :
21059 : /*
21060 : * It's possible that the partition being detached has a foreign key that
21061 : * references a partitioned table. When that happens, there are multiple
21062 : * pg_constraint rows for the partition: one points to the partitioned
21063 : * table itself, while the others point to each of its partitions. Only
21064 : * the topmost one is to be considered here; the child constraints must be
21065 : * left alone, because conceptually those aren't coming from our parent
21066 : * partitioned table, but from this partition itself.
21067 : *
21068 : * We implement this by collecting all the constraint OIDs in a first scan
21069 : * of the FK array, and skipping in the loop below those constraints whose
21070 : * parents are listed here.
21071 : */
21072 1080 : foreach_node(ForeignKeyCacheInfo, fk, fks)
21073 168 : fkoids = lappend_oid(fkoids, fk->conoid);
21074 :
21075 624 : foreach(cell, fks)
21076 : {
21077 168 : ForeignKeyCacheInfo *fk = lfirst(cell);
21078 : HeapTuple contup;
21079 : Form_pg_constraint conform;
21080 :
21081 168 : contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
21082 168 : if (!HeapTupleIsValid(contup))
21083 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
21084 168 : conform = (Form_pg_constraint) GETSTRUCT(contup);
21085 :
21086 : /*
21087 : * Consider only inherited foreign keys, and only if their parents
21088 : * aren't in the list.
21089 : */
21090 168 : if (conform->contype != CONSTRAINT_FOREIGN ||
21091 312 : !OidIsValid(conform->conparentid) ||
21092 144 : list_member_oid(fkoids, conform->conparentid))
21093 : {
21094 66 : ReleaseSysCache(contup);
21095 66 : continue;
21096 : }
21097 :
21098 : /*
21099 : * The constraint on this table must be marked no longer a child of
21100 : * the parent's constraint, as do its check triggers.
21101 : */
21102 102 : ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
21103 :
21104 : /*
21105 : * Also, look up the partition's "check" triggers corresponding to the
21106 : * ENFORCED constraint being detached and detach them from the parent
21107 : * triggers. NOT ENFORCED constraints do not have these triggers;
21108 : * therefore, this step is not needed.
21109 : */
21110 102 : if (fk->conenforced)
21111 : {
21112 : Oid insertTriggerOid,
21113 : updateTriggerOid;
21114 :
21115 102 : GetForeignKeyCheckTriggers(trigrel,
21116 : fk->conoid, fk->confrelid, fk->conrelid,
21117 : &insertTriggerOid, &updateTriggerOid);
21118 : Assert(OidIsValid(insertTriggerOid));
21119 102 : TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
21120 : RelationGetRelid(partRel));
21121 : Assert(OidIsValid(updateTriggerOid));
21122 102 : TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
21123 : RelationGetRelid(partRel));
21124 : }
21125 :
21126 : /*
21127 : * Lastly, create the action triggers on the referenced table, using
21128 : * addFkRecurseReferenced, which requires some elaborate setup (so put
21129 : * it in a separate block). While at it, if the table is partitioned,
21130 : * that function will recurse to create the pg_constraint rows and
21131 : * action triggers for each partition.
21132 : *
21133 : * Note there's no need to do addFkConstraint() here, because the
21134 : * pg_constraint row already exists.
21135 : */
21136 : {
21137 : Constraint *fkconstraint;
21138 : int numfks;
21139 : AttrNumber conkey[INDEX_MAX_KEYS];
21140 : AttrNumber confkey[INDEX_MAX_KEYS];
21141 : Oid conpfeqop[INDEX_MAX_KEYS];
21142 : Oid conppeqop[INDEX_MAX_KEYS];
21143 : Oid conffeqop[INDEX_MAX_KEYS];
21144 : int numfkdelsetcols;
21145 : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
21146 : Relation refdRel;
21147 :
21148 102 : DeconstructFkConstraintRow(contup,
21149 : &numfks,
21150 : conkey,
21151 : confkey,
21152 : conpfeqop,
21153 : conppeqop,
21154 : conffeqop,
21155 : &numfkdelsetcols,
21156 : confdelsetcols);
21157 :
21158 : /* Create a synthetic node we'll use throughout */
21159 102 : fkconstraint = makeNode(Constraint);
21160 102 : fkconstraint->contype = CONSTRAINT_FOREIGN;
21161 102 : fkconstraint->conname = pstrdup(NameStr(conform->conname));
21162 102 : fkconstraint->deferrable = conform->condeferrable;
21163 102 : fkconstraint->initdeferred = conform->condeferred;
21164 102 : fkconstraint->is_enforced = conform->conenforced;
21165 102 : fkconstraint->skip_validation = true;
21166 102 : fkconstraint->initially_valid = conform->convalidated;
21167 : /* a few irrelevant fields omitted here */
21168 102 : fkconstraint->pktable = NULL;
21169 102 : fkconstraint->fk_attrs = NIL;
21170 102 : fkconstraint->pk_attrs = NIL;
21171 102 : fkconstraint->fk_matchtype = conform->confmatchtype;
21172 102 : fkconstraint->fk_upd_action = conform->confupdtype;
21173 102 : fkconstraint->fk_del_action = conform->confdeltype;
21174 102 : fkconstraint->fk_del_set_cols = NIL;
21175 102 : fkconstraint->old_conpfeqop = NIL;
21176 102 : fkconstraint->old_pktable_oid = InvalidOid;
21177 102 : fkconstraint->location = -1;
21178 :
21179 : /* set up colnames, used to generate the constraint name */
21180 252 : for (int i = 0; i < numfks; i++)
21181 : {
21182 : Form_pg_attribute att;
21183 :
21184 150 : att = TupleDescAttr(RelationGetDescr(partRel),
21185 150 : conkey[i] - 1);
21186 :
21187 150 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
21188 150 : makeString(NameStr(att->attname)));
21189 : }
21190 :
21191 102 : refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
21192 :
21193 102 : addFkRecurseReferenced(fkconstraint, partRel,
21194 : refdRel,
21195 : conform->conindid,
21196 : fk->conoid,
21197 : numfks,
21198 : confkey,
21199 : conkey,
21200 : conpfeqop,
21201 : conppeqop,
21202 : conffeqop,
21203 : numfkdelsetcols,
21204 : confdelsetcols,
21205 : true,
21206 : InvalidOid, InvalidOid,
21207 102 : conform->conperiod);
21208 102 : table_close(refdRel, NoLock); /* keep lock till end of xact */
21209 : }
21210 :
21211 102 : ReleaseSysCache(contup);
21212 : }
21213 456 : list_free_deep(fks);
21214 456 : if (trigrel)
21215 84 : table_close(trigrel, RowExclusiveLock);
21216 :
21217 : /*
21218 : * Any sub-constraints that are in the referenced-side of a larger
21219 : * constraint have to be removed. This partition is no longer part of the
21220 : * key space of the constraint.
21221 : */
21222 516 : foreach(cell, GetParentedForeignKeyRefs(partRel))
21223 : {
21224 62 : Oid constrOid = lfirst_oid(cell);
21225 : ObjectAddress constraint;
21226 :
21227 62 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
21228 62 : deleteDependencyRecordsForClass(ConstraintRelationId,
21229 : constrOid,
21230 : ConstraintRelationId,
21231 : DEPENDENCY_INTERNAL);
21232 62 : CommandCounterIncrement();
21233 :
21234 62 : ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
21235 62 : performDeletion(&constraint, DROP_RESTRICT, 0);
21236 : }
21237 :
21238 : /* Now we can detach indexes */
21239 454 : indexes = RelationGetIndexList(partRel);
21240 648 : foreach(cell, indexes)
21241 : {
21242 194 : Oid idxid = lfirst_oid(cell);
21243 : Oid parentidx;
21244 : Relation idx;
21245 : Oid constrOid;
21246 : Oid parentConstrOid;
21247 :
21248 194 : if (!has_superclass(idxid))
21249 12 : continue;
21250 :
21251 182 : parentidx = get_partition_parent(idxid, false);
21252 : Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
21253 :
21254 182 : idx = index_open(idxid, AccessExclusiveLock);
21255 182 : IndexSetParentIndex(idx, InvalidOid);
21256 :
21257 : /*
21258 : * If there's a constraint associated with the index, detach it too.
21259 : * Careful: it is possible for a constraint index in a partition to be
21260 : * the child of a non-constraint index, so verify whether the parent
21261 : * index does actually have a constraint.
21262 : */
21263 182 : constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
21264 : idxid);
21265 182 : parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
21266 : parentidx);
21267 182 : if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
21268 84 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
21269 :
21270 182 : index_close(idx, NoLock);
21271 : }
21272 :
21273 : /* Update pg_class tuple */
21274 454 : classRel = table_open(RelationRelationId, RowExclusiveLock);
21275 454 : tuple = SearchSysCacheCopy1(RELOID,
21276 : ObjectIdGetDatum(RelationGetRelid(partRel)));
21277 454 : if (!HeapTupleIsValid(tuple))
21278 0 : elog(ERROR, "cache lookup failed for relation %u",
21279 : RelationGetRelid(partRel));
21280 : Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
21281 :
21282 : /* Clear relpartbound and reset relispartition */
21283 454 : memset(new_val, 0, sizeof(new_val));
21284 454 : memset(new_null, false, sizeof(new_null));
21285 454 : memset(new_repl, false, sizeof(new_repl));
21286 454 : new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
21287 454 : new_null[Anum_pg_class_relpartbound - 1] = true;
21288 454 : new_repl[Anum_pg_class_relpartbound - 1] = true;
21289 454 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
21290 : new_val, new_null, new_repl);
21291 :
21292 454 : ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
21293 454 : CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
21294 454 : heap_freetuple(newtuple);
21295 454 : table_close(classRel, RowExclusiveLock);
21296 :
21297 : /*
21298 : * Drop identity property from all identity columns of partition.
21299 : */
21300 1294 : for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
21301 : {
21302 840 : Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
21303 :
21304 840 : if (!attr->attisdropped && attr->attidentity)
21305 6 : ATExecDropIdentity(partRel, NameStr(attr->attname), false,
21306 : AccessExclusiveLock, true, true);
21307 : }
21308 :
21309 454 : if (OidIsValid(defaultPartOid))
21310 : {
21311 : /*
21312 : * If the relation being detached is the default partition itself,
21313 : * remove it from the parent's pg_partitioned_table entry.
21314 : *
21315 : * If not, we must invalidate default partition's relcache entry, as
21316 : * in StorePartitionBound: its partition constraint depends on every
21317 : * other partition's partition constraint.
21318 : */
21319 46 : if (RelationGetRelid(partRel) == defaultPartOid)
21320 2 : update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
21321 : else
21322 44 : CacheInvalidateRelcacheByRelid(defaultPartOid);
21323 : }
21324 :
21325 : /*
21326 : * Invalidate the parent's relcache so that the partition is no longer
21327 : * included in its partition descriptor.
21328 : */
21329 454 : CacheInvalidateRelcache(rel);
21330 :
21331 : /*
21332 : * If the partition we just detached is partitioned itself, invalidate
21333 : * relcache for all descendent partitions too to ensure that their
21334 : * rd_partcheck expression trees are rebuilt; must lock partitions before
21335 : * doing so, using the same lockmode as what partRel has been locked with
21336 : * by the caller.
21337 : */
21338 454 : if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21339 : {
21340 : List *children;
21341 :
21342 62 : children = find_all_inheritors(RelationGetRelid(partRel),
21343 : AccessExclusiveLock, NULL);
21344 204 : foreach(cell, children)
21345 : {
21346 142 : CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
21347 : }
21348 : }
21349 454 : }
21350 :
21351 : /*
21352 : * ALTER TABLE ... DETACH PARTITION ... FINALIZE
21353 : *
21354 : * To use when a DETACH PARTITION command previously did not run to
21355 : * completion; this completes the detaching process.
21356 : */
21357 : static ObjectAddress
21358 14 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
21359 : {
21360 : Relation partRel;
21361 : ObjectAddress address;
21362 14 : Snapshot snap = GetActiveSnapshot();
21363 :
21364 14 : partRel = table_openrv(name, AccessExclusiveLock);
21365 :
21366 : /*
21367 : * Wait until existing snapshots are gone. This is important if the
21368 : * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
21369 : * user could immediately run DETACH FINALIZE without actually waiting for
21370 : * existing transactions. We must not complete the detach action until
21371 : * all such queries are complete (otherwise we would present them with an
21372 : * inconsistent view of catalogs).
21373 : */
21374 14 : WaitForOlderSnapshots(snap->xmin, false);
21375 :
21376 14 : DetachPartitionFinalize(rel, partRel, true, InvalidOid);
21377 :
21378 14 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21379 :
21380 14 : table_close(partRel, NoLock);
21381 :
21382 14 : return address;
21383 : }
21384 :
21385 : /*
21386 : * DetachAddConstraintIfNeeded
21387 : * Subroutine for ATExecDetachPartition. Create a constraint that
21388 : * takes the place of the partition constraint, but avoid creating
21389 : * a dupe if a constraint already exists which implies the needed
21390 : * constraint.
21391 : */
21392 : static void
21393 140 : DetachAddConstraintIfNeeded(List **wqueue, Relation partRel)
21394 : {
21395 : List *constraintExpr;
21396 :
21397 140 : constraintExpr = RelationGetPartitionQual(partRel);
21398 140 : constraintExpr = (List *) eval_const_expressions(NULL, (Node *) constraintExpr);
21399 :
21400 : /*
21401 : * Avoid adding a new constraint if the needed constraint is implied by an
21402 : * existing constraint
21403 : */
21404 140 : if (!PartConstraintImpliedByRelConstraint(partRel, constraintExpr))
21405 : {
21406 : AlteredTableInfo *tab;
21407 : Constraint *n;
21408 :
21409 134 : tab = ATGetQueueEntry(wqueue, partRel);
21410 :
21411 : /* Add constraint on partition, equivalent to the partition constraint */
21412 134 : n = makeNode(Constraint);
21413 134 : n->contype = CONSTR_CHECK;
21414 134 : n->conname = NULL;
21415 134 : n->location = -1;
21416 134 : n->is_no_inherit = false;
21417 134 : n->raw_expr = NULL;
21418 134 : n->cooked_expr = nodeToString(make_ands_explicit(constraintExpr));
21419 134 : n->is_enforced = true;
21420 134 : n->initially_valid = true;
21421 134 : n->skip_validation = true;
21422 : /* It's a re-add, since it nominally already exists */
21423 134 : ATAddCheckNNConstraint(wqueue, tab, partRel, n,
21424 : true, false, true, ShareUpdateExclusiveLock);
21425 : }
21426 140 : }
21427 :
21428 : /*
21429 : * DropClonedTriggersFromPartition
21430 : * subroutine for ATExecDetachPartition to remove any triggers that were
21431 : * cloned to the partition when it was created-as-partition or attached.
21432 : * This undoes what CloneRowTriggersToPartition did.
21433 : */
21434 : static void
21435 456 : DropClonedTriggersFromPartition(Oid partitionId)
21436 : {
21437 : ScanKeyData skey;
21438 : SysScanDesc scan;
21439 : HeapTuple trigtup;
21440 : Relation tgrel;
21441 : ObjectAddresses *objects;
21442 :
21443 456 : objects = new_object_addresses();
21444 :
21445 : /*
21446 : * Scan pg_trigger to search for all triggers on this rel.
21447 : */
21448 456 : ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
21449 : F_OIDEQ, ObjectIdGetDatum(partitionId));
21450 456 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
21451 456 : scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
21452 : true, NULL, 1, &skey);
21453 850 : while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
21454 : {
21455 394 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
21456 : ObjectAddress trig;
21457 :
21458 : /* Ignore triggers that weren't cloned */
21459 394 : if (!OidIsValid(pg_trigger->tgparentid))
21460 376 : continue;
21461 :
21462 : /*
21463 : * Ignore internal triggers that are implementation objects of foreign
21464 : * keys, because these will be detached when the foreign keys
21465 : * themselves are.
21466 : */
21467 346 : if (OidIsValid(pg_trigger->tgconstrrelid))
21468 328 : continue;
21469 :
21470 : /*
21471 : * This is ugly, but necessary: remove the dependency markings on the
21472 : * trigger so that it can be removed.
21473 : */
21474 18 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
21475 : TriggerRelationId,
21476 : DEPENDENCY_PARTITION_PRI);
21477 18 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
21478 : RelationRelationId,
21479 : DEPENDENCY_PARTITION_SEC);
21480 :
21481 : /* remember this trigger to remove it below */
21482 18 : ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
21483 18 : add_exact_object_address(&trig, objects);
21484 : }
21485 :
21486 : /* make the dependency removal visible to the deletion below */
21487 456 : CommandCounterIncrement();
21488 456 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
21489 :
21490 : /* done */
21491 456 : free_object_addresses(objects);
21492 456 : systable_endscan(scan);
21493 456 : table_close(tgrel, RowExclusiveLock);
21494 456 : }
21495 :
21496 : /*
21497 : * Before acquiring lock on an index, acquire the same lock on the owning
21498 : * table.
21499 : */
21500 : struct AttachIndexCallbackState
21501 : {
21502 : Oid partitionOid;
21503 : Oid parentTblOid;
21504 : bool lockedParentTbl;
21505 : };
21506 :
21507 : static void
21508 508 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
21509 : void *arg)
21510 : {
21511 : struct AttachIndexCallbackState *state;
21512 : Form_pg_class classform;
21513 : HeapTuple tuple;
21514 :
21515 508 : state = (struct AttachIndexCallbackState *) arg;
21516 :
21517 508 : if (!state->lockedParentTbl)
21518 : {
21519 476 : LockRelationOid(state->parentTblOid, AccessShareLock);
21520 476 : state->lockedParentTbl = true;
21521 : }
21522 :
21523 : /*
21524 : * If we previously locked some other heap, and the name we're looking up
21525 : * no longer refers to an index on that relation, release the now-useless
21526 : * lock. XXX maybe we should do *after* we verify whether the index does
21527 : * not actually belong to the same relation ...
21528 : */
21529 508 : if (relOid != oldRelOid && OidIsValid(state->partitionOid))
21530 : {
21531 0 : UnlockRelationOid(state->partitionOid, AccessShareLock);
21532 0 : state->partitionOid = InvalidOid;
21533 : }
21534 :
21535 : /* Didn't find a relation, so no need for locking or permission checks. */
21536 508 : if (!OidIsValid(relOid))
21537 6 : return;
21538 :
21539 502 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
21540 502 : if (!HeapTupleIsValid(tuple))
21541 0 : return; /* concurrently dropped, so nothing to do */
21542 502 : classform = (Form_pg_class) GETSTRUCT(tuple);
21543 502 : if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
21544 386 : classform->relkind != RELKIND_INDEX)
21545 6 : ereport(ERROR,
21546 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21547 : errmsg("\"%s\" is not an index", rv->relname)));
21548 496 : ReleaseSysCache(tuple);
21549 :
21550 : /*
21551 : * Since we need only examine the heap's tupledesc, an access share lock
21552 : * on it (preventing any DDL) is sufficient.
21553 : */
21554 496 : state->partitionOid = IndexGetRelation(relOid, false);
21555 496 : LockRelationOid(state->partitionOid, AccessShareLock);
21556 : }
21557 :
21558 : /*
21559 : * ALTER INDEX i1 ATTACH PARTITION i2
21560 : */
21561 : static ObjectAddress
21562 476 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
21563 : {
21564 : Relation partIdx;
21565 : Relation partTbl;
21566 : Relation parentTbl;
21567 : ObjectAddress address;
21568 : Oid partIdxId;
21569 : Oid currParent;
21570 : struct AttachIndexCallbackState state;
21571 :
21572 : /*
21573 : * We need to obtain lock on the index 'name' to modify it, but we also
21574 : * need to read its owning table's tuple descriptor -- so we need to lock
21575 : * both. To avoid deadlocks, obtain lock on the table before doing so on
21576 : * the index. Furthermore, we need to examine the parent table of the
21577 : * partition, so lock that one too.
21578 : */
21579 476 : state.partitionOid = InvalidOid;
21580 476 : state.parentTblOid = parentIdx->rd_index->indrelid;
21581 476 : state.lockedParentTbl = false;
21582 : partIdxId =
21583 476 : RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
21584 : RangeVarCallbackForAttachIndex,
21585 : &state);
21586 : /* Not there? */
21587 464 : if (!OidIsValid(partIdxId))
21588 0 : ereport(ERROR,
21589 : (errcode(ERRCODE_UNDEFINED_OBJECT),
21590 : errmsg("index \"%s\" does not exist", name->relname)));
21591 :
21592 : /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
21593 464 : partIdx = relation_open(partIdxId, AccessExclusiveLock);
21594 :
21595 : /* we already hold locks on both tables, so this is safe: */
21596 464 : parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
21597 464 : partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
21598 :
21599 464 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
21600 :
21601 : /* Silently do nothing if already in the right state */
21602 928 : currParent = partIdx->rd_rel->relispartition ?
21603 464 : get_partition_parent(partIdxId, false) : InvalidOid;
21604 464 : if (currParent != RelationGetRelid(parentIdx))
21605 : {
21606 : IndexInfo *childInfo;
21607 : IndexInfo *parentInfo;
21608 : AttrMap *attmap;
21609 : bool found;
21610 : int i;
21611 : PartitionDesc partDesc;
21612 : Oid constraintOid,
21613 440 : cldConstrId = InvalidOid;
21614 :
21615 : /*
21616 : * If this partition already has an index attached, refuse the
21617 : * operation.
21618 : */
21619 440 : refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
21620 :
21621 434 : if (OidIsValid(currParent))
21622 0 : ereport(ERROR,
21623 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21624 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21625 : RelationGetRelationName(partIdx),
21626 : RelationGetRelationName(parentIdx)),
21627 : errdetail("Index \"%s\" is already attached to another index.",
21628 : RelationGetRelationName(partIdx))));
21629 :
21630 : /* Make sure it indexes a partition of the other index's table */
21631 434 : partDesc = RelationGetPartitionDesc(parentTbl, true);
21632 434 : found = false;
21633 716 : for (i = 0; i < partDesc->nparts; i++)
21634 : {
21635 710 : if (partDesc->oids[i] == state.partitionOid)
21636 : {
21637 428 : found = true;
21638 428 : break;
21639 : }
21640 : }
21641 434 : if (!found)
21642 6 : ereport(ERROR,
21643 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21644 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21645 : RelationGetRelationName(partIdx),
21646 : RelationGetRelationName(parentIdx)),
21647 : errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
21648 : RelationGetRelationName(partIdx),
21649 : RelationGetRelationName(parentTbl))));
21650 :
21651 : /* Ensure the indexes are compatible */
21652 428 : childInfo = BuildIndexInfo(partIdx);
21653 428 : parentInfo = BuildIndexInfo(parentIdx);
21654 428 : attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
21655 : RelationGetDescr(parentTbl),
21656 : false);
21657 428 : if (!CompareIndexInfo(childInfo, parentInfo,
21658 428 : partIdx->rd_indcollation,
21659 428 : parentIdx->rd_indcollation,
21660 428 : partIdx->rd_opfamily,
21661 428 : parentIdx->rd_opfamily,
21662 : attmap))
21663 42 : ereport(ERROR,
21664 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21665 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21666 : RelationGetRelationName(partIdx),
21667 : RelationGetRelationName(parentIdx)),
21668 : errdetail("The index definitions do not match.")));
21669 :
21670 : /*
21671 : * If there is a constraint in the parent, make sure there is one in
21672 : * the child too.
21673 : */
21674 386 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
21675 : RelationGetRelid(parentIdx));
21676 :
21677 386 : if (OidIsValid(constraintOid))
21678 : {
21679 184 : cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
21680 : partIdxId);
21681 184 : if (!OidIsValid(cldConstrId))
21682 6 : ereport(ERROR,
21683 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21684 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21685 : RelationGetRelationName(partIdx),
21686 : RelationGetRelationName(parentIdx)),
21687 : errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
21688 : RelationGetRelationName(parentIdx),
21689 : RelationGetRelationName(parentTbl),
21690 : RelationGetRelationName(partIdx))));
21691 : }
21692 :
21693 : /*
21694 : * If it's a primary key, make sure the columns in the partition are
21695 : * NOT NULL.
21696 : */
21697 380 : if (parentIdx->rd_index->indisprimary)
21698 166 : verifyPartitionIndexNotNull(childInfo, partTbl);
21699 :
21700 : /* All good -- do it */
21701 380 : IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
21702 380 : if (OidIsValid(constraintOid))
21703 178 : ConstraintSetParentConstraint(cldConstrId, constraintOid,
21704 : RelationGetRelid(partTbl));
21705 :
21706 380 : free_attrmap(attmap);
21707 :
21708 380 : validatePartitionedIndex(parentIdx, parentTbl);
21709 : }
21710 :
21711 404 : relation_close(parentTbl, AccessShareLock);
21712 : /* keep these locks till commit */
21713 404 : relation_close(partTbl, NoLock);
21714 404 : relation_close(partIdx, NoLock);
21715 :
21716 404 : return address;
21717 : }
21718 :
21719 : /*
21720 : * Verify whether the given partition already contains an index attached
21721 : * to the given partitioned index. If so, raise an error.
21722 : */
21723 : static void
21724 440 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
21725 : {
21726 : Oid existingIdx;
21727 :
21728 440 : existingIdx = index_get_partition(partitionTbl,
21729 : RelationGetRelid(parentIdx));
21730 440 : if (OidIsValid(existingIdx))
21731 6 : ereport(ERROR,
21732 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21733 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21734 : RelationGetRelationName(partIdx),
21735 : RelationGetRelationName(parentIdx)),
21736 : errdetail("Another index is already attached for partition \"%s\".",
21737 : RelationGetRelationName(partitionTbl))));
21738 434 : }
21739 :
21740 : /*
21741 : * Verify whether the set of attached partition indexes to a parent index on
21742 : * a partitioned table is complete. If it is, mark the parent index valid.
21743 : *
21744 : * This should be called each time a partition index is attached.
21745 : */
21746 : static void
21747 422 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
21748 : {
21749 : Relation inheritsRel;
21750 : SysScanDesc scan;
21751 : ScanKeyData key;
21752 422 : int tuples = 0;
21753 : HeapTuple inhTup;
21754 422 : bool updated = false;
21755 :
21756 : Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
21757 :
21758 : /*
21759 : * Scan pg_inherits for this parent index. Count each valid index we find
21760 : * (verifying the pg_index entry for each), and if we reach the total
21761 : * amount we expect, we can mark this parent index as valid.
21762 : */
21763 422 : inheritsRel = table_open(InheritsRelationId, AccessShareLock);
21764 422 : ScanKeyInit(&key, Anum_pg_inherits_inhparent,
21765 : BTEqualStrategyNumber, F_OIDEQ,
21766 : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
21767 422 : scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
21768 : NULL, 1, &key);
21769 1126 : while ((inhTup = systable_getnext(scan)) != NULL)
21770 : {
21771 704 : Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
21772 : HeapTuple indTup;
21773 : Form_pg_index indexForm;
21774 :
21775 704 : indTup = SearchSysCache1(INDEXRELID,
21776 : ObjectIdGetDatum(inhForm->inhrelid));
21777 704 : if (!HeapTupleIsValid(indTup))
21778 0 : elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
21779 704 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
21780 704 : if (indexForm->indisvalid)
21781 642 : tuples += 1;
21782 704 : ReleaseSysCache(indTup);
21783 : }
21784 :
21785 : /* Done with pg_inherits */
21786 422 : systable_endscan(scan);
21787 422 : table_close(inheritsRel, AccessShareLock);
21788 :
21789 : /*
21790 : * If we found as many inherited indexes as the partitioned table has
21791 : * partitions, we're good; update pg_index to set indisvalid.
21792 : */
21793 422 : if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
21794 : {
21795 : Relation idxRel;
21796 : HeapTuple indTup;
21797 : Form_pg_index indexForm;
21798 :
21799 204 : idxRel = table_open(IndexRelationId, RowExclusiveLock);
21800 204 : indTup = SearchSysCacheCopy1(INDEXRELID,
21801 : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
21802 204 : if (!HeapTupleIsValid(indTup))
21803 0 : elog(ERROR, "cache lookup failed for index %u",
21804 : RelationGetRelid(partedIdx));
21805 204 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
21806 :
21807 204 : indexForm->indisvalid = true;
21808 204 : updated = true;
21809 :
21810 204 : CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
21811 :
21812 204 : table_close(idxRel, RowExclusiveLock);
21813 204 : heap_freetuple(indTup);
21814 : }
21815 :
21816 : /*
21817 : * If this index is in turn a partition of a larger index, validating it
21818 : * might cause the parent to become valid also. Try that.
21819 : */
21820 422 : if (updated && partedIdx->rd_rel->relispartition)
21821 : {
21822 : Oid parentIdxId,
21823 : parentTblId;
21824 : Relation parentIdx,
21825 : parentTbl;
21826 :
21827 : /* make sure we see the validation we just did */
21828 42 : CommandCounterIncrement();
21829 :
21830 42 : parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
21831 42 : parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
21832 42 : parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
21833 42 : parentTbl = relation_open(parentTblId, AccessExclusiveLock);
21834 : Assert(!parentIdx->rd_index->indisvalid);
21835 :
21836 42 : validatePartitionedIndex(parentIdx, parentTbl);
21837 :
21838 42 : relation_close(parentIdx, AccessExclusiveLock);
21839 42 : relation_close(parentTbl, AccessExclusiveLock);
21840 : }
21841 422 : }
21842 :
21843 : /*
21844 : * When attaching an index as a partition of a partitioned index which is a
21845 : * primary key, verify that all the columns in the partition are marked NOT
21846 : * NULL.
21847 : */
21848 : static void
21849 166 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
21850 : {
21851 336 : for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
21852 : {
21853 170 : Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
21854 170 : iinfo->ii_IndexAttrNumbers[i] - 1);
21855 :
21856 170 : if (!att->attnotnull)
21857 0 : ereport(ERROR,
21858 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
21859 : errmsg("invalid primary key definition"),
21860 : errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
21861 : NameStr(att->attname),
21862 : RelationGetRelationName(partition)));
21863 : }
21864 166 : }
21865 :
21866 : /*
21867 : * Return an OID list of constraints that reference the given relation
21868 : * that are marked as having a parent constraints.
21869 : */
21870 : static List *
21871 982 : GetParentedForeignKeyRefs(Relation partition)
21872 : {
21873 : Relation pg_constraint;
21874 : HeapTuple tuple;
21875 : SysScanDesc scan;
21876 : ScanKeyData key[2];
21877 982 : List *constraints = NIL;
21878 :
21879 : /*
21880 : * If no indexes, or no columns are referenceable by FKs, we can avoid the
21881 : * scan.
21882 : */
21883 1410 : if (RelationGetIndexList(partition) == NIL ||
21884 428 : bms_is_empty(RelationGetIndexAttrBitmap(partition,
21885 : INDEX_ATTR_BITMAP_KEY)))
21886 710 : return NIL;
21887 :
21888 : /* Search for constraints referencing this table */
21889 272 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
21890 272 : ScanKeyInit(&key[0],
21891 : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
21892 : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
21893 272 : ScanKeyInit(&key[1],
21894 : Anum_pg_constraint_contype, BTEqualStrategyNumber,
21895 : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
21896 :
21897 : /* XXX This is a seqscan, as we don't have a usable index */
21898 272 : scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
21899 444 : while ((tuple = systable_getnext(scan)) != NULL)
21900 : {
21901 172 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
21902 :
21903 : /*
21904 : * We only need to process constraints that are part of larger ones.
21905 : */
21906 172 : if (!OidIsValid(constrForm->conparentid))
21907 0 : continue;
21908 :
21909 172 : constraints = lappend_oid(constraints, constrForm->oid);
21910 : }
21911 :
21912 272 : systable_endscan(scan);
21913 272 : table_close(pg_constraint, AccessShareLock);
21914 :
21915 272 : return constraints;
21916 : }
21917 :
21918 : /*
21919 : * During DETACH PARTITION, verify that any foreign keys pointing to the
21920 : * partitioned table would not become invalid. An error is raised if any
21921 : * referenced values exist.
21922 : */
21923 : static void
21924 526 : ATDetachCheckNoForeignKeyRefs(Relation partition)
21925 : {
21926 : List *constraints;
21927 : ListCell *cell;
21928 :
21929 526 : constraints = GetParentedForeignKeyRefs(partition);
21930 :
21931 602 : foreach(cell, constraints)
21932 : {
21933 110 : Oid constrOid = lfirst_oid(cell);
21934 : HeapTuple tuple;
21935 : Form_pg_constraint constrForm;
21936 : Relation rel;
21937 110 : Trigger trig = {0};
21938 :
21939 110 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
21940 110 : if (!HeapTupleIsValid(tuple))
21941 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
21942 110 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
21943 :
21944 : Assert(OidIsValid(constrForm->conparentid));
21945 : Assert(constrForm->confrelid == RelationGetRelid(partition));
21946 :
21947 : /* prevent data changes into the referencing table until commit */
21948 110 : rel = table_open(constrForm->conrelid, ShareLock);
21949 :
21950 110 : trig.tgoid = InvalidOid;
21951 110 : trig.tgname = NameStr(constrForm->conname);
21952 110 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
21953 110 : trig.tgisinternal = true;
21954 110 : trig.tgconstrrelid = RelationGetRelid(partition);
21955 110 : trig.tgconstrindid = constrForm->conindid;
21956 110 : trig.tgconstraint = constrForm->oid;
21957 110 : trig.tgdeferrable = false;
21958 110 : trig.tginitdeferred = false;
21959 : /* we needn't fill in remaining fields */
21960 :
21961 110 : RI_PartitionRemove_Check(&trig, rel, partition);
21962 :
21963 76 : ReleaseSysCache(tuple);
21964 :
21965 76 : table_close(rel, NoLock);
21966 : }
21967 492 : }
21968 :
21969 : /*
21970 : * resolve column compression specification to compression method.
21971 : */
21972 : static char
21973 260866 : GetAttributeCompression(Oid atttypid, const char *compression)
21974 : {
21975 : char cmethod;
21976 :
21977 260866 : if (compression == NULL || strcmp(compression, "default") == 0)
21978 260686 : return InvalidCompressionMethod;
21979 :
21980 : /*
21981 : * To specify a nondefault method, the column data type must be toastable.
21982 : * Note this says nothing about whether the column's attstorage setting
21983 : * permits compression; we intentionally allow attstorage and
21984 : * attcompression to be independent. But with a non-toastable type,
21985 : * attstorage could not be set to a value that would permit compression.
21986 : *
21987 : * We don't actually need to enforce this, since nothing bad would happen
21988 : * if attcompression were non-default; it would never be consulted. But
21989 : * it seems more user-friendly to complain about a certainly-useless
21990 : * attempt to set the property.
21991 : */
21992 180 : if (!TypeIsToastable(atttypid))
21993 6 : ereport(ERROR,
21994 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
21995 : errmsg("column data type %s does not support compression",
21996 : format_type_be(atttypid))));
21997 :
21998 174 : cmethod = CompressionNameToMethod(compression);
21999 174 : if (!CompressionMethodIsValid(cmethod))
22000 12 : ereport(ERROR,
22001 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22002 : errmsg("invalid compression method \"%s\"", compression)));
22003 :
22004 162 : return cmethod;
22005 : }
22006 :
22007 : /*
22008 : * resolve column storage specification
22009 : */
22010 : static char
22011 254 : GetAttributeStorage(Oid atttypid, const char *storagemode)
22012 : {
22013 254 : char cstorage = 0;
22014 :
22015 254 : if (pg_strcasecmp(storagemode, "plain") == 0)
22016 54 : cstorage = TYPSTORAGE_PLAIN;
22017 200 : else if (pg_strcasecmp(storagemode, "external") == 0)
22018 158 : cstorage = TYPSTORAGE_EXTERNAL;
22019 42 : else if (pg_strcasecmp(storagemode, "extended") == 0)
22020 16 : cstorage = TYPSTORAGE_EXTENDED;
22021 26 : else if (pg_strcasecmp(storagemode, "main") == 0)
22022 20 : cstorage = TYPSTORAGE_MAIN;
22023 6 : else if (pg_strcasecmp(storagemode, "default") == 0)
22024 6 : cstorage = get_typstorage(atttypid);
22025 : else
22026 0 : ereport(ERROR,
22027 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22028 : errmsg("invalid storage type \"%s\"",
22029 : storagemode)));
22030 :
22031 : /*
22032 : * safety check: do not allow toasted storage modes unless column datatype
22033 : * is TOAST-aware.
22034 : */
22035 254 : if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
22036 6 : ereport(ERROR,
22037 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22038 : errmsg("column data type %s can only have storage PLAIN",
22039 : format_type_be(atttypid))));
22040 :
22041 248 : return cstorage;
22042 : }
|