Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * tablecmds.c
4 : * Commands for creating and altering table structures and settings
5 : *
6 : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/commands/tablecmds.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : #include "postgres.h"
16 :
17 : #include "access/attmap.h"
18 : #include "access/genam.h"
19 : #include "access/gist.h"
20 : #include "access/heapam.h"
21 : #include "access/heapam_xlog.h"
22 : #include "access/multixact.h"
23 : #include "access/reloptions.h"
24 : #include "access/relscan.h"
25 : #include "access/sysattr.h"
26 : #include "access/tableam.h"
27 : #include "access/toast_compression.h"
28 : #include "access/tupconvert.h"
29 : #include "access/xact.h"
30 : #include "access/xlog.h"
31 : #include "access/xloginsert.h"
32 : #include "catalog/catalog.h"
33 : #include "catalog/heap.h"
34 : #include "catalog/index.h"
35 : #include "catalog/namespace.h"
36 : #include "catalog/objectaccess.h"
37 : #include "catalog/partition.h"
38 : #include "catalog/pg_am.h"
39 : #include "catalog/pg_attrdef.h"
40 : #include "catalog/pg_collation.h"
41 : #include "catalog/pg_constraint.h"
42 : #include "catalog/pg_depend.h"
43 : #include "catalog/pg_extension_d.h"
44 : #include "catalog/pg_foreign_table.h"
45 : #include "catalog/pg_inherits.h"
46 : #include "catalog/pg_largeobject.h"
47 : #include "catalog/pg_largeobject_metadata.h"
48 : #include "catalog/pg_namespace.h"
49 : #include "catalog/pg_opclass.h"
50 : #include "catalog/pg_policy.h"
51 : #include "catalog/pg_proc.h"
52 : #include "catalog/pg_publication_rel.h"
53 : #include "catalog/pg_rewrite.h"
54 : #include "catalog/pg_statistic_ext.h"
55 : #include "catalog/pg_tablespace.h"
56 : #include "catalog/pg_trigger.h"
57 : #include "catalog/pg_type.h"
58 : #include "catalog/storage.h"
59 : #include "catalog/storage_xlog.h"
60 : #include "catalog/toasting.h"
61 : #include "commands/comment.h"
62 : #include "commands/defrem.h"
63 : #include "commands/event_trigger.h"
64 : #include "commands/extension.h"
65 : #include "commands/repack.h"
66 : #include "commands/sequence.h"
67 : #include "commands/tablecmds.h"
68 : #include "commands/tablespace.h"
69 : #include "commands/trigger.h"
70 : #include "commands/typecmds.h"
71 : #include "commands/user.h"
72 : #include "commands/vacuum.h"
73 : #include "common/int.h"
74 : #include "executor/executor.h"
75 : #include "foreign/fdwapi.h"
76 : #include "foreign/foreign.h"
77 : #include "miscadmin.h"
78 : #include "nodes/makefuncs.h"
79 : #include "nodes/nodeFuncs.h"
80 : #include "nodes/parsenodes.h"
81 : #include "optimizer/optimizer.h"
82 : #include "parser/parse_coerce.h"
83 : #include "parser/parse_collate.h"
84 : #include "parser/parse_expr.h"
85 : #include "parser/parse_relation.h"
86 : #include "parser/parse_type.h"
87 : #include "parser/parse_utilcmd.h"
88 : #include "parser/parser.h"
89 : #include "partitioning/partbounds.h"
90 : #include "partitioning/partdesc.h"
91 : #include "pgstat.h"
92 : #include "rewrite/rewriteDefine.h"
93 : #include "rewrite/rewriteHandler.h"
94 : #include "rewrite/rewriteManip.h"
95 : #include "storage/bufmgr.h"
96 : #include "storage/lmgr.h"
97 : #include "storage/lock.h"
98 : #include "storage/predicate.h"
99 : #include "storage/smgr.h"
100 : #include "tcop/utility.h"
101 : #include "utils/acl.h"
102 : #include "utils/builtins.h"
103 : #include "utils/fmgroids.h"
104 : #include "utils/inval.h"
105 : #include "utils/lsyscache.h"
106 : #include "utils/memutils.h"
107 : #include "utils/partcache.h"
108 : #include "utils/relcache.h"
109 : #include "utils/ruleutils.h"
110 : #include "utils/snapmgr.h"
111 : #include "utils/syscache.h"
112 : #include "utils/timestamp.h"
113 : #include "utils/typcache.h"
114 : #include "utils/usercontext.h"
115 :
116 : /*
117 : * ON COMMIT action list
118 : */
119 : typedef struct OnCommitItem
120 : {
121 : Oid relid; /* relid of relation */
122 : OnCommitAction oncommit; /* what to do at end of xact */
123 :
124 : /*
125 : * If this entry was created during the current transaction,
126 : * creating_subid is the ID of the creating subxact; if created in a prior
127 : * transaction, creating_subid is zero. If deleted during the current
128 : * transaction, deleting_subid is the ID of the deleting subxact; if no
129 : * deletion request is pending, deleting_subid is zero.
130 : */
131 : SubTransactionId creating_subid;
132 : SubTransactionId deleting_subid;
133 : } OnCommitItem;
134 :
135 : static List *on_commits = NIL;
136 :
137 :
138 : /*
139 : * State information for ALTER TABLE
140 : *
141 : * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
142 : * structs, one for each table modified by the operation (the named table
143 : * plus any child tables that are affected). We save lists of subcommands
144 : * to apply to this table (possibly modified by parse transformation steps);
145 : * these lists will be executed in Phase 2. If a Phase 3 step is needed,
146 : * necessary information is stored in the constraints and newvals lists.
147 : *
148 : * Phase 2 is divided into multiple passes; subcommands are executed in
149 : * a pass determined by subcommand type.
150 : */
151 :
152 : typedef enum AlterTablePass
153 : {
154 : AT_PASS_UNSET = -1, /* UNSET will cause ERROR */
155 : AT_PASS_DROP, /* DROP (all flavors) */
156 : AT_PASS_ALTER_TYPE, /* ALTER COLUMN TYPE */
157 : AT_PASS_ADD_COL, /* ADD COLUMN */
158 : AT_PASS_SET_EXPRESSION, /* ALTER SET EXPRESSION */
159 : AT_PASS_OLD_INDEX, /* re-add existing indexes */
160 : AT_PASS_OLD_CONSTR, /* re-add existing constraints */
161 : /* We could support a RENAME COLUMN pass here, but not currently used */
162 : AT_PASS_ADD_CONSTR, /* ADD constraints (initial examination) */
163 : AT_PASS_COL_ATTRS, /* set column attributes, eg NOT NULL */
164 : AT_PASS_ADD_INDEXCONSTR, /* ADD index-based constraints */
165 : AT_PASS_ADD_INDEX, /* ADD indexes */
166 : AT_PASS_ADD_OTHERCONSTR, /* ADD other constraints, defaults */
167 : AT_PASS_MISC, /* other stuff */
168 : } AlterTablePass;
169 :
170 : #define AT_NUM_PASSES (AT_PASS_MISC + 1)
171 :
172 : typedef struct AlteredTableInfo
173 : {
174 : /* Information saved before any work commences: */
175 : Oid relid; /* Relation to work on */
176 : char relkind; /* Its relkind */
177 : TupleDesc oldDesc; /* Pre-modification tuple descriptor */
178 :
179 : /*
180 : * Transiently set during Phase 2, normally set to NULL.
181 : *
182 : * ATRewriteCatalogs sets this when it starts, and closes when ATExecCmd
183 : * returns control. This can be exploited by ATExecCmd subroutines to
184 : * close/reopen across transaction boundaries.
185 : */
186 : Relation rel;
187 :
188 : /* Information saved by Phase 1 for Phase 2: */
189 : List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
190 : /* Information saved by Phases 1/2 for Phase 3: */
191 : List *constraints; /* List of NewConstraint */
192 : List *newvals; /* List of NewColumnValue */
193 : List *afterStmts; /* List of utility command parsetrees */
194 : bool verify_new_notnull; /* T if we should recheck NOT NULL */
195 : int rewrite; /* Reason for forced rewrite, if any */
196 : bool chgAccessMethod; /* T if SET ACCESS METHOD is used */
197 : Oid newAccessMethod; /* new access method; 0 means no change,
198 : * if above is true */
199 : Oid newTableSpace; /* new tablespace; 0 means no change */
200 : bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
201 : char newrelpersistence; /* if above is true */
202 : Expr *partition_constraint; /* for attach partition validation */
203 : /* true, if validating default due to some other attach/detach */
204 : bool validate_default;
205 : /* Objects to rebuild after completing ALTER TYPE operations */
206 : List *changedConstraintOids; /* OIDs of constraints to rebuild */
207 : List *changedConstraintDefs; /* string definitions of same */
208 : List *changedIndexOids; /* OIDs of indexes to rebuild */
209 : List *changedIndexDefs; /* string definitions of same */
210 : char *replicaIdentityIndex; /* index to reset as REPLICA IDENTITY */
211 : char *clusterOnIndex; /* index to use for CLUSTER */
212 : List *changedStatisticsOids; /* OIDs of statistics to rebuild */
213 : List *changedStatisticsDefs; /* string definitions of same */
214 : } AlteredTableInfo;
215 :
216 : /* Struct describing one new constraint to check in Phase 3 scan */
217 : /* Note: new not-null constraints are handled elsewhere */
218 : typedef struct NewConstraint
219 : {
220 : char *name; /* Constraint name, or NULL if none */
221 : ConstrType contype; /* CHECK or FOREIGN */
222 : Oid refrelid; /* PK rel, if FOREIGN */
223 : Oid refindid; /* OID of PK's index, if FOREIGN */
224 : bool conwithperiod; /* Whether the new FOREIGN KEY uses PERIOD */
225 : Oid conid; /* OID of pg_constraint entry, if FOREIGN */
226 : Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
227 : ExprState *qualstate; /* Execution state for CHECK expr */
228 : } NewConstraint;
229 :
230 : /*
231 : * Struct describing one new column value that needs to be computed during
232 : * Phase 3 copy (this could be either a new column with a non-null default, or
233 : * a column that we're changing the type of). Columns without such an entry
234 : * are just copied from the old table during ATRewriteTable. Note that the
235 : * expr is an expression over *old* table values, except when is_generated
236 : * is true; then it is an expression over columns of the *new* tuple.
237 : */
238 : typedef struct NewColumnValue
239 : {
240 : AttrNumber attnum; /* which column */
241 : Expr *expr; /* expression to compute */
242 : ExprState *exprstate; /* execution state */
243 : bool is_generated; /* is it a GENERATED expression? */
244 : } NewColumnValue;
245 :
246 : /*
247 : * Error-reporting support for RemoveRelations
248 : */
249 : struct dropmsgstrings
250 : {
251 : char kind;
252 : int nonexistent_code;
253 : const char *nonexistent_msg;
254 : const char *skipping_msg;
255 : const char *nota_msg;
256 : const char *drophint_msg;
257 : };
258 :
259 : static const struct dropmsgstrings dropmsgstringarray[] = {
260 : {RELKIND_RELATION,
261 : ERRCODE_UNDEFINED_TABLE,
262 : gettext_noop("table \"%s\" does not exist"),
263 : gettext_noop("table \"%s\" does not exist, skipping"),
264 : gettext_noop("\"%s\" is not a table"),
265 : gettext_noop("Use DROP TABLE to remove a table.")},
266 : {RELKIND_SEQUENCE,
267 : ERRCODE_UNDEFINED_TABLE,
268 : gettext_noop("sequence \"%s\" does not exist"),
269 : gettext_noop("sequence \"%s\" does not exist, skipping"),
270 : gettext_noop("\"%s\" is not a sequence"),
271 : gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
272 : {RELKIND_VIEW,
273 : ERRCODE_UNDEFINED_TABLE,
274 : gettext_noop("view \"%s\" does not exist"),
275 : gettext_noop("view \"%s\" does not exist, skipping"),
276 : gettext_noop("\"%s\" is not a view"),
277 : gettext_noop("Use DROP VIEW to remove a view.")},
278 : {RELKIND_MATVIEW,
279 : ERRCODE_UNDEFINED_TABLE,
280 : gettext_noop("materialized view \"%s\" does not exist"),
281 : gettext_noop("materialized view \"%s\" does not exist, skipping"),
282 : gettext_noop("\"%s\" is not a materialized view"),
283 : gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
284 : {RELKIND_INDEX,
285 : ERRCODE_UNDEFINED_OBJECT,
286 : gettext_noop("index \"%s\" does not exist"),
287 : gettext_noop("index \"%s\" does not exist, skipping"),
288 : gettext_noop("\"%s\" is not an index"),
289 : gettext_noop("Use DROP INDEX to remove an index.")},
290 : {RELKIND_COMPOSITE_TYPE,
291 : ERRCODE_UNDEFINED_OBJECT,
292 : gettext_noop("type \"%s\" does not exist"),
293 : gettext_noop("type \"%s\" does not exist, skipping"),
294 : gettext_noop("\"%s\" is not a type"),
295 : gettext_noop("Use DROP TYPE to remove a type.")},
296 : {RELKIND_FOREIGN_TABLE,
297 : ERRCODE_UNDEFINED_OBJECT,
298 : gettext_noop("foreign table \"%s\" does not exist"),
299 : gettext_noop("foreign table \"%s\" does not exist, skipping"),
300 : gettext_noop("\"%s\" is not a foreign table"),
301 : gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
302 : {RELKIND_PARTITIONED_TABLE,
303 : ERRCODE_UNDEFINED_TABLE,
304 : gettext_noop("table \"%s\" does not exist"),
305 : gettext_noop("table \"%s\" does not exist, skipping"),
306 : gettext_noop("\"%s\" is not a table"),
307 : gettext_noop("Use DROP TABLE to remove a table.")},
308 : {RELKIND_PARTITIONED_INDEX,
309 : ERRCODE_UNDEFINED_OBJECT,
310 : gettext_noop("index \"%s\" does not exist"),
311 : gettext_noop("index \"%s\" does not exist, skipping"),
312 : gettext_noop("\"%s\" is not an index"),
313 : gettext_noop("Use DROP INDEX to remove an index.")},
314 : {RELKIND_PROPGRAPH,
315 : ERRCODE_UNDEFINED_OBJECT,
316 : gettext_noop("property graph \"%s\" does not exist"),
317 : gettext_noop("property graph \"%s\" does not exist, skipping"),
318 : gettext_noop("\"%s\" is not a property graph"),
319 : gettext_noop("Use DROP PROPERTY GRAPH to remove a property graph.")},
320 : {'\0', 0, NULL, NULL, NULL, NULL}
321 : };
322 :
323 : /* communication between RemoveRelations and RangeVarCallbackForDropRelation */
324 : struct DropRelationCallbackState
325 : {
326 : /* These fields are set by RemoveRelations: */
327 : char expected_relkind;
328 : LOCKMODE heap_lockmode;
329 : /* These fields are state to track which subsidiary locks are held: */
330 : Oid heapOid;
331 : Oid partParentOid;
332 : /* These fields are passed back by RangeVarCallbackForDropRelation: */
333 : char actual_relkind;
334 : char actual_relpersistence;
335 : };
336 :
337 : /* Alter table target-type flags for ATSimplePermissions */
338 : #define ATT_TABLE 0x0001
339 : #define ATT_VIEW 0x0002
340 : #define ATT_MATVIEW 0x0004
341 : #define ATT_INDEX 0x0008
342 : #define ATT_COMPOSITE_TYPE 0x0010
343 : #define ATT_FOREIGN_TABLE 0x0020
344 : #define ATT_PARTITIONED_INDEX 0x0040
345 : #define ATT_SEQUENCE 0x0080
346 : #define ATT_PARTITIONED_TABLE 0x0100
347 :
348 : /*
349 : * ForeignTruncateInfo
350 : *
351 : * Information related to truncation of foreign tables. This is used for
352 : * the elements in a hash table. It uses the server OID as lookup key,
353 : * and includes a per-server list of all foreign tables involved in the
354 : * truncation.
355 : */
356 : typedef struct ForeignTruncateInfo
357 : {
358 : Oid serverid;
359 : List *rels;
360 : } ForeignTruncateInfo;
361 :
362 : /* Partial or complete FK creation in addFkConstraint() */
363 : typedef enum addFkConstraintSides
364 : {
365 : addFkReferencedSide,
366 : addFkReferencingSide,
367 : addFkBothSides,
368 : } addFkConstraintSides;
369 :
370 : /*
371 : * Hold extension dependencies of one partition index, during
372 : * MERGE/SPLIT PARTITION processing.
373 : *
374 : * collectPartitionIndexExtDeps() builds a list of these entries sorted by
375 : * parentIndexOid with exactly one entry per parent partitioned index; the
376 : * list is then consumed by applyPartitionIndexExtDeps() to re-record the
377 : * same dependencies on the newly created partition's indexes.
378 : *
379 : * extensionOids is kept sorted ascending so that equality checks between
380 : * entries from different partitions can be done in a single pass.
381 : * indexOid is carried only so that conflict errors can cite specific
382 : * partition index names.
383 : */
384 : typedef struct PartitionIndexExtDepEntry
385 : {
386 : Oid parentIndexOid; /* OID of the parent partitioned index */
387 : Oid indexOid; /* OID of a representative partition index */
388 : List *extensionOids; /* OIDs of dependent extensions, sorted asc */
389 : } PartitionIndexExtDepEntry;
390 :
391 : /*
392 : * Partition tables are expected to be dropped when the parent partitioned
393 : * table gets dropped. Hence for partitioning we use AUTO dependency.
394 : * Otherwise, for regular inheritance use NORMAL dependency.
395 : */
396 : #define child_dependency_type(child_is_partition) \
397 : ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
398 :
399 : static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
400 : static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
401 : static void truncate_check_activity(Relation rel);
402 : static void RangeVarCallbackForTruncate(const RangeVar *relation,
403 : Oid relId, Oid oldRelId, void *arg);
404 : static List *MergeAttributes(List *columns, const List *supers, char relpersistence,
405 : bool is_partition, List **supconstr,
406 : List **supnotnulls);
407 : static List *MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced);
408 : static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef);
409 : static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
410 : static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
411 : static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
412 : static void StoreCatalogInheritance(Oid relationId, List *supers,
413 : bool child_is_partition);
414 : static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
415 : int32 seqNumber, Relation inhRelation,
416 : bool child_is_partition);
417 : static int findAttrByName(const char *attributeName, const List *columns);
418 : static void AlterIndexNamespaces(Relation classRel, Relation rel,
419 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
420 : static void AlterSeqNamespaces(Relation classRel, Relation rel,
421 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
422 : LOCKMODE lockmode);
423 : static ObjectAddress ATExecAlterConstraint(List **wqueue, Relation rel,
424 : ATAlterConstraint *cmdcon,
425 : bool recurse, LOCKMODE lockmode);
426 : static bool ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel,
427 : Relation tgrel, Relation rel, HeapTuple contuple,
428 : bool recurse, LOCKMODE lockmode);
429 : static bool ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
430 : Relation conrel, Relation tgrel,
431 : Oid fkrelid, Oid pkrelid,
432 : HeapTuple contuple, LOCKMODE lockmode,
433 : Oid ReferencedParentDelTrigger,
434 : Oid ReferencedParentUpdTrigger,
435 : Oid ReferencingParentInsTrigger,
436 : Oid ReferencingParentUpdTrigger);
437 : static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
438 : Relation conrel, HeapTuple contuple,
439 : bool recurse, bool recursing,
440 : LOCKMODE lockmode);
441 : static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
442 : Relation conrel, Relation tgrel, Relation rel,
443 : HeapTuple contuple, bool recurse,
444 : List **otherrelids, LOCKMODE lockmode);
445 : static bool ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
446 : Relation conrel, Relation rel,
447 : HeapTuple contuple, LOCKMODE lockmode);
448 : static void AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
449 : bool deferrable, bool initdeferred,
450 : List **otherrelids);
451 : static void AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
452 : Relation conrel, Relation tgrel,
453 : Oid fkrelid, Oid pkrelid,
454 : HeapTuple contuple, LOCKMODE lockmode,
455 : Oid ReferencedParentDelTrigger,
456 : Oid ReferencedParentUpdTrigger,
457 : Oid ReferencingParentInsTrigger,
458 : Oid ReferencingParentUpdTrigger);
459 : static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
460 : Relation conrel, Oid conrelid,
461 : bool recurse, bool recursing,
462 : LOCKMODE lockmode);
463 : static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
464 : Relation conrel, Relation tgrel, Relation rel,
465 : HeapTuple contuple, bool recurse,
466 : List **otherrelids, LOCKMODE lockmode);
467 : static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
468 : HeapTuple contuple);
469 : static ObjectAddress ATExecValidateConstraint(List **wqueue,
470 : Relation rel, char *constrName,
471 : bool recurse, bool recursing, LOCKMODE lockmode);
472 : static void QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
473 : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode);
474 : static void QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
475 : char *constrName, HeapTuple contuple,
476 : bool recurse, bool recursing, LOCKMODE lockmode);
477 : static void QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
478 : HeapTuple contuple, bool recurse, bool recursing,
479 : LOCKMODE lockmode);
480 : static int transformColumnNameList(Oid relId, List *colList,
481 : int16 *attnums, Oid *atttypids, Oid *attcollids);
482 : static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
483 : List **attnamelist,
484 : int16 *attnums, Oid *atttypids, Oid *attcollids,
485 : Oid *opclasses, bool *pk_has_without_overlaps);
486 : static Oid transformFkeyCheckAttrs(Relation pkrel,
487 : int numattrs, int16 *attnums,
488 : bool with_period, Oid *opclasses,
489 : bool *pk_has_without_overlaps);
490 : static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
491 : static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
492 : Oid *funcid);
493 : static void validateForeignKeyConstraint(char *conname,
494 : Relation rel, Relation pkrel,
495 : Oid pkindOid, Oid constraintOid, bool hasperiod);
496 : static void CheckAlterTableIsSafe(Relation rel);
497 : static void ATController(AlterTableStmt *parsetree,
498 : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
499 : AlterTableUtilityContext *context);
500 : static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
501 : bool recurse, bool recursing, LOCKMODE lockmode,
502 : AlterTableUtilityContext *context);
503 : static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
504 : AlterTableUtilityContext *context);
505 : static void ATExecCmd(List **wqueue, AlteredTableInfo *tab,
506 : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
507 : AlterTableUtilityContext *context);
508 : static AlterTableCmd *ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab,
509 : Relation rel, AlterTableCmd *cmd,
510 : bool recurse, LOCKMODE lockmode,
511 : AlterTablePass cur_pass,
512 : AlterTableUtilityContext *context);
513 : static void ATRewriteTables(AlterTableStmt *parsetree,
514 : List **wqueue, LOCKMODE lockmode,
515 : AlterTableUtilityContext *context);
516 : static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
517 : static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
518 : static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets);
519 : static void ATSimpleRecursion(List **wqueue, Relation rel,
520 : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
521 : AlterTableUtilityContext *context);
522 : static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
523 : static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
524 : LOCKMODE lockmode,
525 : AlterTableUtilityContext *context);
526 : static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
527 : DropBehavior behavior);
528 : static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
529 : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
530 : AlterTableUtilityContext *context);
531 : static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
532 : Relation rel, AlterTableCmd **cmd,
533 : bool recurse, bool recursing,
534 : LOCKMODE lockmode, AlterTablePass cur_pass,
535 : AlterTableUtilityContext *context);
536 : static bool check_for_column_name_collision(Relation rel, const char *colname,
537 : bool if_not_exists);
538 : static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
539 : static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
540 : static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
541 : LOCKMODE lockmode);
542 : static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
543 : bool is_valid, bool queue_validation);
544 : static ObjectAddress ATExecSetNotNull(List **wqueue, Relation rel,
545 : char *conName, char *colName,
546 : bool recurse, bool recursing,
547 : LOCKMODE lockmode);
548 : static bool NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr);
549 : static bool ConstraintImpliedByRelConstraint(Relation scanrel,
550 : List *testConstraint, List *provenConstraint);
551 : static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
552 : Node *newDefault, LOCKMODE lockmode);
553 : static ObjectAddress ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
554 : Node *newDefault);
555 : static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
556 : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
557 : static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
558 : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
559 : static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
560 : bool recurse, bool recursing);
561 : static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
562 : Node *newExpr, LOCKMODE lockmode);
563 : static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
564 : static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
565 : static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
566 : Node *newValue, LOCKMODE lockmode);
567 : static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
568 : Node *options, bool isReset, LOCKMODE lockmode);
569 : static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
570 : Node *newValue, LOCKMODE lockmode);
571 : static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
572 : AlterTableCmd *cmd, LOCKMODE lockmode,
573 : AlterTableUtilityContext *context);
574 : static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
575 : DropBehavior behavior,
576 : bool recurse, bool recursing,
577 : bool missing_ok, LOCKMODE lockmode,
578 : ObjectAddresses *addrs);
579 : static void ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
580 : bool recurse, LOCKMODE lockmode,
581 : AlterTableUtilityContext *context);
582 : static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
583 : static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
584 : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
585 : static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
586 : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
587 : static ObjectAddress ATExecAddConstraint(List **wqueue,
588 : AlteredTableInfo *tab, Relation rel,
589 : Constraint *newConstraint, bool recurse, bool is_readd,
590 : LOCKMODE lockmode);
591 : static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
592 : static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
593 : IndexStmt *stmt, LOCKMODE lockmode);
594 : static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
595 : AlteredTableInfo *tab, Relation rel,
596 : Constraint *constr,
597 : bool recurse, bool recursing, bool is_readd,
598 : LOCKMODE lockmode);
599 : static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
600 : Relation rel, Constraint *fkconstraint,
601 : bool recurse, bool recursing,
602 : LOCKMODE lockmode);
603 : static int validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
604 : int numfksetcols, int16 *fksetcolsattnums,
605 : List *fksetcols);
606 : static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
607 : char *constraintname,
608 : Constraint *fkconstraint, Relation rel,
609 : Relation pkrel, Oid indexOid,
610 : Oid parentConstr,
611 : int numfks, int16 *pkattnum, int16 *fkattnum,
612 : Oid *pfeqoperators, Oid *ppeqoperators,
613 : Oid *ffeqoperators, int numfkdelsetcols,
614 : int16 *fkdelsetcols, bool is_internal,
615 : bool with_period);
616 : static void addFkRecurseReferenced(Constraint *fkconstraint,
617 : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
618 : int numfks, int16 *pkattnum, int16 *fkattnum,
619 : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
620 : int numfkdelsetcols, int16 *fkdelsetcols,
621 : bool old_check_ok,
622 : Oid parentDelTrigger, Oid parentUpdTrigger,
623 : bool with_period);
624 : static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
625 : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
626 : int numfks, int16 *pkattnum, int16 *fkattnum,
627 : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
628 : int numfkdelsetcols, int16 *fkdelsetcols,
629 : bool old_check_ok, LOCKMODE lockmode,
630 : Oid parentInsTrigger, Oid parentUpdTrigger,
631 : bool with_period);
632 : static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
633 : Relation partitionRel);
634 : static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
635 : static void CloneFkReferencing(List **wqueue, Relation parentRel,
636 : Relation partRel);
637 : static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
638 : Constraint *fkconstraint, Oid constraintOid,
639 : Oid indexOid,
640 : Oid parentInsTrigger, Oid parentUpdTrigger,
641 : Oid *insertTrigOid, Oid *updateTrigOid);
642 : static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
643 : Constraint *fkconstraint, Oid constraintOid,
644 : Oid indexOid,
645 : Oid parentDelTrigger, Oid parentUpdTrigger,
646 : Oid *deleteTrigOid, Oid *updateTrigOid);
647 : static bool tryAttachPartitionForeignKey(List **wqueue,
648 : ForeignKeyCacheInfo *fk,
649 : Relation partition,
650 : Oid parentConstrOid, int numfks,
651 : AttrNumber *mapped_conkey, AttrNumber *confkey,
652 : Oid *conpfeqop,
653 : Oid parentInsTrigger,
654 : Oid parentUpdTrigger,
655 : Relation trigrel);
656 : static void AttachPartitionForeignKey(List **wqueue, Relation partition,
657 : Oid partConstrOid, Oid parentConstrOid,
658 : Oid parentInsTrigger, Oid parentUpdTrigger,
659 : Relation trigrel);
660 : static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
661 : Oid conoid, Oid conrelid);
662 : static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
663 : Oid confrelid, Oid conrelid);
664 : static void GetForeignKeyActionTriggers(Relation trigrel,
665 : Oid conoid, Oid confrelid, Oid conrelid,
666 : Oid *deleteTriggerOid,
667 : Oid *updateTriggerOid);
668 : static void GetForeignKeyCheckTriggers(Relation trigrel,
669 : Oid conoid, Oid confrelid, Oid conrelid,
670 : Oid *insertTriggerOid,
671 : Oid *updateTriggerOid);
672 : static void ATExecDropConstraint(Relation rel, const char *constrName,
673 : DropBehavior behavior, bool recurse,
674 : bool missing_ok, LOCKMODE lockmode);
675 : static ObjectAddress dropconstraint_internal(Relation rel,
676 : HeapTuple constraintTup, DropBehavior behavior,
677 : bool recurse, bool recursing,
678 : bool missing_ok, LOCKMODE lockmode);
679 : static void ATPrepAlterColumnType(List **wqueue,
680 : AlteredTableInfo *tab, Relation rel,
681 : bool recurse, bool recursing,
682 : AlterTableCmd *cmd, LOCKMODE lockmode,
683 : AlterTableUtilityContext *context);
684 : static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
685 : static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
686 : AlterTableCmd *cmd, LOCKMODE lockmode);
687 : static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
688 : Relation rel, AttrNumber attnum, const char *colName);
689 : static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
690 : static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
691 : static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
692 : static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
693 : LOCKMODE lockmode);
694 : static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId,
695 : char *cmd, List **wqueue, LOCKMODE lockmode,
696 : bool rewrite);
697 : static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
698 : Oid objid, Relation rel, List *domname,
699 : const char *conname);
700 : static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
701 : static void TryReuseForeignKey(Oid oldId, Constraint *con);
702 : static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
703 : List *options, LOCKMODE lockmode);
704 : static void change_owner_fix_column_acls(Oid relationOid,
705 : Oid oldOwnerId, Oid newOwnerId);
706 : static void change_owner_recurse_to_sequences(Oid relationOid,
707 : Oid newOwnerId, LOCKMODE lockmode);
708 : static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
709 : LOCKMODE lockmode);
710 : static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
711 : static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
712 : static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
713 : static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
714 : bool toLogged);
715 : static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
716 : const char *tablespacename, LOCKMODE lockmode);
717 : static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
718 : static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
719 : static void ATExecSetRelOptions(Relation rel, List *defList,
720 : AlterTableType operation,
721 : LOCKMODE lockmode);
722 : static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
723 : char fires_when, bool skip_system, bool recurse,
724 : LOCKMODE lockmode);
725 : static void ATExecEnableDisableRule(Relation rel, const char *rulename,
726 : char fires_when, LOCKMODE lockmode);
727 : static void ATPrepChangeInherit(Relation child_rel);
728 : static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
729 : static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
730 : static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
731 : DependencyType deptype);
732 : static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
733 : static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
734 : static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
735 : static void ATExecGenericOptions(Relation rel, List *options);
736 : static void ATExecSetRowSecurity(Relation rel, bool rls);
737 : static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
738 : static ObjectAddress ATExecSetCompression(Relation rel,
739 : const char *column, Node *newValue, LOCKMODE lockmode);
740 :
741 : static void index_copy_data(Relation rel, RelFileLocator newrlocator);
742 : static const char *storage_name(char c);
743 :
744 : static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
745 : Oid oldRelOid, void *arg);
746 : static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
747 : Oid oldrelid, void *arg);
748 : static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
749 : static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
750 : List **partexprs, Oid *partopclass, Oid *partcollation,
751 : PartitionStrategy strategy);
752 : static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
753 : static void RemoveInheritance(Relation child_rel, Relation parent_rel,
754 : bool expect_detached);
755 : static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
756 : PartitionCmd *cmd,
757 : AlterTableUtilityContext *context);
758 : static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
759 : static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
760 : List *partConstraint,
761 : bool validate_default);
762 : static void CloneRowTriggersToPartition(Relation parent, Relation partition);
763 : static void DropClonedTriggersFromPartition(Oid partitionId);
764 : static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
765 : Relation rel, RangeVar *name,
766 : bool concurrent);
767 : static void DetachPartitionFinalize(Relation rel, Relation partRel,
768 : bool concurrent, Oid defaultPartOid);
769 : static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
770 : static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
771 : RangeVar *name);
772 : static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
773 : static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
774 : Relation partitionTbl);
775 : static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
776 : static List *GetParentedForeignKeyRefs(Relation partition);
777 : static void ATDetachCheckNoForeignKeyRefs(Relation partition);
778 : static char GetAttributeCompression(Oid atttypid, const char *compression);
779 : static char GetAttributeStorage(Oid atttypid, const char *storagemode);
780 :
781 : static void ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel,
782 : PartitionCmd *cmd, AlterTableUtilityContext *context);
783 : static void ATExecSplitPartition(List **wqueue, AlteredTableInfo *tab,
784 : Relation rel, PartitionCmd *cmd,
785 : AlterTableUtilityContext *context);
786 : static List *collectPartitionIndexExtDeps(List *partitionOids);
787 : static void applyPartitionIndexExtDeps(Oid newPartOid, List *extDepState);
788 : static void freePartitionIndexExtDeps(List *extDepState);
789 :
790 : /* ----------------------------------------------------------------
791 : * DefineRelation
792 : * Creates a new relation.
793 : *
794 : * stmt carries parsetree information from an ordinary CREATE TABLE statement.
795 : * The other arguments are used to extend the behavior for other cases:
796 : * relkind: relkind to assign to the new relation
797 : * ownerId: if not InvalidOid, use this as the new relation's owner.
798 : * typaddress: if not null, it's set to the pg_type entry's address.
799 : * queryString: for error reporting
800 : *
801 : * Note that permissions checks are done against current user regardless of
802 : * ownerId. A nonzero ownerId is used when someone is creating a relation
803 : * "on behalf of" someone else, so we still want to see that the current user
804 : * has permissions to do it.
805 : *
806 : * If successful, returns the address of the new relation.
807 : * ----------------------------------------------------------------
808 : */
809 : ObjectAddress
810 41919 : DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
811 : ObjectAddress *typaddress, const char *queryString)
812 : {
813 : char relname[NAMEDATALEN];
814 : Oid namespaceId;
815 : Oid relationId;
816 : Oid tablespaceId;
817 : Relation rel;
818 : TupleDesc descriptor;
819 : List *inheritOids;
820 : List *old_constraints;
821 : List *old_notnulls;
822 : List *rawDefaults;
823 : List *cookedDefaults;
824 : List *nncols;
825 41919 : List *connames = NIL;
826 : Datum reloptions;
827 : ListCell *listptr;
828 : AttrNumber attnum;
829 : bool partitioned;
830 41919 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
831 : Oid ofTypeId;
832 : ObjectAddress address;
833 : LOCKMODE parentLockmode;
834 41919 : Oid accessMethodId = InvalidOid;
835 :
836 : /*
837 : * Truncate relname to appropriate length (probably a waste of time, as
838 : * parser should have done this already).
839 : */
840 41919 : strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
841 :
842 : /*
843 : * Check consistency of arguments
844 : */
845 41919 : if (stmt->oncommit != ONCOMMIT_NOOP
846 128 : && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
847 8 : ereport(ERROR,
848 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
849 : errmsg("ON COMMIT can only be used on temporary tables")));
850 :
851 41911 : if (stmt->partspec != NULL)
852 : {
853 3626 : if (relkind != RELKIND_RELATION)
854 0 : elog(ERROR, "unexpected relkind: %d", (int) relkind);
855 :
856 3626 : relkind = RELKIND_PARTITIONED_TABLE;
857 3626 : partitioned = true;
858 : }
859 : else
860 38285 : partitioned = false;
861 :
862 41911 : if (relkind == RELKIND_PARTITIONED_TABLE &&
863 3626 : stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
864 4 : ereport(ERROR,
865 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
866 : errmsg("partitioned tables cannot be unlogged")));
867 :
868 : /*
869 : * Look up the namespace in which we are supposed to create the relation,
870 : * check we have permission to create there, lock it against concurrent
871 : * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
872 : * namespace is selected.
873 : */
874 : namespaceId =
875 41907 : RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
876 :
877 : /*
878 : * Security check: disallow creating temp tables from security-restricted
879 : * code. This is needed because calling code might not expect untrusted
880 : * tables to appear in pg_temp at the front of its search path.
881 : */
882 41907 : if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
883 2321 : && InSecurityRestrictedOperation())
884 0 : ereport(ERROR,
885 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
886 : errmsg("cannot create temporary table within security-restricted operation")));
887 :
888 : /*
889 : * Determine the lockmode to use when scanning parents. A self-exclusive
890 : * lock is needed here.
891 : *
892 : * For regular inheritance, if two backends attempt to add children to the
893 : * same parent simultaneously, and that parent has no pre-existing
894 : * children, then both will attempt to update the parent's relhassubclass
895 : * field, leading to a "tuple concurrently updated" error. Also, this
896 : * interlocks against a concurrent ANALYZE on the parent table, which
897 : * might otherwise be attempting to clear the parent's relhassubclass
898 : * field, if its previous children were recently dropped.
899 : *
900 : * If the child table is a partition, then we instead grab an exclusive
901 : * lock on the parent because its partition descriptor will be changed by
902 : * addition of the new partition.
903 : */
904 41907 : parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
905 : ShareUpdateExclusiveLock);
906 :
907 : /* Determine the list of OIDs of the parents. */
908 41907 : inheritOids = NIL;
909 50034 : foreach(listptr, stmt->inhRelations)
910 : {
911 8127 : RangeVar *rv = (RangeVar *) lfirst(listptr);
912 : Oid parentOid;
913 :
914 8127 : parentOid = RangeVarGetRelid(rv, parentLockmode, false);
915 :
916 : /*
917 : * Reject duplications in the list of parents.
918 : */
919 8127 : if (list_member_oid(inheritOids, parentOid))
920 0 : ereport(ERROR,
921 : (errcode(ERRCODE_DUPLICATE_TABLE),
922 : errmsg("relation \"%s\" would be inherited from more than once",
923 : get_rel_name(parentOid))));
924 :
925 8127 : inheritOids = lappend_oid(inheritOids, parentOid);
926 : }
927 :
928 : /*
929 : * Select tablespace to use: an explicitly indicated one, or (in the case
930 : * of a partitioned table) the parent's, if it has one.
931 : */
932 41907 : if (stmt->tablespacename)
933 : {
934 85 : tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
935 :
936 81 : if (partitioned && tablespaceId == MyDatabaseTableSpace)
937 4 : ereport(ERROR,
938 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
939 : errmsg("cannot specify default tablespace for partitioned relations")));
940 : }
941 41822 : else if (stmt->partbound)
942 : {
943 : Assert(list_length(inheritOids) == 1);
944 6490 : tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
945 : }
946 : else
947 35332 : tablespaceId = InvalidOid;
948 :
949 : /* still nothing? use the default */
950 41899 : if (!OidIsValid(tablespaceId))
951 41796 : tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
952 : partitioned);
953 :
954 : /* Check permissions except when using database's default */
955 41895 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
956 : {
957 : AclResult aclresult;
958 :
959 119 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
960 : ACL_CREATE);
961 119 : if (aclresult != ACLCHECK_OK)
962 4 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
963 4 : get_tablespace_name(tablespaceId));
964 : }
965 :
966 : /* In all cases disallow placing user relations in pg_global */
967 41891 : if (tablespaceId == GLOBALTABLESPACE_OID)
968 12 : ereport(ERROR,
969 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
970 : errmsg("only shared relations can be placed in pg_global tablespace")));
971 :
972 : /* Identify user ID that will own the table */
973 41879 : if (!OidIsValid(ownerId))
974 41724 : ownerId = GetUserId();
975 :
976 : /*
977 : * Parse and validate reloptions, if any.
978 : */
979 41879 : reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
980 : true, false);
981 :
982 41867 : switch (relkind)
983 : {
984 10742 : case RELKIND_VIEW:
985 10742 : (void) view_reloptions(reloptions, true);
986 10730 : break;
987 3610 : case RELKIND_PARTITIONED_TABLE:
988 3610 : (void) partitioned_table_reloptions(reloptions, true);
989 3606 : break;
990 27515 : default:
991 27515 : (void) heap_reloptions(relkind, reloptions, true);
992 : }
993 :
994 41787 : if (stmt->ofTypename)
995 : {
996 : AclResult aclresult;
997 :
998 57 : ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
999 :
1000 57 : aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
1001 57 : if (aclresult != ACLCHECK_OK)
1002 4 : aclcheck_error_type(aclresult, ofTypeId);
1003 : }
1004 : else
1005 41730 : ofTypeId = InvalidOid;
1006 :
1007 : /*
1008 : * Look up inheritance ancestors and generate relation schema, including
1009 : * inherited attributes. (Note that stmt->tableElts is destructively
1010 : * modified by MergeAttributes.)
1011 : */
1012 41623 : stmt->tableElts =
1013 41783 : MergeAttributes(stmt->tableElts, inheritOids,
1014 41783 : stmt->relation->relpersistence,
1015 41783 : stmt->partbound != NULL,
1016 : &old_constraints, &old_notnulls);
1017 :
1018 : /*
1019 : * Create a tuple descriptor from the relation schema. Note that this
1020 : * deals with column names, types, and in-descriptor NOT NULL flags, but
1021 : * not default values, NOT NULL or CHECK constraints; we handle those
1022 : * below.
1023 : */
1024 41623 : descriptor = BuildDescForRelation(stmt->tableElts);
1025 :
1026 : /*
1027 : * Find columns with default values and prepare for insertion of the
1028 : * defaults. Pre-cooked (that is, inherited) defaults go into a list of
1029 : * CookedConstraint structs that we'll pass to heap_create_with_catalog,
1030 : * while raw defaults go into a list of RawColumnDefault structs that will
1031 : * be processed by AddRelationNewConstraints. (We can't deal with raw
1032 : * expressions until we can do transformExpr.)
1033 : */
1034 41591 : rawDefaults = NIL;
1035 41591 : cookedDefaults = NIL;
1036 41591 : attnum = 0;
1037 :
1038 208056 : foreach(listptr, stmt->tableElts)
1039 : {
1040 166465 : ColumnDef *colDef = lfirst(listptr);
1041 :
1042 166465 : attnum++;
1043 166465 : if (colDef->raw_default != NULL)
1044 : {
1045 : RawColumnDefault *rawEnt;
1046 :
1047 : Assert(colDef->cooked_default == NULL);
1048 :
1049 2179 : rawEnt = palloc_object(RawColumnDefault);
1050 2179 : rawEnt->attnum = attnum;
1051 2179 : rawEnt->raw_default = colDef->raw_default;
1052 2179 : rawEnt->generated = colDef->generated;
1053 2179 : rawDefaults = lappend(rawDefaults, rawEnt);
1054 : }
1055 164286 : else if (colDef->cooked_default != NULL)
1056 : {
1057 : CookedConstraint *cooked;
1058 :
1059 350 : cooked = palloc_object(CookedConstraint);
1060 350 : cooked->contype = CONSTR_DEFAULT;
1061 350 : cooked->conoid = InvalidOid; /* until created */
1062 350 : cooked->name = NULL;
1063 350 : cooked->attnum = attnum;
1064 350 : cooked->expr = colDef->cooked_default;
1065 350 : cooked->is_enforced = true;
1066 350 : cooked->skip_validation = false;
1067 350 : cooked->is_local = true; /* not used for defaults */
1068 350 : cooked->inhcount = 0; /* ditto */
1069 350 : cooked->is_no_inherit = false;
1070 350 : cookedDefaults = lappend(cookedDefaults, cooked);
1071 : }
1072 : }
1073 :
1074 41591 : TupleDescFinalize(descriptor);
1075 :
1076 : /*
1077 : * For relations with table AM and partitioned tables, select access
1078 : * method to use: an explicitly indicated one, or (in the case of a
1079 : * partitioned table) the parent's, if it has one.
1080 : */
1081 41591 : if (stmt->accessMethod != NULL)
1082 : {
1083 : Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
1084 87 : accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1085 : }
1086 41504 : else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
1087 : {
1088 26746 : if (stmt->partbound)
1089 : {
1090 : Assert(list_length(inheritOids) == 1);
1091 6376 : accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1092 : }
1093 :
1094 26746 : if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
1095 23127 : accessMethodId = get_table_am_oid(default_table_access_method, false);
1096 : }
1097 :
1098 : /*
1099 : * Create the relation. Inherited defaults and CHECK constraints are
1100 : * passed in for immediate handling --- since they don't need parsing,
1101 : * they can be stored immediately.
1102 : */
1103 41579 : relationId = heap_create_with_catalog(relname,
1104 : namespaceId,
1105 : tablespaceId,
1106 : InvalidOid,
1107 : InvalidOid,
1108 : ofTypeId,
1109 : ownerId,
1110 : accessMethodId,
1111 : descriptor,
1112 : list_concat(cookedDefaults,
1113 : old_constraints),
1114 : relkind,
1115 41579 : stmt->relation->relpersistence,
1116 : false,
1117 : false,
1118 : stmt->oncommit,
1119 : reloptions,
1120 : true,
1121 : allowSystemTableMods,
1122 : false,
1123 : InvalidOid,
1124 : typaddress);
1125 :
1126 : /*
1127 : * We must bump the command counter to make the newly-created relation
1128 : * tuple visible for opening.
1129 : */
1130 41543 : CommandCounterIncrement();
1131 :
1132 : /*
1133 : * Open the new relation and acquire exclusive lock on it. This isn't
1134 : * really necessary for locking out other backends (since they can't see
1135 : * the new rel anyway until we commit), but it keeps the lock manager from
1136 : * complaining about deadlock risks.
1137 : */
1138 41543 : rel = relation_open(relationId, AccessExclusiveLock);
1139 :
1140 : /*
1141 : * Now add any newly specified column default and generation expressions
1142 : * to the new relation. These are passed to us in the form of raw
1143 : * parsetrees; we need to transform them to executable expression trees
1144 : * before they can be added. The most convenient way to do that is to
1145 : * apply the parser's transformExpr routine, but transformExpr doesn't
1146 : * work unless we have a pre-existing relation. So, the transformation has
1147 : * to be postponed to this final step of CREATE TABLE.
1148 : *
1149 : * This needs to be before processing the partitioning clauses because
1150 : * those could refer to generated columns.
1151 : */
1152 41543 : if (rawDefaults)
1153 1838 : AddRelationNewConstraints(rel, rawDefaults, NIL,
1154 : true, true, false, queryString);
1155 :
1156 : /*
1157 : * Make column generation expressions visible for use by partitioning.
1158 : */
1159 41415 : CommandCounterIncrement();
1160 :
1161 : /* Process and store partition bound, if any. */
1162 41415 : if (stmt->partbound)
1163 : {
1164 : PartitionBoundSpec *bound;
1165 : ParseState *pstate;
1166 6438 : Oid parentId = linitial_oid(inheritOids),
1167 : defaultPartOid;
1168 : Relation parent,
1169 6438 : defaultRel = NULL;
1170 : ParseNamespaceItem *nsitem;
1171 :
1172 : /* Already have strong enough lock on the parent */
1173 6438 : parent = table_open(parentId, NoLock);
1174 :
1175 : /*
1176 : * We are going to try to validate the partition bound specification
1177 : * against the partition key of parentRel, so it better have one.
1178 : */
1179 6438 : if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1180 12 : ereport(ERROR,
1181 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1182 : errmsg("\"%s\" is not partitioned",
1183 : RelationGetRelationName(parent))));
1184 :
1185 : /*
1186 : * The partition constraint of the default partition depends on the
1187 : * partition bounds of every other partition. It is possible that
1188 : * another backend might be about to execute a query on the default
1189 : * partition table, and that the query relies on previously cached
1190 : * default partition constraints. We must therefore take a table lock
1191 : * strong enough to prevent all queries on the default partition from
1192 : * proceeding until we commit and send out a shared-cache-inval notice
1193 : * that will make them update their index lists.
1194 : *
1195 : * Order of locking: The relation being added won't be visible to
1196 : * other backends until it is committed, hence here in
1197 : * DefineRelation() the order of locking the default partition and the
1198 : * relation being added does not matter. But at all other places we
1199 : * need to lock the default relation before we lock the relation being
1200 : * added or removed i.e. we should take the lock in same order at all
1201 : * the places such that lock parent, lock default partition and then
1202 : * lock the partition so as to avoid a deadlock.
1203 : */
1204 : defaultPartOid =
1205 6426 : get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
1206 : true));
1207 6426 : if (OidIsValid(defaultPartOid))
1208 251 : defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1209 :
1210 : /* Transform the bound values */
1211 6426 : pstate = make_parsestate(NULL);
1212 6426 : pstate->p_sourcetext = queryString;
1213 :
1214 : /*
1215 : * Add an nsitem containing this relation, so that transformExpr
1216 : * called on partition bound expressions is able to report errors
1217 : * using a proper context.
1218 : */
1219 6426 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1220 : NULL, false, false);
1221 6426 : addNSItemToQuery(pstate, nsitem, false, true, true);
1222 :
1223 6426 : bound = transformPartitionBound(pstate, parent, stmt->partbound);
1224 :
1225 : /*
1226 : * Check first that the new partition's bound is valid and does not
1227 : * overlap with any of existing partitions of the parent.
1228 : */
1229 6290 : check_new_partition_bound(relname, parent, bound, pstate);
1230 :
1231 : /*
1232 : * If the default partition exists, its partition constraints will
1233 : * change after the addition of this new partition such that it won't
1234 : * allow any row that qualifies for this new partition. So, check that
1235 : * the existing data in the default partition satisfies the constraint
1236 : * as it will exist after adding this partition.
1237 : */
1238 6214 : if (OidIsValid(defaultPartOid))
1239 : {
1240 231 : check_default_partition_contents(parent, defaultRel, bound);
1241 : /* Keep the lock until commit. */
1242 219 : table_close(defaultRel, NoLock);
1243 : }
1244 :
1245 : /* Update the pg_class entry. */
1246 6202 : StorePartitionBound(rel, parent, bound);
1247 :
1248 6202 : table_close(parent, NoLock);
1249 : }
1250 :
1251 : /* Store inheritance information for new rel. */
1252 41179 : StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1253 :
1254 : /*
1255 : * Process the partitioning specification (if any) and store the partition
1256 : * key information into the catalog.
1257 : */
1258 41179 : if (partitioned)
1259 : {
1260 : ParseState *pstate;
1261 : int partnatts;
1262 : AttrNumber partattrs[PARTITION_MAX_KEYS];
1263 : Oid partopclass[PARTITION_MAX_KEYS];
1264 : Oid partcollation[PARTITION_MAX_KEYS];
1265 3606 : List *partexprs = NIL;
1266 :
1267 3606 : pstate = make_parsestate(NULL);
1268 3606 : pstate->p_sourcetext = queryString;
1269 :
1270 3606 : partnatts = list_length(stmt->partspec->partParams);
1271 :
1272 : /* Protect fixed-size arrays here and in executor */
1273 3606 : if (partnatts > PARTITION_MAX_KEYS)
1274 0 : ereport(ERROR,
1275 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
1276 : errmsg("cannot partition using more than %d columns",
1277 : PARTITION_MAX_KEYS)));
1278 :
1279 : /*
1280 : * We need to transform the raw parsetrees corresponding to partition
1281 : * expressions into executable expression trees. Like column defaults
1282 : * and CHECK constraints, we could not have done the transformation
1283 : * earlier.
1284 : */
1285 3606 : stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1286 :
1287 3586 : ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1288 : partattrs, &partexprs, partopclass,
1289 3586 : partcollation, stmt->partspec->strategy);
1290 :
1291 3498 : StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1292 : partexprs,
1293 : partopclass, partcollation);
1294 :
1295 : /* make it all visible */
1296 3498 : CommandCounterIncrement();
1297 : }
1298 :
1299 : /*
1300 : * If we're creating a partition, create now all the indexes, triggers,
1301 : * FKs defined in the parent.
1302 : *
1303 : * We can't do it earlier, because DefineIndex wants to know the partition
1304 : * key which we just stored.
1305 : */
1306 41071 : if (stmt->partbound)
1307 : {
1308 6198 : Oid parentId = linitial_oid(inheritOids);
1309 : Relation parent;
1310 : List *idxlist;
1311 : ListCell *cell;
1312 :
1313 : /* Already have strong enough lock on the parent */
1314 6198 : parent = table_open(parentId, NoLock);
1315 6198 : idxlist = RelationGetIndexList(parent);
1316 :
1317 : /*
1318 : * For each index in the parent table, create one in the partition
1319 : */
1320 7291 : foreach(cell, idxlist)
1321 : {
1322 1105 : Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1323 : AttrMap *attmap;
1324 : IndexStmt *idxstmt;
1325 : Oid constraintOid;
1326 :
1327 1105 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1328 : {
1329 24 : if (idxRel->rd_index->indisunique)
1330 8 : ereport(ERROR,
1331 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1332 : errmsg("cannot create foreign partition of partitioned table \"%s\"",
1333 : RelationGetRelationName(parent)),
1334 : errdetail("Table \"%s\" contains indexes that are unique.",
1335 : RelationGetRelationName(parent))));
1336 : else
1337 : {
1338 16 : index_close(idxRel, AccessShareLock);
1339 16 : continue;
1340 : }
1341 : }
1342 :
1343 1081 : attmap = build_attrmap_by_name(RelationGetDescr(rel),
1344 : RelationGetDescr(parent),
1345 : false);
1346 : idxstmt =
1347 1081 : generateClonedIndexStmt(NULL, idxRel,
1348 : attmap, &constraintOid);
1349 1081 : DefineIndex(NULL,
1350 : RelationGetRelid(rel),
1351 : idxstmt,
1352 : InvalidOid,
1353 : RelationGetRelid(idxRel),
1354 : constraintOid,
1355 : -1,
1356 : false, false, false, false, false);
1357 :
1358 1077 : index_close(idxRel, AccessShareLock);
1359 : }
1360 :
1361 6186 : list_free(idxlist);
1362 :
1363 : /*
1364 : * If there are any row-level triggers, clone them to the new
1365 : * partition.
1366 : */
1367 6186 : if (parent->trigdesc != NULL)
1368 260 : CloneRowTriggersToPartition(parent, rel);
1369 :
1370 : /*
1371 : * And foreign keys too. Note that because we're freshly creating the
1372 : * table, there is no need to verify these new constraints.
1373 : */
1374 6186 : CloneForeignKeyConstraints(NULL, parent, rel);
1375 :
1376 6186 : table_close(parent, NoLock);
1377 : }
1378 :
1379 : /*
1380 : * Now add any newly specified CHECK constraints to the new relation. Same
1381 : * as for defaults above, but these need to come after partitioning is set
1382 : * up. We save the constraint names that were used, to avoid dupes below.
1383 : */
1384 41059 : if (stmt->constraints)
1385 : {
1386 : List *conlist;
1387 :
1388 498 : conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1389 : true, true, false, queryString);
1390 1509 : foreach_ptr(CookedConstraint, cons, conlist)
1391 : {
1392 553 : if (cons->name != NULL)
1393 553 : connames = lappend(connames, cons->name);
1394 : }
1395 : }
1396 :
1397 : /*
1398 : * Finally, merge the not-null constraints that are declared directly with
1399 : * those that come from parent relations (making sure to count inheritance
1400 : * appropriately for each), create them, and set the attnotnull flag on
1401 : * columns that don't yet have it.
1402 : */
1403 41039 : nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1404 : old_notnulls, connames);
1405 92209 : foreach_int(attrnum, nncols)
1406 10235 : set_attnotnull(NULL, rel, attrnum, true, false);
1407 :
1408 40987 : ObjectAddressSet(address, RelationRelationId, relationId);
1409 :
1410 : /*
1411 : * Clean up. We keep lock on new relation (although it shouldn't be
1412 : * visible to anyone else anyway, until commit).
1413 : */
1414 40987 : relation_close(rel, NoLock);
1415 :
1416 40987 : return address;
1417 : }
1418 :
1419 : /*
1420 : * BuildDescForRelation
1421 : *
1422 : * Given a list of ColumnDef nodes, build a TupleDesc.
1423 : *
1424 : * Note: This is only for the limited purpose of table and view creation. Not
1425 : * everything is filled in. A real tuple descriptor should be obtained from
1426 : * the relcache.
1427 : */
1428 : TupleDesc
1429 44252 : BuildDescForRelation(const List *columns)
1430 : {
1431 : int natts;
1432 : AttrNumber attnum;
1433 : ListCell *l;
1434 : TupleDesc desc;
1435 : char *attname;
1436 : Oid atttypid;
1437 : int32 atttypmod;
1438 : Oid attcollation;
1439 : int attdim;
1440 :
1441 : /*
1442 : * allocate a new tuple descriptor
1443 : */
1444 44252 : natts = list_length(columns);
1445 44252 : desc = CreateTemplateTupleDesc(natts);
1446 :
1447 44252 : attnum = 0;
1448 :
1449 214275 : foreach(l, columns)
1450 : {
1451 170063 : ColumnDef *entry = lfirst(l);
1452 : AclResult aclresult;
1453 : Form_pg_attribute att;
1454 :
1455 : /*
1456 : * for each entry in the list, get the name and type information from
1457 : * the list and have TupleDescInitEntry fill in the attribute
1458 : * information we need.
1459 : */
1460 170063 : attnum++;
1461 :
1462 170063 : attname = entry->colname;
1463 170063 : typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1464 :
1465 170063 : aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1466 170063 : if (aclresult != ACLCHECK_OK)
1467 28 : aclcheck_error_type(aclresult, atttypid);
1468 :
1469 170035 : attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1470 170035 : attdim = list_length(entry->typeName->arrayBounds);
1471 170035 : if (attdim > PG_INT16_MAX)
1472 0 : ereport(ERROR,
1473 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1474 : errmsg("too many array dimensions"));
1475 :
1476 170035 : if (entry->typeName->setof)
1477 0 : ereport(ERROR,
1478 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1479 : errmsg("column \"%s\" cannot be declared SETOF",
1480 : attname)));
1481 :
1482 170035 : TupleDescInitEntry(desc, attnum, attname,
1483 : atttypid, atttypmod, attdim);
1484 170035 : att = TupleDescAttr(desc, attnum - 1);
1485 :
1486 : /* Override TupleDescInitEntry's settings as requested */
1487 170035 : TupleDescInitEntryCollation(desc, attnum, attcollation);
1488 :
1489 : /* Fill in additional stuff not handled by TupleDescInitEntry */
1490 170035 : att->attnotnull = entry->is_not_null;
1491 170035 : att->attislocal = entry->is_local;
1492 170035 : att->attinhcount = entry->inhcount;
1493 170035 : att->attidentity = entry->identity;
1494 170035 : att->attgenerated = entry->generated;
1495 170035 : att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1496 170027 : if (entry->storage)
1497 16741 : att->attstorage = entry->storage;
1498 153286 : else if (entry->storage_name)
1499 39 : att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1500 :
1501 170023 : populate_compact_attribute(desc, attnum - 1);
1502 : }
1503 :
1504 44212 : TupleDescFinalize(desc);
1505 :
1506 44212 : return desc;
1507 : }
1508 :
1509 : /*
1510 : * Emit the right error or warning message for a "DROP" command issued on a
1511 : * non-existent relation
1512 : */
1513 : static void
1514 641 : DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
1515 : {
1516 : const struct dropmsgstrings *rentry;
1517 :
1518 721 : if (rel->schemaname != NULL &&
1519 80 : !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
1520 : {
1521 28 : if (!missing_ok)
1522 : {
1523 0 : ereport(ERROR,
1524 : (errcode(ERRCODE_UNDEFINED_SCHEMA),
1525 : errmsg("schema \"%s\" does not exist", rel->schemaname)));
1526 : }
1527 : else
1528 : {
1529 28 : ereport(NOTICE,
1530 : (errmsg("schema \"%s\" does not exist, skipping",
1531 : rel->schemaname)));
1532 : }
1533 28 : return;
1534 : }
1535 :
1536 898 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1537 : {
1538 898 : if (rentry->kind == rightkind)
1539 : {
1540 613 : if (!missing_ok)
1541 : {
1542 90 : ereport(ERROR,
1543 : (errcode(rentry->nonexistent_code),
1544 : errmsg(rentry->nonexistent_msg, rel->relname)));
1545 : }
1546 : else
1547 : {
1548 523 : ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
1549 523 : break;
1550 : }
1551 : }
1552 : }
1553 :
1554 : Assert(rentry->kind != '\0'); /* Should be impossible */
1555 : }
1556 :
1557 : /*
1558 : * Emit the right error message for a "DROP" command issued on a
1559 : * relation of the wrong type
1560 : */
1561 : static void
1562 4 : DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
1563 : {
1564 : const struct dropmsgstrings *rentry;
1565 : const struct dropmsgstrings *wentry;
1566 :
1567 4 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1568 4 : if (rentry->kind == rightkind)
1569 4 : break;
1570 : Assert(rentry->kind != '\0');
1571 :
1572 40 : for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
1573 40 : if (wentry->kind == wrongkind)
1574 4 : break;
1575 : /* wrongkind could be something we don't have in our table... */
1576 :
1577 4 : ereport(ERROR,
1578 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1579 : errmsg(rentry->nota_msg, relname),
1580 : (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
1581 : }
1582 :
1583 : /*
1584 : * RemoveRelations
1585 : * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
1586 : * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE, DROP PROPERTY GRAPH
1587 : */
1588 : void
1589 11699 : RemoveRelations(DropStmt *drop)
1590 : {
1591 : ObjectAddresses *objects;
1592 : char relkind;
1593 : ListCell *cell;
1594 11699 : int flags = 0;
1595 11699 : LOCKMODE lockmode = AccessExclusiveLock;
1596 :
1597 : /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1598 11699 : if (drop->concurrent)
1599 : {
1600 : /*
1601 : * Note that for temporary relations this lock may get upgraded later
1602 : * on, but as no other session can access a temporary relation, this
1603 : * is actually fine.
1604 : */
1605 95 : lockmode = ShareUpdateExclusiveLock;
1606 : Assert(drop->removeType == OBJECT_INDEX);
1607 95 : if (list_length(drop->objects) != 1)
1608 4 : ereport(ERROR,
1609 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1610 : errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1611 91 : if (drop->behavior == DROP_CASCADE)
1612 0 : ereport(ERROR,
1613 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1614 : errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1615 : }
1616 :
1617 : /*
1618 : * First we identify all the relations, then we delete them in a single
1619 : * performMultipleDeletions() call. This is to avoid unwanted DROP
1620 : * RESTRICT errors if one of the relations depends on another.
1621 : */
1622 :
1623 : /* Determine required relkind */
1624 11695 : switch (drop->removeType)
1625 : {
1626 10127 : case OBJECT_TABLE:
1627 10127 : relkind = RELKIND_RELATION;
1628 10127 : break;
1629 :
1630 541 : case OBJECT_INDEX:
1631 541 : relkind = RELKIND_INDEX;
1632 541 : break;
1633 :
1634 119 : case OBJECT_SEQUENCE:
1635 119 : relkind = RELKIND_SEQUENCE;
1636 119 : break;
1637 :
1638 672 : case OBJECT_VIEW:
1639 672 : relkind = RELKIND_VIEW;
1640 672 : break;
1641 :
1642 83 : case OBJECT_MATVIEW:
1643 83 : relkind = RELKIND_MATVIEW;
1644 83 : break;
1645 :
1646 107 : case OBJECT_FOREIGN_TABLE:
1647 107 : relkind = RELKIND_FOREIGN_TABLE;
1648 107 : break;
1649 :
1650 46 : case OBJECT_PROPGRAPH:
1651 46 : relkind = RELKIND_PROPGRAPH;
1652 46 : break;
1653 :
1654 0 : default:
1655 0 : elog(ERROR, "unrecognized drop object type: %d",
1656 : (int) drop->removeType);
1657 : relkind = 0; /* keep compiler quiet */
1658 : break;
1659 : }
1660 :
1661 : /* Lock and validate each relation; build a list of object addresses */
1662 11695 : objects = new_object_addresses();
1663 :
1664 25781 : foreach(cell, drop->objects)
1665 : {
1666 14197 : RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1667 : Oid relOid;
1668 : ObjectAddress obj;
1669 : struct DropRelationCallbackState state;
1670 :
1671 : /*
1672 : * These next few steps are a great deal like relation_openrv, but we
1673 : * don't bother building a relcache entry since we don't need it.
1674 : *
1675 : * Check for shared-cache-inval messages before trying to access the
1676 : * relation. This is needed to cover the case where the name
1677 : * identifies a rel that has been dropped and recreated since the
1678 : * start of our transaction: if we don't flush the old syscache entry,
1679 : * then we'll latch onto that entry and suffer an error later.
1680 : */
1681 14197 : AcceptInvalidationMessages();
1682 :
1683 : /* Look up the appropriate relation using namespace search. */
1684 14197 : state.expected_relkind = relkind;
1685 28394 : state.heap_lockmode = drop->concurrent ?
1686 14197 : ShareUpdateExclusiveLock : AccessExclusiveLock;
1687 : /* We must initialize these fields to show that no locks are held: */
1688 14197 : state.heapOid = InvalidOid;
1689 14197 : state.partParentOid = InvalidOid;
1690 :
1691 14197 : relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1692 : RangeVarCallbackForDropRelation,
1693 : &state);
1694 :
1695 : /* Not there? */
1696 14180 : if (!OidIsValid(relOid))
1697 : {
1698 641 : DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1699 551 : continue;
1700 : }
1701 :
1702 : /*
1703 : * Decide if concurrent mode needs to be used here or not. The
1704 : * callback retrieved the rel's persistence for us.
1705 : */
1706 13539 : if (drop->concurrent &&
1707 87 : state.actual_relpersistence != RELPERSISTENCE_TEMP)
1708 : {
1709 : Assert(list_length(drop->objects) == 1 &&
1710 : drop->removeType == OBJECT_INDEX);
1711 75 : flags |= PERFORM_DELETION_CONCURRENTLY;
1712 : }
1713 :
1714 : /*
1715 : * Concurrent index drop cannot be used with partitioned indexes,
1716 : * either.
1717 : */
1718 13539 : if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1719 75 : state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1720 4 : ereport(ERROR,
1721 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1722 : errmsg("cannot drop partitioned index \"%s\" concurrently",
1723 : rel->relname)));
1724 :
1725 : /*
1726 : * If we're told to drop a partitioned index, we must acquire lock on
1727 : * all the children of its parent partitioned table before proceeding.
1728 : * Otherwise we'd try to lock the child index partitions before their
1729 : * tables, leading to potential deadlock against other sessions that
1730 : * will lock those objects in the other order.
1731 : */
1732 13535 : if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1733 50 : (void) find_all_inheritors(state.heapOid,
1734 : state.heap_lockmode,
1735 : NULL);
1736 :
1737 : /* OK, we're ready to delete this one */
1738 13535 : obj.classId = RelationRelationId;
1739 13535 : obj.objectId = relOid;
1740 13535 : obj.objectSubId = 0;
1741 :
1742 13535 : add_exact_object_address(&obj, objects);
1743 : }
1744 :
1745 11584 : performMultipleDeletions(objects, drop->behavior, flags);
1746 :
1747 11481 : free_object_addresses(objects);
1748 11481 : }
1749 :
1750 : /*
1751 : * Before acquiring a table lock, check whether we have sufficient rights.
1752 : * In the case of DROP INDEX, also try to lock the table before the index.
1753 : * Also, if the table to be dropped is a partition, we try to lock the parent
1754 : * first.
1755 : */
1756 : static void
1757 14436 : RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
1758 : void *arg)
1759 : {
1760 : HeapTuple tuple;
1761 : struct DropRelationCallbackState *state;
1762 : char expected_relkind;
1763 : bool is_partition;
1764 : Form_pg_class classform;
1765 : LOCKMODE heap_lockmode;
1766 14436 : bool invalid_system_index = false;
1767 :
1768 14436 : state = (struct DropRelationCallbackState *) arg;
1769 14436 : heap_lockmode = state->heap_lockmode;
1770 :
1771 : /*
1772 : * If we previously locked some other index's heap, and the name we're
1773 : * looking up no longer refers to that relation, release the now-useless
1774 : * lock.
1775 : */
1776 14436 : if (relOid != oldRelOid && OidIsValid(state->heapOid))
1777 : {
1778 0 : UnlockRelationOid(state->heapOid, heap_lockmode);
1779 0 : state->heapOid = InvalidOid;
1780 : }
1781 :
1782 : /*
1783 : * Similarly, if we previously locked some other partition's heap, and the
1784 : * name we're looking up no longer refers to that relation, release the
1785 : * now-useless lock.
1786 : */
1787 14436 : if (relOid != oldRelOid && OidIsValid(state->partParentOid))
1788 : {
1789 0 : UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
1790 0 : state->partParentOid = InvalidOid;
1791 : }
1792 :
1793 : /* Didn't find a relation, so no need for locking or permission checks. */
1794 14436 : if (!OidIsValid(relOid))
1795 645 : return;
1796 :
1797 13791 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1798 13791 : if (!HeapTupleIsValid(tuple))
1799 0 : return; /* concurrently dropped, so nothing to do */
1800 13791 : classform = (Form_pg_class) GETSTRUCT(tuple);
1801 13791 : is_partition = classform->relispartition;
1802 :
1803 : /* Pass back some data to save lookups in RemoveRelations */
1804 13791 : state->actual_relkind = classform->relkind;
1805 13791 : state->actual_relpersistence = classform->relpersistence;
1806 :
1807 : /*
1808 : * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
1809 : * but RemoveRelations() can only pass one relkind for a given relation.
1810 : * It chooses RELKIND_RELATION for both regular and partitioned tables.
1811 : * That means we must be careful before giving the wrong type error when
1812 : * the relation is RELKIND_PARTITIONED_TABLE. An equivalent problem
1813 : * exists with indexes.
1814 : */
1815 13791 : if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1816 2232 : expected_relkind = RELKIND_RELATION;
1817 11559 : else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1818 55 : expected_relkind = RELKIND_INDEX;
1819 : else
1820 11504 : expected_relkind = classform->relkind;
1821 :
1822 13791 : if (state->expected_relkind != expected_relkind)
1823 4 : DropErrorMsgWrongType(rel->relname, classform->relkind,
1824 4 : state->expected_relkind);
1825 :
1826 : /* Allow DROP to either table owner or schema owner */
1827 13787 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
1828 12 : !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
1829 12 : aclcheck_error(ACLCHECK_NOT_OWNER,
1830 12 : get_relkind_objtype(classform->relkind),
1831 12 : rel->relname);
1832 :
1833 : /*
1834 : * Check the case of a system index that might have been invalidated by a
1835 : * failed concurrent process and allow its drop. For the time being, this
1836 : * only concerns indexes of toast relations that became invalid during a
1837 : * REINDEX CONCURRENTLY process.
1838 : */
1839 13775 : if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
1840 : {
1841 : HeapTuple locTuple;
1842 : Form_pg_index indexform;
1843 : bool indisvalid;
1844 :
1845 0 : locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
1846 0 : if (!HeapTupleIsValid(locTuple))
1847 : {
1848 0 : ReleaseSysCache(tuple);
1849 0 : return;
1850 : }
1851 :
1852 0 : indexform = (Form_pg_index) GETSTRUCT(locTuple);
1853 0 : indisvalid = indexform->indisvalid;
1854 0 : ReleaseSysCache(locTuple);
1855 :
1856 : /* Mark object as being an invalid index of system catalogs */
1857 0 : if (!indisvalid)
1858 0 : invalid_system_index = true;
1859 : }
1860 :
1861 : /* In the case of an invalid index, it is fine to bypass this check */
1862 13775 : if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
1863 1 : ereport(ERROR,
1864 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1865 : errmsg("permission denied: \"%s\" is a system catalog",
1866 : rel->relname)));
1867 :
1868 13774 : ReleaseSysCache(tuple);
1869 :
1870 : /*
1871 : * In DROP INDEX, attempt to acquire lock on the parent table before
1872 : * locking the index. index_drop() will need this anyway, and since
1873 : * regular queries lock tables before their indexes, we risk deadlock if
1874 : * we do it the other way around. No error if we don't find a pg_index
1875 : * entry, though --- the relation may have been dropped. Note that this
1876 : * code will execute for either plain or partitioned indexes.
1877 : */
1878 13774 : if (expected_relkind == RELKIND_INDEX &&
1879 : relOid != oldRelOid)
1880 : {
1881 533 : state->heapOid = IndexGetRelation(relOid, true);
1882 533 : if (OidIsValid(state->heapOid))
1883 533 : LockRelationOid(state->heapOid, heap_lockmode);
1884 : }
1885 :
1886 : /*
1887 : * Similarly, if the relation is a partition, we must acquire lock on its
1888 : * parent before locking the partition. That's because queries lock the
1889 : * parent before its partitions, so we risk deadlock if we do it the other
1890 : * way around.
1891 : */
1892 13774 : if (is_partition && relOid != oldRelOid)
1893 : {
1894 397 : state->partParentOid = get_partition_parent(relOid, true);
1895 397 : if (OidIsValid(state->partParentOid))
1896 397 : LockRelationOid(state->partParentOid, AccessExclusiveLock);
1897 : }
1898 : }
1899 :
1900 : /*
1901 : * ExecuteTruncate
1902 : * Executes a TRUNCATE command.
1903 : *
1904 : * This is a multi-relation truncate. We first open and grab exclusive
1905 : * lock on all relations involved, checking permissions and otherwise
1906 : * verifying that the relation is OK for truncation. Note that if relations
1907 : * are foreign tables, at this stage, we have not yet checked that their
1908 : * foreign data in external data sources are OK for truncation. These are
1909 : * checked when foreign data are actually truncated later. In CASCADE mode,
1910 : * relations having FK references to the targeted relations are automatically
1911 : * added to the group; in RESTRICT mode, we check that all FK references are
1912 : * internal to the group that's being truncated. Finally all the relations
1913 : * are truncated and reindexed.
1914 : */
1915 : void
1916 1154 : ExecuteTruncate(TruncateStmt *stmt)
1917 : {
1918 1154 : List *rels = NIL;
1919 1154 : List *relids = NIL;
1920 1154 : List *relids_logged = NIL;
1921 : ListCell *cell;
1922 :
1923 : /*
1924 : * Open, exclusive-lock, and check all the explicitly-specified relations
1925 : */
1926 2456 : foreach(cell, stmt->relations)
1927 : {
1928 1338 : RangeVar *rv = lfirst(cell);
1929 : Relation rel;
1930 1338 : bool recurse = rv->inh;
1931 : Oid myrelid;
1932 1338 : LOCKMODE lockmode = AccessExclusiveLock;
1933 :
1934 1338 : myrelid = RangeVarGetRelidExtended(rv, lockmode,
1935 : 0, RangeVarCallbackForTruncate,
1936 : NULL);
1937 :
1938 : /* don't throw error for "TRUNCATE foo, foo" */
1939 1315 : if (list_member_oid(relids, myrelid))
1940 1 : continue;
1941 :
1942 : /* open the relation, we already hold a lock on it */
1943 1314 : rel = table_open(myrelid, NoLock);
1944 :
1945 : /*
1946 : * RangeVarGetRelidExtended() has done most checks with its callback,
1947 : * but other checks with the now-opened Relation remain.
1948 : */
1949 1314 : truncate_check_activity(rel);
1950 :
1951 1309 : rels = lappend(rels, rel);
1952 1309 : relids = lappend_oid(relids, myrelid);
1953 :
1954 : /* Log this relation only if needed for logical decoding */
1955 1309 : if (RelationIsLogicallyLogged(rel))
1956 39 : relids_logged = lappend_oid(relids_logged, myrelid);
1957 :
1958 1309 : if (recurse)
1959 : {
1960 : ListCell *child;
1961 : List *children;
1962 :
1963 1273 : children = find_all_inheritors(myrelid, lockmode, NULL);
1964 :
1965 3766 : foreach(child, children)
1966 : {
1967 2493 : Oid childrelid = lfirst_oid(child);
1968 :
1969 2493 : if (list_member_oid(relids, childrelid))
1970 1273 : continue;
1971 :
1972 : /* find_all_inheritors already got lock */
1973 1220 : rel = table_open(childrelid, NoLock);
1974 :
1975 : /*
1976 : * It is possible that the parent table has children that are
1977 : * temp tables of other backends. We cannot safely access
1978 : * such tables (because of buffering issues), and the best
1979 : * thing to do is to silently ignore them. Note that this
1980 : * check is the same as one of the checks done in
1981 : * truncate_check_activity() called below, still it is kept
1982 : * here for simplicity.
1983 : */
1984 1220 : if (RELATION_IS_OTHER_TEMP(rel))
1985 : {
1986 4 : table_close(rel, lockmode);
1987 4 : continue;
1988 : }
1989 :
1990 : /*
1991 : * Inherited TRUNCATE commands perform access permission
1992 : * checks on the parent table only. So we skip checking the
1993 : * children's permissions and don't call
1994 : * truncate_check_perms() here.
1995 : */
1996 1216 : truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
1997 1216 : truncate_check_activity(rel);
1998 :
1999 1216 : rels = lappend(rels, rel);
2000 1216 : relids = lappend_oid(relids, childrelid);
2001 :
2002 : /* Log this relation only if needed for logical decoding */
2003 1216 : if (RelationIsLogicallyLogged(rel))
2004 11 : relids_logged = lappend_oid(relids_logged, childrelid);
2005 : }
2006 : }
2007 36 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2008 8 : ereport(ERROR,
2009 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2010 : errmsg("cannot truncate only a partitioned table"),
2011 : errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
2012 : }
2013 :
2014 1118 : ExecuteTruncateGuts(rels, relids, relids_logged,
2015 1118 : stmt->behavior, stmt->restart_seqs, false);
2016 :
2017 : /* And close the rels */
2018 3481 : foreach(cell, rels)
2019 : {
2020 2416 : Relation rel = (Relation) lfirst(cell);
2021 :
2022 2416 : table_close(rel, NoLock);
2023 : }
2024 1065 : }
2025 :
2026 : /*
2027 : * ExecuteTruncateGuts
2028 : *
2029 : * Internal implementation of TRUNCATE. This is called by the actual TRUNCATE
2030 : * command (see above) as well as replication subscribers that execute a
2031 : * replicated TRUNCATE action.
2032 : *
2033 : * explicit_rels is the list of Relations to truncate that the command
2034 : * specified. relids is the list of Oids corresponding to explicit_rels.
2035 : * relids_logged is the list of Oids (a subset of relids) that require
2036 : * WAL-logging. This is all a bit redundant, but the existing callers have
2037 : * this information handy in this form.
2038 : */
2039 : void
2040 1138 : ExecuteTruncateGuts(List *explicit_rels,
2041 : List *relids,
2042 : List *relids_logged,
2043 : DropBehavior behavior, bool restart_seqs,
2044 : bool run_as_table_owner)
2045 : {
2046 : List *rels;
2047 1138 : List *seq_relids = NIL;
2048 1138 : HTAB *ft_htab = NULL;
2049 : EState *estate;
2050 : ResultRelInfo *resultRelInfos;
2051 : ResultRelInfo *resultRelInfo;
2052 : SubTransactionId mySubid;
2053 : ListCell *cell;
2054 : Oid *logrelids;
2055 :
2056 : /*
2057 : * Check the explicitly-specified relations.
2058 : *
2059 : * In CASCADE mode, suck in all referencing relations as well. This
2060 : * requires multiple iterations to find indirectly-dependent relations. At
2061 : * each phase, we need to exclusive-lock new rels before looking for their
2062 : * dependencies, else we might miss something. Also, we check each rel as
2063 : * soon as we open it, to avoid a faux pas such as holding lock for a long
2064 : * time on a rel we have no permissions for.
2065 : */
2066 1138 : rels = list_copy(explicit_rels);
2067 1138 : if (behavior == DROP_CASCADE)
2068 : {
2069 : for (;;)
2070 26 : {
2071 : List *newrelids;
2072 :
2073 51 : newrelids = heap_truncate_find_FKs(relids);
2074 51 : if (newrelids == NIL)
2075 25 : break; /* nothing else to add */
2076 :
2077 88 : foreach(cell, newrelids)
2078 : {
2079 62 : Oid relid = lfirst_oid(cell);
2080 : Relation rel;
2081 :
2082 62 : rel = table_open(relid, AccessExclusiveLock);
2083 62 : ereport(NOTICE,
2084 : (errmsg("truncate cascades to table \"%s\"",
2085 : RelationGetRelationName(rel))));
2086 62 : truncate_check_rel(relid, rel->rd_rel);
2087 62 : truncate_check_perms(relid, rel->rd_rel);
2088 62 : truncate_check_activity(rel);
2089 62 : rels = lappend(rels, rel);
2090 62 : relids = lappend_oid(relids, relid);
2091 :
2092 : /* Log this relation only if needed for logical decoding */
2093 62 : if (RelationIsLogicallyLogged(rel))
2094 0 : relids_logged = lappend_oid(relids_logged, relid);
2095 : }
2096 : }
2097 : }
2098 :
2099 : /*
2100 : * Check foreign key references. In CASCADE mode, this should be
2101 : * unnecessary since we just pulled in all the references; but as a
2102 : * cross-check, do it anyway if in an Assert-enabled build.
2103 : */
2104 : #ifdef USE_ASSERT_CHECKING
2105 : heap_truncate_check_FKs(rels, false);
2106 : #else
2107 1138 : if (behavior == DROP_RESTRICT)
2108 1113 : heap_truncate_check_FKs(rels, false);
2109 : #endif
2110 :
2111 : /*
2112 : * If we are asked to restart sequences, find all the sequences, lock them
2113 : * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2114 : * We want to do this early since it's pointless to do all the truncation
2115 : * work only to fail on sequence permissions.
2116 : */
2117 1089 : if (restart_seqs)
2118 : {
2119 32 : foreach(cell, rels)
2120 : {
2121 16 : Relation rel = (Relation) lfirst(cell);
2122 16 : List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2123 : ListCell *seqcell;
2124 :
2125 39 : foreach(seqcell, seqlist)
2126 : {
2127 23 : Oid seq_relid = lfirst_oid(seqcell);
2128 : Relation seq_rel;
2129 :
2130 23 : seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2131 :
2132 : /* This check must match AlterSequence! */
2133 23 : if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2134 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
2135 0 : RelationGetRelationName(seq_rel));
2136 :
2137 23 : seq_relids = lappend_oid(seq_relids, seq_relid);
2138 :
2139 23 : relation_close(seq_rel, NoLock);
2140 : }
2141 : }
2142 : }
2143 :
2144 : /* Prepare to catch AFTER triggers. */
2145 1089 : AfterTriggerBeginQuery();
2146 :
2147 : /*
2148 : * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2149 : * each relation. We don't need to call ExecOpenIndices, though.
2150 : *
2151 : * We put the ResultRelInfos in the es_opened_result_relations list, even
2152 : * though we don't have a range table and don't populate the
2153 : * es_result_relations array. That's a bit bogus, but it's enough to make
2154 : * ExecGetTriggerResultRel() find them.
2155 : */
2156 1089 : estate = CreateExecutorState();
2157 : resultRelInfos = (ResultRelInfo *)
2158 1089 : palloc(list_length(rels) * sizeof(ResultRelInfo));
2159 1089 : resultRelInfo = resultRelInfos;
2160 3607 : foreach(cell, rels)
2161 : {
2162 2518 : Relation rel = (Relation) lfirst(cell);
2163 :
2164 2518 : InitResultRelInfo(resultRelInfo,
2165 : rel,
2166 : 0, /* dummy rangetable index */
2167 : NULL,
2168 : 0);
2169 2518 : estate->es_opened_result_relations =
2170 2518 : lappend(estate->es_opened_result_relations, resultRelInfo);
2171 2518 : resultRelInfo++;
2172 : }
2173 :
2174 : /*
2175 : * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2176 : * truncating (this is because one of them might throw an error). Also, if
2177 : * we were to allow them to prevent statement execution, that would need
2178 : * to be handled here.
2179 : */
2180 1089 : resultRelInfo = resultRelInfos;
2181 3607 : foreach(cell, rels)
2182 : {
2183 : UserContext ucxt;
2184 :
2185 2518 : if (run_as_table_owner)
2186 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2187 : &ucxt);
2188 2518 : ExecBSTruncateTriggers(estate, resultRelInfo);
2189 2518 : if (run_as_table_owner)
2190 36 : RestoreUserContext(&ucxt);
2191 2518 : resultRelInfo++;
2192 : }
2193 :
2194 : /*
2195 : * OK, truncate each table.
2196 : */
2197 1089 : mySubid = GetCurrentSubTransactionId();
2198 :
2199 3607 : foreach(cell, rels)
2200 : {
2201 2518 : Relation rel = (Relation) lfirst(cell);
2202 :
2203 : /* Skip partitioned tables as there is nothing to do */
2204 2518 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2205 477 : continue;
2206 :
2207 : /*
2208 : * Build the lists of foreign tables belonging to each foreign server
2209 : * and pass each list to the foreign data wrapper's callback function,
2210 : * so that each server can truncate its all foreign tables in bulk.
2211 : * Each list is saved as a single entry in a hash table that uses the
2212 : * server OID as lookup key.
2213 : */
2214 2041 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2215 17 : {
2216 17 : Oid serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
2217 : bool found;
2218 : ForeignTruncateInfo *ft_info;
2219 :
2220 : /* First time through, initialize hashtable for foreign tables */
2221 17 : if (!ft_htab)
2222 : {
2223 : HASHCTL hctl;
2224 :
2225 15 : memset(&hctl, 0, sizeof(HASHCTL));
2226 15 : hctl.keysize = sizeof(Oid);
2227 15 : hctl.entrysize = sizeof(ForeignTruncateInfo);
2228 15 : hctl.hcxt = CurrentMemoryContext;
2229 :
2230 15 : ft_htab = hash_create("TRUNCATE for Foreign Tables",
2231 : 32, /* start small and extend */
2232 : &hctl,
2233 : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2234 : }
2235 :
2236 : /* Find or create cached entry for the foreign table */
2237 17 : ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2238 17 : if (!found)
2239 15 : ft_info->rels = NIL;
2240 :
2241 : /*
2242 : * Save the foreign table in the entry of the server that the
2243 : * foreign table belongs to.
2244 : */
2245 17 : ft_info->rels = lappend(ft_info->rels, rel);
2246 17 : continue;
2247 : }
2248 :
2249 : /*
2250 : * Normally, we need a transaction-safe truncation here. However, if
2251 : * the table was either created in the current (sub)transaction or has
2252 : * a new relfilenumber in the current (sub)transaction, then we can
2253 : * just truncate it in-place, because a rollback would cause the whole
2254 : * table or the current physical file to be thrown away anyway.
2255 : */
2256 2024 : if (rel->rd_createSubid == mySubid ||
2257 2009 : rel->rd_newRelfilelocatorSubid == mySubid)
2258 : {
2259 : /* Immediate, non-rollbackable truncation is OK */
2260 47 : heap_truncate_one_rel(rel);
2261 : }
2262 : else
2263 : {
2264 : Oid heap_relid;
2265 : Oid toast_relid;
2266 1977 : ReindexParams reindex_params = {0};
2267 :
2268 : /*
2269 : * This effectively deletes all rows in the table, and may be done
2270 : * in a serializable transaction. In that case we must record a
2271 : * rw-conflict in to this transaction from each transaction
2272 : * holding a predicate lock on the table.
2273 : */
2274 1977 : CheckTableForSerializableConflictIn(rel);
2275 :
2276 : /*
2277 : * Need the full transaction-safe pushups.
2278 : *
2279 : * Create a new empty storage file for the relation, and assign it
2280 : * as the relfilenumber value. The old storage file is scheduled
2281 : * for deletion at commit.
2282 : */
2283 1977 : RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2284 :
2285 1977 : heap_relid = RelationGetRelid(rel);
2286 :
2287 : /*
2288 : * The same for the toast table, if any.
2289 : */
2290 1977 : toast_relid = rel->rd_rel->reltoastrelid;
2291 1977 : if (OidIsValid(toast_relid))
2292 : {
2293 1193 : Relation toastrel = relation_open(toast_relid,
2294 : AccessExclusiveLock);
2295 :
2296 1193 : RelationSetNewRelfilenumber(toastrel,
2297 1193 : toastrel->rd_rel->relpersistence);
2298 1193 : table_close(toastrel, NoLock);
2299 : }
2300 :
2301 : /*
2302 : * Reconstruct the indexes to match, and we're done.
2303 : */
2304 1977 : reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2305 : &reindex_params);
2306 : }
2307 :
2308 2024 : pgstat_count_truncate(rel);
2309 : }
2310 :
2311 : /* Now go through the hash table, and truncate foreign tables */
2312 1089 : if (ft_htab)
2313 : {
2314 : ForeignTruncateInfo *ft_info;
2315 : HASH_SEQ_STATUS seq;
2316 :
2317 15 : hash_seq_init(&seq, ft_htab);
2318 :
2319 15 : PG_TRY();
2320 : {
2321 26 : while ((ft_info = hash_seq_search(&seq)) != NULL)
2322 : {
2323 15 : FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2324 :
2325 : /* truncate_check_rel() has checked that already */
2326 : Assert(routine->ExecForeignTruncate != NULL);
2327 :
2328 15 : routine->ExecForeignTruncate(ft_info->rels,
2329 : behavior,
2330 : restart_seqs);
2331 : }
2332 : }
2333 4 : PG_FINALLY();
2334 : {
2335 15 : hash_destroy(ft_htab);
2336 : }
2337 15 : PG_END_TRY();
2338 : }
2339 :
2340 : /*
2341 : * Restart owned sequences if we were asked to.
2342 : */
2343 1108 : foreach(cell, seq_relids)
2344 : {
2345 23 : Oid seq_relid = lfirst_oid(cell);
2346 :
2347 23 : ResetSequence(seq_relid);
2348 : }
2349 :
2350 : /*
2351 : * Write a WAL record to allow this set of actions to be logically
2352 : * decoded.
2353 : *
2354 : * Assemble an array of relids so we can write a single WAL record for the
2355 : * whole action.
2356 : */
2357 1085 : if (relids_logged != NIL)
2358 : {
2359 : xl_heap_truncate xlrec;
2360 33 : int i = 0;
2361 :
2362 : /* should only get here if effective_wal_level is 'logical' */
2363 : Assert(XLogLogicalInfoActive());
2364 :
2365 33 : logrelids = palloc(list_length(relids_logged) * sizeof(Oid));
2366 84 : foreach(cell, relids_logged)
2367 51 : logrelids[i++] = lfirst_oid(cell);
2368 :
2369 33 : xlrec.dbId = MyDatabaseId;
2370 33 : xlrec.nrelids = list_length(relids_logged);
2371 33 : xlrec.flags = 0;
2372 33 : if (behavior == DROP_CASCADE)
2373 1 : xlrec.flags |= XLH_TRUNCATE_CASCADE;
2374 33 : if (restart_seqs)
2375 2 : xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
2376 :
2377 33 : XLogBeginInsert();
2378 33 : XLogRegisterData(&xlrec, SizeOfHeapTruncate);
2379 33 : XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
2380 :
2381 33 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2382 :
2383 33 : (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2384 : }
2385 :
2386 : /*
2387 : * Process all AFTER STATEMENT TRUNCATE triggers.
2388 : */
2389 1085 : resultRelInfo = resultRelInfos;
2390 3599 : foreach(cell, rels)
2391 : {
2392 : UserContext ucxt;
2393 :
2394 2514 : if (run_as_table_owner)
2395 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2396 : &ucxt);
2397 2514 : ExecASTruncateTriggers(estate, resultRelInfo);
2398 2514 : if (run_as_table_owner)
2399 36 : RestoreUserContext(&ucxt);
2400 2514 : resultRelInfo++;
2401 : }
2402 :
2403 : /* Handle queued AFTER triggers */
2404 1085 : AfterTriggerEndQuery(estate);
2405 :
2406 : /* We can clean up the EState now */
2407 1085 : FreeExecutorState(estate);
2408 :
2409 : /*
2410 : * Close any rels opened by CASCADE (can't do this while EState still
2411 : * holds refs)
2412 : */
2413 1085 : rels = list_difference_ptr(rels, explicit_rels);
2414 1147 : foreach(cell, rels)
2415 : {
2416 62 : Relation rel = (Relation) lfirst(cell);
2417 :
2418 62 : table_close(rel, NoLock);
2419 : }
2420 1085 : }
2421 :
2422 : /*
2423 : * Check that a given relation is safe to truncate. Subroutine for
2424 : * ExecuteTruncate() and RangeVarCallbackForTruncate().
2425 : */
2426 : static void
2427 2694 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
2428 : {
2429 2694 : char *relname = NameStr(reltuple->relname);
2430 :
2431 : /*
2432 : * Only allow truncate on regular tables, foreign tables using foreign
2433 : * data wrappers supporting TRUNCATE and partitioned tables (although, the
2434 : * latter are only being included here for the following checks; no
2435 : * physical truncation will occur in their case.).
2436 : */
2437 2694 : if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
2438 : {
2439 19 : Oid serverid = GetForeignServerIdByRelId(relid);
2440 19 : FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
2441 :
2442 18 : if (!fdwroutine->ExecForeignTruncate)
2443 1 : ereport(ERROR,
2444 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2445 : errmsg("cannot truncate foreign table \"%s\"",
2446 : relname)));
2447 : }
2448 2675 : else if (reltuple->relkind != RELKIND_RELATION &&
2449 488 : reltuple->relkind != RELKIND_PARTITIONED_TABLE)
2450 0 : ereport(ERROR,
2451 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2452 : errmsg("\"%s\" is not a table", relname)));
2453 :
2454 : /*
2455 : * Most system catalogs can't be truncated at all, or at least not unless
2456 : * allow_system_table_mods=on. As an exception, however, we allow
2457 : * pg_largeobject and pg_largeobject_metadata to be truncated as part of
2458 : * pg_upgrade, because we need to change its relfilenode to match the old
2459 : * cluster, and allowing a TRUNCATE command to be executed is the easiest
2460 : * way of doing that.
2461 : */
2462 2692 : if (!allowSystemTableMods && IsSystemClass(relid, reltuple)
2463 65 : && (!IsBinaryUpgrade ||
2464 32 : (relid != LargeObjectRelationId &&
2465 : relid != LargeObjectMetadataRelationId)))
2466 1 : ereport(ERROR,
2467 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2468 : errmsg("permission denied: \"%s\" is a system catalog",
2469 : relname)));
2470 :
2471 2691 : InvokeObjectTruncateHook(relid);
2472 2691 : }
2473 :
2474 : /*
2475 : * Check that current user has the permission to truncate given relation.
2476 : */
2477 : static void
2478 1475 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
2479 : {
2480 1475 : char *relname = NameStr(reltuple->relname);
2481 : AclResult aclresult;
2482 :
2483 : /* Permissions checks */
2484 1475 : aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2485 1475 : if (aclresult != ACLCHECK_OK)
2486 20 : aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2487 : relname);
2488 1455 : }
2489 :
2490 : /*
2491 : * Set of extra sanity checks to check if a given relation is safe to
2492 : * truncate. This is split with truncate_check_rel() as
2493 : * RangeVarCallbackForTruncate() cannot open a Relation yet.
2494 : */
2495 : static void
2496 2592 : truncate_check_activity(Relation rel)
2497 : {
2498 : /*
2499 : * Don't allow truncate on temp tables of other backends ... their local
2500 : * buffer manager is not going to cope.
2501 : */
2502 2592 : if (RELATION_IS_OTHER_TEMP(rel))
2503 1 : ereport(ERROR,
2504 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2505 : errmsg("cannot truncate temporary tables of other sessions")));
2506 :
2507 : /*
2508 : * Also check for active uses of the relation in the current transaction,
2509 : * including open scans and pending AFTER trigger events.
2510 : */
2511 2591 : CheckTableNotInUse(rel, "TRUNCATE");
2512 2587 : }
2513 :
2514 : /*
2515 : * storage_name
2516 : * returns the name corresponding to a typstorage/attstorage enum value
2517 : */
2518 : static const char *
2519 16 : storage_name(char c)
2520 : {
2521 16 : switch (c)
2522 : {
2523 0 : case TYPSTORAGE_PLAIN:
2524 0 : return "PLAIN";
2525 0 : case TYPSTORAGE_EXTERNAL:
2526 0 : return "EXTERNAL";
2527 8 : case TYPSTORAGE_EXTENDED:
2528 8 : return "EXTENDED";
2529 8 : case TYPSTORAGE_MAIN:
2530 8 : return "MAIN";
2531 0 : default:
2532 0 : return "???";
2533 : }
2534 : }
2535 :
2536 : /*----------
2537 : * MergeAttributes
2538 : * Returns new schema given initial schema and superclasses.
2539 : *
2540 : * Input arguments:
2541 : * 'columns' is the column/attribute definition for the table. (It's a list
2542 : * of ColumnDef's.) It is destructively changed.
2543 : * 'supers' is a list of OIDs of parent relations, already locked by caller.
2544 : * 'relpersistence' is the persistence type of the table.
2545 : * 'is_partition' tells if the table is a partition.
2546 : *
2547 : * Output arguments:
2548 : * 'supconstr' receives a list of CookedConstraint representing
2549 : * CHECK constraints belonging to parent relations, updated as
2550 : * necessary to be valid for the child.
2551 : * 'supnotnulls' receives a list of CookedConstraint representing
2552 : * not-null constraints based on those from parent relations.
2553 : *
2554 : * Return value:
2555 : * Completed schema list.
2556 : *
2557 : * Notes:
2558 : * The order in which the attributes are inherited is very important.
2559 : * Intuitively, the inherited attributes should come first. If a table
2560 : * inherits from multiple parents, the order of those attributes are
2561 : * according to the order of the parents specified in CREATE TABLE.
2562 : *
2563 : * Here's an example:
2564 : *
2565 : * create table person (name text, age int4, location point);
2566 : * create table emp (salary int4, manager text) inherits(person);
2567 : * create table student (gpa float8) inherits (person);
2568 : * create table stud_emp (percent int4) inherits (emp, student);
2569 : *
2570 : * The order of the attributes of stud_emp is:
2571 : *
2572 : * person {1:name, 2:age, 3:location}
2573 : * / \
2574 : * {6:gpa} student emp {4:salary, 5:manager}
2575 : * \ /
2576 : * stud_emp {7:percent}
2577 : *
2578 : * If the same attribute name appears multiple times, then it appears
2579 : * in the result table in the proper location for its first appearance.
2580 : *
2581 : * Constraints (including not-null constraints) for the child table
2582 : * are the union of all relevant constraints, from both the child schema
2583 : * and parent tables. In addition, in legacy inheritance, each column that
2584 : * appears in a primary key in any of the parents also gets a NOT NULL
2585 : * constraint (partitioning doesn't need this, because the PK itself gets
2586 : * inherited.)
2587 : *
2588 : * The default value for a child column is defined as:
2589 : * (1) If the child schema specifies a default, that value is used.
2590 : * (2) If neither the child nor any parent specifies a default, then
2591 : * the column will not have a default.
2592 : * (3) If conflicting defaults are inherited from different parents
2593 : * (and not overridden by the child), an error is raised.
2594 : * (4) Otherwise the inherited default is used.
2595 : *
2596 : * Note that the default-value infrastructure is used for generated
2597 : * columns' expressions too, so most of the preceding paragraph applies
2598 : * to generation expressions too. We insist that a child column be
2599 : * generated if and only if its parent(s) are, but it need not have
2600 : * the same generation expression.
2601 : *----------
2602 : */
2603 : static List *
2604 41783 : MergeAttributes(List *columns, const List *supers, char relpersistence,
2605 : bool is_partition, List **supconstr, List **supnotnulls)
2606 : {
2607 41783 : List *inh_columns = NIL;
2608 41783 : List *constraints = NIL;
2609 41783 : List *nnconstraints = NIL;
2610 41783 : bool have_bogus_defaults = false;
2611 : int child_attno;
2612 : static Node bogus_marker = {0}; /* marks conflicting defaults */
2613 41783 : List *saved_columns = NIL;
2614 : ListCell *lc;
2615 :
2616 : /*
2617 : * Check for and reject tables with too many columns. We perform this
2618 : * check relatively early for two reasons: (a) we don't run the risk of
2619 : * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
2620 : * okay if we're processing <= 1600 columns, but could take minutes to
2621 : * execute if the user attempts to create a table with hundreds of
2622 : * thousands of columns.
2623 : *
2624 : * Note that we also need to check that we do not exceed this figure after
2625 : * including columns from inherited relations.
2626 : */
2627 41783 : if (list_length(columns) > MaxHeapAttributeNumber)
2628 0 : ereport(ERROR,
2629 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2630 : errmsg("tables can have at most %d columns",
2631 : MaxHeapAttributeNumber)));
2632 :
2633 : /*
2634 : * Check for duplicate names in the explicit list of attributes.
2635 : *
2636 : * Although we might consider merging such entries in the same way that we
2637 : * handle name conflicts for inherited attributes, it seems to make more
2638 : * sense to assume such conflicts are errors.
2639 : *
2640 : * We don't use foreach() here because we have two nested loops over the
2641 : * columns list, with possible element deletions in the inner one. If we
2642 : * used foreach_delete_current() it could only fix up the state of one of
2643 : * the loops, so it seems cleaner to use looping over list indexes for
2644 : * both loops. Note that any deletion will happen beyond where the outer
2645 : * loop is, so its index never needs adjustment.
2646 : */
2647 193252 : for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
2648 : {
2649 151485 : ColumnDef *coldef = list_nth_node(ColumnDef, columns, coldefpos);
2650 :
2651 151485 : if (!is_partition && coldef->typeName == NULL)
2652 : {
2653 : /*
2654 : * Typed table column option that does not belong to a column from
2655 : * the type. This works because the columns from the type come
2656 : * first in the list. (We omit this check for partition column
2657 : * lists; those are processed separately below.)
2658 : */
2659 4 : ereport(ERROR,
2660 : (errcode(ERRCODE_UNDEFINED_COLUMN),
2661 : errmsg("column \"%s\" does not exist",
2662 : coldef->colname)));
2663 : }
2664 :
2665 : /* restpos scans all entries beyond coldef; incr is in loop body */
2666 4107661 : for (int restpos = coldefpos + 1; restpos < list_length(columns);)
2667 : {
2668 3956192 : ColumnDef *restdef = list_nth_node(ColumnDef, columns, restpos);
2669 :
2670 3956192 : if (strcmp(coldef->colname, restdef->colname) == 0)
2671 : {
2672 33 : if (coldef->is_from_type)
2673 : {
2674 : /*
2675 : * merge the column options into the column from the type
2676 : */
2677 21 : coldef->is_not_null = restdef->is_not_null;
2678 21 : coldef->raw_default = restdef->raw_default;
2679 21 : coldef->cooked_default = restdef->cooked_default;
2680 21 : coldef->constraints = restdef->constraints;
2681 21 : coldef->is_from_type = false;
2682 21 : columns = list_delete_nth_cell(columns, restpos);
2683 : }
2684 : else
2685 12 : ereport(ERROR,
2686 : (errcode(ERRCODE_DUPLICATE_COLUMN),
2687 : errmsg("column \"%s\" specified more than once",
2688 : coldef->colname)));
2689 : }
2690 : else
2691 3956159 : restpos++;
2692 : }
2693 : }
2694 :
2695 : /*
2696 : * In case of a partition, there are no new column definitions, only dummy
2697 : * ColumnDefs created for column constraints. Set them aside for now and
2698 : * process them at the end.
2699 : */
2700 41767 : if (is_partition)
2701 : {
2702 6482 : saved_columns = columns;
2703 6482 : columns = NIL;
2704 : }
2705 :
2706 : /*
2707 : * Scan the parents left-to-right, and merge their attributes to form a
2708 : * list of inherited columns (inh_columns).
2709 : */
2710 41767 : child_attno = 0;
2711 49822 : foreach(lc, supers)
2712 : {
2713 8111 : Oid parent = lfirst_oid(lc);
2714 : Relation relation;
2715 : TupleDesc tupleDesc;
2716 : TupleConstr *constr;
2717 : AttrMap *newattmap;
2718 : List *inherited_defaults;
2719 : List *cols_with_defaults;
2720 : List *nnconstrs;
2721 : ListCell *lc1;
2722 : ListCell *lc2;
2723 8111 : Bitmapset *nncols = NULL;
2724 :
2725 : /* caller already got lock */
2726 8111 : relation = table_open(parent, NoLock);
2727 :
2728 : /*
2729 : * Check for active uses of the parent partitioned table in the
2730 : * current transaction, such as being used in some manner by an
2731 : * enclosing command.
2732 : */
2733 8111 : if (is_partition)
2734 6482 : CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
2735 :
2736 : /*
2737 : * We do not allow partitioned tables and partitions to participate in
2738 : * regular inheritance.
2739 : */
2740 8107 : if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
2741 4 : ereport(ERROR,
2742 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2743 : errmsg("cannot inherit from partitioned table \"%s\"",
2744 : RelationGetRelationName(relation))));
2745 8103 : if (relation->rd_rel->relispartition && !is_partition)
2746 4 : ereport(ERROR,
2747 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2748 : errmsg("cannot inherit from partition \"%s\"",
2749 : RelationGetRelationName(relation))));
2750 :
2751 8099 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2752 6478 : relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2753 6466 : relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2754 0 : ereport(ERROR,
2755 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2756 : errmsg("inherited relation \"%s\" is not a table or foreign table",
2757 : RelationGetRelationName(relation))));
2758 :
2759 : /*
2760 : * If the parent is permanent, so must be all of its partitions. Note
2761 : * that inheritance allows that case.
2762 : */
2763 8099 : if (is_partition &&
2764 6478 : relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
2765 : relpersistence == RELPERSISTENCE_TEMP)
2766 4 : ereport(ERROR,
2767 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2768 : errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
2769 : RelationGetRelationName(relation))));
2770 :
2771 : /* Permanent rels cannot inherit from temporary ones */
2772 8095 : if (relpersistence != RELPERSISTENCE_TEMP &&
2773 7825 : relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
2774 16 : ereport(ERROR,
2775 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2776 : errmsg(!is_partition
2777 : ? "cannot inherit from temporary relation \"%s\""
2778 : : "cannot create a permanent relation as partition of temporary relation \"%s\"",
2779 : RelationGetRelationName(relation))));
2780 :
2781 : /* If existing rel is temp, it must belong to this session */
2782 8079 : if (RELATION_IS_OTHER_TEMP(relation))
2783 0 : ereport(ERROR,
2784 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2785 : errmsg(!is_partition
2786 : ? "cannot inherit from temporary relation of another session"
2787 : : "cannot create as partition of temporary relation of another session")));
2788 :
2789 : /*
2790 : * We should have an UNDER permission flag for this, but for now,
2791 : * demand that creator of a child table own the parent.
2792 : */
2793 8079 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
2794 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
2795 0 : RelationGetRelationName(relation));
2796 :
2797 8079 : tupleDesc = RelationGetDescr(relation);
2798 8079 : constr = tupleDesc->constr;
2799 :
2800 : /*
2801 : * newattmap->attnums[] will contain the child-table attribute numbers
2802 : * for the attributes of this parent table. (They are not the same
2803 : * for parents after the first one, nor if we have dropped columns.)
2804 : */
2805 8079 : newattmap = make_attrmap(tupleDesc->natts);
2806 :
2807 : /* We can't process inherited defaults until newattmap is complete. */
2808 8079 : inherited_defaults = cols_with_defaults = NIL;
2809 :
2810 : /*
2811 : * Request attnotnull on columns that have a not-null constraint
2812 : * that's not marked NO INHERIT (even if not valid).
2813 : */
2814 8079 : nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
2815 : true, false);
2816 17894 : foreach_ptr(CookedConstraint, cc, nnconstrs)
2817 1736 : nncols = bms_add_member(nncols, cc->attnum);
2818 :
2819 24190 : for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
2820 16111 : parent_attno++)
2821 : {
2822 16135 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2823 : parent_attno - 1);
2824 16135 : char *attributeName = NameStr(attribute->attname);
2825 : int exist_attno;
2826 : ColumnDef *newdef;
2827 : ColumnDef *mergeddef;
2828 :
2829 : /*
2830 : * Ignore dropped columns in the parent.
2831 : */
2832 16135 : if (attribute->attisdropped)
2833 132 : continue; /* leave newattmap->attnums entry as zero */
2834 :
2835 : /*
2836 : * Create new column definition
2837 : */
2838 16003 : newdef = makeColumnDef(attributeName, attribute->atttypid,
2839 : attribute->atttypmod, attribute->attcollation);
2840 16003 : newdef->storage = attribute->attstorage;
2841 16003 : newdef->generated = attribute->attgenerated;
2842 16003 : if (CompressionMethodIsValid(attribute->attcompression))
2843 24 : newdef->compression =
2844 24 : pstrdup(GetCompressionMethodName(attribute->attcompression));
2845 :
2846 : /*
2847 : * Regular inheritance children are independent enough not to
2848 : * inherit identity columns. But partitions are integral part of
2849 : * a partitioned table and inherit identity column.
2850 : */
2851 16003 : if (is_partition)
2852 13057 : newdef->identity = attribute->attidentity;
2853 :
2854 : /*
2855 : * Does it match some previously considered column from another
2856 : * parent?
2857 : */
2858 16003 : exist_attno = findAttrByName(attributeName, inh_columns);
2859 16003 : if (exist_attno > 0)
2860 : {
2861 : /*
2862 : * Yes, try to merge the two column definitions.
2863 : */
2864 245 : mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
2865 :
2866 221 : newattmap->attnums[parent_attno - 1] = exist_attno;
2867 :
2868 : /*
2869 : * Partitions have only one parent, so conflict should never
2870 : * occur.
2871 : */
2872 : Assert(!is_partition);
2873 : }
2874 : else
2875 : {
2876 : /*
2877 : * No, create a new inherited column
2878 : */
2879 15758 : newdef->inhcount = 1;
2880 15758 : newdef->is_local = false;
2881 15758 : inh_columns = lappend(inh_columns, newdef);
2882 :
2883 15758 : newattmap->attnums[parent_attno - 1] = ++child_attno;
2884 15758 : mergeddef = newdef;
2885 : }
2886 :
2887 : /*
2888 : * mark attnotnull if parent has it
2889 : */
2890 15979 : if (bms_is_member(parent_attno, nncols))
2891 1736 : mergeddef->is_not_null = true;
2892 :
2893 : /*
2894 : * Locate default/generation expression if any
2895 : */
2896 15979 : if (attribute->atthasdef)
2897 : {
2898 : Node *this_default;
2899 :
2900 542 : this_default = TupleDescGetDefault(tupleDesc, parent_attno);
2901 542 : if (this_default == NULL)
2902 0 : elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
2903 : parent_attno, RelationGetRelationName(relation));
2904 :
2905 : /*
2906 : * If it's a GENERATED default, it might contain Vars that
2907 : * need to be mapped to the inherited column(s)' new numbers.
2908 : * We can't do that till newattmap is ready, so just remember
2909 : * all the inherited default expressions for the moment.
2910 : */
2911 542 : inherited_defaults = lappend(inherited_defaults, this_default);
2912 542 : cols_with_defaults = lappend(cols_with_defaults, mergeddef);
2913 : }
2914 : }
2915 :
2916 : /*
2917 : * Now process any inherited default expressions, adjusting attnos
2918 : * using the completed newattmap map.
2919 : */
2920 8597 : forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
2921 : {
2922 542 : Node *this_default = (Node *) lfirst(lc1);
2923 542 : ColumnDef *def = (ColumnDef *) lfirst(lc2);
2924 : bool found_whole_row;
2925 :
2926 : /* Adjust Vars to match new table's column numbering */
2927 542 : this_default = map_variable_attnos(this_default,
2928 : 1, 0,
2929 : newattmap,
2930 : InvalidOid, &found_whole_row);
2931 :
2932 : /*
2933 : * For the moment we have to reject whole-row variables. We could
2934 : * convert them, if we knew the new table's rowtype OID, but that
2935 : * hasn't been assigned yet. (A variable could only appear in a
2936 : * generation expression, so the error message is correct.)
2937 : */
2938 542 : if (found_whole_row)
2939 0 : ereport(ERROR,
2940 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2941 : errmsg("cannot convert whole-row table reference"),
2942 : errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
2943 : def->colname,
2944 : RelationGetRelationName(relation))));
2945 :
2946 : /*
2947 : * If we already had a default from some prior parent, check to
2948 : * see if they are the same. If so, no problem; if not, mark the
2949 : * column as having a bogus default. Below, we will complain if
2950 : * the bogus default isn't overridden by the child columns.
2951 : */
2952 : Assert(def->raw_default == NULL);
2953 542 : if (def->cooked_default == NULL)
2954 514 : def->cooked_default = this_default;
2955 28 : else if (!equal(def->cooked_default, this_default))
2956 : {
2957 24 : def->cooked_default = &bogus_marker;
2958 24 : have_bogus_defaults = true;
2959 : }
2960 : }
2961 :
2962 : /*
2963 : * Now copy the CHECK constraints of this parent, adjusting attnos
2964 : * using the completed newattmap map. Identically named constraints
2965 : * are merged if possible, else we throw error.
2966 : */
2967 8055 : if (constr && constr->num_check > 0)
2968 : {
2969 245 : ConstrCheck *check = constr->check;
2970 :
2971 770 : for (int i = 0; i < constr->num_check; i++)
2972 : {
2973 525 : char *name = check[i].ccname;
2974 : Node *expr;
2975 : bool found_whole_row;
2976 :
2977 : /* ignore if the constraint is non-inheritable */
2978 525 : if (check[i].ccnoinherit)
2979 32 : continue;
2980 :
2981 : /* Adjust Vars to match new table's column numbering */
2982 493 : expr = map_variable_attnos(stringToNode(check[i].ccbin),
2983 : 1, 0,
2984 : newattmap,
2985 : InvalidOid, &found_whole_row);
2986 :
2987 : /*
2988 : * For the moment we have to reject whole-row variables. We
2989 : * could convert them, if we knew the new table's rowtype OID,
2990 : * but that hasn't been assigned yet.
2991 : */
2992 493 : if (found_whole_row)
2993 0 : ereport(ERROR,
2994 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2995 : errmsg("cannot convert whole-row table reference"),
2996 : errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
2997 : name,
2998 : RelationGetRelationName(relation))));
2999 :
3000 493 : constraints = MergeCheckConstraint(constraints, name, expr,
3001 493 : check[i].ccenforced);
3002 : }
3003 : }
3004 :
3005 : /*
3006 : * Also copy the not-null constraints from this parent. The
3007 : * attnotnull markings were already installed above.
3008 : */
3009 17846 : foreach_ptr(CookedConstraint, nn, nnconstrs)
3010 : {
3011 : Assert(nn->contype == CONSTR_NOTNULL);
3012 :
3013 1736 : nn->attnum = newattmap->attnums[nn->attnum - 1];
3014 :
3015 1736 : nnconstraints = lappend(nnconstraints, nn);
3016 : }
3017 :
3018 8055 : free_attrmap(newattmap);
3019 :
3020 : /*
3021 : * Close the parent rel, but keep our lock on it until xact commit.
3022 : * That will prevent someone else from deleting or ALTERing the parent
3023 : * before the child is committed.
3024 : */
3025 8055 : table_close(relation, NoLock);
3026 : }
3027 :
3028 : /*
3029 : * If we had no inherited attributes, the result columns are just the
3030 : * explicitly declared columns. Otherwise, we need to merge the declared
3031 : * columns into the inherited column list. Although, we never have any
3032 : * explicitly declared columns if the table is a partition.
3033 : */
3034 41711 : if (inh_columns != NIL)
3035 : {
3036 7765 : int newcol_attno = 0;
3037 :
3038 8413 : foreach(lc, columns)
3039 : {
3040 700 : ColumnDef *newdef = lfirst_node(ColumnDef, lc);
3041 700 : char *attributeName = newdef->colname;
3042 : int exist_attno;
3043 :
3044 : /*
3045 : * Partitions have only one parent and have no column definitions
3046 : * of their own, so conflict should never occur.
3047 : */
3048 : Assert(!is_partition);
3049 :
3050 700 : newcol_attno++;
3051 :
3052 : /*
3053 : * Does it match some inherited column?
3054 : */
3055 700 : exist_attno = findAttrByName(attributeName, inh_columns);
3056 700 : if (exist_attno > 0)
3057 : {
3058 : /*
3059 : * Yes, try to merge the two column definitions.
3060 : */
3061 251 : MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
3062 : }
3063 : else
3064 : {
3065 : /*
3066 : * No, attach new column unchanged to result columns.
3067 : */
3068 449 : inh_columns = lappend(inh_columns, newdef);
3069 : }
3070 : }
3071 :
3072 7713 : columns = inh_columns;
3073 :
3074 : /*
3075 : * Check that we haven't exceeded the legal # of columns after merging
3076 : * in inherited columns.
3077 : */
3078 7713 : if (list_length(columns) > MaxHeapAttributeNumber)
3079 0 : ereport(ERROR,
3080 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
3081 : errmsg("tables can have at most %d columns",
3082 : MaxHeapAttributeNumber)));
3083 : }
3084 :
3085 : /*
3086 : * Now that we have the column definition list for a partition, we can
3087 : * check whether the columns referenced in the column constraint specs
3088 : * actually exist. Also, merge column defaults.
3089 : */
3090 41659 : if (is_partition)
3091 : {
3092 6589 : foreach(lc, saved_columns)
3093 : {
3094 151 : ColumnDef *restdef = lfirst(lc);
3095 151 : bool found = false;
3096 : ListCell *l;
3097 :
3098 549 : foreach(l, columns)
3099 : {
3100 422 : ColumnDef *coldef = lfirst(l);
3101 :
3102 422 : if (strcmp(coldef->colname, restdef->colname) == 0)
3103 : {
3104 151 : found = true;
3105 :
3106 : /*
3107 : * Check for conflicts related to generated columns.
3108 : *
3109 : * Same rules as above: generated-ness has to match the
3110 : * parent, but the contents of the generation expression
3111 : * can be different.
3112 : */
3113 151 : if (coldef->generated)
3114 : {
3115 80 : if (restdef->raw_default && !restdef->generated)
3116 8 : ereport(ERROR,
3117 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3118 : errmsg("column \"%s\" inherits from generated column but specifies default",
3119 : restdef->colname)));
3120 72 : if (restdef->identity)
3121 0 : ereport(ERROR,
3122 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3123 : errmsg("column \"%s\" inherits from generated column but specifies identity",
3124 : restdef->colname)));
3125 : }
3126 : else
3127 : {
3128 71 : if (restdef->generated)
3129 8 : ereport(ERROR,
3130 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3131 : errmsg("child column \"%s\" specifies generation expression",
3132 : restdef->colname),
3133 : errhint("A child table column cannot be generated unless its parent column is.")));
3134 : }
3135 :
3136 135 : if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
3137 8 : ereport(ERROR,
3138 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3139 : errmsg("column \"%s\" inherits from generated column of different kind",
3140 : restdef->colname),
3141 : errdetail("Parent column is %s, child column is %s.",
3142 : coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3143 : restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3144 :
3145 : /*
3146 : * Override the parent's default value for this column
3147 : * (coldef->cooked_default) with the partition's local
3148 : * definition (restdef->raw_default), if there's one. It
3149 : * should be physically impossible to get a cooked default
3150 : * in the local definition or a raw default in the
3151 : * inherited definition, but make sure they're nulls, for
3152 : * future-proofing.
3153 : */
3154 : Assert(restdef->cooked_default == NULL);
3155 : Assert(coldef->raw_default == NULL);
3156 127 : if (restdef->raw_default)
3157 : {
3158 79 : coldef->raw_default = restdef->raw_default;
3159 79 : coldef->cooked_default = NULL;
3160 : }
3161 : }
3162 : }
3163 :
3164 : /* complain for constraints on columns not in parent */
3165 127 : if (!found)
3166 0 : ereport(ERROR,
3167 : (errcode(ERRCODE_UNDEFINED_COLUMN),
3168 : errmsg("column \"%s\" does not exist",
3169 : restdef->colname)));
3170 : }
3171 : }
3172 :
3173 : /*
3174 : * If we found any conflicting parent default values, check to make sure
3175 : * they were overridden by the child.
3176 : */
3177 41635 : if (have_bogus_defaults)
3178 : {
3179 60 : foreach(lc, columns)
3180 : {
3181 48 : ColumnDef *def = lfirst(lc);
3182 :
3183 48 : if (def->cooked_default == &bogus_marker)
3184 : {
3185 12 : if (def->generated)
3186 8 : ereport(ERROR,
3187 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3188 : errmsg("column \"%s\" inherits conflicting generation expressions",
3189 : def->colname),
3190 : errhint("To resolve the conflict, specify a generation expression explicitly.")));
3191 : else
3192 4 : ereport(ERROR,
3193 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3194 : errmsg("column \"%s\" inherits conflicting default values",
3195 : def->colname),
3196 : errhint("To resolve the conflict, specify a default explicitly.")));
3197 : }
3198 : }
3199 : }
3200 :
3201 41623 : *supconstr = constraints;
3202 41623 : *supnotnulls = nnconstraints;
3203 :
3204 41623 : return columns;
3205 : }
3206 :
3207 :
3208 : /*
3209 : * MergeCheckConstraint
3210 : * Try to merge an inherited CHECK constraint with previous ones
3211 : *
3212 : * If we inherit identically-named constraints from multiple parents, we must
3213 : * merge them, or throw an error if they don't have identical definitions.
3214 : *
3215 : * constraints is a list of CookedConstraint structs for previous constraints.
3216 : *
3217 : * If the new constraint matches an existing one, then the existing
3218 : * constraint's inheritance count is updated. If there is a conflict (same
3219 : * name but different expression), throw an error. If the constraint neither
3220 : * matches nor conflicts with an existing one, a new constraint is appended to
3221 : * the list.
3222 : */
3223 : static List *
3224 493 : MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
3225 : {
3226 : ListCell *lc;
3227 : CookedConstraint *newcon;
3228 :
3229 1521 : foreach(lc, constraints)
3230 : {
3231 1128 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
3232 :
3233 : Assert(ccon->contype == CONSTR_CHECK);
3234 :
3235 : /* Non-matching names never conflict */
3236 1128 : if (strcmp(ccon->name, name) != 0)
3237 1028 : continue;
3238 :
3239 100 : if (equal(expr, ccon->expr))
3240 : {
3241 : /* OK to merge constraint with existing */
3242 100 : if (pg_add_s16_overflow(ccon->inhcount, 1,
3243 : &ccon->inhcount))
3244 0 : ereport(ERROR,
3245 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3246 : errmsg("too many inheritance parents"));
3247 :
3248 : /*
3249 : * When enforceability differs, the merged constraint should be
3250 : * marked as ENFORCED because one of the parents is ENFORCED.
3251 : */
3252 100 : if (!ccon->is_enforced && is_enforced)
3253 : {
3254 32 : ccon->is_enforced = true;
3255 32 : ccon->skip_validation = false;
3256 : }
3257 :
3258 100 : return constraints;
3259 : }
3260 :
3261 0 : ereport(ERROR,
3262 : (errcode(ERRCODE_DUPLICATE_OBJECT),
3263 : errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
3264 : name)));
3265 : }
3266 :
3267 : /*
3268 : * Constraint couldn't be merged with an existing one and also didn't
3269 : * conflict with an existing one, so add it as a new one to the list.
3270 : */
3271 393 : newcon = palloc0_object(CookedConstraint);
3272 393 : newcon->contype = CONSTR_CHECK;
3273 393 : newcon->name = pstrdup(name);
3274 393 : newcon->expr = expr;
3275 393 : newcon->inhcount = 1;
3276 393 : newcon->is_enforced = is_enforced;
3277 393 : newcon->skip_validation = !is_enforced;
3278 393 : return lappend(constraints, newcon);
3279 : }
3280 :
3281 : /*
3282 : * MergeChildAttribute
3283 : * Merge given child attribute definition into given inherited attribute.
3284 : *
3285 : * Input arguments:
3286 : * 'inh_columns' is the list of inherited ColumnDefs.
3287 : * 'exist_attno' is the number of the inherited attribute in inh_columns
3288 : * 'newcol_attno' is the attribute number in child table's schema definition
3289 : * 'newdef' is the column/attribute definition from the child table.
3290 : *
3291 : * The ColumnDef in 'inh_columns' list is modified. The child attribute's
3292 : * ColumnDef remains unchanged.
3293 : *
3294 : * Notes:
3295 : * - The attribute is merged according to the rules laid out in the prologue
3296 : * of MergeAttributes().
3297 : * - If matching inherited attribute exists but the child attribute can not be
3298 : * merged into it, the function throws respective errors.
3299 : * - A partition can not have its own column definitions. Hence this function
3300 : * is applicable only to a regular inheritance child.
3301 : */
3302 : static void
3303 251 : MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
3304 : {
3305 251 : char *attributeName = newdef->colname;
3306 : ColumnDef *inhdef;
3307 : Oid inhtypeid,
3308 : newtypeid;
3309 : int32 inhtypmod,
3310 : newtypmod;
3311 : Oid inhcollid,
3312 : newcollid;
3313 :
3314 251 : if (exist_attno == newcol_attno)
3315 229 : ereport(NOTICE,
3316 : (errmsg("merging column \"%s\" with inherited definition",
3317 : attributeName)));
3318 : else
3319 22 : ereport(NOTICE,
3320 : (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
3321 : errdetail("User-specified column moved to the position of the inherited column.")));
3322 :
3323 251 : inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3324 :
3325 : /*
3326 : * Must have the same type and typmod
3327 : */
3328 251 : typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
3329 251 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3330 251 : if (inhtypeid != newtypeid || inhtypmod != newtypmod)
3331 8 : ereport(ERROR,
3332 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3333 : errmsg("column \"%s\" has a type conflict",
3334 : attributeName),
3335 : errdetail("%s versus %s",
3336 : format_type_with_typemod(inhtypeid, inhtypmod),
3337 : format_type_with_typemod(newtypeid, newtypmod))));
3338 :
3339 : /*
3340 : * Must have the same collation
3341 : */
3342 243 : inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
3343 243 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3344 243 : if (inhcollid != newcollid)
3345 4 : ereport(ERROR,
3346 : (errcode(ERRCODE_COLLATION_MISMATCH),
3347 : errmsg("column \"%s\" has a collation conflict",
3348 : attributeName),
3349 : errdetail("\"%s\" versus \"%s\"",
3350 : get_collation_name(inhcollid),
3351 : get_collation_name(newcollid))));
3352 :
3353 : /*
3354 : * Identity is never inherited by a regular inheritance child. Pick
3355 : * child's identity definition if there's one.
3356 : */
3357 239 : inhdef->identity = newdef->identity;
3358 :
3359 : /*
3360 : * Copy storage parameter
3361 : */
3362 239 : if (inhdef->storage == 0)
3363 0 : inhdef->storage = newdef->storage;
3364 239 : else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
3365 4 : ereport(ERROR,
3366 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3367 : errmsg("column \"%s\" has a storage parameter conflict",
3368 : attributeName),
3369 : errdetail("%s versus %s",
3370 : storage_name(inhdef->storage),
3371 : storage_name(newdef->storage))));
3372 :
3373 : /*
3374 : * Copy compression parameter
3375 : */
3376 235 : if (inhdef->compression == NULL)
3377 231 : inhdef->compression = newdef->compression;
3378 4 : else if (newdef->compression != NULL)
3379 : {
3380 4 : if (strcmp(inhdef->compression, newdef->compression) != 0)
3381 4 : ereport(ERROR,
3382 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3383 : errmsg("column \"%s\" has a compression method conflict",
3384 : attributeName),
3385 : errdetail("%s versus %s", inhdef->compression, newdef->compression)));
3386 : }
3387 :
3388 : /*
3389 : * Merge of not-null constraints = OR 'em together
3390 : */
3391 231 : inhdef->is_not_null |= newdef->is_not_null;
3392 :
3393 : /*
3394 : * Check for conflicts related to generated columns.
3395 : *
3396 : * If the parent column is generated, the child column will be made a
3397 : * generated column if it isn't already. If it is a generated column,
3398 : * we'll take its generation expression in preference to the parent's. We
3399 : * must check that the child column doesn't specify a default value or
3400 : * identity, which matches the rules for a single column in
3401 : * parse_utilcmd.c.
3402 : *
3403 : * Conversely, if the parent column is not generated, the child column
3404 : * can't be either. (We used to allow that, but it results in being able
3405 : * to override the generation expression via UPDATEs through the parent.)
3406 : */
3407 231 : if (inhdef->generated)
3408 : {
3409 41 : if (newdef->raw_default && !newdef->generated)
3410 8 : ereport(ERROR,
3411 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3412 : errmsg("column \"%s\" inherits from generated column but specifies default",
3413 : inhdef->colname)));
3414 33 : if (newdef->identity)
3415 8 : ereport(ERROR,
3416 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3417 : errmsg("column \"%s\" inherits from generated column but specifies identity",
3418 : inhdef->colname)));
3419 : }
3420 : else
3421 : {
3422 190 : if (newdef->generated)
3423 8 : ereport(ERROR,
3424 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3425 : errmsg("child column \"%s\" specifies generation expression",
3426 : inhdef->colname),
3427 : errhint("A child table column cannot be generated unless its parent column is.")));
3428 : }
3429 :
3430 207 : if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
3431 8 : ereport(ERROR,
3432 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3433 : errmsg("column \"%s\" inherits from generated column of different kind",
3434 : inhdef->colname),
3435 : errdetail("Parent column is %s, child column is %s.",
3436 : inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3437 : newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3438 :
3439 : /*
3440 : * If new def has a default, override previous default
3441 : */
3442 199 : if (newdef->raw_default != NULL)
3443 : {
3444 20 : inhdef->raw_default = newdef->raw_default;
3445 20 : inhdef->cooked_default = newdef->cooked_default;
3446 : }
3447 :
3448 : /* Mark the column as locally defined */
3449 199 : inhdef->is_local = true;
3450 199 : }
3451 :
3452 : /*
3453 : * MergeInheritedAttribute
3454 : * Merge given parent attribute definition into specified attribute
3455 : * inherited from the previous parents.
3456 : *
3457 : * Input arguments:
3458 : * 'inh_columns' is the list of previously inherited ColumnDefs.
3459 : * 'exist_attno' is the number the existing matching attribute in inh_columns.
3460 : * 'newdef' is the new parent column/attribute definition to be merged.
3461 : *
3462 : * The matching ColumnDef in 'inh_columns' list is modified and returned.
3463 : *
3464 : * Notes:
3465 : * - The attribute is merged according to the rules laid out in the prologue
3466 : * of MergeAttributes().
3467 : * - If matching inherited attribute exists but the new attribute can not be
3468 : * merged into it, the function throws respective errors.
3469 : * - A partition inherits from only a single parent. Hence this function is
3470 : * applicable only to a regular inheritance.
3471 : */
3472 : static ColumnDef *
3473 245 : MergeInheritedAttribute(List *inh_columns,
3474 : int exist_attno,
3475 : const ColumnDef *newdef)
3476 : {
3477 245 : char *attributeName = newdef->colname;
3478 : ColumnDef *prevdef;
3479 : Oid prevtypeid,
3480 : newtypeid;
3481 : int32 prevtypmod,
3482 : newtypmod;
3483 : Oid prevcollid,
3484 : newcollid;
3485 :
3486 245 : ereport(NOTICE,
3487 : (errmsg("merging multiple inherited definitions of column \"%s\"",
3488 : attributeName)));
3489 245 : prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3490 :
3491 : /*
3492 : * Must have the same type and typmod
3493 : */
3494 245 : typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
3495 245 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3496 245 : if (prevtypeid != newtypeid || prevtypmod != newtypmod)
3497 0 : ereport(ERROR,
3498 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3499 : errmsg("inherited column \"%s\" has a type conflict",
3500 : attributeName),
3501 : errdetail("%s versus %s",
3502 : format_type_with_typemod(prevtypeid, prevtypmod),
3503 : format_type_with_typemod(newtypeid, newtypmod))));
3504 :
3505 : /*
3506 : * Must have the same collation
3507 : */
3508 245 : prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
3509 245 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3510 245 : if (prevcollid != newcollid)
3511 0 : ereport(ERROR,
3512 : (errcode(ERRCODE_COLLATION_MISMATCH),
3513 : errmsg("inherited column \"%s\" has a collation conflict",
3514 : attributeName),
3515 : errdetail("\"%s\" versus \"%s\"",
3516 : get_collation_name(prevcollid),
3517 : get_collation_name(newcollid))));
3518 :
3519 : /*
3520 : * Copy/check storage parameter
3521 : */
3522 245 : if (prevdef->storage == 0)
3523 0 : prevdef->storage = newdef->storage;
3524 245 : else if (prevdef->storage != newdef->storage)
3525 4 : ereport(ERROR,
3526 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3527 : errmsg("inherited column \"%s\" has a storage parameter conflict",
3528 : attributeName),
3529 : errdetail("%s versus %s",
3530 : storage_name(prevdef->storage),
3531 : storage_name(newdef->storage))));
3532 :
3533 : /*
3534 : * Copy/check compression parameter
3535 : */
3536 241 : if (prevdef->compression == NULL)
3537 229 : prevdef->compression = newdef->compression;
3538 12 : else if (newdef->compression != NULL)
3539 : {
3540 4 : if (strcmp(prevdef->compression, newdef->compression) != 0)
3541 4 : ereport(ERROR,
3542 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3543 : errmsg("column \"%s\" has a compression method conflict",
3544 : attributeName),
3545 : errdetail("%s versus %s",
3546 : prevdef->compression, newdef->compression)));
3547 : }
3548 :
3549 : /*
3550 : * Check for GENERATED conflicts
3551 : */
3552 237 : if (prevdef->generated != newdef->generated)
3553 16 : ereport(ERROR,
3554 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3555 : errmsg("inherited column \"%s\" has a generation conflict",
3556 : attributeName)));
3557 :
3558 : /*
3559 : * Default and other constraints are handled by the caller.
3560 : */
3561 :
3562 221 : if (pg_add_s16_overflow(prevdef->inhcount, 1,
3563 : &prevdef->inhcount))
3564 0 : ereport(ERROR,
3565 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3566 : errmsg("too many inheritance parents"));
3567 :
3568 221 : return prevdef;
3569 : }
3570 :
3571 : /*
3572 : * StoreCatalogInheritance
3573 : * Updates the system catalogs with proper inheritance information.
3574 : *
3575 : * supers is a list of the OIDs of the new relation's direct ancestors.
3576 : */
3577 : static void
3578 41179 : StoreCatalogInheritance(Oid relationId, List *supers,
3579 : bool child_is_partition)
3580 : {
3581 : Relation relation;
3582 : int32 seqNumber;
3583 : ListCell *entry;
3584 :
3585 : /*
3586 : * sanity checks
3587 : */
3588 : Assert(OidIsValid(relationId));
3589 :
3590 41179 : if (supers == NIL)
3591 33706 : return;
3592 :
3593 : /*
3594 : * Store INHERITS information in pg_inherits using direct ancestors only.
3595 : * Also enter dependencies on the direct ancestors, and make sure they are
3596 : * marked with relhassubclass = true.
3597 : *
3598 : * (Once upon a time, both direct and indirect ancestors were found here
3599 : * and then entered into pg_ipl. Since that catalog doesn't exist
3600 : * anymore, there's no need to look for indirect ancestors.)
3601 : */
3602 7473 : relation = table_open(InheritsRelationId, RowExclusiveLock);
3603 :
3604 7473 : seqNumber = 1;
3605 15168 : foreach(entry, supers)
3606 : {
3607 7695 : Oid parentOid = lfirst_oid(entry);
3608 :
3609 7695 : StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
3610 : child_is_partition);
3611 7695 : seqNumber++;
3612 : }
3613 :
3614 7473 : table_close(relation, RowExclusiveLock);
3615 : }
3616 :
3617 : /*
3618 : * Make catalog entries showing relationId as being an inheritance child
3619 : * of parentOid. inhRelation is the already-opened pg_inherits catalog.
3620 : */
3621 : static void
3622 9764 : StoreCatalogInheritance1(Oid relationId, Oid parentOid,
3623 : int32 seqNumber, Relation inhRelation,
3624 : bool child_is_partition)
3625 : {
3626 : ObjectAddress childobject,
3627 : parentobject;
3628 :
3629 : /* store the pg_inherits row */
3630 9764 : StoreSingleInheritance(relationId, parentOid, seqNumber);
3631 :
3632 : /*
3633 : * Store a dependency too
3634 : */
3635 9764 : parentobject.classId = RelationRelationId;
3636 9764 : parentobject.objectId = parentOid;
3637 9764 : parentobject.objectSubId = 0;
3638 9764 : childobject.classId = RelationRelationId;
3639 9764 : childobject.objectId = relationId;
3640 9764 : childobject.objectSubId = 0;
3641 :
3642 9764 : recordDependencyOn(&childobject, &parentobject,
3643 : child_dependency_type(child_is_partition));
3644 :
3645 : /*
3646 : * Post creation hook of this inheritance. Since object_access_hook
3647 : * doesn't take multiple object identifiers, we relay oid of parent
3648 : * relation using auxiliary_id argument.
3649 : */
3650 9764 : InvokeObjectPostAlterHookArg(InheritsRelationId,
3651 : relationId, 0,
3652 : parentOid, false);
3653 :
3654 : /*
3655 : * Mark the parent as having subclasses.
3656 : */
3657 9764 : SetRelationHasSubclass(parentOid, true);
3658 9764 : }
3659 :
3660 : /*
3661 : * Look for an existing column entry with the given name.
3662 : *
3663 : * Returns the index (starting with 1) if attribute already exists in columns,
3664 : * 0 if it doesn't.
3665 : */
3666 : static int
3667 16703 : findAttrByName(const char *attributeName, const List *columns)
3668 : {
3669 : ListCell *lc;
3670 16703 : int i = 1;
3671 :
3672 30252 : foreach(lc, columns)
3673 : {
3674 14045 : if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
3675 496 : return i;
3676 :
3677 13549 : i++;
3678 : }
3679 16207 : return 0;
3680 : }
3681 :
3682 :
3683 : /*
3684 : * SetRelationHasSubclass
3685 : * Set the value of the relation's relhassubclass field in pg_class.
3686 : *
3687 : * It's always safe to set this field to true, because all SQL commands are
3688 : * ready to see true and then find no children. On the other hand, commands
3689 : * generally assume zero children if this is false.
3690 : *
3691 : * Caller must hold any self-exclusive lock until end of transaction. If the
3692 : * new value is false, caller must have acquired that lock before reading the
3693 : * evidence that justified the false value. That way, it properly waits if
3694 : * another backend is simultaneously concluding no need to change the tuple
3695 : * (new and old values are true).
3696 : *
3697 : * NOTE: an important side-effect of this operation is that an SI invalidation
3698 : * message is sent out to all backends --- including me --- causing plans
3699 : * referencing the relation to be rebuilt with the new list of children.
3700 : * This must happen even if we find that no change is needed in the pg_class
3701 : * row.
3702 : */
3703 : void
3704 12263 : SetRelationHasSubclass(Oid relationId, bool relhassubclass)
3705 : {
3706 : Relation relationRelation;
3707 : HeapTuple tuple;
3708 : Form_pg_class classtuple;
3709 :
3710 : Assert(CheckRelationOidLockedByMe(relationId,
3711 : ShareUpdateExclusiveLock, false) ||
3712 : CheckRelationOidLockedByMe(relationId,
3713 : ShareRowExclusiveLock, true));
3714 :
3715 : /*
3716 : * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3717 : */
3718 12263 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3719 12263 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3720 12263 : if (!HeapTupleIsValid(tuple))
3721 0 : elog(ERROR, "cache lookup failed for relation %u", relationId);
3722 12263 : classtuple = (Form_pg_class) GETSTRUCT(tuple);
3723 :
3724 12263 : if (classtuple->relhassubclass != relhassubclass)
3725 : {
3726 5530 : classtuple->relhassubclass = relhassubclass;
3727 5530 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3728 : }
3729 : else
3730 : {
3731 : /* no need to change tuple, but force relcache rebuild anyway */
3732 6733 : CacheInvalidateRelcacheByTuple(tuple);
3733 : }
3734 :
3735 12263 : heap_freetuple(tuple);
3736 12263 : table_close(relationRelation, RowExclusiveLock);
3737 12263 : }
3738 :
3739 : /*
3740 : * CheckRelationTableSpaceMove
3741 : * Check if relation can be moved to new tablespace.
3742 : *
3743 : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3744 : *
3745 : * Returns true if the relation can be moved to the new tablespace; raises
3746 : * an error if it is not possible to do the move; returns false if the move
3747 : * would have no effect.
3748 : */
3749 : bool
3750 155 : CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
3751 : {
3752 : Oid oldTableSpaceId;
3753 :
3754 : /*
3755 : * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3756 : * stored as 0.
3757 : */
3758 155 : oldTableSpaceId = rel->rd_rel->reltablespace;
3759 155 : if (newTableSpaceId == oldTableSpaceId ||
3760 150 : (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3761 10 : return false;
3762 :
3763 : /*
3764 : * We cannot support moving mapped relations into different tablespaces.
3765 : * (In particular this eliminates all shared catalogs.)
3766 : */
3767 145 : if (RelationIsMapped(rel))
3768 0 : ereport(ERROR,
3769 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3770 : errmsg("cannot move system relation \"%s\"",
3771 : RelationGetRelationName(rel))));
3772 :
3773 : /* Cannot move a non-shared relation into pg_global */
3774 145 : if (newTableSpaceId == GLOBALTABLESPACE_OID)
3775 8 : ereport(ERROR,
3776 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3777 : errmsg("only shared relations can be placed in pg_global tablespace")));
3778 :
3779 : /*
3780 : * Do not allow moving temp tables of other backends ... their local
3781 : * buffer manager is not going to cope.
3782 : */
3783 137 : if (RELATION_IS_OTHER_TEMP(rel))
3784 0 : ereport(ERROR,
3785 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3786 : errmsg("cannot move temporary tables of other sessions")));
3787 :
3788 137 : return true;
3789 : }
3790 :
3791 : /*
3792 : * SetRelationTableSpace
3793 : * Set new reltablespace and relfilenumber in pg_class entry.
3794 : *
3795 : * newTableSpaceId is the new tablespace for the relation, and
3796 : * newRelFilenumber its new filenumber. If newRelFilenumber is
3797 : * InvalidRelFileNumber, this field is not updated.
3798 : *
3799 : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3800 : *
3801 : * The caller of this routine had better check if a relation can be
3802 : * moved to this new tablespace by calling CheckRelationTableSpaceMove()
3803 : * first, and is responsible for making the change visible with
3804 : * CommandCounterIncrement().
3805 : */
3806 : void
3807 137 : SetRelationTableSpace(Relation rel,
3808 : Oid newTableSpaceId,
3809 : RelFileNumber newRelFilenumber)
3810 : {
3811 : Relation pg_class;
3812 : HeapTuple tuple;
3813 : ItemPointerData otid;
3814 : Form_pg_class rd_rel;
3815 137 : Oid reloid = RelationGetRelid(rel);
3816 :
3817 : Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3818 :
3819 : /* Get a modifiable copy of the relation's pg_class row. */
3820 137 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
3821 :
3822 137 : tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3823 137 : if (!HeapTupleIsValid(tuple))
3824 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
3825 137 : otid = tuple->t_self;
3826 137 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3827 :
3828 : /* Update the pg_class row. */
3829 274 : rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3830 137 : InvalidOid : newTableSpaceId;
3831 137 : if (RelFileNumberIsValid(newRelFilenumber))
3832 108 : rd_rel->relfilenode = newRelFilenumber;
3833 137 : CatalogTupleUpdate(pg_class, &otid, tuple);
3834 137 : UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3835 :
3836 : /*
3837 : * Record dependency on tablespace. This is only required for relations
3838 : * that have no physical storage.
3839 : */
3840 137 : if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3841 20 : changeDependencyOnTablespace(RelationRelationId, reloid,
3842 : rd_rel->reltablespace);
3843 :
3844 137 : heap_freetuple(tuple);
3845 137 : table_close(pg_class, RowExclusiveLock);
3846 137 : }
3847 :
3848 : /*
3849 : * renameatt_check - basic sanity checks before attribute rename
3850 : */
3851 : static void
3852 675 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3853 : {
3854 675 : char relkind = classform->relkind;
3855 :
3856 675 : if (classform->reloftype && !recursing)
3857 4 : ereport(ERROR,
3858 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3859 : errmsg("cannot rename column of typed table")));
3860 :
3861 : /*
3862 : * Renaming the columns of sequences or toast tables doesn't actually
3863 : * break anything from the system's point of view, since internal
3864 : * references are by attnum. But it doesn't seem right to allow users to
3865 : * change names that are hardcoded into the system, hence the following
3866 : * restriction.
3867 : */
3868 671 : if (relkind != RELKIND_RELATION &&
3869 56 : relkind != RELKIND_VIEW &&
3870 56 : relkind != RELKIND_MATVIEW &&
3871 24 : relkind != RELKIND_COMPOSITE_TYPE &&
3872 24 : relkind != RELKIND_INDEX &&
3873 24 : relkind != RELKIND_PARTITIONED_INDEX &&
3874 0 : relkind != RELKIND_FOREIGN_TABLE &&
3875 : relkind != RELKIND_PARTITIONED_TABLE)
3876 0 : ereport(ERROR,
3877 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3878 : errmsg("cannot rename columns of relation \"%s\"",
3879 : NameStr(classform->relname)),
3880 : errdetail_relkind_not_supported(relkind)));
3881 :
3882 : /*
3883 : * permissions checking. only the owner of a class can change its schema.
3884 : */
3885 671 : if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
3886 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
3887 0 : NameStr(classform->relname));
3888 671 : if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
3889 1 : ereport(ERROR,
3890 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3891 : errmsg("permission denied: \"%s\" is a system catalog",
3892 : NameStr(classform->relname))));
3893 670 : }
3894 :
3895 : /*
3896 : * renameatt_internal - workhorse for renameatt
3897 : *
3898 : * Return value is the attribute number in the 'myrelid' relation.
3899 : */
3900 : static AttrNumber
3901 367 : renameatt_internal(Oid myrelid,
3902 : const char *oldattname,
3903 : const char *newattname,
3904 : bool recurse,
3905 : bool recursing,
3906 : int expected_parents,
3907 : DropBehavior behavior)
3908 : {
3909 : Relation targetrelation;
3910 : Relation attrelation;
3911 : HeapTuple atttup;
3912 : Form_pg_attribute attform;
3913 : AttrNumber attnum;
3914 :
3915 : /*
3916 : * Grab an exclusive lock on the target table, which we will NOT release
3917 : * until end of transaction.
3918 : */
3919 367 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
3920 367 : renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
3921 :
3922 : /*
3923 : * if the 'recurse' flag is set then we are supposed to rename this
3924 : * attribute in all classes that inherit from 'relname' (as well as in
3925 : * 'relname').
3926 : *
3927 : * any permissions or problems with duplicate attributes will cause the
3928 : * whole transaction to abort, which is what we want -- all or nothing.
3929 : */
3930 367 : if (recurse)
3931 : {
3932 : List *child_oids,
3933 : *child_numparents;
3934 : ListCell *lo,
3935 : *li;
3936 :
3937 : /*
3938 : * we need the number of parents for each child so that the recursive
3939 : * calls to renameatt() can determine whether there are any parents
3940 : * outside the inheritance hierarchy being processed.
3941 : */
3942 165 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3943 : &child_numparents);
3944 :
3945 : /*
3946 : * find_all_inheritors does the recursive search of the inheritance
3947 : * hierarchy, so all we have to do is process all of the relids in the
3948 : * list that it returns.
3949 : */
3950 488 : forboth(lo, child_oids, li, child_numparents)
3951 : {
3952 343 : Oid childrelid = lfirst_oid(lo);
3953 343 : int numparents = lfirst_int(li);
3954 :
3955 343 : if (childrelid == myrelid)
3956 165 : continue;
3957 : /* note we need not recurse again */
3958 178 : renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
3959 : }
3960 : }
3961 : else
3962 : {
3963 : /*
3964 : * If we are told not to recurse, there had better not be any child
3965 : * tables; else the rename would put them out of step.
3966 : *
3967 : * expected_parents will only be 0 if we are not already recursing.
3968 : */
3969 226 : if (expected_parents == 0 &&
3970 24 : find_inheritance_children(myrelid, NoLock) != NIL)
3971 8 : ereport(ERROR,
3972 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3973 : errmsg("inherited column \"%s\" must be renamed in child tables too",
3974 : oldattname)));
3975 : }
3976 :
3977 : /* rename attributes in typed tables of composite type */
3978 339 : if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
3979 : {
3980 : List *child_oids;
3981 : ListCell *lo;
3982 :
3983 16 : child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
3984 16 : RelationGetRelationName(targetrelation),
3985 : behavior);
3986 :
3987 16 : foreach(lo, child_oids)
3988 4 : renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
3989 : }
3990 :
3991 335 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
3992 :
3993 335 : atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
3994 335 : if (!HeapTupleIsValid(atttup))
3995 16 : ereport(ERROR,
3996 : (errcode(ERRCODE_UNDEFINED_COLUMN),
3997 : errmsg("column \"%s\" does not exist",
3998 : oldattname)));
3999 319 : attform = (Form_pg_attribute) GETSTRUCT(atttup);
4000 :
4001 319 : attnum = attform->attnum;
4002 319 : if (attnum <= 0)
4003 0 : ereport(ERROR,
4004 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4005 : errmsg("cannot rename system column \"%s\"",
4006 : oldattname)));
4007 :
4008 : /*
4009 : * if the attribute is inherited, forbid the renaming. if this is a
4010 : * top-level call to renameatt(), then expected_parents will be 0, so the
4011 : * effect of this code will be to prohibit the renaming if the attribute
4012 : * is inherited at all. if this is a recursive call to renameatt(),
4013 : * expected_parents will be the number of parents the current relation has
4014 : * within the inheritance hierarchy being processed, so we'll prohibit the
4015 : * renaming only if there are additional parents from elsewhere.
4016 : */
4017 319 : if (attform->attinhcount > expected_parents)
4018 20 : ereport(ERROR,
4019 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4020 : errmsg("cannot rename inherited column \"%s\"",
4021 : oldattname)));
4022 :
4023 : /* new name should not already exist */
4024 299 : (void) check_for_column_name_collision(targetrelation, newattname, false);
4025 :
4026 : /* apply the update */
4027 291 : namestrcpy(&(attform->attname), newattname);
4028 :
4029 291 : CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
4030 :
4031 291 : InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
4032 :
4033 291 : heap_freetuple(atttup);
4034 :
4035 291 : table_close(attrelation, RowExclusiveLock);
4036 :
4037 291 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4038 :
4039 291 : return attnum;
4040 : }
4041 :
4042 : /*
4043 : * Perform permissions and integrity checks before acquiring a relation lock.
4044 : */
4045 : static void
4046 276 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
4047 : void *arg)
4048 : {
4049 : HeapTuple tuple;
4050 : Form_pg_class form;
4051 :
4052 276 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
4053 276 : if (!HeapTupleIsValid(tuple))
4054 24 : return; /* concurrently dropped */
4055 252 : form = (Form_pg_class) GETSTRUCT(tuple);
4056 252 : renameatt_check(relid, form, false);
4057 247 : ReleaseSysCache(tuple);
4058 : }
4059 :
4060 : /*
4061 : * renameatt - changes the name of an attribute in a relation
4062 : *
4063 : * The returned ObjectAddress is that of the renamed column.
4064 : */
4065 : ObjectAddress
4066 210 : renameatt(RenameStmt *stmt)
4067 : {
4068 : Oid relid;
4069 : AttrNumber attnum;
4070 : ObjectAddress address;
4071 :
4072 : /* lock level taken here should match renameatt_internal */
4073 210 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4074 210 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4075 : RangeVarCallbackForRenameAttribute,
4076 : NULL);
4077 :
4078 201 : if (!OidIsValid(relid))
4079 : {
4080 16 : ereport(NOTICE,
4081 : (errmsg("relation \"%s\" does not exist, skipping",
4082 : stmt->relation->relname)));
4083 16 : return InvalidObjectAddress;
4084 : }
4085 :
4086 : attnum =
4087 185 : renameatt_internal(relid,
4088 185 : stmt->subname, /* old att name */
4089 185 : stmt->newname, /* new att name */
4090 185 : stmt->relation->inh, /* recursive? */
4091 : false, /* recursing? */
4092 : 0, /* expected inhcount */
4093 : stmt->behavior);
4094 :
4095 129 : ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4096 :
4097 129 : return address;
4098 : }
4099 :
4100 : /*
4101 : * same logic as renameatt_internal
4102 : */
4103 : static ObjectAddress
4104 60 : rename_constraint_internal(Oid myrelid,
4105 : Oid mytypid,
4106 : const char *oldconname,
4107 : const char *newconname,
4108 : bool recurse,
4109 : bool recursing,
4110 : int expected_parents)
4111 : {
4112 60 : Relation targetrelation = NULL;
4113 : Oid constraintOid;
4114 : HeapTuple tuple;
4115 : Form_pg_constraint con;
4116 : ObjectAddress address;
4117 :
4118 : Assert(!myrelid || !mytypid);
4119 :
4120 60 : if (mytypid)
4121 : {
4122 4 : constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
4123 : }
4124 : else
4125 : {
4126 56 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
4127 :
4128 : /*
4129 : * don't tell it whether we're recursing; we allow changing typed
4130 : * tables here
4131 : */
4132 56 : renameatt_check(myrelid, RelationGetForm(targetrelation), false);
4133 :
4134 56 : constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
4135 : }
4136 :
4137 60 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
4138 60 : if (!HeapTupleIsValid(tuple))
4139 0 : elog(ERROR, "cache lookup failed for constraint %u",
4140 : constraintOid);
4141 60 : con = (Form_pg_constraint) GETSTRUCT(tuple);
4142 :
4143 60 : if (myrelid &&
4144 56 : (con->contype == CONSTRAINT_CHECK ||
4145 16 : con->contype == CONSTRAINT_NOTNULL) &&
4146 44 : !con->connoinherit)
4147 : {
4148 36 : if (recurse)
4149 : {
4150 : List *child_oids,
4151 : *child_numparents;
4152 : ListCell *lo,
4153 : *li;
4154 :
4155 24 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
4156 : &child_numparents);
4157 :
4158 56 : forboth(lo, child_oids, li, child_numparents)
4159 : {
4160 32 : Oid childrelid = lfirst_oid(lo);
4161 32 : int numparents = lfirst_int(li);
4162 :
4163 32 : if (childrelid == myrelid)
4164 24 : continue;
4165 :
4166 8 : rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
4167 : }
4168 : }
4169 : else
4170 : {
4171 16 : if (expected_parents == 0 &&
4172 4 : find_inheritance_children(myrelid, NoLock) != NIL)
4173 4 : ereport(ERROR,
4174 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4175 : errmsg("inherited constraint \"%s\" must be renamed in child tables too",
4176 : oldconname)));
4177 : }
4178 :
4179 32 : if (con->coninhcount > expected_parents)
4180 4 : ereport(ERROR,
4181 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4182 : errmsg("cannot rename inherited constraint \"%s\"",
4183 : oldconname)));
4184 : }
4185 :
4186 52 : if (con->conindid
4187 12 : && (con->contype == CONSTRAINT_PRIMARY
4188 4 : || con->contype == CONSTRAINT_UNIQUE
4189 0 : || con->contype == CONSTRAINT_EXCLUSION))
4190 : /* rename the index; this renames the constraint as well */
4191 12 : RenameRelationInternal(con->conindid, newconname, false, true);
4192 : else
4193 40 : RenameConstraintById(constraintOid, newconname);
4194 :
4195 52 : ObjectAddressSet(address, ConstraintRelationId, constraintOid);
4196 :
4197 52 : ReleaseSysCache(tuple);
4198 :
4199 52 : if (targetrelation)
4200 : {
4201 : /*
4202 : * Invalidate relcache so as others can see the new constraint name.
4203 : */
4204 48 : CacheInvalidateRelcache(targetrelation);
4205 :
4206 48 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4207 : }
4208 :
4209 52 : return address;
4210 : }
4211 :
4212 : ObjectAddress
4213 56 : RenameConstraint(RenameStmt *stmt)
4214 : {
4215 56 : Oid relid = InvalidOid;
4216 56 : Oid typid = InvalidOid;
4217 :
4218 56 : if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4219 : {
4220 : Relation rel;
4221 : HeapTuple tup;
4222 :
4223 4 : typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4224 4 : rel = table_open(TypeRelationId, RowExclusiveLock);
4225 4 : tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4226 4 : if (!HeapTupleIsValid(tup))
4227 0 : elog(ERROR, "cache lookup failed for type %u", typid);
4228 4 : checkDomainOwner(tup);
4229 4 : ReleaseSysCache(tup);
4230 4 : table_close(rel, NoLock);
4231 : }
4232 : else
4233 : {
4234 : /* lock level taken here should match rename_constraint_internal */
4235 52 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4236 52 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4237 : RangeVarCallbackForRenameAttribute,
4238 : NULL);
4239 52 : if (!OidIsValid(relid))
4240 : {
4241 4 : ereport(NOTICE,
4242 : (errmsg("relation \"%s\" does not exist, skipping",
4243 : stmt->relation->relname)));
4244 4 : return InvalidObjectAddress;
4245 : }
4246 : }
4247 :
4248 : return
4249 52 : rename_constraint_internal(relid, typid,
4250 52 : stmt->subname,
4251 52 : stmt->newname,
4252 100 : (stmt->relation &&
4253 48 : stmt->relation->inh), /* recursive? */
4254 : false, /* recursing? */
4255 52 : 0 /* expected inhcount */ );
4256 : }
4257 :
4258 : /*
4259 : * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE/PROPERTY GRAPH
4260 : * RENAME
4261 : */
4262 : ObjectAddress
4263 327 : RenameRelation(RenameStmt *stmt)
4264 : {
4265 327 : bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4266 : Oid relid;
4267 : ObjectAddress address;
4268 :
4269 : /*
4270 : * Grab an exclusive lock on the target table, index, sequence, view,
4271 : * materialized view, or foreign table, which we will NOT release until
4272 : * end of transaction.
4273 : *
4274 : * Lock level used here should match RenameRelationInternal, to avoid lock
4275 : * escalation. However, because ALTER INDEX can be used with any relation
4276 : * type, we mustn't believe without verification.
4277 : */
4278 : for (;;)
4279 8 : {
4280 : LOCKMODE lockmode;
4281 : char relkind;
4282 : bool obj_is_index;
4283 :
4284 335 : lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4285 :
4286 335 : relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4287 335 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4288 : RangeVarCallbackForAlterRelation,
4289 : stmt);
4290 :
4291 298 : if (!OidIsValid(relid))
4292 : {
4293 12 : ereport(NOTICE,
4294 : (errmsg("relation \"%s\" does not exist, skipping",
4295 : stmt->relation->relname)));
4296 12 : return InvalidObjectAddress;
4297 : }
4298 :
4299 : /*
4300 : * We allow mismatched statement and object types (e.g., ALTER INDEX
4301 : * to rename a table), but we might've used the wrong lock level. If
4302 : * that happens, retry with the correct lock level. We don't bother
4303 : * if we already acquired AccessExclusiveLock with an index, however.
4304 : */
4305 286 : relkind = get_rel_relkind(relid);
4306 286 : obj_is_index = (relkind == RELKIND_INDEX ||
4307 : relkind == RELKIND_PARTITIONED_INDEX);
4308 286 : if (obj_is_index || is_index_stmt == obj_is_index)
4309 : break;
4310 :
4311 8 : UnlockRelationOid(relid, lockmode);
4312 8 : is_index_stmt = obj_is_index;
4313 : }
4314 :
4315 : /* Do the work */
4316 278 : RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4317 :
4318 266 : ObjectAddressSet(address, RelationRelationId, relid);
4319 :
4320 266 : return address;
4321 : }
4322 :
4323 : /*
4324 : * RenameRelationInternal - change the name of a relation
4325 : */
4326 : void
4327 1108 : RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
4328 : {
4329 : Relation targetrelation;
4330 : Relation relrelation; /* for RELATION relation */
4331 : ItemPointerData otid;
4332 : HeapTuple reltup;
4333 : Form_pg_class relform;
4334 : Oid namespaceId;
4335 :
4336 : /*
4337 : * Grab a lock on the target relation, which we will NOT release until end
4338 : * of transaction. We need at least a self-exclusive lock so that
4339 : * concurrent DDL doesn't overwrite the rename if they start updating
4340 : * while still seeing the old version. The lock also guards against
4341 : * triggering relcache reloads in concurrent sessions, which might not
4342 : * handle this information changing under them. For indexes, we can use a
4343 : * reduced lock level because RelationReloadIndexInfo() handles indexes
4344 : * specially.
4345 : */
4346 1108 : targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4347 1108 : namespaceId = RelationGetNamespace(targetrelation);
4348 :
4349 : /*
4350 : * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4351 : */
4352 1108 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4353 :
4354 1108 : reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
4355 1108 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4356 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4357 1108 : otid = reltup->t_self;
4358 1108 : relform = (Form_pg_class) GETSTRUCT(reltup);
4359 :
4360 1108 : if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4361 12 : ereport(ERROR,
4362 : (errcode(ERRCODE_DUPLICATE_TABLE),
4363 : errmsg("relation \"%s\" already exists",
4364 : newrelname)));
4365 :
4366 : /*
4367 : * RenameRelation is careful not to believe the caller's idea of the
4368 : * relation kind being handled. We don't have to worry about this, but
4369 : * let's not be totally oblivious to it. We can process an index as
4370 : * not-an-index, but not the other way around.
4371 : */
4372 : Assert(!is_index ||
4373 : is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4374 : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4375 :
4376 : /*
4377 : * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4378 : * because it's a copy...)
4379 : */
4380 1096 : namestrcpy(&(relform->relname), newrelname);
4381 :
4382 1096 : CatalogTupleUpdate(relrelation, &otid, reltup);
4383 1096 : UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
4384 :
4385 1096 : InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4386 : InvalidOid, is_internal);
4387 :
4388 1096 : heap_freetuple(reltup);
4389 1096 : table_close(relrelation, RowExclusiveLock);
4390 :
4391 : /*
4392 : * Also rename the associated type, if any.
4393 : */
4394 1096 : if (OidIsValid(targetrelation->rd_rel->reltype))
4395 128 : RenameTypeInternal(targetrelation->rd_rel->reltype,
4396 : newrelname, namespaceId);
4397 :
4398 : /*
4399 : * Also rename the associated constraint, if any.
4400 : */
4401 1096 : if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4402 606 : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4403 : {
4404 502 : Oid constraintId = get_index_constraint(myrelid);
4405 :
4406 502 : if (OidIsValid(constraintId))
4407 24 : RenameConstraintById(constraintId, newrelname);
4408 : }
4409 :
4410 : /*
4411 : * Close rel, but keep lock!
4412 : */
4413 1096 : relation_close(targetrelation, NoLock);
4414 1096 : }
4415 :
4416 : /*
4417 : * ResetRelRewrite - reset relrewrite
4418 : */
4419 : void
4420 381 : ResetRelRewrite(Oid myrelid)
4421 : {
4422 : Relation relrelation; /* for RELATION relation */
4423 : HeapTuple reltup;
4424 : Form_pg_class relform;
4425 :
4426 : /*
4427 : * Find relation's pg_class tuple.
4428 : */
4429 381 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4430 :
4431 381 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4432 381 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4433 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4434 381 : relform = (Form_pg_class) GETSTRUCT(reltup);
4435 :
4436 : /*
4437 : * Update pg_class tuple.
4438 : */
4439 381 : relform->relrewrite = InvalidOid;
4440 :
4441 381 : CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4442 :
4443 381 : heap_freetuple(reltup);
4444 381 : table_close(relrelation, RowExclusiveLock);
4445 381 : }
4446 :
4447 : /*
4448 : * Disallow ALTER TABLE (and similar commands) when the current backend has
4449 : * any open reference to the target table besides the one just acquired by
4450 : * the calling command; this implies there's an open cursor or active plan.
4451 : * We need this check because our lock doesn't protect us against stomping
4452 : * on our own foot, only other people's feet!
4453 : *
4454 : * For ALTER TABLE, the only case known to cause serious trouble is ALTER
4455 : * COLUMN TYPE, and some changes are obviously pretty benign, so this could
4456 : * possibly be relaxed to only error out for certain types of alterations.
4457 : * But the use-case for allowing any of these things is not obvious, so we
4458 : * won't work hard at it for now.
4459 : *
4460 : * We also reject these commands if there are any pending AFTER trigger events
4461 : * for the rel. This is certainly necessary for the rewriting variants of
4462 : * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
4463 : * events would try to fetch the wrong tuples. It might be overly cautious
4464 : * in other cases, but again it seems better to err on the side of paranoia.
4465 : *
4466 : * REINDEX calls this with "rel" referencing the index to be rebuilt; here
4467 : * we are worried about active indexscans on the index. The trigger-event
4468 : * check can be skipped, since we are doing no damage to the parent table.
4469 : *
4470 : * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
4471 : */
4472 : void
4473 115443 : CheckTableNotInUse(Relation rel, const char *stmt)
4474 : {
4475 : int expected_refcnt;
4476 :
4477 115443 : expected_refcnt = rel->rd_isnailed ? 2 : 1;
4478 115443 : if (rel->rd_refcnt != expected_refcnt)
4479 28 : ereport(ERROR,
4480 : (errcode(ERRCODE_OBJECT_IN_USE),
4481 : /* translator: first %s is a SQL command, eg ALTER TABLE */
4482 : errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4483 : stmt, RelationGetRelationName(rel))));
4484 :
4485 115415 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
4486 189026 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4487 93762 : AfterTriggerPendingOnRel(RelationGetRelid(rel)))
4488 12 : ereport(ERROR,
4489 : (errcode(ERRCODE_OBJECT_IN_USE),
4490 : /* translator: first %s is a SQL command, eg ALTER TABLE */
4491 : errmsg("cannot %s \"%s\" because it has pending trigger events",
4492 : stmt, RelationGetRelationName(rel))));
4493 115403 : }
4494 :
4495 : /*
4496 : * CheckAlterTableIsSafe
4497 : * Verify that it's safe to allow ALTER TABLE on this relation.
4498 : *
4499 : * This consists of CheckTableNotInUse() plus a check that the relation
4500 : * isn't another session's temp table. We must split out the temp-table
4501 : * check because there are callers of CheckTableNotInUse() that don't want
4502 : * that, notably DROP TABLE. (We must allow DROP or we couldn't clean out
4503 : * an orphaned temp schema.) Compare truncate_check_activity().
4504 : */
4505 : static void
4506 40942 : CheckAlterTableIsSafe(Relation rel)
4507 : {
4508 : /*
4509 : * Don't allow ALTER on temp tables of other backends. Their local buffer
4510 : * manager is not going to cope if we need to change the table's contents.
4511 : * Even if we don't, there may be optimizations that assume temp tables
4512 : * aren't subject to such interference.
4513 : */
4514 40942 : if (RELATION_IS_OTHER_TEMP(rel))
4515 2 : ereport(ERROR,
4516 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4517 : errmsg("cannot alter temporary tables of other sessions")));
4518 :
4519 : /*
4520 : * Also check for active uses of the relation in the current transaction,
4521 : * including open scans and pending AFTER trigger events.
4522 : */
4523 40940 : CheckTableNotInUse(rel, "ALTER TABLE");
4524 40916 : }
4525 :
4526 : /*
4527 : * AlterTableLookupRelation
4528 : * Look up, and lock, the OID for the relation named by an alter table
4529 : * statement.
4530 : */
4531 : Oid
4532 21737 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
4533 : {
4534 43409 : return RangeVarGetRelidExtended(stmt->relation, lockmode,
4535 21737 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4536 : RangeVarCallbackForAlterRelation,
4537 : stmt);
4538 : }
4539 :
4540 : /*
4541 : * AlterTable
4542 : * Execute ALTER TABLE, which can be a list of subcommands
4543 : *
4544 : * ALTER TABLE is performed in three phases:
4545 : * 1. Examine subcommands and perform pre-transformation checking.
4546 : * 2. Validate and transform subcommands, and update system catalogs.
4547 : * 3. Scan table(s) to check new constraints, and optionally recopy
4548 : * the data into new table(s).
4549 : * Phase 3 is not performed unless one or more of the subcommands requires
4550 : * it. The intention of this design is to allow multiple independent
4551 : * updates of the table schema to be performed with only one pass over the
4552 : * data.
4553 : *
4554 : * ATPrepCmd performs phase 1. A "work queue" entry is created for
4555 : * each table to be affected (there may be multiple affected tables if the
4556 : * commands traverse a table inheritance hierarchy). Also we do preliminary
4557 : * validation of the subcommands. Because earlier subcommands may change
4558 : * the catalog state seen by later commands, there are limits to what can
4559 : * be done in this phase. Generally, this phase acquires table locks,
4560 : * checks permissions and relkind, and recurses to find child tables.
4561 : *
4562 : * ATRewriteCatalogs performs phase 2 for each affected table.
4563 : * Certain subcommands need to be performed before others to avoid
4564 : * unnecessary conflicts; for example, DROP COLUMN should come before
4565 : * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
4566 : * lists, one for each logical "pass" of phase 2.
4567 : *
4568 : * ATRewriteTables performs phase 3 for those tables that need it.
4569 : *
4570 : * For most subcommand types, phases 2 and 3 do no explicit recursion,
4571 : * since phase 1 already does it. However, for certain subcommand types
4572 : * it is only possible to determine how to recurse at phase 2 time; for
4573 : * those cases, phase 1 sets the cmd->recurse flag.
4574 : *
4575 : * Thanks to the magic of MVCC, an error anywhere along the way rolls back
4576 : * the whole operation; we don't have to do anything special to clean up.
4577 : *
4578 : * The caller must lock the relation, with an appropriate lock level
4579 : * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
4580 : * or higher. We pass the lock level down
4581 : * so that we can apply it recursively to inherited tables. Note that the
4582 : * lock level we want as we recurse might well be higher than required for
4583 : * that specific subcommand. So we pass down the overall lock requirement,
4584 : * rather than reassess it at lower levels.
4585 : *
4586 : * The caller also provides a "context" which is to be passed back to
4587 : * utility.c when we need to execute a subcommand such as CREATE INDEX.
4588 : * Some of the fields therein, such as the relid, are used here as well.
4589 : */
4590 : void
4591 21564 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
4592 : AlterTableUtilityContext *context)
4593 : {
4594 : Relation rel;
4595 :
4596 : /* Caller is required to provide an adequate lock. */
4597 21564 : rel = relation_open(context->relid, NoLock);
4598 :
4599 21564 : CheckAlterTableIsSafe(rel);
4600 :
4601 21550 : ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4602 18653 : }
4603 :
4604 : /*
4605 : * AlterTableInternal
4606 : *
4607 : * ALTER TABLE with target specified by OID
4608 : *
4609 : * We do not reject if the relation is already open, because it's quite
4610 : * likely that one or more layers of caller have it open. That means it
4611 : * is unsafe to use this entry point for alterations that could break
4612 : * existing query plans. On the assumption it's not used for such, we
4613 : * don't have to reject pending AFTER triggers, either.
4614 : *
4615 : * Also, since we don't have an AlterTableUtilityContext, this cannot be
4616 : * used for any subcommand types that require parse transformation or
4617 : * could generate subcommands that have to be passed to ProcessUtility.
4618 : */
4619 : void
4620 198 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
4621 : {
4622 : Relation rel;
4623 198 : LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4624 :
4625 198 : rel = relation_open(relid, lockmode);
4626 :
4627 198 : EventTriggerAlterTableRelid(relid);
4628 :
4629 198 : ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4630 198 : }
4631 :
4632 : /*
4633 : * AlterTableGetLockLevel
4634 : *
4635 : * Sets the overall lock level required for the supplied list of subcommands.
4636 : * Policy for doing this set according to needs of AlterTable(), see
4637 : * comments there for overall explanation.
4638 : *
4639 : * Function is called before and after parsing, so it must give same
4640 : * answer each time it is called. Some subcommands are transformed
4641 : * into other subcommand types, so the transform must never be made to a
4642 : * lower lock level than previously assigned. All transforms are noted below.
4643 : *
4644 : * Since this is called before we lock the table we cannot use table metadata
4645 : * to influence the type of lock we acquire.
4646 : *
4647 : * There should be no lockmodes hardcoded into the subcommand functions. All
4648 : * lockmode decisions for ALTER TABLE are made here only. The one exception is
4649 : * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
4650 : * and does not travel through this section of code and cannot be combined with
4651 : * any of the subcommands given here.
4652 : *
4653 : * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
4654 : * so any changes that might affect SELECTs running on standbys need to use
4655 : * AccessExclusiveLocks even if you think a lesser lock would do, unless you
4656 : * have a solution for that also.
4657 : *
4658 : * Also note that pg_dump uses only an AccessShareLock, meaning that anything
4659 : * that takes a lock less than AccessExclusiveLock can change object definitions
4660 : * while pg_dump is running. Be careful to check that the appropriate data is
4661 : * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
4662 : * otherwise we might end up with an inconsistent dump that can't restore.
4663 : */
4664 : LOCKMODE
4665 21935 : AlterTableGetLockLevel(List *cmds)
4666 : {
4667 : /*
4668 : * This only works if we read catalog tables using MVCC snapshots.
4669 : */
4670 : ListCell *lcmd;
4671 21935 : LOCKMODE lockmode = ShareUpdateExclusiveLock;
4672 :
4673 44732 : foreach(lcmd, cmds)
4674 : {
4675 22797 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4676 22797 : LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4677 :
4678 22797 : switch (cmd->subtype)
4679 : {
4680 : /*
4681 : * These subcommands rewrite the heap, so require full locks.
4682 : */
4683 2660 : case AT_AddColumn: /* may rewrite heap, in some cases and visible
4684 : * to SELECT */
4685 : case AT_SetAccessMethod: /* must rewrite heap */
4686 : case AT_SetTableSpace: /* must rewrite heap */
4687 : case AT_AlterColumnType: /* must rewrite heap */
4688 2660 : cmd_lockmode = AccessExclusiveLock;
4689 2660 : break;
4690 :
4691 : /*
4692 : * These subcommands may require addition of toast tables. If
4693 : * we add a toast table to a table currently being scanned, we
4694 : * might miss data added to the new toast table by concurrent
4695 : * insert transactions.
4696 : */
4697 159 : case AT_SetStorage: /* may add toast tables, see
4698 : * ATRewriteCatalogs() */
4699 159 : cmd_lockmode = AccessExclusiveLock;
4700 159 : break;
4701 :
4702 : /*
4703 : * Removing constraints can affect SELECTs that have been
4704 : * optimized assuming the constraint holds true. See also
4705 : * CloneFkReferenced.
4706 : */
4707 784 : case AT_DropConstraint: /* as DROP INDEX */
4708 : case AT_DropNotNull: /* may change some SQL plans */
4709 784 : cmd_lockmode = AccessExclusiveLock;
4710 784 : break;
4711 :
4712 : /*
4713 : * Subcommands that may be visible to concurrent SELECTs
4714 : */
4715 1225 : case AT_DropColumn: /* change visible to SELECT */
4716 : case AT_AddColumnToView: /* CREATE VIEW */
4717 : case AT_DropOids: /* used to equiv to DropColumn */
4718 : case AT_EnableAlwaysRule: /* may change SELECT rules */
4719 : case AT_EnableReplicaRule: /* may change SELECT rules */
4720 : case AT_EnableRule: /* may change SELECT rules */
4721 : case AT_DisableRule: /* may change SELECT rules */
4722 1225 : cmd_lockmode = AccessExclusiveLock;
4723 1225 : break;
4724 :
4725 : /*
4726 : * Changing owner may remove implicit SELECT privileges
4727 : */
4728 1158 : case AT_ChangeOwner: /* change visible to SELECT */
4729 1158 : cmd_lockmode = AccessExclusiveLock;
4730 1158 : break;
4731 :
4732 : /*
4733 : * Changing foreign table options may affect optimization.
4734 : */
4735 143 : case AT_GenericOptions:
4736 : case AT_AlterColumnGenericOptions:
4737 143 : cmd_lockmode = AccessExclusiveLock;
4738 143 : break;
4739 :
4740 : /*
4741 : * These subcommands affect write operations only.
4742 : */
4743 191 : case AT_EnableTrig:
4744 : case AT_EnableAlwaysTrig:
4745 : case AT_EnableReplicaTrig:
4746 : case AT_EnableTrigAll:
4747 : case AT_EnableTrigUser:
4748 : case AT_DisableTrig:
4749 : case AT_DisableTrigAll:
4750 : case AT_DisableTrigUser:
4751 191 : cmd_lockmode = ShareRowExclusiveLock;
4752 191 : break;
4753 :
4754 : /*
4755 : * These subcommands affect write operations only. XXX
4756 : * Theoretically, these could be ShareRowExclusiveLock.
4757 : */
4758 2056 : case AT_ColumnDefault:
4759 : case AT_CookedColumnDefault:
4760 : case AT_AlterConstraint:
4761 : case AT_AddIndex: /* from ADD CONSTRAINT */
4762 : case AT_AddIndexConstraint:
4763 : case AT_ReplicaIdentity:
4764 : case AT_SetNotNull:
4765 : case AT_EnableRowSecurity:
4766 : case AT_DisableRowSecurity:
4767 : case AT_ForceRowSecurity:
4768 : case AT_NoForceRowSecurity:
4769 : case AT_AddIdentity:
4770 : case AT_DropIdentity:
4771 : case AT_SetIdentity:
4772 : case AT_SetExpression:
4773 : case AT_DropExpression:
4774 : case AT_SetCompression:
4775 2056 : cmd_lockmode = AccessExclusiveLock;
4776 2056 : break;
4777 :
4778 10082 : case AT_AddConstraint:
4779 : case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4780 : case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4781 10082 : if (IsA(cmd->def, Constraint))
4782 : {
4783 10082 : Constraint *con = (Constraint *) cmd->def;
4784 :
4785 10082 : switch (con->contype)
4786 : {
4787 7465 : case CONSTR_EXCLUSION:
4788 : case CONSTR_PRIMARY:
4789 : case CONSTR_UNIQUE:
4790 :
4791 : /*
4792 : * Cases essentially the same as CREATE INDEX. We
4793 : * could reduce the lock strength to ShareLock if
4794 : * we can work out how to allow concurrent catalog
4795 : * updates. XXX Might be set down to
4796 : * ShareRowExclusiveLock but requires further
4797 : * analysis.
4798 : */
4799 7465 : cmd_lockmode = AccessExclusiveLock;
4800 7465 : break;
4801 1782 : case CONSTR_FOREIGN:
4802 :
4803 : /*
4804 : * We add triggers to both tables when we add a
4805 : * Foreign Key, so the lock level must be at least
4806 : * as strong as CREATE TRIGGER.
4807 : */
4808 1782 : cmd_lockmode = ShareRowExclusiveLock;
4809 1782 : break;
4810 :
4811 835 : default:
4812 835 : cmd_lockmode = AccessExclusiveLock;
4813 : }
4814 : }
4815 10082 : break;
4816 :
4817 : /*
4818 : * These subcommands affect inheritance behaviour. Queries
4819 : * started before us will continue to see the old inheritance
4820 : * behaviour, while queries started after we commit will see
4821 : * new behaviour. No need to prevent reads or writes to the
4822 : * subtable while we hook it up though. Changing the TupDesc
4823 : * may be a problem, so keep highest lock.
4824 : */
4825 386 : case AT_AddInherit:
4826 : case AT_DropInherit:
4827 386 : cmd_lockmode = AccessExclusiveLock;
4828 386 : break;
4829 :
4830 : /*
4831 : * These subcommands affect implicit row type conversion. They
4832 : * have affects similar to CREATE/DROP CAST on queries. don't
4833 : * provide for invalidating parse trees as a result of such
4834 : * changes, so we keep these at AccessExclusiveLock.
4835 : */
4836 46 : case AT_AddOf:
4837 : case AT_DropOf:
4838 46 : cmd_lockmode = AccessExclusiveLock;
4839 46 : break;
4840 :
4841 : /*
4842 : * Only used by CREATE OR REPLACE VIEW which must conflict
4843 : * with an SELECTs currently using the view.
4844 : */
4845 137 : case AT_ReplaceRelOptions:
4846 137 : cmd_lockmode = AccessExclusiveLock;
4847 137 : break;
4848 :
4849 : /*
4850 : * These subcommands affect general strategies for performance
4851 : * and maintenance, though don't change the semantic results
4852 : * from normal data reads and writes. Delaying an ALTER TABLE
4853 : * behind currently active writes only delays the point where
4854 : * the new strategy begins to take effect, so there is no
4855 : * benefit in waiting. In this case the minimum restriction
4856 : * applies: we don't currently allow concurrent catalog
4857 : * updates.
4858 : */
4859 158 : case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4860 : case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4861 : case AT_DropCluster: /* Uses MVCC in getIndexes() */
4862 : case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4863 : case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4864 158 : cmd_lockmode = ShareUpdateExclusiveLock;
4865 158 : break;
4866 :
4867 75 : case AT_SetLogged:
4868 : case AT_SetUnLogged:
4869 75 : cmd_lockmode = AccessExclusiveLock;
4870 75 : break;
4871 :
4872 275 : case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4873 275 : cmd_lockmode = ShareUpdateExclusiveLock;
4874 275 : break;
4875 :
4876 : /*
4877 : * Rel options are more complex than first appears. Options
4878 : * are set here for tables, views and indexes; for historical
4879 : * reasons these can all be used with ALTER TABLE, so we can't
4880 : * decide between them using the basic grammar.
4881 : */
4882 498 : case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4883 : * getTables() */
4884 : case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4885 : * getTables() */
4886 498 : cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4887 498 : break;
4888 :
4889 1911 : case AT_AttachPartition:
4890 1911 : cmd_lockmode = ShareUpdateExclusiveLock;
4891 1911 : break;
4892 :
4893 385 : case AT_DetachPartition:
4894 385 : if (((PartitionCmd *) cmd->def)->concurrent)
4895 87 : cmd_lockmode = ShareUpdateExclusiveLock;
4896 : else
4897 298 : cmd_lockmode = AccessExclusiveLock;
4898 385 : break;
4899 :
4900 11 : case AT_DetachPartitionFinalize:
4901 11 : cmd_lockmode = ShareUpdateExclusiveLock;
4902 11 : break;
4903 :
4904 457 : case AT_MergePartitions:
4905 : case AT_SplitPartition:
4906 457 : cmd_lockmode = AccessExclusiveLock;
4907 457 : break;
4908 :
4909 0 : default: /* oops */
4910 0 : elog(ERROR, "unrecognized alter table type: %d",
4911 : (int) cmd->subtype);
4912 : break;
4913 : }
4914 :
4915 : /*
4916 : * Take the greatest lockmode from any subcommand
4917 : */
4918 22797 : if (cmd_lockmode > lockmode)
4919 19113 : lockmode = cmd_lockmode;
4920 : }
4921 :
4922 21935 : return lockmode;
4923 : }
4924 :
4925 : /*
4926 : * ATController provides top level control over the phases.
4927 : *
4928 : * parsetree is passed in to allow it to be passed to event triggers
4929 : * when requested.
4930 : */
4931 : static void
4932 21748 : ATController(AlterTableStmt *parsetree,
4933 : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4934 : AlterTableUtilityContext *context)
4935 : {
4936 21748 : List *wqueue = NIL;
4937 : ListCell *lcmd;
4938 :
4939 : /* Phase 1: preliminary examination of commands, create work queue */
4940 44057 : foreach(lcmd, cmds)
4941 : {
4942 22606 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4943 :
4944 22606 : ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4945 : }
4946 :
4947 : /* Close the relation, but keep lock until commit */
4948 21451 : relation_close(rel, NoLock);
4949 :
4950 : /* Phase 2: update system catalogs */
4951 21451 : ATRewriteCatalogs(&wqueue, lockmode, context);
4952 :
4953 : /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4954 19256 : ATRewriteTables(parsetree, &wqueue, lockmode, context);
4955 18851 : }
4956 :
4957 : /*
4958 : * ATPrepCmd
4959 : *
4960 : * Traffic cop for ALTER TABLE Phase 1 operations, including simple
4961 : * recursion and permission checks.
4962 : *
4963 : * Caller must have acquired appropriate lock type on relation already.
4964 : * This lock should be held until commit.
4965 : */
4966 : static void
4967 23225 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4968 : bool recurse, bool recursing, LOCKMODE lockmode,
4969 : AlterTableUtilityContext *context)
4970 : {
4971 : AlteredTableInfo *tab;
4972 23225 : AlterTablePass pass = AT_PASS_UNSET;
4973 :
4974 : /* Find or create work queue entry for this table */
4975 23225 : tab = ATGetQueueEntry(wqueue, rel);
4976 :
4977 : /*
4978 : * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
4979 : * partitions that are pending detach.
4980 : */
4981 23225 : if (rel->rd_rel->relispartition &&
4982 1822 : cmd->subtype != AT_DetachPartitionFinalize &&
4983 911 : PartitionHasPendingDetach(RelationGetRelid(rel)))
4984 1 : ereport(ERROR,
4985 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4986 : errmsg("cannot alter partition \"%s\" with an incomplete detach",
4987 : RelationGetRelationName(rel)),
4988 : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
4989 :
4990 : /*
4991 : * Copy the original subcommand for each table, so we can scribble on it.
4992 : * This avoids conflicts when different child tables need to make
4993 : * different parse transformations (for example, the same column may have
4994 : * different column numbers in different children).
4995 : */
4996 23224 : cmd = copyObject(cmd);
4997 :
4998 : /*
4999 : * Do permissions and relkind checking, recursion to child tables if
5000 : * needed, and any additional phase-1 processing needed. (But beware of
5001 : * adding any processing that looks at table details that another
5002 : * subcommand could change. In some cases we reject multiple subcommands
5003 : * that could try to change the same state in contrary ways.)
5004 : */
5005 23224 : switch (cmd->subtype)
5006 : {
5007 1617 : case AT_AddColumn: /* ADD COLUMN */
5008 1617 : ATSimplePermissions(cmd->subtype, rel,
5009 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5010 : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5011 1617 : ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
5012 : lockmode, context);
5013 : /* Recursion occurs during execution phase */
5014 1609 : pass = AT_PASS_ADD_COL;
5015 1609 : break;
5016 21 : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5017 21 : ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
5018 21 : ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
5019 : lockmode, context);
5020 : /* Recursion occurs during execution phase */
5021 21 : pass = AT_PASS_ADD_COL;
5022 21 : break;
5023 407 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5024 :
5025 : /*
5026 : * We allow defaults on views so that INSERT into a view can have
5027 : * default-ish behavior. This works because the rewriter
5028 : * substitutes default values into INSERTs before it expands
5029 : * rules.
5030 : */
5031 407 : ATSimplePermissions(cmd->subtype, rel,
5032 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5033 : ATT_FOREIGN_TABLE);
5034 407 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5035 : /* No command-specific prep needed */
5036 407 : pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
5037 407 : break;
5038 53 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5039 : /* This is currently used only in CREATE TABLE */
5040 : /* (so the permission check really isn't necessary) */
5041 53 : ATSimplePermissions(cmd->subtype, rel,
5042 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5043 : /* This command never recurses */
5044 53 : pass = AT_PASS_ADD_OTHERCONSTR;
5045 53 : break;
5046 107 : case AT_AddIdentity:
5047 107 : ATSimplePermissions(cmd->subtype, rel,
5048 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5049 : ATT_FOREIGN_TABLE);
5050 : /* Set up recursion for phase 2; no other prep needed */
5051 107 : if (recurse)
5052 103 : cmd->recurse = true;
5053 107 : pass = AT_PASS_ADD_OTHERCONSTR;
5054 107 : break;
5055 41 : case AT_SetIdentity:
5056 41 : ATSimplePermissions(cmd->subtype, rel,
5057 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5058 : ATT_FOREIGN_TABLE);
5059 : /* Set up recursion for phase 2; no other prep needed */
5060 41 : if (recurse)
5061 37 : cmd->recurse = true;
5062 : /* This should run after AddIdentity, so do it in MISC pass */
5063 41 : pass = AT_PASS_MISC;
5064 41 : break;
5065 37 : case AT_DropIdentity:
5066 37 : ATSimplePermissions(cmd->subtype, rel,
5067 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5068 : ATT_FOREIGN_TABLE);
5069 : /* Set up recursion for phase 2; no other prep needed */
5070 37 : if (recurse)
5071 33 : cmd->recurse = true;
5072 37 : pass = AT_PASS_DROP;
5073 37 : break;
5074 181 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5075 181 : ATSimplePermissions(cmd->subtype, rel,
5076 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5077 : /* Set up recursion for phase 2; no other prep needed */
5078 177 : if (recurse)
5079 165 : cmd->recurse = true;
5080 177 : pass = AT_PASS_DROP;
5081 177 : break;
5082 276 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5083 276 : ATSimplePermissions(cmd->subtype, rel,
5084 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5085 : /* Set up recursion for phase 2; no other prep needed */
5086 272 : if (recurse)
5087 252 : cmd->recurse = true;
5088 272 : pass = AT_PASS_COL_ATTRS;
5089 272 : break;
5090 169 : case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */
5091 169 : ATSimplePermissions(cmd->subtype, rel,
5092 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5093 169 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5094 169 : pass = AT_PASS_SET_EXPRESSION;
5095 169 : break;
5096 57 : case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
5097 57 : ATSimplePermissions(cmd->subtype, rel,
5098 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5099 57 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5100 57 : ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
5101 41 : pass = AT_PASS_DROP;
5102 41 : break;
5103 111 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5104 111 : ATSimplePermissions(cmd->subtype, rel,
5105 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
5106 : ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
5107 111 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5108 : /* No command-specific prep needed */
5109 111 : pass = AT_PASS_MISC;
5110 111 : break;
5111 29 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5112 : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5113 29 : ATSimplePermissions(cmd->subtype, rel,
5114 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5115 : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5116 : /* This command never recurses */
5117 21 : pass = AT_PASS_MISC;
5118 21 : break;
5119 173 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5120 173 : ATSimplePermissions(cmd->subtype, rel,
5121 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5122 : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5123 173 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5124 : /* No command-specific prep needed */
5125 173 : pass = AT_PASS_MISC;
5126 173 : break;
5127 48 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5128 48 : ATSimplePermissions(cmd->subtype, rel,
5129 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5130 : /* This command never recurses */
5131 : /* No command-specific prep needed */
5132 48 : pass = AT_PASS_MISC;
5133 48 : break;
5134 1151 : case AT_DropColumn: /* DROP COLUMN */
5135 1151 : ATSimplePermissions(cmd->subtype, rel,
5136 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5137 : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5138 1147 : ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
5139 : lockmode, context);
5140 : /* Recursion occurs during execution phase */
5141 1139 : pass = AT_PASS_DROP;
5142 1139 : break;
5143 0 : case AT_AddIndex: /* ADD INDEX */
5144 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5145 : /* This command never recurses */
5146 : /* No command-specific prep needed */
5147 0 : pass = AT_PASS_ADD_INDEX;
5148 0 : break;
5149 10379 : case AT_AddConstraint: /* ADD CONSTRAINT */
5150 10379 : ATSimplePermissions(cmd->subtype, rel,
5151 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5152 10379 : ATPrepAddPrimaryKey(wqueue, rel, cmd, recurse, lockmode, context);
5153 10359 : if (recurse)
5154 : {
5155 : /* recurses at exec time; lock descendants and set flag */
5156 10116 : (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5157 10116 : cmd->recurse = true;
5158 : }
5159 10359 : pass = AT_PASS_ADD_CONSTR;
5160 10359 : break;
5161 0 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5162 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5163 : /* This command never recurses */
5164 : /* No command-specific prep needed */
5165 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5166 0 : break;
5167 578 : case AT_DropConstraint: /* DROP CONSTRAINT */
5168 578 : ATSimplePermissions(cmd->subtype, rel,
5169 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5170 578 : ATCheckPartitionsNotInUse(rel, lockmode);
5171 : /* Other recursion occurs during execution phase */
5172 : /* No command-specific prep needed except saving recurse flag */
5173 574 : if (recurse)
5174 550 : cmd->recurse = true;
5175 574 : pass = AT_PASS_DROP;
5176 574 : break;
5177 952 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5178 952 : ATSimplePermissions(cmd->subtype, rel,
5179 : ATT_TABLE | ATT_PARTITIONED_TABLE |
5180 : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5181 : /* See comments for ATPrepAlterColumnType */
5182 952 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
5183 : AT_PASS_UNSET, context);
5184 : Assert(cmd != NULL);
5185 : /* Performs own recursion */
5186 948 : ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
5187 : lockmode, context);
5188 817 : pass = AT_PASS_ALTER_TYPE;
5189 817 : break;
5190 94 : case AT_AlterColumnGenericOptions:
5191 94 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5192 : /* This command never recurses */
5193 : /* No command-specific prep needed */
5194 94 : pass = AT_PASS_MISC;
5195 94 : break;
5196 1142 : case AT_ChangeOwner: /* ALTER OWNER */
5197 : /* This command never recurses */
5198 : /* No command-specific prep needed */
5199 1142 : pass = AT_PASS_MISC;
5200 1142 : break;
5201 43 : case AT_ClusterOn: /* CLUSTER ON */
5202 : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5203 43 : ATSimplePermissions(cmd->subtype, rel,
5204 : ATT_TABLE | ATT_MATVIEW);
5205 : /* These commands never recurse */
5206 : /* No command-specific prep needed */
5207 35 : pass = AT_PASS_MISC;
5208 35 : break;
5209 75 : case AT_SetLogged: /* SET LOGGED */
5210 : case AT_SetUnLogged: /* SET UNLOGGED */
5211 75 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
5212 67 : if (tab->chgPersistence)
5213 0 : ereport(ERROR,
5214 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5215 : errmsg("cannot change persistence setting twice")));
5216 67 : ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
5217 59 : pass = AT_PASS_MISC;
5218 59 : break;
5219 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5220 4 : ATSimplePermissions(cmd->subtype, rel,
5221 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5222 4 : pass = AT_PASS_DROP;
5223 4 : break;
5224 85 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5225 85 : ATSimplePermissions(cmd->subtype, rel,
5226 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5227 :
5228 : /* check if another access method change was already requested */
5229 85 : if (tab->chgAccessMethod)
5230 12 : ereport(ERROR,
5231 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5232 : errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
5233 :
5234 73 : ATPrepSetAccessMethod(tab, rel, cmd->name);
5235 73 : pass = AT_PASS_MISC; /* does not matter; no work in Phase 2 */
5236 73 : break;
5237 111 : case AT_SetTableSpace: /* SET TABLESPACE */
5238 111 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
5239 : ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
5240 : /* This command never recurses */
5241 111 : ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
5242 111 : pass = AT_PASS_MISC; /* doesn't actually matter */
5243 111 : break;
5244 633 : case AT_SetRelOptions: /* SET (...) */
5245 : case AT_ResetRelOptions: /* RESET (...) */
5246 : case AT_ReplaceRelOptions: /* reset them all, then set just these */
5247 633 : ATSimplePermissions(cmd->subtype, rel,
5248 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5249 : ATT_MATVIEW | ATT_INDEX);
5250 : /* This command never recurses */
5251 : /* No command-specific prep needed */
5252 632 : pass = AT_PASS_MISC;
5253 632 : break;
5254 305 : case AT_AddInherit: /* INHERIT */
5255 305 : ATSimplePermissions(cmd->subtype, rel,
5256 : ATT_TABLE | ATT_FOREIGN_TABLE);
5257 : /* This command never recurses */
5258 301 : ATPrepChangeInherit(rel);
5259 289 : pass = AT_PASS_MISC;
5260 289 : break;
5261 81 : case AT_DropInherit: /* NO INHERIT */
5262 81 : ATSimplePermissions(cmd->subtype, rel,
5263 : ATT_TABLE | ATT_FOREIGN_TABLE);
5264 : /* This command never recurses */
5265 77 : ATPrepChangeInherit(rel);
5266 69 : pass = AT_PASS_MISC;
5267 69 : break;
5268 300 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5269 300 : ATSimplePermissions(cmd->subtype, rel,
5270 : ATT_TABLE | ATT_PARTITIONED_TABLE);
5271 : /* Recursion occurs during execution phase */
5272 296 : if (recurse)
5273 288 : cmd->recurse = true;
5274 296 : pass = AT_PASS_MISC;
5275 296 : break;
5276 275 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5277 275 : ATSimplePermissions(cmd->subtype, rel,
5278 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5279 : /* Recursion occurs during execution phase */
5280 : /* No command-specific prep needed except saving recurse flag */
5281 275 : if (recurse)
5282 275 : cmd->recurse = true;
5283 275 : pass = AT_PASS_MISC;
5284 275 : break;
5285 306 : case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
5286 306 : ATSimplePermissions(cmd->subtype, rel,
5287 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5288 306 : pass = AT_PASS_MISC;
5289 : /* This command never recurses */
5290 : /* No command-specific prep needed */
5291 306 : break;
5292 191 : case AT_EnableTrig: /* ENABLE TRIGGER variants */
5293 : case AT_EnableAlwaysTrig:
5294 : case AT_EnableReplicaTrig:
5295 : case AT_EnableTrigAll:
5296 : case AT_EnableTrigUser:
5297 : case AT_DisableTrig: /* DISABLE TRIGGER variants */
5298 : case AT_DisableTrigAll:
5299 : case AT_DisableTrigUser:
5300 191 : ATSimplePermissions(cmd->subtype, rel,
5301 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5302 : /* Set up recursion for phase 2; no other prep needed */
5303 191 : if (recurse)
5304 174 : cmd->recurse = true;
5305 191 : pass = AT_PASS_MISC;
5306 191 : break;
5307 411 : case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
5308 : case AT_EnableAlwaysRule:
5309 : case AT_EnableReplicaRule:
5310 : case AT_DisableRule:
5311 : case AT_AddOf: /* OF */
5312 : case AT_DropOf: /* NOT OF */
5313 : case AT_EnableRowSecurity:
5314 : case AT_DisableRowSecurity:
5315 : case AT_ForceRowSecurity:
5316 : case AT_NoForceRowSecurity:
5317 411 : ATSimplePermissions(cmd->subtype, rel,
5318 : ATT_TABLE | ATT_PARTITIONED_TABLE);
5319 : /* These commands never recurse */
5320 : /* No command-specific prep needed */
5321 411 : pass = AT_PASS_MISC;
5322 411 : break;
5323 33 : case AT_GenericOptions:
5324 33 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5325 : /* No command-specific prep needed */
5326 33 : pass = AT_PASS_MISC;
5327 33 : break;
5328 1903 : case AT_AttachPartition:
5329 1903 : ATSimplePermissions(cmd->subtype, rel,
5330 : ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
5331 : /* No command-specific prep needed */
5332 1899 : pass = AT_PASS_MISC;
5333 1899 : break;
5334 385 : case AT_DetachPartition:
5335 385 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5336 : /* No command-specific prep needed */
5337 373 : pass = AT_PASS_MISC;
5338 373 : break;
5339 11 : case AT_DetachPartitionFinalize:
5340 11 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5341 : /* No command-specific prep needed */
5342 7 : pass = AT_PASS_MISC;
5343 7 : break;
5344 449 : case AT_MergePartitions:
5345 : case AT_SplitPartition:
5346 449 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5347 : /* No command-specific prep needed */
5348 445 : pass = AT_PASS_MISC;
5349 445 : break;
5350 0 : default: /* oops */
5351 0 : elog(ERROR, "unrecognized alter table type: %d",
5352 : (int) cmd->subtype);
5353 : pass = AT_PASS_UNSET; /* keep compiler quiet */
5354 : break;
5355 : }
5356 : Assert(pass > AT_PASS_UNSET);
5357 :
5358 : /* Add the subcommand to the appropriate list for phase 2 */
5359 22920 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
5360 22920 : }
5361 :
5362 : /*
5363 : * ATRewriteCatalogs
5364 : *
5365 : * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
5366 : * dispatched in a "safe" execution order (designed to avoid unnecessary
5367 : * conflicts).
5368 : */
5369 : static void
5370 21451 : ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
5371 : AlterTableUtilityContext *context)
5372 : {
5373 : ListCell *ltab;
5374 :
5375 : /*
5376 : * We process all the tables "in parallel", one pass at a time. This is
5377 : * needed because we may have to propagate work from one table to another
5378 : * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
5379 : * re-adding of the foreign key constraint to the other table). Work can
5380 : * only be propagated into later passes, however.
5381 : */
5382 269389 : for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
5383 : {
5384 : /* Go through each table that needs to be processed */
5385 509534 : foreach(ltab, *wqueue)
5386 : {
5387 261596 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5388 261596 : List *subcmds = tab->subcmds[pass];
5389 : ListCell *lcmd;
5390 :
5391 261596 : if (subcmds == NIL)
5392 224972 : continue;
5393 :
5394 : /*
5395 : * Open the relation and store it in tab. This allows subroutines
5396 : * close and reopen, if necessary. Appropriate lock was obtained
5397 : * by phase 1, needn't get it again.
5398 : */
5399 36624 : tab->rel = relation_open(tab->relid, NoLock);
5400 :
5401 73443 : foreach(lcmd, subcmds)
5402 39014 : ATExecCmd(wqueue, tab,
5403 39014 : lfirst_node(AlterTableCmd, lcmd),
5404 : lockmode, pass, context);
5405 :
5406 : /*
5407 : * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
5408 : * (this is not done in ATExecAlterColumnType since it should be
5409 : * done only once if multiple columns of a table are altered).
5410 : */
5411 34429 : if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
5412 890 : ATPostAlterTypeCleanup(wqueue, tab, lockmode);
5413 :
5414 34429 : if (tab->rel)
5415 : {
5416 34429 : relation_close(tab->rel, NoLock);
5417 34429 : tab->rel = NULL;
5418 : }
5419 : }
5420 : }
5421 :
5422 : /* Check to see if a toast table must be added. */
5423 41562 : foreach(ltab, *wqueue)
5424 : {
5425 22306 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5426 :
5427 : /*
5428 : * If the table is source table of ATTACH PARTITION command, we did
5429 : * not modify anything about it that will change its toasting
5430 : * requirement, so no need to check.
5431 : */
5432 22306 : if (((tab->relkind == RELKIND_RELATION ||
5433 4350 : tab->relkind == RELKIND_PARTITIONED_TABLE) &&
5434 21066 : tab->partition_constraint == NULL) ||
5435 2647 : tab->relkind == RELKIND_MATVIEW)
5436 19689 : AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
5437 : }
5438 19256 : }
5439 :
5440 : /*
5441 : * ATExecCmd: dispatch a subcommand to appropriate execution routine
5442 : */
5443 : static void
5444 39014 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
5445 : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
5446 : AlterTableUtilityContext *context)
5447 : {
5448 39014 : ObjectAddress address = InvalidObjectAddress;
5449 39014 : Relation rel = tab->rel;
5450 :
5451 39014 : switch (cmd->subtype)
5452 : {
5453 1626 : case AT_AddColumn: /* ADD COLUMN */
5454 : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5455 1626 : address = ATExecAddColumn(wqueue, tab, rel, &cmd,
5456 1626 : cmd->recurse, false,
5457 : lockmode, cur_pass, context);
5458 1454 : break;
5459 383 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5460 383 : address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
5461 339 : break;
5462 53 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5463 53 : address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
5464 53 : break;
5465 107 : case AT_AddIdentity:
5466 107 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5467 : cur_pass, context);
5468 : Assert(cmd != NULL);
5469 99 : address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5470 63 : break;
5471 41 : case AT_SetIdentity:
5472 41 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5473 : cur_pass, context);
5474 : Assert(cmd != NULL);
5475 41 : address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5476 25 : break;
5477 37 : case AT_DropIdentity:
5478 37 : address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
5479 25 : break;
5480 177 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5481 177 : address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
5482 109 : break;
5483 272 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5484 272 : address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
5485 272 : cmd->recurse, false, lockmode);
5486 252 : break;
5487 169 : case AT_SetExpression:
5488 169 : address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
5489 157 : break;
5490 37 : case AT_DropExpression:
5491 37 : address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
5492 21 : break;
5493 111 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5494 111 : address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
5495 79 : break;
5496 17 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5497 17 : address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
5498 17 : break;
5499 4 : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5500 4 : address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
5501 4 : break;
5502 173 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5503 173 : address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
5504 165 : break;
5505 48 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5506 48 : address = ATExecSetCompression(rel, cmd->name, cmd->def,
5507 : lockmode);
5508 44 : break;
5509 1139 : case AT_DropColumn: /* DROP COLUMN */
5510 1139 : address = ATExecDropColumn(wqueue, rel, cmd->name,
5511 1139 : cmd->behavior, cmd->recurse, false,
5512 1139 : cmd->missing_ok, lockmode,
5513 : NULL);
5514 1011 : break;
5515 761 : case AT_AddIndex: /* ADD INDEX */
5516 761 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
5517 : lockmode);
5518 648 : break;
5519 307 : case AT_ReAddIndex: /* ADD INDEX */
5520 307 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
5521 : lockmode);
5522 307 : break;
5523 53 : case AT_ReAddStatistics: /* ADD STATISTICS */
5524 53 : address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
5525 : true, lockmode);
5526 53 : break;
5527 18405 : case AT_AddConstraint: /* ADD CONSTRAINT */
5528 : /* Transform the command only during initial examination */
5529 18405 : if (cur_pass == AT_PASS_ADD_CONSTR)
5530 10339 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
5531 10359 : cmd->recurse, lockmode,
5532 : cur_pass, context);
5533 : /* Depending on constraint type, might be no more work to do now */
5534 18385 : if (cmd != NULL)
5535 : address =
5536 8046 : ATExecAddConstraint(wqueue, tab, rel,
5537 8046 : (Constraint *) cmd->def,
5538 8046 : cmd->recurse, false, lockmode);
5539 17928 : break;
5540 257 : case AT_ReAddConstraint: /* Re-add pre-existing check constraint */
5541 : address =
5542 257 : ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
5543 : true, true, lockmode);
5544 249 : break;
5545 9 : case AT_ReAddDomainConstraint: /* Re-add pre-existing domain check
5546 : * constraint */
5547 : address =
5548 9 : AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
5549 9 : ((AlterDomainStmt *) cmd->def)->def,
5550 : NULL);
5551 5 : break;
5552 52 : case AT_ReAddComment: /* Re-add existing comment */
5553 52 : address = CommentObject((CommentStmt *) cmd->def);
5554 52 : break;
5555 6653 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5556 6653 : address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
5557 : lockmode);
5558 6645 : break;
5559 296 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5560 296 : address = ATExecAlterConstraint(wqueue, rel,
5561 296 : castNode(ATAlterConstraint, cmd->def),
5562 296 : cmd->recurse, lockmode);
5563 240 : break;
5564 275 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5565 275 : address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
5566 : false, lockmode);
5567 271 : break;
5568 574 : case AT_DropConstraint: /* DROP CONSTRAINT */
5569 574 : ATExecDropConstraint(rel, cmd->name, cmd->behavior,
5570 574 : cmd->recurse,
5571 574 : cmd->missing_ok, lockmode);
5572 434 : break;
5573 793 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5574 : /* parse transformation was done earlier */
5575 793 : address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
5576 765 : break;
5577 94 : case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
5578 : address =
5579 94 : ATExecAlterColumnGenericOptions(rel, cmd->name,
5580 94 : (List *) cmd->def, lockmode);
5581 90 : break;
5582 1142 : case AT_ChangeOwner: /* ALTER OWNER */
5583 1139 : ATExecChangeOwner(RelationGetRelid(rel),
5584 1142 : get_rolespec_oid(cmd->newowner, false),
5585 : false, lockmode);
5586 1131 : break;
5587 39 : case AT_ClusterOn: /* CLUSTER ON */
5588 39 : address = ATExecClusterOn(rel, cmd->name, lockmode);
5589 39 : break;
5590 8 : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5591 8 : ATExecDropCluster(rel, lockmode);
5592 8 : break;
5593 59 : case AT_SetLogged: /* SET LOGGED */
5594 : case AT_SetUnLogged: /* SET UNLOGGED */
5595 59 : break;
5596 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5597 : /* nothing to do here, oid columns don't exist anymore */
5598 4 : break;
5599 61 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5600 :
5601 : /*
5602 : * Only do this for partitioned tables, for which this is just a
5603 : * catalog change. Tables with storage are handled by Phase 3.
5604 : */
5605 61 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
5606 33 : tab->chgAccessMethod)
5607 29 : ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
5608 61 : break;
5609 111 : case AT_SetTableSpace: /* SET TABLESPACE */
5610 :
5611 : /*
5612 : * Only do this for partitioned tables and indexes, for which this
5613 : * is just a catalog change. Other relation types which have
5614 : * storage are handled by Phase 3.
5615 : */
5616 111 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
5617 103 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
5618 24 : ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
5619 :
5620 107 : break;
5621 632 : case AT_SetRelOptions: /* SET (...) */
5622 : case AT_ResetRelOptions: /* RESET (...) */
5623 : case AT_ReplaceRelOptions: /* replace entire option list */
5624 632 : ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
5625 598 : break;
5626 65 : case AT_EnableTrig: /* ENABLE TRIGGER name */
5627 65 : ATExecEnableDisableTrigger(rel, cmd->name,
5628 : TRIGGER_FIRES_ON_ORIGIN, false,
5629 65 : cmd->recurse,
5630 : lockmode);
5631 65 : break;
5632 27 : case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
5633 27 : ATExecEnableDisableTrigger(rel, cmd->name,
5634 : TRIGGER_FIRES_ALWAYS, false,
5635 27 : cmd->recurse,
5636 : lockmode);
5637 27 : break;
5638 8 : case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
5639 8 : ATExecEnableDisableTrigger(rel, cmd->name,
5640 : TRIGGER_FIRES_ON_REPLICA, false,
5641 8 : cmd->recurse,
5642 : lockmode);
5643 8 : break;
5644 75 : case AT_DisableTrig: /* DISABLE TRIGGER name */
5645 75 : ATExecEnableDisableTrigger(rel, cmd->name,
5646 : TRIGGER_DISABLED, false,
5647 75 : cmd->recurse,
5648 : lockmode);
5649 75 : break;
5650 0 : case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
5651 0 : ATExecEnableDisableTrigger(rel, NULL,
5652 : TRIGGER_FIRES_ON_ORIGIN, false,
5653 0 : cmd->recurse,
5654 : lockmode);
5655 0 : break;
5656 8 : case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
5657 8 : ATExecEnableDisableTrigger(rel, NULL,
5658 : TRIGGER_DISABLED, false,
5659 8 : cmd->recurse,
5660 : lockmode);
5661 8 : break;
5662 0 : case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
5663 0 : ATExecEnableDisableTrigger(rel, NULL,
5664 : TRIGGER_FIRES_ON_ORIGIN, true,
5665 0 : cmd->recurse,
5666 : lockmode);
5667 0 : break;
5668 8 : case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
5669 8 : ATExecEnableDisableTrigger(rel, NULL,
5670 : TRIGGER_DISABLED, true,
5671 8 : cmd->recurse,
5672 : lockmode);
5673 8 : break;
5674 :
5675 5 : case AT_EnableRule: /* ENABLE RULE name */
5676 5 : ATExecEnableDisableRule(rel, cmd->name,
5677 : RULE_FIRES_ON_ORIGIN, lockmode);
5678 5 : break;
5679 0 : case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
5680 0 : ATExecEnableDisableRule(rel, cmd->name,
5681 : RULE_FIRES_ALWAYS, lockmode);
5682 0 : break;
5683 4 : case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
5684 4 : ATExecEnableDisableRule(rel, cmd->name,
5685 : RULE_FIRES_ON_REPLICA, lockmode);
5686 4 : break;
5687 20 : case AT_DisableRule: /* DISABLE RULE name */
5688 20 : ATExecEnableDisableRule(rel, cmd->name,
5689 : RULE_DISABLED, lockmode);
5690 20 : break;
5691 :
5692 289 : case AT_AddInherit:
5693 289 : address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
5694 209 : break;
5695 69 : case AT_DropInherit:
5696 69 : address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
5697 65 : break;
5698 42 : case AT_AddOf:
5699 42 : address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
5700 18 : break;
5701 4 : case AT_DropOf:
5702 4 : ATExecDropOf(rel, lockmode);
5703 4 : break;
5704 318 : case AT_ReplicaIdentity:
5705 318 : ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
5706 286 : break;
5707 240 : case AT_EnableRowSecurity:
5708 240 : ATExecSetRowSecurity(rel, true);
5709 240 : break;
5710 6 : case AT_DisableRowSecurity:
5711 6 : ATExecSetRowSecurity(rel, false);
5712 6 : break;
5713 70 : case AT_ForceRowSecurity:
5714 70 : ATExecForceNoForceRowSecurity(rel, true);
5715 70 : break;
5716 20 : case AT_NoForceRowSecurity:
5717 20 : ATExecForceNoForceRowSecurity(rel, false);
5718 20 : break;
5719 33 : case AT_GenericOptions:
5720 33 : ATExecGenericOptions(rel, (List *) cmd->def);
5721 32 : break;
5722 1899 : case AT_AttachPartition:
5723 1899 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5724 : cur_pass, context);
5725 : Assert(cmd != NULL);
5726 1883 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5727 1608 : address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
5728 : context);
5729 : else
5730 275 : address = ATExecAttachPartitionIdx(wqueue, rel,
5731 275 : ((PartitionCmd *) cmd->def)->name);
5732 1619 : break;
5733 373 : case AT_DetachPartition:
5734 373 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5735 : cur_pass, context);
5736 : Assert(cmd != NULL);
5737 : /* ATPrepCmd ensures it must be a table */
5738 : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5739 373 : address = ATExecDetachPartition(wqueue, tab, rel,
5740 373 : ((PartitionCmd *) cmd->def)->name,
5741 373 : ((PartitionCmd *) cmd->def)->concurrent);
5742 296 : break;
5743 7 : case AT_DetachPartitionFinalize:
5744 7 : address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
5745 7 : break;
5746 180 : case AT_MergePartitions:
5747 180 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5748 : cur_pass, context);
5749 : Assert(cmd != NULL);
5750 : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5751 124 : ATExecMergePartitions(wqueue, tab, rel, (PartitionCmd *) cmd->def,
5752 : context);
5753 90 : break;
5754 265 : case AT_SplitPartition:
5755 265 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5756 : cur_pass, context);
5757 : Assert(cmd != NULL);
5758 : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5759 133 : ATExecSplitPartition(wqueue, tab, rel, (PartitionCmd *) cmd->def,
5760 : context);
5761 125 : break;
5762 0 : default: /* oops */
5763 0 : elog(ERROR, "unrecognized alter table type: %d",
5764 : (int) cmd->subtype);
5765 : break;
5766 : }
5767 :
5768 : /*
5769 : * Report the subcommand to interested event triggers.
5770 : */
5771 36819 : if (cmd)
5772 26480 : EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
5773 :
5774 : /*
5775 : * Bump the command counter to ensure the next subcommand in the sequence
5776 : * can see the changes so far
5777 : */
5778 36819 : CommandCounterIncrement();
5779 36819 : }
5780 :
5781 : /*
5782 : * ATParseTransformCmd: perform parse transformation for one subcommand
5783 : *
5784 : * Returns the transformed subcommand tree, if there is one, else NULL.
5785 : *
5786 : * The parser may hand back additional AlterTableCmd(s) and/or other
5787 : * utility statements, either before or after the original subcommand.
5788 : * Other AlterTableCmds are scheduled into the appropriate slot of the
5789 : * AlteredTableInfo (they had better be for later passes than the current one).
5790 : * Utility statements that are supposed to happen before the AlterTableCmd
5791 : * are executed immediately. Those that are supposed to happen afterwards
5792 : * are added to the tab->afterStmts list to be done at the very end.
5793 : */
5794 : static AlterTableCmd *
5795 15709 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
5796 : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
5797 : AlterTablePass cur_pass, AlterTableUtilityContext *context)
5798 : {
5799 15709 : AlterTableCmd *newcmd = NULL;
5800 15709 : AlterTableStmt *atstmt = makeNode(AlterTableStmt);
5801 : List *beforeStmts;
5802 : List *afterStmts;
5803 : ListCell *lc;
5804 :
5805 : /* Gin up an AlterTableStmt with just this subcommand and this table */
5806 15709 : atstmt->relation =
5807 15709 : makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5808 15709 : pstrdup(RelationGetRelationName(rel)),
5809 : -1);
5810 15709 : atstmt->relation->inh = recurse;
5811 15709 : atstmt->cmds = list_make1(cmd);
5812 15709 : atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
5813 15709 : atstmt->missing_ok = false;
5814 :
5815 : /* Transform the AlterTableStmt */
5816 15709 : atstmt = transformAlterTableStmt(RelationGetRelid(rel),
5817 : atstmt,
5818 : context->queryString,
5819 : &beforeStmts,
5820 : &afterStmts);
5821 :
5822 : /* Execute any statements that should happen before these subcommand(s) */
5823 15784 : foreach(lc, beforeStmts)
5824 : {
5825 315 : Node *stmt = (Node *) lfirst(lc);
5826 :
5827 315 : ProcessUtilityForAlterTable(stmt, context);
5828 307 : CommandCounterIncrement();
5829 : }
5830 :
5831 : /* Examine the transformed subcommands and schedule them appropriately */
5832 36083 : foreach(lc, atstmt->cmds)
5833 : {
5834 20614 : AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
5835 : AlterTablePass pass;
5836 :
5837 : /*
5838 : * This switch need only cover the subcommand types that can be added
5839 : * by parse_utilcmd.c; otherwise, we'll use the default strategy of
5840 : * executing the subcommand immediately, as a substitute for the
5841 : * original subcommand. (Note, however, that this does cause
5842 : * AT_AddConstraint subcommands to be rescheduled into later passes,
5843 : * which is important for index and foreign key constraints.)
5844 : *
5845 : * We assume we needn't do any phase-1 checks for added subcommands.
5846 : */
5847 20614 : switch (cmd2->subtype)
5848 : {
5849 777 : case AT_AddIndex:
5850 777 : pass = AT_PASS_ADD_INDEX;
5851 777 : break;
5852 6653 : case AT_AddIndexConstraint:
5853 6653 : pass = AT_PASS_ADD_INDEXCONSTR;
5854 6653 : break;
5855 8054 : case AT_AddConstraint:
5856 : /* Recursion occurs during execution phase */
5857 8054 : if (recurse)
5858 8017 : cmd2->recurse = true;
5859 8054 : switch (castNode(Constraint, cmd2->def)->contype)
5860 : {
5861 5568 : case CONSTR_NOTNULL:
5862 5568 : pass = AT_PASS_COL_ATTRS;
5863 5568 : break;
5864 0 : case CONSTR_PRIMARY:
5865 : case CONSTR_UNIQUE:
5866 : case CONSTR_EXCLUSION:
5867 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5868 0 : break;
5869 2486 : default:
5870 2486 : pass = AT_PASS_ADD_OTHERCONSTR;
5871 2486 : break;
5872 : }
5873 8054 : break;
5874 0 : case AT_AlterColumnGenericOptions:
5875 : /* This command never recurses */
5876 : /* No command-specific prep needed */
5877 0 : pass = AT_PASS_MISC;
5878 0 : break;
5879 5130 : default:
5880 5130 : pass = cur_pass;
5881 5130 : break;
5882 : }
5883 :
5884 20614 : if (pass < cur_pass)
5885 : {
5886 : /* Cannot schedule into a pass we already finished */
5887 0 : elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
5888 : pass);
5889 : }
5890 20614 : else if (pass > cur_pass)
5891 : {
5892 : /* OK, queue it up for later */
5893 15484 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
5894 : }
5895 : else
5896 : {
5897 : /*
5898 : * We should see at most one subcommand for the current pass,
5899 : * which is the transformed version of the original subcommand.
5900 : */
5901 5130 : if (newcmd == NULL && cmd->subtype == cmd2->subtype)
5902 : {
5903 : /* Found the transformed version of our subcommand */
5904 5130 : newcmd = cmd2;
5905 : }
5906 : else
5907 0 : elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
5908 : pass);
5909 : }
5910 : }
5911 :
5912 : /* Queue up any after-statements to happen at the end */
5913 15469 : tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
5914 :
5915 15469 : return newcmd;
5916 : }
5917 :
5918 : /*
5919 : * ATRewriteTables: ALTER TABLE phase 3
5920 : */
5921 : static void
5922 19256 : ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
5923 : AlterTableUtilityContext *context)
5924 : {
5925 : ListCell *ltab;
5926 :
5927 : /* Go through each table that needs to be checked or rewritten */
5928 41144 : foreach(ltab, *wqueue)
5929 : {
5930 22222 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5931 :
5932 : /* Relations without storage may be ignored here */
5933 22222 : if (!RELKIND_HAS_STORAGE(tab->relkind))
5934 4166 : continue;
5935 :
5936 : /*
5937 : * If we change column data types, the operation has to be propagated
5938 : * to tables that use this table's rowtype as a column type.
5939 : * tab->newvals will also be non-NULL in the case where we're adding a
5940 : * column with a default. We choose to forbid that case as well,
5941 : * since composite types might eventually support defaults.
5942 : *
5943 : * (Eventually we'll probably need to check for composite type
5944 : * dependencies even when we're just scanning the table without a
5945 : * rewrite, but at the moment a composite type does not enforce any
5946 : * constraints, so it's not necessary/appropriate to enforce them just
5947 : * during ALTER.)
5948 : */
5949 18056 : if (tab->newvals != NIL || tab->rewrite > 0)
5950 : {
5951 : Relation rel;
5952 :
5953 1330 : rel = table_open(tab->relid, NoLock);
5954 1330 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
5955 1294 : table_close(rel, NoLock);
5956 : }
5957 :
5958 : /*
5959 : * We only need to rewrite the table if at least one column needs to
5960 : * be recomputed, or we are changing its persistence or access method.
5961 : *
5962 : * There are two reasons for requiring a rewrite when changing
5963 : * persistence: on one hand, we need to ensure that the buffers
5964 : * belonging to each of the two relations are marked with or without
5965 : * BM_PERMANENT properly. On the other hand, since rewriting creates
5966 : * and assigns a new relfilenumber, we automatically create or drop an
5967 : * init fork for the relation as appropriate.
5968 : */
5969 18020 : if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
5970 729 : {
5971 : /* Build a temporary relation and copy data */
5972 : Relation OldHeap;
5973 : Oid OIDNewHeap;
5974 : Oid NewAccessMethod;
5975 : Oid NewTableSpace;
5976 : char persistence;
5977 :
5978 798 : OldHeap = table_open(tab->relid, NoLock);
5979 :
5980 : /*
5981 : * We don't support rewriting of system catalogs; there are too
5982 : * many corner cases and too little benefit. In particular this
5983 : * is certainly not going to work for mapped catalogs.
5984 : */
5985 798 : if (IsSystemRelation(OldHeap))
5986 0 : ereport(ERROR,
5987 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5988 : errmsg("cannot rewrite system relation \"%s\"",
5989 : RelationGetRelationName(OldHeap))));
5990 :
5991 798 : if (RelationIsUsedAsCatalogTable(OldHeap))
5992 1 : ereport(ERROR,
5993 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5994 : errmsg("cannot rewrite table \"%s\" used as a catalog table",
5995 : RelationGetRelationName(OldHeap))));
5996 :
5997 : /*
5998 : * Don't allow rewrite on temp tables of other backends ... their
5999 : * local buffer manager is not going to cope. (This is redundant
6000 : * with the check in CheckAlterTableIsSafe, but for safety we'll
6001 : * check here too.)
6002 : */
6003 797 : if (RELATION_IS_OTHER_TEMP(OldHeap))
6004 0 : ereport(ERROR,
6005 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6006 : errmsg("cannot rewrite temporary tables of other sessions")));
6007 :
6008 : /*
6009 : * Select destination tablespace (same as original unless user
6010 : * requested a change)
6011 : */
6012 797 : if (tab->newTableSpace)
6013 0 : NewTableSpace = tab->newTableSpace;
6014 : else
6015 797 : NewTableSpace = OldHeap->rd_rel->reltablespace;
6016 :
6017 : /*
6018 : * Select destination access method (same as original unless user
6019 : * requested a change)
6020 : */
6021 797 : if (tab->chgAccessMethod)
6022 24 : NewAccessMethod = tab->newAccessMethod;
6023 : else
6024 773 : NewAccessMethod = OldHeap->rd_rel->relam;
6025 :
6026 : /*
6027 : * Select persistence of transient table (same as original unless
6028 : * user requested a change)
6029 : */
6030 797 : persistence = tab->chgPersistence ?
6031 762 : tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
6032 :
6033 797 : table_close(OldHeap, NoLock);
6034 :
6035 : /*
6036 : * Fire off an Event Trigger now, before actually rewriting the
6037 : * table.
6038 : *
6039 : * We don't support Event Trigger for nested commands anywhere,
6040 : * here included, and parsetree is given NULL when coming from
6041 : * AlterTableInternal.
6042 : *
6043 : * And fire it only once.
6044 : */
6045 797 : if (parsetree)
6046 797 : EventTriggerTableRewrite((Node *) parsetree,
6047 : tab->relid,
6048 : tab->rewrite);
6049 :
6050 : /*
6051 : * Create transient table that will receive the modified data.
6052 : *
6053 : * Ensure it is marked correctly as logged or unlogged. We have
6054 : * to do this here so that buffers for the new relfilenumber will
6055 : * have the right persistence set, and at the same time ensure
6056 : * that the original filenumbers's buffers will get read in with
6057 : * the correct setting (i.e. the original one). Otherwise a
6058 : * rollback after the rewrite would possibly result with buffers
6059 : * for the original filenumbers having the wrong persistence
6060 : * setting.
6061 : *
6062 : * NB: This relies on swap_relation_files() also swapping the
6063 : * persistence. That wouldn't work for pg_class, but that can't be
6064 : * unlogged anyway.
6065 : */
6066 793 : OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
6067 : persistence, lockmode);
6068 :
6069 : /*
6070 : * Copy the heap data into the new table with the desired
6071 : * modifications, and test the current data within the table
6072 : * against new constraints generated by ALTER TABLE commands.
6073 : */
6074 793 : ATRewriteTable(tab, OIDNewHeap);
6075 :
6076 : /*
6077 : * Swap the physical files of the old and new heaps, then rebuild
6078 : * indexes and discard the old heap. We can use RecentXmin for
6079 : * the table's new relfrozenxid because we rewrote all the tuples
6080 : * in ATRewriteTable, so no older Xid remains in the table. Also,
6081 : * we never try to swap toast tables by content, since we have no
6082 : * interest in letting this code work on system catalogs.
6083 : */
6084 733 : finish_heap_swap(tab->relid, OIDNewHeap,
6085 : false, false, true,
6086 733 : !OidIsValid(tab->newTableSpace),
6087 : true, /* reindex */
6088 : RecentXmin,
6089 : ReadNextMultiXactId(),
6090 : persistence);
6091 :
6092 729 : InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
6093 : }
6094 17222 : else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
6095 : {
6096 16 : if (tab->chgPersistence)
6097 16 : SequenceChangePersistence(tab->relid, tab->newrelpersistence);
6098 : }
6099 : else
6100 : {
6101 : /*
6102 : * If required, test the current data within the table against new
6103 : * constraints generated by ALTER TABLE commands, but don't
6104 : * rebuild data.
6105 : */
6106 17206 : if (tab->constraints != NIL || tab->verify_new_notnull ||
6107 15020 : tab->partition_constraint != NULL)
6108 3495 : ATRewriteTable(tab, InvalidOid);
6109 :
6110 : /*
6111 : * If we had SET TABLESPACE but no reason to reconstruct tuples,
6112 : * just do a block-by-block copy.
6113 : */
6114 16977 : if (tab->newTableSpace)
6115 87 : ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
6116 : }
6117 :
6118 : /*
6119 : * Also change persistence of owned sequences, so that it matches the
6120 : * table persistence.
6121 : */
6122 17722 : if (tab->chgPersistence)
6123 : {
6124 51 : List *seqlist = getOwnedSequences(tab->relid);
6125 : ListCell *lc;
6126 :
6127 83 : foreach(lc, seqlist)
6128 : {
6129 32 : Oid seq_relid = lfirst_oid(lc);
6130 :
6131 32 : SequenceChangePersistence(seq_relid, tab->newrelpersistence);
6132 : }
6133 : }
6134 : }
6135 :
6136 : /*
6137 : * Foreign key constraints are checked in a final pass, since (a) it's
6138 : * generally best to examine each one separately, and (b) it's at least
6139 : * theoretically possible that we have changed both relations of the
6140 : * foreign key, and we'd better have finished both rewrites before we try
6141 : * to read the tables.
6142 : */
6143 40561 : foreach(ltab, *wqueue)
6144 : {
6145 21710 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6146 21710 : Relation rel = NULL;
6147 : ListCell *lcon;
6148 :
6149 : /* Relations without storage may be ignored here too */
6150 21710 : if (!RELKIND_HAS_STORAGE(tab->relkind))
6151 4061 : continue;
6152 :
6153 19028 : foreach(lcon, tab->constraints)
6154 : {
6155 1450 : NewConstraint *con = lfirst(lcon);
6156 :
6157 1450 : if (con->contype == CONSTR_FOREIGN)
6158 : {
6159 828 : Constraint *fkconstraint = (Constraint *) con->qual;
6160 : Relation refrel;
6161 :
6162 828 : if (rel == NULL)
6163 : {
6164 : /* Long since locked, no need for another */
6165 820 : rel = table_open(tab->relid, NoLock);
6166 : }
6167 :
6168 828 : refrel = table_open(con->refrelid, RowShareLock);
6169 :
6170 828 : validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
6171 : con->refindid,
6172 : con->conid,
6173 828 : con->conwithperiod);
6174 :
6175 : /*
6176 : * No need to mark the constraint row as validated, we did
6177 : * that when we inserted the row earlier.
6178 : */
6179 :
6180 757 : table_close(refrel, NoLock);
6181 : }
6182 : }
6183 :
6184 17578 : if (rel)
6185 749 : table_close(rel, NoLock);
6186 : }
6187 :
6188 : /* Finally, run any afterStmts that were queued up */
6189 40463 : foreach(ltab, *wqueue)
6190 : {
6191 21612 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6192 : ListCell *lc;
6193 :
6194 21668 : foreach(lc, tab->afterStmts)
6195 : {
6196 56 : Node *stmt = (Node *) lfirst(lc);
6197 :
6198 56 : ProcessUtilityForAlterTable(stmt, context);
6199 56 : CommandCounterIncrement();
6200 : }
6201 : }
6202 18851 : }
6203 :
6204 : /*
6205 : * ATRewriteTable: scan or rewrite one table
6206 : *
6207 : * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
6208 : * must already hold AccessExclusiveLock on it.
6209 : */
6210 : static void
6211 4288 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
6212 : {
6213 : Relation oldrel;
6214 : Relation newrel;
6215 : TupleDesc oldTupDesc;
6216 : TupleDesc newTupDesc;
6217 4288 : bool needscan = false;
6218 : List *notnull_attrs;
6219 : List *notnull_virtual_attrs;
6220 : int i;
6221 : ListCell *l;
6222 : EState *estate;
6223 : CommandId mycid;
6224 : BulkInsertState bistate;
6225 : uint32 ti_options;
6226 4288 : ExprState *partqualstate = NULL;
6227 :
6228 : /*
6229 : * Open the relation(s). We have surely already locked the existing
6230 : * table.
6231 : */
6232 4288 : oldrel = table_open(tab->relid, NoLock);
6233 4288 : oldTupDesc = tab->oldDesc;
6234 4288 : newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
6235 :
6236 4288 : if (OidIsValid(OIDNewHeap))
6237 : {
6238 : Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
6239 : false));
6240 793 : newrel = table_open(OIDNewHeap, NoLock);
6241 : }
6242 : else
6243 3495 : newrel = NULL;
6244 :
6245 : /*
6246 : * Prepare a BulkInsertState and options for table_tuple_insert. The FSM
6247 : * is empty, so don't bother using it.
6248 : */
6249 4288 : if (newrel)
6250 : {
6251 793 : mycid = GetCurrentCommandId(true);
6252 793 : bistate = GetBulkInsertState();
6253 793 : ti_options = TABLE_INSERT_SKIP_FSM;
6254 : }
6255 : else
6256 : {
6257 : /* keep compiler quiet about using these uninitialized */
6258 3495 : mycid = 0;
6259 3495 : bistate = NULL;
6260 3495 : ti_options = 0;
6261 : }
6262 :
6263 : /*
6264 : * Generate the constraint and default execution states
6265 : */
6266 :
6267 4288 : estate = CreateExecutorState();
6268 :
6269 : /* Build the needed expression execution states */
6270 5894 : foreach(l, tab->constraints)
6271 : {
6272 1606 : NewConstraint *con = lfirst(l);
6273 :
6274 1606 : switch (con->contype)
6275 : {
6276 774 : case CONSTR_CHECK:
6277 774 : needscan = true;
6278 774 : con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
6279 774 : break;
6280 832 : case CONSTR_FOREIGN:
6281 : /* Nothing to do here */
6282 832 : break;
6283 0 : default:
6284 0 : elog(ERROR, "unrecognized constraint type: %d",
6285 : (int) con->contype);
6286 : }
6287 : }
6288 :
6289 : /* Build expression execution states for partition check quals */
6290 4288 : if (tab->partition_constraint)
6291 : {
6292 1403 : needscan = true;
6293 1403 : partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
6294 : }
6295 :
6296 5138 : foreach(l, tab->newvals)
6297 : {
6298 850 : NewColumnValue *ex = lfirst(l);
6299 :
6300 : /* expr already planned */
6301 850 : ex->exprstate = ExecInitExpr(ex->expr, NULL);
6302 : }
6303 :
6304 4288 : notnull_attrs = notnull_virtual_attrs = NIL;
6305 4288 : if (newrel || tab->verify_new_notnull)
6306 : {
6307 : /*
6308 : * If we are rebuilding the tuples OR if we added any new but not
6309 : * verified not-null constraints, check all *valid* not-null
6310 : * constraints. This is a bit of overkill but it minimizes risk of
6311 : * bugs.
6312 : *
6313 : * notnull_attrs does *not* collect attribute numbers for valid
6314 : * not-null constraints over virtual generated columns; instead, they
6315 : * are collected in notnull_virtual_attrs for verification elsewhere.
6316 : */
6317 5552 : for (i = 0; i < newTupDesc->natts; i++)
6318 : {
6319 4066 : CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
6320 :
6321 4066 : if (attr->attnullability == ATTNULLABLE_VALID &&
6322 1476 : !attr->attisdropped)
6323 : {
6324 1476 : Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
6325 :
6326 1476 : if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
6327 1416 : notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
6328 : else
6329 60 : notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
6330 60 : wholeatt->attnum);
6331 : }
6332 : }
6333 1486 : if (notnull_attrs || notnull_virtual_attrs)
6334 1075 : needscan = true;
6335 : }
6336 :
6337 4288 : if (newrel || needscan)
6338 : {
6339 : ExprContext *econtext;
6340 : TupleTableSlot *oldslot;
6341 : TupleTableSlot *newslot;
6342 : TableScanDesc scan;
6343 : MemoryContext oldCxt;
6344 3586 : List *dropped_attrs = NIL;
6345 : ListCell *lc;
6346 : Snapshot snapshot;
6347 3586 : ResultRelInfo *rInfo = NULL;
6348 :
6349 : /*
6350 : * When adding or changing a virtual generated column with a not-null
6351 : * constraint, we need to evaluate whether the generation expression
6352 : * is null. For that, we borrow ExecRelGenVirtualNotNull(). Here, we
6353 : * prepare a dummy ResultRelInfo.
6354 : */
6355 3586 : if (notnull_virtual_attrs != NIL)
6356 : {
6357 : MemoryContext oldcontext;
6358 :
6359 : Assert(newTupDesc->constr->has_generated_virtual);
6360 : Assert(newTupDesc->constr->has_not_null);
6361 40 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
6362 40 : rInfo = makeNode(ResultRelInfo);
6363 40 : InitResultRelInfo(rInfo,
6364 : oldrel,
6365 : 0, /* dummy rangetable index */
6366 : NULL,
6367 : estate->es_instrument);
6368 40 : MemoryContextSwitchTo(oldcontext);
6369 : }
6370 :
6371 3586 : if (newrel)
6372 793 : ereport(DEBUG1,
6373 : (errmsg_internal("rewriting table \"%s\"",
6374 : RelationGetRelationName(oldrel))));
6375 : else
6376 2793 : ereport(DEBUG1,
6377 : (errmsg_internal("verifying table \"%s\"",
6378 : RelationGetRelationName(oldrel))));
6379 :
6380 3586 : if (newrel)
6381 : {
6382 : /*
6383 : * All predicate locks on the tuples or pages are about to be made
6384 : * invalid, because we move tuples around. Promote them to
6385 : * relation locks.
6386 : */
6387 793 : TransferPredicateLocksToHeapRelation(oldrel);
6388 : }
6389 :
6390 3586 : econtext = GetPerTupleExprContext(estate);
6391 :
6392 : /*
6393 : * Create necessary tuple slots. When rewriting, two slots are needed,
6394 : * otherwise one suffices. In the case where one slot suffices, we
6395 : * need to use the new tuple descriptor, otherwise some constraints
6396 : * can't be evaluated. Note that even when the tuple layout is the
6397 : * same and no rewrite is required, the tupDescs might not be
6398 : * (consider ADD COLUMN without a default).
6399 : */
6400 3586 : if (tab->rewrite)
6401 : {
6402 : Assert(newrel != NULL);
6403 793 : oldslot = MakeSingleTupleTableSlot(oldTupDesc,
6404 : table_slot_callbacks(oldrel));
6405 793 : newslot = MakeSingleTupleTableSlot(newTupDesc,
6406 : table_slot_callbacks(newrel));
6407 :
6408 : /*
6409 : * Set all columns in the new slot to NULL initially, to ensure
6410 : * columns added as part of the rewrite are initialized to NULL.
6411 : * That is necessary as tab->newvals will not contain an
6412 : * expression for columns with a NULL default, e.g. when adding a
6413 : * column without a default together with a column with a default
6414 : * requiring an actual rewrite.
6415 : */
6416 793 : ExecStoreAllNullTuple(newslot);
6417 : }
6418 : else
6419 : {
6420 2793 : oldslot = MakeSingleTupleTableSlot(newTupDesc,
6421 : table_slot_callbacks(oldrel));
6422 2793 : newslot = NULL;
6423 : }
6424 :
6425 : /*
6426 : * Any attributes that are dropped according to the new tuple
6427 : * descriptor can be set to NULL. We precompute the list of dropped
6428 : * attributes to avoid needing to do so in the per-tuple loop.
6429 : */
6430 12736 : for (i = 0; i < newTupDesc->natts; i++)
6431 : {
6432 9150 : if (TupleDescAttr(newTupDesc, i)->attisdropped)
6433 604 : dropped_attrs = lappend_int(dropped_attrs, i);
6434 : }
6435 :
6436 : /*
6437 : * Scan through the rows, generating a new row if needed and then
6438 : * checking all the constraints.
6439 : */
6440 3586 : snapshot = RegisterSnapshot(GetLatestSnapshot());
6441 3586 : scan = table_beginscan(oldrel, snapshot, 0, NULL,
6442 : SO_NONE);
6443 :
6444 : /*
6445 : * Switch to per-tuple memory context and reset it for each tuple
6446 : * produced, so we don't leak memory.
6447 : */
6448 3586 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6449 :
6450 491271 : while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
6451 : {
6452 : TupleTableSlot *insertslot;
6453 :
6454 484388 : if (tab->rewrite > 0)
6455 : {
6456 : /* Extract data from old tuple */
6457 67503 : slot_getallattrs(oldslot);
6458 67503 : ExecClearTuple(newslot);
6459 :
6460 : /* copy attributes */
6461 67503 : memcpy(newslot->tts_values, oldslot->tts_values,
6462 67503 : sizeof(Datum) * oldslot->tts_nvalid);
6463 67503 : memcpy(newslot->tts_isnull, oldslot->tts_isnull,
6464 67503 : sizeof(bool) * oldslot->tts_nvalid);
6465 :
6466 : /* Set dropped attributes to null in new tuple */
6467 67632 : foreach(lc, dropped_attrs)
6468 129 : newslot->tts_isnull[lfirst_int(lc)] = true;
6469 :
6470 : /*
6471 : * Constraints and GENERATED expressions might reference the
6472 : * tableoid column, so fill tts_tableOid with the desired
6473 : * value. (We must do this each time, because it gets
6474 : * overwritten with newrel's OID during storing.)
6475 : */
6476 67503 : newslot->tts_tableOid = RelationGetRelid(oldrel);
6477 :
6478 : /*
6479 : * Process supplied expressions to replace selected columns.
6480 : *
6481 : * First, evaluate expressions whose inputs come from the old
6482 : * tuple.
6483 : */
6484 67503 : econtext->ecxt_scantuple = oldslot;
6485 :
6486 137986 : foreach(l, tab->newvals)
6487 : {
6488 70503 : NewColumnValue *ex = lfirst(l);
6489 :
6490 70503 : if (ex->is_generated)
6491 264 : continue;
6492 :
6493 70239 : newslot->tts_values[ex->attnum - 1]
6494 70219 : = ExecEvalExpr(ex->exprstate,
6495 : econtext,
6496 70239 : &newslot->tts_isnull[ex->attnum - 1]);
6497 : }
6498 :
6499 67483 : ExecStoreVirtualTuple(newslot);
6500 :
6501 : /*
6502 : * Now, evaluate any expressions whose inputs come from the
6503 : * new tuple. We assume these columns won't reference each
6504 : * other, so that there's no ordering dependency.
6505 : */
6506 67483 : econtext->ecxt_scantuple = newslot;
6507 :
6508 137966 : foreach(l, tab->newvals)
6509 : {
6510 70483 : NewColumnValue *ex = lfirst(l);
6511 :
6512 70483 : if (!ex->is_generated)
6513 70219 : continue;
6514 :
6515 264 : newslot->tts_values[ex->attnum - 1]
6516 264 : = ExecEvalExpr(ex->exprstate,
6517 : econtext,
6518 264 : &newslot->tts_isnull[ex->attnum - 1]);
6519 : }
6520 :
6521 67483 : insertslot = newslot;
6522 : }
6523 : else
6524 : {
6525 : /*
6526 : * If there's no rewrite, old and new table are guaranteed to
6527 : * have the same AM, so we can just use the old slot to verify
6528 : * new constraints etc.
6529 : */
6530 416885 : insertslot = oldslot;
6531 : }
6532 :
6533 : /* Now check any constraints on the possibly-changed tuple */
6534 484368 : econtext->ecxt_scantuple = insertslot;
6535 :
6536 2579594 : foreach_int(attn, notnull_attrs)
6537 : {
6538 1611034 : if (slot_attisnull(insertslot, attn))
6539 : {
6540 88 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
6541 :
6542 88 : ereport(ERROR,
6543 : (errcode(ERRCODE_NOT_NULL_VIOLATION),
6544 : errmsg("column \"%s\" of relation \"%s\" contains null values",
6545 : NameStr(attr->attname),
6546 : RelationGetRelationName(oldrel)),
6547 : errtablecol(oldrel, attn)));
6548 : }
6549 : }
6550 :
6551 484280 : if (notnull_virtual_attrs != NIL)
6552 : {
6553 : AttrNumber attnum;
6554 :
6555 56 : attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
6556 : estate,
6557 : notnull_virtual_attrs);
6558 56 : if (attnum != InvalidAttrNumber)
6559 : {
6560 20 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
6561 :
6562 20 : ereport(ERROR,
6563 : errcode(ERRCODE_NOT_NULL_VIOLATION),
6564 : errmsg("column \"%s\" of relation \"%s\" contains null values",
6565 : NameStr(attr->attname),
6566 : RelationGetRelationName(oldrel)),
6567 : errtablecol(oldrel, attnum));
6568 : }
6569 : }
6570 :
6571 489601 : foreach(l, tab->constraints)
6572 : {
6573 5453 : NewConstraint *con = lfirst(l);
6574 :
6575 5453 : switch (con->contype)
6576 : {
6577 5387 : case CONSTR_CHECK:
6578 5387 : if (!ExecCheck(con->qualstate, econtext))
6579 112 : ereport(ERROR,
6580 : (errcode(ERRCODE_CHECK_VIOLATION),
6581 : errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
6582 : con->name,
6583 : RelationGetRelationName(oldrel)),
6584 : errtableconstraint(oldrel, con->name)));
6585 5275 : break;
6586 66 : case CONSTR_NOTNULL:
6587 : case CONSTR_FOREIGN:
6588 : /* Nothing to do here */
6589 66 : break;
6590 0 : default:
6591 0 : elog(ERROR, "unrecognized constraint type: %d",
6592 : (int) con->contype);
6593 : }
6594 : }
6595 :
6596 484148 : if (partqualstate && !ExecCheck(partqualstate, econtext))
6597 : {
6598 49 : if (tab->validate_default)
6599 17 : ereport(ERROR,
6600 : (errcode(ERRCODE_CHECK_VIOLATION),
6601 : errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
6602 : RelationGetRelationName(oldrel)),
6603 : errtable(oldrel)));
6604 : else
6605 32 : ereport(ERROR,
6606 : (errcode(ERRCODE_CHECK_VIOLATION),
6607 : errmsg("partition constraint of relation \"%s\" is violated by some row",
6608 : RelationGetRelationName(oldrel)),
6609 : errtable(oldrel)));
6610 : }
6611 :
6612 : /* Write the tuple out to the new relation */
6613 484099 : if (newrel)
6614 67443 : table_tuple_insert(newrel, insertslot, mycid,
6615 : ti_options, bistate);
6616 :
6617 484099 : ResetExprContext(econtext);
6618 :
6619 484099 : CHECK_FOR_INTERRUPTS();
6620 : }
6621 :
6622 3297 : MemoryContextSwitchTo(oldCxt);
6623 3297 : table_endscan(scan);
6624 3297 : UnregisterSnapshot(snapshot);
6625 :
6626 3297 : ExecDropSingleTupleTableSlot(oldslot);
6627 3297 : if (newslot)
6628 733 : ExecDropSingleTupleTableSlot(newslot);
6629 : }
6630 :
6631 3999 : FreeExecutorState(estate);
6632 :
6633 3999 : table_close(oldrel, NoLock);
6634 3999 : if (newrel)
6635 : {
6636 733 : FreeBulkInsertState(bistate);
6637 :
6638 733 : table_finish_bulk_insert(newrel, ti_options);
6639 :
6640 733 : table_close(newrel, NoLock);
6641 : }
6642 3999 : }
6643 :
6644 : /*
6645 : * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
6646 : */
6647 : static AlteredTableInfo *
6648 29209 : ATGetQueueEntry(List **wqueue, Relation rel)
6649 : {
6650 29209 : Oid relid = RelationGetRelid(rel);
6651 : AlteredTableInfo *tab;
6652 : ListCell *ltab;
6653 :
6654 37673 : foreach(ltab, *wqueue)
6655 : {
6656 12347 : tab = (AlteredTableInfo *) lfirst(ltab);
6657 12347 : if (tab->relid == relid)
6658 3883 : return tab;
6659 : }
6660 :
6661 : /*
6662 : * Not there, so add it. Note that we make a copy of the relation's
6663 : * existing descriptor before anything interesting can happen to it.
6664 : */
6665 25326 : tab = palloc0_object(AlteredTableInfo);
6666 25326 : tab->relid = relid;
6667 25326 : tab->rel = NULL; /* set later */
6668 25326 : tab->relkind = rel->rd_rel->relkind;
6669 25326 : tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
6670 25326 : tab->newAccessMethod = InvalidOid;
6671 25326 : tab->chgAccessMethod = false;
6672 25326 : tab->newTableSpace = InvalidOid;
6673 25326 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
6674 25326 : tab->chgPersistence = false;
6675 :
6676 25326 : *wqueue = lappend(*wqueue, tab);
6677 :
6678 25326 : return tab;
6679 : }
6680 :
6681 : static const char *
6682 73 : alter_table_type_to_string(AlterTableType cmdtype)
6683 : {
6684 73 : switch (cmdtype)
6685 : {
6686 0 : case AT_AddColumn:
6687 : case AT_AddColumnToView:
6688 0 : return "ADD COLUMN";
6689 0 : case AT_ColumnDefault:
6690 : case AT_CookedColumnDefault:
6691 0 : return "ALTER COLUMN ... SET DEFAULT";
6692 4 : case AT_DropNotNull:
6693 4 : return "ALTER COLUMN ... DROP NOT NULL";
6694 4 : case AT_SetNotNull:
6695 4 : return "ALTER COLUMN ... SET NOT NULL";
6696 0 : case AT_SetExpression:
6697 0 : return "ALTER COLUMN ... SET EXPRESSION";
6698 0 : case AT_DropExpression:
6699 0 : return "ALTER COLUMN ... DROP EXPRESSION";
6700 0 : case AT_SetStatistics:
6701 0 : return "ALTER COLUMN ... SET STATISTICS";
6702 8 : case AT_SetOptions:
6703 8 : return "ALTER COLUMN ... SET";
6704 0 : case AT_ResetOptions:
6705 0 : return "ALTER COLUMN ... RESET";
6706 0 : case AT_SetStorage:
6707 0 : return "ALTER COLUMN ... SET STORAGE";
6708 0 : case AT_SetCompression:
6709 0 : return "ALTER COLUMN ... SET COMPRESSION";
6710 4 : case AT_DropColumn:
6711 4 : return "DROP COLUMN";
6712 0 : case AT_AddIndex:
6713 : case AT_ReAddIndex:
6714 0 : return NULL; /* not real grammar */
6715 0 : case AT_AddConstraint:
6716 : case AT_ReAddConstraint:
6717 : case AT_ReAddDomainConstraint:
6718 : case AT_AddIndexConstraint:
6719 0 : return "ADD CONSTRAINT";
6720 4 : case AT_AlterConstraint:
6721 4 : return "ALTER CONSTRAINT";
6722 0 : case AT_ValidateConstraint:
6723 0 : return "VALIDATE CONSTRAINT";
6724 0 : case AT_DropConstraint:
6725 0 : return "DROP CONSTRAINT";
6726 0 : case AT_ReAddComment:
6727 0 : return NULL; /* not real grammar */
6728 0 : case AT_AlterColumnType:
6729 0 : return "ALTER COLUMN ... SET DATA TYPE";
6730 0 : case AT_AlterColumnGenericOptions:
6731 0 : return "ALTER COLUMN ... OPTIONS";
6732 0 : case AT_ChangeOwner:
6733 0 : return "OWNER TO";
6734 4 : case AT_ClusterOn:
6735 4 : return "CLUSTER ON";
6736 4 : case AT_DropCluster:
6737 4 : return "SET WITHOUT CLUSTER";
6738 0 : case AT_SetAccessMethod:
6739 0 : return "SET ACCESS METHOD";
6740 4 : case AT_SetLogged:
6741 4 : return "SET LOGGED";
6742 4 : case AT_SetUnLogged:
6743 4 : return "SET UNLOGGED";
6744 0 : case AT_DropOids:
6745 0 : return "SET WITHOUT OIDS";
6746 0 : case AT_SetTableSpace:
6747 0 : return "SET TABLESPACE";
6748 1 : case AT_SetRelOptions:
6749 1 : return "SET";
6750 0 : case AT_ResetRelOptions:
6751 0 : return "RESET";
6752 0 : case AT_ReplaceRelOptions:
6753 0 : return NULL; /* not real grammar */
6754 0 : case AT_EnableTrig:
6755 0 : return "ENABLE TRIGGER";
6756 0 : case AT_EnableAlwaysTrig:
6757 0 : return "ENABLE ALWAYS TRIGGER";
6758 0 : case AT_EnableReplicaTrig:
6759 0 : return "ENABLE REPLICA TRIGGER";
6760 0 : case AT_DisableTrig:
6761 0 : return "DISABLE TRIGGER";
6762 0 : case AT_EnableTrigAll:
6763 0 : return "ENABLE TRIGGER ALL";
6764 0 : case AT_DisableTrigAll:
6765 0 : return "DISABLE TRIGGER ALL";
6766 0 : case AT_EnableTrigUser:
6767 0 : return "ENABLE TRIGGER USER";
6768 0 : case AT_DisableTrigUser:
6769 0 : return "DISABLE TRIGGER USER";
6770 0 : case AT_EnableRule:
6771 0 : return "ENABLE RULE";
6772 0 : case AT_EnableAlwaysRule:
6773 0 : return "ENABLE ALWAYS RULE";
6774 0 : case AT_EnableReplicaRule:
6775 0 : return "ENABLE REPLICA RULE";
6776 0 : case AT_DisableRule:
6777 0 : return "DISABLE RULE";
6778 4 : case AT_AddInherit:
6779 4 : return "INHERIT";
6780 4 : case AT_DropInherit:
6781 4 : return "NO INHERIT";
6782 0 : case AT_AddOf:
6783 0 : return "OF";
6784 0 : case AT_DropOf:
6785 0 : return "NOT OF";
6786 0 : case AT_ReplicaIdentity:
6787 0 : return "REPLICA IDENTITY";
6788 0 : case AT_EnableRowSecurity:
6789 0 : return "ENABLE ROW SECURITY";
6790 0 : case AT_DisableRowSecurity:
6791 0 : return "DISABLE ROW SECURITY";
6792 0 : case AT_ForceRowSecurity:
6793 0 : return "FORCE ROW SECURITY";
6794 0 : case AT_NoForceRowSecurity:
6795 0 : return "NO FORCE ROW SECURITY";
6796 0 : case AT_GenericOptions:
6797 0 : return "OPTIONS";
6798 4 : case AT_AttachPartition:
6799 4 : return "ATTACH PARTITION";
6800 12 : case AT_DetachPartition:
6801 12 : return "DETACH PARTITION";
6802 4 : case AT_DetachPartitionFinalize:
6803 4 : return "DETACH PARTITION ... FINALIZE";
6804 0 : case AT_MergePartitions:
6805 0 : return "MERGE PARTITIONS";
6806 4 : case AT_SplitPartition:
6807 4 : return "SPLIT PARTITION";
6808 0 : case AT_AddIdentity:
6809 0 : return "ALTER COLUMN ... ADD IDENTITY";
6810 0 : case AT_SetIdentity:
6811 0 : return "ALTER COLUMN ... SET";
6812 0 : case AT_DropIdentity:
6813 0 : return "ALTER COLUMN ... DROP IDENTITY";
6814 0 : case AT_ReAddStatistics:
6815 0 : return NULL; /* not real grammar */
6816 : }
6817 :
6818 0 : return NULL;
6819 : }
6820 :
6821 : /*
6822 : * ATSimplePermissions
6823 : *
6824 : * - Ensure that it is a relation (or possibly a view)
6825 : * - Ensure this user is the owner
6826 : * - Ensure that it is not a system table
6827 : */
6828 : static void
6829 25901 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
6830 : {
6831 : int actual_target;
6832 :
6833 25901 : switch (rel->rd_rel->relkind)
6834 : {
6835 20066 : case RELKIND_RELATION:
6836 20066 : actual_target = ATT_TABLE;
6837 20066 : break;
6838 4320 : case RELKIND_PARTITIONED_TABLE:
6839 4320 : actual_target = ATT_PARTITIONED_TABLE;
6840 4320 : break;
6841 280 : case RELKIND_VIEW:
6842 280 : actual_target = ATT_VIEW;
6843 280 : break;
6844 30 : case RELKIND_MATVIEW:
6845 30 : actual_target = ATT_MATVIEW;
6846 30 : break;
6847 145 : case RELKIND_INDEX:
6848 145 : actual_target = ATT_INDEX;
6849 145 : break;
6850 303 : case RELKIND_PARTITIONED_INDEX:
6851 303 : actual_target = ATT_PARTITIONED_INDEX;
6852 303 : break;
6853 145 : case RELKIND_COMPOSITE_TYPE:
6854 145 : actual_target = ATT_COMPOSITE_TYPE;
6855 145 : break;
6856 595 : case RELKIND_FOREIGN_TABLE:
6857 595 : actual_target = ATT_FOREIGN_TABLE;
6858 595 : break;
6859 16 : case RELKIND_SEQUENCE:
6860 16 : actual_target = ATT_SEQUENCE;
6861 16 : break;
6862 1 : default:
6863 1 : actual_target = 0;
6864 1 : break;
6865 : }
6866 :
6867 : /* Wrong target type? */
6868 25901 : if ((actual_target & allowed_targets) == 0)
6869 : {
6870 73 : const char *action_str = alter_table_type_to_string(cmdtype);
6871 :
6872 73 : if (action_str)
6873 73 : ereport(ERROR,
6874 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6875 : /* translator: %s is a group of some SQL keywords */
6876 : errmsg("ALTER action %s cannot be performed on relation \"%s\"",
6877 : action_str, RelationGetRelationName(rel)),
6878 : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
6879 : else
6880 : /* internal error? */
6881 0 : elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
6882 : RelationGetRelationName(rel));
6883 : }
6884 :
6885 : /* Permissions checks */
6886 25828 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
6887 8 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
6888 8 : RelationGetRelationName(rel));
6889 :
6890 25820 : if (!allowSystemTableMods && IsSystemRelation(rel))
6891 0 : ereport(ERROR,
6892 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6893 : errmsg("permission denied: \"%s\" is a system catalog",
6894 : RelationGetRelationName(rel))));
6895 25820 : }
6896 :
6897 : /*
6898 : * ATSimpleRecursion
6899 : *
6900 : * Simple table recursion sufficient for most ALTER TABLE operations.
6901 : * All direct and indirect children are processed in an unspecified order.
6902 : * Note that if a child inherits from the original table via multiple
6903 : * inheritance paths, it will be visited just once.
6904 : */
6905 : static void
6906 917 : ATSimpleRecursion(List **wqueue, Relation rel,
6907 : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
6908 : AlterTableUtilityContext *context)
6909 : {
6910 : /*
6911 : * Propagate to children, if desired and if there are (or might be) any
6912 : * children.
6913 : */
6914 917 : if (recurse && rel->rd_rel->relhassubclass)
6915 : {
6916 59 : Oid relid = RelationGetRelid(rel);
6917 : ListCell *child;
6918 : List *children;
6919 :
6920 59 : children = find_all_inheritors(relid, lockmode, NULL);
6921 :
6922 : /*
6923 : * find_all_inheritors does the recursive search of the inheritance
6924 : * hierarchy, so all we have to do is process all of the relids in the
6925 : * list that it returns.
6926 : */
6927 256 : foreach(child, children)
6928 : {
6929 197 : Oid childrelid = lfirst_oid(child);
6930 : Relation childrel;
6931 :
6932 197 : if (childrelid == relid)
6933 59 : continue;
6934 : /* find_all_inheritors already got lock */
6935 138 : childrel = relation_open(childrelid, NoLock);
6936 138 : CheckAlterTableIsSafe(childrel);
6937 138 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
6938 138 : relation_close(childrel, NoLock);
6939 : }
6940 : }
6941 917 : }
6942 :
6943 : /*
6944 : * Obtain list of partitions of the given table, locking them all at the given
6945 : * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
6946 : *
6947 : * This function is a no-op if the given relation is not a partitioned table;
6948 : * in particular, nothing is done if it's a legacy inheritance parent.
6949 : */
6950 : static void
6951 578 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
6952 : {
6953 578 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6954 : {
6955 : List *inh;
6956 : ListCell *cell;
6957 :
6958 121 : inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
6959 : /* first element is the parent rel; must ignore it */
6960 398 : for_each_from(cell, inh, 1)
6961 : {
6962 : Relation childrel;
6963 :
6964 : /* find_all_inheritors already got lock */
6965 281 : childrel = table_open(lfirst_oid(cell), NoLock);
6966 281 : CheckAlterTableIsSafe(childrel);
6967 277 : table_close(childrel, NoLock);
6968 : }
6969 117 : list_free(inh);
6970 : }
6971 574 : }
6972 :
6973 : /*
6974 : * ATTypedTableRecursion
6975 : *
6976 : * Propagate ALTER TYPE operations to the typed tables of that type.
6977 : * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
6978 : * recursion to inheritance children of the typed tables.
6979 : */
6980 : static void
6981 129 : ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
6982 : LOCKMODE lockmode, AlterTableUtilityContext *context)
6983 : {
6984 : ListCell *child;
6985 : List *children;
6986 :
6987 : Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6988 :
6989 129 : children = find_typed_table_dependencies(rel->rd_rel->reltype,
6990 129 : RelationGetRelationName(rel),
6991 : cmd->behavior);
6992 :
6993 137 : foreach(child, children)
6994 : {
6995 20 : Oid childrelid = lfirst_oid(child);
6996 : Relation childrel;
6997 :
6998 20 : childrel = relation_open(childrelid, lockmode);
6999 20 : CheckAlterTableIsSafe(childrel);
7000 20 : ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
7001 20 : relation_close(childrel, NoLock);
7002 : }
7003 117 : }
7004 :
7005 :
7006 : /*
7007 : * find_composite_type_dependencies
7008 : *
7009 : * Check to see if the type "typeOid" is being used as a column in some table
7010 : * (possibly nested several levels deep in composite types, arrays, etc!).
7011 : * Eventually, we'd like to propagate the check or rewrite operation
7012 : * into such tables, but for now, just error out if we find any.
7013 : *
7014 : * Caller should provide either the associated relation of a rowtype,
7015 : * or a type name (not both) for use in the error message, if any.
7016 : *
7017 : * Note that "typeOid" is not necessarily a composite type; it could also be
7018 : * another container type such as an array or range, or a domain over one of
7019 : * these things. The name of this function is therefore somewhat historical,
7020 : * but it's not worth changing.
7021 : *
7022 : * We assume that functions and views depending on the type are not reasons
7023 : * to reject the ALTER. (How safe is this really?)
7024 : */
7025 : void
7026 3359 : find_composite_type_dependencies(Oid typeOid, Relation origRelation,
7027 : const char *origTypeName)
7028 : {
7029 : Relation depRel;
7030 : ScanKeyData key[2];
7031 : SysScanDesc depScan;
7032 : HeapTuple depTup;
7033 :
7034 : /* since this function recurses, it could be driven to stack overflow */
7035 3359 : check_stack_depth();
7036 :
7037 : /*
7038 : * We scan pg_depend to find those things that depend on the given type.
7039 : * (We assume we can ignore refobjsubid for a type.)
7040 : */
7041 3359 : depRel = table_open(DependRelationId, AccessShareLock);
7042 :
7043 3359 : ScanKeyInit(&key[0],
7044 : Anum_pg_depend_refclassid,
7045 : BTEqualStrategyNumber, F_OIDEQ,
7046 : ObjectIdGetDatum(TypeRelationId));
7047 3359 : ScanKeyInit(&key[1],
7048 : Anum_pg_depend_refobjid,
7049 : BTEqualStrategyNumber, F_OIDEQ,
7050 : ObjectIdGetDatum(typeOid));
7051 :
7052 3359 : depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
7053 : NULL, 2, key);
7054 :
7055 5150 : while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
7056 : {
7057 1895 : Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
7058 : Relation rel;
7059 : TupleDesc tupleDesc;
7060 : Form_pg_attribute att;
7061 :
7062 : /* Check for directly dependent types */
7063 1895 : if (pg_depend->classid == TypeRelationId)
7064 : {
7065 : /*
7066 : * This must be an array, domain, or range containing the given
7067 : * type, so recursively check for uses of this type. Note that
7068 : * any error message will mention the original type not the
7069 : * container; this is intentional.
7070 : */
7071 1625 : find_composite_type_dependencies(pg_depend->objid,
7072 : origRelation, origTypeName);
7073 1609 : continue;
7074 : }
7075 :
7076 : /* Else, ignore dependees that aren't relations */
7077 270 : if (pg_depend->classid != RelationRelationId)
7078 81 : continue;
7079 :
7080 189 : rel = relation_open(pg_depend->objid, AccessShareLock);
7081 189 : tupleDesc = RelationGetDescr(rel);
7082 :
7083 : /*
7084 : * If objsubid identifies a specific column, refer to that in error
7085 : * messages. Otherwise, search to see if there's a user column of the
7086 : * type. (We assume system columns are never of interesting types.)
7087 : * The search is needed because an index containing an expression
7088 : * column of the target type will just be recorded as a whole-relation
7089 : * dependency. If we do not find a column of the type, the dependency
7090 : * must indicate that the type is transiently referenced in an index
7091 : * expression but not stored on disk, which we assume is OK, just as
7092 : * we do for references in views. (It could also be that the target
7093 : * type is embedded in some container type that is stored in an index
7094 : * column, but the previous recursion should catch such cases.)
7095 : */
7096 189 : if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
7097 84 : att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
7098 : else
7099 : {
7100 105 : att = NULL;
7101 270 : for (int attno = 1; attno <= tupleDesc->natts; attno++)
7102 : {
7103 169 : att = TupleDescAttr(tupleDesc, attno - 1);
7104 169 : if (att->atttypid == typeOid && !att->attisdropped)
7105 4 : break;
7106 165 : att = NULL;
7107 : }
7108 105 : if (att == NULL)
7109 : {
7110 : /* No such column, so assume OK */
7111 101 : relation_close(rel, AccessShareLock);
7112 101 : continue;
7113 : }
7114 : }
7115 :
7116 : /*
7117 : * We definitely should reject if the relation has storage. If it's
7118 : * partitioned, then perhaps we don't have to reject: if there are
7119 : * partitions then we'll fail when we find one, else there is no
7120 : * stored data to worry about. However, it's possible that the type
7121 : * change would affect conclusions about whether the type is sortable
7122 : * or hashable and thus (if it's a partitioning column) break the
7123 : * partitioning rule. For now, reject for partitioned rels too.
7124 : */
7125 88 : if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
7126 0 : RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7127 : {
7128 88 : if (origTypeName)
7129 20 : ereport(ERROR,
7130 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7131 : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7132 : origTypeName,
7133 : RelationGetRelationName(rel),
7134 : NameStr(att->attname))));
7135 68 : else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7136 12 : ereport(ERROR,
7137 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7138 : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7139 : RelationGetRelationName(origRelation),
7140 : RelationGetRelationName(rel),
7141 : NameStr(att->attname))));
7142 56 : else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7143 4 : ereport(ERROR,
7144 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7145 : errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7146 : RelationGetRelationName(origRelation),
7147 : RelationGetRelationName(rel),
7148 : NameStr(att->attname))));
7149 : else
7150 52 : ereport(ERROR,
7151 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7152 : errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7153 : RelationGetRelationName(origRelation),
7154 : RelationGetRelationName(rel),
7155 : NameStr(att->attname))));
7156 : }
7157 0 : else if (OidIsValid(rel->rd_rel->reltype))
7158 : {
7159 : /*
7160 : * A view or composite type itself isn't a problem, but we must
7161 : * recursively check for indirect dependencies via its rowtype.
7162 : */
7163 0 : find_composite_type_dependencies(rel->rd_rel->reltype,
7164 : origRelation, origTypeName);
7165 : }
7166 :
7167 0 : relation_close(rel, AccessShareLock);
7168 : }
7169 :
7170 3255 : systable_endscan(depScan);
7171 :
7172 3255 : relation_close(depRel, AccessShareLock);
7173 3255 : }
7174 :
7175 :
7176 : /*
7177 : * find_typed_table_dependencies
7178 : *
7179 : * Check to see if a composite type is being used as the type of a
7180 : * typed table. Abort if any are found and behavior is RESTRICT.
7181 : * Else return the list of tables.
7182 : */
7183 : static List *
7184 145 : find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
7185 : {
7186 : Relation classRel;
7187 : ScanKeyData key[1];
7188 : TableScanDesc scan;
7189 : HeapTuple tuple;
7190 145 : List *result = NIL;
7191 :
7192 145 : classRel = table_open(RelationRelationId, AccessShareLock);
7193 :
7194 145 : ScanKeyInit(&key[0],
7195 : Anum_pg_class_reloftype,
7196 : BTEqualStrategyNumber, F_OIDEQ,
7197 : ObjectIdGetDatum(typeOid));
7198 :
7199 145 : scan = table_beginscan_catalog(classRel, 1, key);
7200 :
7201 169 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7202 : {
7203 40 : Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
7204 :
7205 40 : if (behavior == DROP_RESTRICT)
7206 16 : ereport(ERROR,
7207 : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
7208 : errmsg("cannot alter type \"%s\" because it is the type of a typed table",
7209 : typeName),
7210 : errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
7211 : else
7212 24 : result = lappend_oid(result, classform->oid);
7213 : }
7214 :
7215 129 : table_endscan(scan);
7216 129 : table_close(classRel, AccessShareLock);
7217 :
7218 129 : return result;
7219 : }
7220 :
7221 :
7222 : /*
7223 : * check_of_type
7224 : *
7225 : * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
7226 : * isn't suitable, throw an error. Currently, we require that the type
7227 : * originated with CREATE TYPE AS. We could support any row type, but doing so
7228 : * would require handling a number of extra corner cases in the DDL commands.
7229 : * (Also, allowing domain-over-composite would open up a can of worms about
7230 : * whether and how the domain's constraints should apply to derived tables.)
7231 : */
7232 : void
7233 119 : check_of_type(HeapTuple typetuple)
7234 : {
7235 119 : Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7236 119 : bool typeOk = false;
7237 :
7238 119 : if (typ->typtype == TYPTYPE_COMPOSITE)
7239 : {
7240 : Relation typeRelation;
7241 :
7242 : Assert(OidIsValid(typ->typrelid));
7243 115 : typeRelation = relation_open(typ->typrelid, AccessShareLock);
7244 115 : typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7245 :
7246 : /*
7247 : * Close the parent rel, but keep our AccessShareLock on it until xact
7248 : * commit. That will prevent someone else from deleting or ALTERing
7249 : * the type before the typed table creation/conversion commits.
7250 : */
7251 115 : relation_close(typeRelation, NoLock);
7252 :
7253 115 : if (!typeOk)
7254 4 : ereport(ERROR,
7255 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7256 : errmsg("type %s is the row type of another table",
7257 : format_type_be(typ->oid)),
7258 : errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7259 : }
7260 : else
7261 4 : ereport(ERROR,
7262 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7263 : errmsg("type %s is not a composite type",
7264 : format_type_be(typ->oid))));
7265 111 : }
7266 :
7267 :
7268 : /*
7269 : * ALTER TABLE ADD COLUMN
7270 : *
7271 : * Adds an additional attribute to a relation making the assumption that
7272 : * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
7273 : * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
7274 : * AlterTableCmd's.
7275 : *
7276 : * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
7277 : * have to decide at runtime whether to recurse or not depending on whether we
7278 : * actually add a column or merely merge with an existing column. (We can't
7279 : * check this in a static pre-pass because it won't handle multiple inheritance
7280 : * situations correctly.)
7281 : */
7282 : static void
7283 1638 : ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
7284 : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
7285 : AlterTableUtilityContext *context)
7286 : {
7287 1638 : if (rel->rd_rel->reloftype && !recursing)
7288 4 : ereport(ERROR,
7289 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7290 : errmsg("cannot add column to typed table")));
7291 :
7292 1634 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7293 42 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
7294 :
7295 1630 : if (recurse && !is_view)
7296 1555 : cmd->recurse = true;
7297 1630 : }
7298 :
7299 : /*
7300 : * Add a column to a table. The return value is the address of the
7301 : * new column in the parent relation.
7302 : *
7303 : * cmd is pass-by-ref so that we can replace it with the parse-transformed
7304 : * copy (but that happens only after we check for IF NOT EXISTS).
7305 : */
7306 : static ObjectAddress
7307 2140 : ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
7308 : AlterTableCmd **cmd, bool recurse, bool recursing,
7309 : LOCKMODE lockmode, AlterTablePass cur_pass,
7310 : AlterTableUtilityContext *context)
7311 : {
7312 2140 : Oid myrelid = RelationGetRelid(rel);
7313 2140 : ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
7314 2140 : bool if_not_exists = (*cmd)->missing_ok;
7315 : Relation pgclass,
7316 : attrdesc;
7317 : HeapTuple reltup;
7318 : Form_pg_class relform;
7319 : Form_pg_attribute attribute;
7320 : int newattnum;
7321 : char relkind;
7322 : Expr *defval;
7323 : List *children;
7324 : ListCell *child;
7325 : AlterTableCmd *childcmd;
7326 : ObjectAddress address;
7327 : TupleDesc tupdesc;
7328 :
7329 : /* since this function recurses, it could be driven to stack overflow */
7330 2140 : check_stack_depth();
7331 :
7332 : /* At top level, permission check was done in ATPrepCmd, else do it */
7333 2140 : if (recursing)
7334 514 : ATSimplePermissions((*cmd)->subtype, rel,
7335 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
7336 :
7337 2140 : if (rel->rd_rel->relispartition && !recursing)
7338 8 : ereport(ERROR,
7339 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7340 : errmsg("cannot add column to a partition")));
7341 :
7342 2132 : attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
7343 :
7344 : /*
7345 : * Are we adding the column to a recursion child? If so, check whether to
7346 : * merge with an existing definition for the column. If we do merge, we
7347 : * must not recurse. Children will already have the column, and recursing
7348 : * into them would mess up attinhcount.
7349 : */
7350 2132 : if (colDef->inhcount > 0)
7351 : {
7352 : HeapTuple tuple;
7353 :
7354 : /* Does child already have a column by this name? */
7355 514 : tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
7356 514 : if (HeapTupleIsValid(tuple))
7357 : {
7358 40 : Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7359 : Oid ctypeId;
7360 : int32 ctypmod;
7361 : Oid ccollid;
7362 :
7363 : /* Child column must match on type, typmod, and collation */
7364 40 : typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
7365 40 : if (ctypeId != childatt->atttypid ||
7366 40 : ctypmod != childatt->atttypmod)
7367 0 : ereport(ERROR,
7368 : (errcode(ERRCODE_DATATYPE_MISMATCH),
7369 : errmsg("child table \"%s\" has different type for column \"%s\"",
7370 : RelationGetRelationName(rel), colDef->colname)));
7371 40 : ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
7372 40 : if (ccollid != childatt->attcollation)
7373 0 : ereport(ERROR,
7374 : (errcode(ERRCODE_COLLATION_MISMATCH),
7375 : errmsg("child table \"%s\" has different collation for column \"%s\"",
7376 : RelationGetRelationName(rel), colDef->colname),
7377 : errdetail("\"%s\" versus \"%s\"",
7378 : get_collation_name(ccollid),
7379 : get_collation_name(childatt->attcollation))));
7380 :
7381 : /* Bump the existing child att's inhcount */
7382 40 : if (pg_add_s16_overflow(childatt->attinhcount, 1,
7383 : &childatt->attinhcount))
7384 0 : ereport(ERROR,
7385 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7386 : errmsg("too many inheritance parents"));
7387 40 : CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
7388 :
7389 40 : heap_freetuple(tuple);
7390 :
7391 : /* Inform the user about the merge */
7392 40 : ereport(NOTICE,
7393 : (errmsg("merging definition of column \"%s\" for child \"%s\"",
7394 : colDef->colname, RelationGetRelationName(rel))));
7395 :
7396 40 : table_close(attrdesc, RowExclusiveLock);
7397 :
7398 : /* Make the child column change visible */
7399 40 : CommandCounterIncrement();
7400 :
7401 40 : return InvalidObjectAddress;
7402 : }
7403 : }
7404 :
7405 : /* skip if the name already exists and if_not_exists is true */
7406 2092 : if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
7407 : {
7408 44 : table_close(attrdesc, RowExclusiveLock);
7409 44 : return InvalidObjectAddress;
7410 : }
7411 :
7412 : /*
7413 : * Okay, we need to add the column, so go ahead and do parse
7414 : * transformation. This can result in queueing up, or even immediately
7415 : * executing, subsidiary operations (such as creation of unique indexes);
7416 : * so we mustn't do it until we have made the if_not_exists check.
7417 : *
7418 : * When recursing, the command was already transformed and we needn't do
7419 : * so again. Also, if context isn't given we can't transform. (That
7420 : * currently happens only for AT_AddColumnToView; we expect that view.c
7421 : * passed us a ColumnDef that doesn't need work.)
7422 : */
7423 2028 : if (context != NULL && !recursing)
7424 : {
7425 1533 : *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
7426 : cur_pass, context);
7427 : Assert(*cmd != NULL);
7428 1529 : colDef = castNode(ColumnDef, (*cmd)->def);
7429 : }
7430 :
7431 : /*
7432 : * Regular inheritance children are independent enough not to inherit the
7433 : * identity column from parent hence cannot recursively add identity
7434 : * column if the table has inheritance children.
7435 : *
7436 : * Partitions, on the other hand, are integral part of a partitioned table
7437 : * and inherit identity column. Hence propagate identity column down the
7438 : * partition hierarchy.
7439 : */
7440 2024 : if (colDef->identity &&
7441 36 : recurse &&
7442 68 : rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
7443 32 : find_inheritance_children(myrelid, NoLock) != NIL)
7444 4 : ereport(ERROR,
7445 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7446 : errmsg("cannot recursively add identity column to table that has child tables")));
7447 :
7448 2020 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
7449 :
7450 2020 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
7451 2020 : if (!HeapTupleIsValid(reltup))
7452 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
7453 2020 : relform = (Form_pg_class) GETSTRUCT(reltup);
7454 2020 : relkind = relform->relkind;
7455 :
7456 : /* Determine the new attribute's number */
7457 2020 : newattnum = relform->relnatts + 1;
7458 2020 : if (newattnum > MaxHeapAttributeNumber)
7459 0 : ereport(ERROR,
7460 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
7461 : errmsg("tables can have at most %d columns",
7462 : MaxHeapAttributeNumber)));
7463 :
7464 : /*
7465 : * Construct new attribute's pg_attribute entry.
7466 : */
7467 2020 : tupdesc = BuildDescForRelation(list_make1(colDef));
7468 :
7469 2012 : attribute = TupleDescAttr(tupdesc, 0);
7470 :
7471 : /* Fix up attribute number */
7472 2012 : attribute->attnum = newattnum;
7473 :
7474 : /* make sure datatype is legal for a column */
7475 4024 : CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
7476 2012 : list_make1_oid(rel->rd_rel->reltype),
7477 2012 : (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
7478 :
7479 1980 : InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
7480 :
7481 1980 : table_close(attrdesc, RowExclusiveLock);
7482 :
7483 : /*
7484 : * Update pg_class tuple as appropriate
7485 : */
7486 1980 : relform->relnatts = newattnum;
7487 :
7488 1980 : CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
7489 :
7490 1980 : heap_freetuple(reltup);
7491 :
7492 : /* Post creation hook for new attribute */
7493 1980 : InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
7494 :
7495 1980 : table_close(pgclass, RowExclusiveLock);
7496 :
7497 : /* Make the attribute's catalog entry visible */
7498 1980 : CommandCounterIncrement();
7499 :
7500 : /*
7501 : * Store the DEFAULT, if any, in the catalogs
7502 : */
7503 1980 : if (colDef->raw_default)
7504 : {
7505 : RawColumnDefault *rawEnt;
7506 :
7507 766 : rawEnt = palloc_object(RawColumnDefault);
7508 766 : rawEnt->attnum = attribute->attnum;
7509 766 : rawEnt->raw_default = copyObject(colDef->raw_default);
7510 766 : rawEnt->generated = colDef->generated;
7511 :
7512 : /*
7513 : * This function is intended for CREATE TABLE, so it processes a
7514 : * _list_ of defaults, but we just do one.
7515 : */
7516 766 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
7517 : false, true, false, NULL);
7518 :
7519 : /* Make the additional catalog changes visible */
7520 678 : CommandCounterIncrement();
7521 : }
7522 :
7523 : /*
7524 : * Tell Phase 3 to fill in the default expression, if there is one.
7525 : *
7526 : * If there is no default, Phase 3 doesn't have to do anything, because
7527 : * that effectively means that the default is NULL. The heap tuple access
7528 : * routines always check for attnum > # of attributes in tuple, and return
7529 : * NULL if so, so without any modification of the tuple data we will get
7530 : * the effect of NULL values in the new column.
7531 : *
7532 : * Note: we use build_column_default, and not just the cooked default
7533 : * returned by AddRelationNewConstraints, so that the right thing happens
7534 : * when a datatype's default applies.
7535 : *
7536 : * Note: it might seem that this should happen at the end of Phase 2, so
7537 : * that the effects of subsequent subcommands can be taken into account.
7538 : * It's intentional that we do it now, though. The new column should be
7539 : * filled according to what is said in the ADD COLUMN subcommand, so that
7540 : * the effects are the same as if this subcommand had been run by itself
7541 : * and the later subcommands had been issued in new ALTER TABLE commands.
7542 : *
7543 : * We can skip this entirely for relations without storage, since Phase 3
7544 : * is certainly not going to touch them.
7545 : */
7546 1892 : if (RELKIND_HAS_STORAGE(relkind))
7547 : {
7548 : bool has_domain_constraints;
7549 1622 : bool has_missing = false;
7550 1622 : bool has_volatile = false;
7551 :
7552 : /*
7553 : * For an identity column, we can't use build_column_default(),
7554 : * because the sequence ownership isn't set yet. So do it manually.
7555 : */
7556 1622 : if (colDef->identity)
7557 : {
7558 28 : NextValueExpr *nve = makeNode(NextValueExpr);
7559 :
7560 28 : nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
7561 28 : nve->typeId = attribute->atttypid;
7562 :
7563 28 : defval = (Expr *) nve;
7564 : }
7565 : else
7566 1594 : defval = (Expr *) build_column_default(rel, attribute->attnum);
7567 :
7568 : has_domain_constraints =
7569 1622 : DomainHasConstraints(attribute->atttypid, &has_volatile);
7570 :
7571 : /*
7572 : * If the domain has volatile constraints, we must do a table rewrite
7573 : * since the constraint result could differ per row and cannot be
7574 : * evaluated once and cached as a missing value.
7575 : */
7576 1622 : if (has_volatile)
7577 12 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
7578 :
7579 : /* Build CoerceToDomain(NULL) expression if needed */
7580 1622 : if (!defval && has_domain_constraints)
7581 : {
7582 : Oid baseTypeId;
7583 : int32 baseTypeMod;
7584 : Oid baseTypeColl;
7585 :
7586 12 : baseTypeMod = attribute->atttypmod;
7587 12 : baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
7588 12 : baseTypeColl = get_typcollation(baseTypeId);
7589 12 : defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
7590 12 : defval = (Expr *) coerce_to_target_type(NULL,
7591 : (Node *) defval,
7592 : baseTypeId,
7593 : attribute->atttypid,
7594 : attribute->atttypmod,
7595 : COERCION_ASSIGNMENT,
7596 : COERCE_IMPLICIT_CAST,
7597 : -1);
7598 12 : if (defval == NULL) /* should not happen */
7599 0 : elog(ERROR, "failed to coerce base type to domain");
7600 : }
7601 :
7602 1622 : if (defval)
7603 : {
7604 : NewColumnValue *newval;
7605 :
7606 : /* Prepare defval for execution, either here or in Phase 3 */
7607 635 : defval = expression_planner(defval);
7608 :
7609 : /* Add the new default to the newvals list */
7610 635 : newval = palloc0_object(NewColumnValue);
7611 635 : newval->attnum = attribute->attnum;
7612 635 : newval->expr = defval;
7613 635 : newval->is_generated = (colDef->generated != '\0');
7614 :
7615 635 : tab->newvals = lappend(tab->newvals, newval);
7616 :
7617 : /*
7618 : * Attempt to skip a complete table rewrite by storing the
7619 : * specified DEFAULT value outside of the heap. This is only
7620 : * allowed for plain relations and non-generated columns, and the
7621 : * default expression can't be volatile (stable is OK), and the
7622 : * domain constraint expressions can't be volatile (stable is OK).
7623 : *
7624 : * Note that contain_volatile_functions considers CoerceToDomain
7625 : * immutable, so we rely on DomainHasConstraints (called above)
7626 : * rather than checking defval alone.
7627 : *
7628 : * For domains with non-volatile constraints, we evaluate the
7629 : * default using soft error handling: if the constraint check
7630 : * fails (e.g., CHECK(value > 10) with DEFAULT 8), we fall back to
7631 : * a table rewrite. This preserves the historical behavior that
7632 : * such a failure is only raised when the table has rows.
7633 : */
7634 635 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
7635 635 : !colDef->generated &&
7636 510 : !has_volatile &&
7637 498 : !contain_volatile_functions((Node *) defval))
7638 384 : {
7639 : EState *estate;
7640 : ExprState *exprState;
7641 : Datum missingval;
7642 : bool missingIsNull;
7643 384 : ErrorSaveContext escontext = {T_ErrorSaveContext};
7644 :
7645 : /* Evaluate the default expression with soft errors */
7646 384 : estate = CreateExecutorState();
7647 384 : exprState = ExecPrepareExprWithContext(defval, estate,
7648 : (Node *) &escontext);
7649 384 : missingval = ExecEvalExpr(exprState,
7650 384 : GetPerTupleExprContext(estate),
7651 : &missingIsNull);
7652 :
7653 : /*
7654 : * If the domain constraint check failed (via errsave),
7655 : * missingval is unreliable. Fall back to a table rewrite;
7656 : * Phase 3 will re-evaluate with hard errors, so the user gets
7657 : * an error only if the table has rows.
7658 : */
7659 384 : if (escontext.error_occurred)
7660 : {
7661 24 : missingIsNull = true;
7662 24 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
7663 : }
7664 :
7665 : /* If it turns out NULL, nothing to do; else store it */
7666 384 : if (!missingIsNull)
7667 : {
7668 360 : StoreAttrMissingVal(rel, attribute->attnum, missingval);
7669 : /* Make the additional catalog change visible */
7670 360 : CommandCounterIncrement();
7671 360 : has_missing = true;
7672 : }
7673 384 : FreeExecutorState(estate);
7674 : }
7675 : else
7676 : {
7677 : /*
7678 : * Failed to use missing mode. We have to do a table rewrite
7679 : * to install the value --- unless it's a virtual generated
7680 : * column.
7681 : */
7682 251 : if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
7683 182 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
7684 : }
7685 : }
7686 :
7687 1622 : if (!has_missing)
7688 : {
7689 : /*
7690 : * If the new column is NOT NULL, and there is no missing value,
7691 : * tell Phase 3 it needs to check for NULLs.
7692 : */
7693 1262 : tab->verify_new_notnull |= colDef->is_not_null;
7694 : }
7695 : }
7696 :
7697 : /*
7698 : * Add needed dependency entries for the new column.
7699 : */
7700 1892 : add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
7701 1892 : add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
7702 :
7703 : /*
7704 : * Propagate to children as appropriate. Unlike most other ALTER
7705 : * routines, we have to do this one level of recursion at a time; we can't
7706 : * use find_all_inheritors to do it in one pass.
7707 : */
7708 : children =
7709 1892 : find_inheritance_children(RelationGetRelid(rel), lockmode);
7710 :
7711 : /*
7712 : * If we are told not to recurse, there had better not be any child
7713 : * tables; else the addition would put them out of step.
7714 : */
7715 1892 : if (children && !recurse)
7716 8 : ereport(ERROR,
7717 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7718 : errmsg("column must be added to child tables too")));
7719 :
7720 : /* Children should see column as singly inherited */
7721 1884 : if (!recursing)
7722 : {
7723 1410 : childcmd = copyObject(*cmd);
7724 1410 : colDef = castNode(ColumnDef, childcmd->def);
7725 1410 : colDef->inhcount = 1;
7726 1410 : colDef->is_local = false;
7727 : }
7728 : else
7729 474 : childcmd = *cmd; /* no need to copy again */
7730 :
7731 2398 : foreach(child, children)
7732 : {
7733 514 : Oid childrelid = lfirst_oid(child);
7734 : Relation childrel;
7735 : AlteredTableInfo *childtab;
7736 :
7737 : /* find_inheritance_children already got lock */
7738 514 : childrel = table_open(childrelid, NoLock);
7739 514 : CheckAlterTableIsSafe(childrel);
7740 :
7741 : /* Find or create work queue entry for this table */
7742 514 : childtab = ATGetQueueEntry(wqueue, childrel);
7743 :
7744 : /* Recurse to child; return value is ignored */
7745 514 : ATExecAddColumn(wqueue, childtab, childrel,
7746 : &childcmd, recurse, true,
7747 : lockmode, cur_pass, context);
7748 :
7749 514 : table_close(childrel, NoLock);
7750 : }
7751 :
7752 1884 : ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
7753 1884 : return address;
7754 : }
7755 :
7756 : /*
7757 : * If a new or renamed column will collide with the name of an existing
7758 : * column and if_not_exists is false then error out, else do nothing.
7759 : */
7760 : static bool
7761 2391 : check_for_column_name_collision(Relation rel, const char *colname,
7762 : bool if_not_exists)
7763 : {
7764 : HeapTuple attTuple;
7765 : int attnum;
7766 :
7767 : /*
7768 : * this test is deliberately not attisdropped-aware, since if one tries to
7769 : * add a column matching a dropped column name, it's gonna fail anyway.
7770 : */
7771 2391 : attTuple = SearchSysCache2(ATTNAME,
7772 : ObjectIdGetDatum(RelationGetRelid(rel)),
7773 : PointerGetDatum(colname));
7774 2391 : if (!HeapTupleIsValid(attTuple))
7775 2319 : return true;
7776 :
7777 72 : attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
7778 72 : ReleaseSysCache(attTuple);
7779 :
7780 : /*
7781 : * We throw a different error message for conflicts with system column
7782 : * names, since they are normally not shown and the user might otherwise
7783 : * be confused about the reason for the conflict.
7784 : */
7785 72 : if (attnum <= 0)
7786 8 : ereport(ERROR,
7787 : (errcode(ERRCODE_DUPLICATE_COLUMN),
7788 : errmsg("column name \"%s\" conflicts with a system column name",
7789 : colname)));
7790 : else
7791 : {
7792 64 : if (if_not_exists)
7793 : {
7794 44 : ereport(NOTICE,
7795 : (errcode(ERRCODE_DUPLICATE_COLUMN),
7796 : errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
7797 : colname, RelationGetRelationName(rel))));
7798 44 : return false;
7799 : }
7800 :
7801 20 : ereport(ERROR,
7802 : (errcode(ERRCODE_DUPLICATE_COLUMN),
7803 : errmsg("column \"%s\" of relation \"%s\" already exists",
7804 : colname, RelationGetRelationName(rel))));
7805 : }
7806 :
7807 : return true;
7808 : }
7809 :
7810 : /*
7811 : * Install a column's dependency on its datatype.
7812 : */
7813 : static void
7814 2657 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
7815 : {
7816 : ObjectAddress myself,
7817 : referenced;
7818 :
7819 2657 : myself.classId = RelationRelationId;
7820 2657 : myself.objectId = relid;
7821 2657 : myself.objectSubId = attnum;
7822 2657 : referenced.classId = TypeRelationId;
7823 2657 : referenced.objectId = typid;
7824 2657 : referenced.objectSubId = 0;
7825 2657 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7826 2657 : }
7827 :
7828 : /*
7829 : * Install a column's dependency on its collation.
7830 : */
7831 : static void
7832 2657 : add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
7833 : {
7834 : ObjectAddress myself,
7835 : referenced;
7836 :
7837 : /* We know the default collation is pinned, so don't bother recording it */
7838 2657 : if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
7839 : {
7840 12 : myself.classId = RelationRelationId;
7841 12 : myself.objectId = relid;
7842 12 : myself.objectSubId = attnum;
7843 12 : referenced.classId = CollationRelationId;
7844 12 : referenced.objectId = collid;
7845 12 : referenced.objectSubId = 0;
7846 12 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7847 : }
7848 2657 : }
7849 :
7850 : /*
7851 : * ALTER TABLE ALTER COLUMN DROP NOT NULL
7852 : *
7853 : * Return the address of the modified column. If the column was already
7854 : * nullable, InvalidObjectAddress is returned.
7855 : */
7856 : static ObjectAddress
7857 177 : ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
7858 : LOCKMODE lockmode)
7859 : {
7860 : HeapTuple tuple;
7861 : HeapTuple conTup;
7862 : Form_pg_attribute attTup;
7863 : AttrNumber attnum;
7864 : Relation attr_rel;
7865 : ObjectAddress address;
7866 :
7867 : /*
7868 : * lookup the attribute
7869 : */
7870 177 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7871 :
7872 177 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7873 177 : if (!HeapTupleIsValid(tuple))
7874 12 : ereport(ERROR,
7875 : (errcode(ERRCODE_UNDEFINED_COLUMN),
7876 : errmsg("column \"%s\" of relation \"%s\" does not exist",
7877 : colName, RelationGetRelationName(rel))));
7878 165 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7879 165 : attnum = attTup->attnum;
7880 165 : ObjectAddressSubSet(address, RelationRelationId,
7881 : RelationGetRelid(rel), attnum);
7882 :
7883 : /* If the column is already nullable there's nothing to do. */
7884 165 : if (!attTup->attnotnull)
7885 : {
7886 0 : table_close(attr_rel, RowExclusiveLock);
7887 0 : return InvalidObjectAddress;
7888 : }
7889 :
7890 : /* Prevent them from altering a system attribute */
7891 165 : if (attnum <= 0)
7892 0 : ereport(ERROR,
7893 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7894 : errmsg("cannot alter system column \"%s\"",
7895 : colName)));
7896 :
7897 165 : if (attTup->attidentity)
7898 12 : ereport(ERROR,
7899 : (errcode(ERRCODE_SYNTAX_ERROR),
7900 : errmsg("column \"%s\" of relation \"%s\" is an identity column",
7901 : colName, RelationGetRelationName(rel))));
7902 :
7903 : /*
7904 : * If rel is partition, shouldn't drop NOT NULL if parent has the same.
7905 : */
7906 153 : if (rel->rd_rel->relispartition)
7907 : {
7908 8 : Oid parentId = get_partition_parent(RelationGetRelid(rel), false);
7909 8 : Relation parent = table_open(parentId, AccessShareLock);
7910 8 : TupleDesc tupDesc = RelationGetDescr(parent);
7911 : AttrNumber parent_attnum;
7912 :
7913 8 : parent_attnum = get_attnum(parentId, colName);
7914 8 : if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
7915 8 : ereport(ERROR,
7916 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7917 : errmsg("column \"%s\" is marked NOT NULL in parent table",
7918 : colName)));
7919 0 : table_close(parent, AccessShareLock);
7920 : }
7921 :
7922 : /*
7923 : * Find the constraint that makes this column NOT NULL, and drop it.
7924 : * dropconstraint_internal() resets attnotnull.
7925 : */
7926 145 : conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7927 145 : if (conTup == NULL)
7928 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
7929 : colName, RelationGetRelationName(rel));
7930 :
7931 : /* The normal case: we have a pg_constraint row, remove it */
7932 145 : dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
7933 : false, lockmode);
7934 109 : heap_freetuple(conTup);
7935 :
7936 109 : InvokeObjectPostAlterHook(RelationRelationId,
7937 : RelationGetRelid(rel), attnum);
7938 :
7939 109 : table_close(attr_rel, RowExclusiveLock);
7940 :
7941 109 : return address;
7942 : }
7943 :
7944 : /*
7945 : * set_attnotnull
7946 : * Helper to update/validate the pg_attribute status of a not-null
7947 : * constraint
7948 : *
7949 : * pg_attribute.attnotnull is set true, if it isn't already.
7950 : * If queue_validation is true, also set up wqueue to validate the constraint.
7951 : * wqueue may be given as NULL when validation is not needed (e.g., on table
7952 : * creation).
7953 : */
7954 : static void
7955 16507 : set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
7956 : bool is_valid, bool queue_validation)
7957 : {
7958 : Form_pg_attribute attr;
7959 : CompactAttribute *thisatt;
7960 :
7961 : Assert(!queue_validation || wqueue);
7962 :
7963 16507 : CheckAlterTableIsSafe(rel);
7964 :
7965 : /*
7966 : * Exit quickly by testing attnotnull from the tupledesc's copy of the
7967 : * attribute.
7968 : */
7969 16507 : attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
7970 16507 : if (attr->attisdropped)
7971 0 : return;
7972 :
7973 16507 : if (!attr->attnotnull)
7974 : {
7975 : Relation attr_rel;
7976 : HeapTuple tuple;
7977 :
7978 983 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7979 :
7980 983 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
7981 983 : if (!HeapTupleIsValid(tuple))
7982 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
7983 : attnum, RelationGetRelid(rel));
7984 :
7985 983 : thisatt = TupleDescCompactAttr(RelationGetDescr(rel), attnum - 1);
7986 983 : thisatt->attnullability = ATTNULLABLE_VALID;
7987 :
7988 983 : attr = (Form_pg_attribute) GETSTRUCT(tuple);
7989 :
7990 983 : attr->attnotnull = true;
7991 983 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
7992 :
7993 : /*
7994 : * If the nullness isn't already proven by validated constraints, have
7995 : * ALTER TABLE phase 3 test for it.
7996 : */
7997 983 : if (queue_validation && wqueue &&
7998 816 : !NotNullImpliedByRelConstraints(rel, attr))
7999 : {
8000 : AlteredTableInfo *tab;
8001 :
8002 784 : tab = ATGetQueueEntry(wqueue, rel);
8003 784 : tab->verify_new_notnull = true;
8004 : }
8005 :
8006 983 : CommandCounterIncrement();
8007 :
8008 983 : table_close(attr_rel, RowExclusiveLock);
8009 983 : heap_freetuple(tuple);
8010 : }
8011 : else
8012 : {
8013 15524 : CacheInvalidateRelcache(rel);
8014 : }
8015 : }
8016 :
8017 : /*
8018 : * ALTER TABLE ALTER COLUMN SET NOT NULL
8019 : *
8020 : * Add a not-null constraint to a single table and its children. Returns
8021 : * the address of the constraint added to the parent relation, if one gets
8022 : * added, or InvalidObjectAddress otherwise.
8023 : *
8024 : * We must recurse to child tables during execution, rather than using
8025 : * ALTER TABLE's normal prep-time recursion.
8026 : */
8027 : static ObjectAddress
8028 469 : ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
8029 : bool recurse, bool recursing, LOCKMODE lockmode)
8030 : {
8031 : HeapTuple tuple;
8032 : AttrNumber attnum;
8033 : ObjectAddress address;
8034 : Constraint *constraint;
8035 : CookedConstraint *ccon;
8036 : List *cooked;
8037 469 : bool is_no_inherit = false;
8038 :
8039 : /* Guard against stack overflow due to overly deep inheritance tree. */
8040 469 : check_stack_depth();
8041 :
8042 : /* At top level, permission check was done in ATPrepCmd, else do it */
8043 469 : if (recursing)
8044 : {
8045 197 : ATSimplePermissions(AT_AddConstraint, rel,
8046 : ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
8047 : Assert(conName != NULL);
8048 : }
8049 :
8050 469 : attnum = get_attnum(RelationGetRelid(rel), colName);
8051 469 : if (attnum == InvalidAttrNumber)
8052 12 : ereport(ERROR,
8053 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8054 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8055 : colName, RelationGetRelationName(rel))));
8056 :
8057 : /* Prevent them from altering a system attribute */
8058 457 : if (attnum <= 0)
8059 0 : ereport(ERROR,
8060 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8061 : errmsg("cannot alter system column \"%s\"",
8062 : colName)));
8063 :
8064 : /* See if there's already a constraint */
8065 457 : tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
8066 457 : if (HeapTupleIsValid(tuple))
8067 : {
8068 105 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
8069 105 : bool changed = false;
8070 :
8071 : /*
8072 : * Don't let a NO INHERIT constraint be changed into inherit.
8073 : */
8074 105 : if (conForm->connoinherit && recurse)
8075 8 : ereport(ERROR,
8076 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8077 : errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
8078 : NameStr(conForm->conname),
8079 : RelationGetRelationName(rel)));
8080 :
8081 : /*
8082 : * If we find an appropriate constraint, we're almost done, but just
8083 : * need to change some properties on it: if we're recursing, increment
8084 : * coninhcount; if not, set conislocal if not already set.
8085 : */
8086 97 : if (recursing)
8087 : {
8088 68 : if (pg_add_s16_overflow(conForm->coninhcount, 1,
8089 : &conForm->coninhcount))
8090 0 : ereport(ERROR,
8091 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
8092 : errmsg("too many inheritance parents"));
8093 68 : changed = true;
8094 : }
8095 29 : else if (!conForm->conislocal)
8096 : {
8097 0 : conForm->conislocal = true;
8098 0 : changed = true;
8099 : }
8100 29 : else if (!conForm->convalidated)
8101 : {
8102 : /*
8103 : * Flip attnotnull and convalidated, and also validate the
8104 : * constraint.
8105 : */
8106 16 : return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
8107 : recurse, recursing, lockmode);
8108 : }
8109 :
8110 81 : if (changed)
8111 : {
8112 : Relation constr_rel;
8113 :
8114 68 : constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
8115 :
8116 68 : CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
8117 68 : ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
8118 68 : table_close(constr_rel, RowExclusiveLock);
8119 : }
8120 :
8121 81 : if (changed)
8122 68 : return address;
8123 : else
8124 13 : return InvalidObjectAddress;
8125 : }
8126 :
8127 : /*
8128 : * If we're asked not to recurse, and children exist, raise an error for
8129 : * partitioned tables. For inheritance, we act as if NO INHERIT had been
8130 : * specified.
8131 : */
8132 372 : if (!recurse &&
8133 20 : find_inheritance_children(RelationGetRelid(rel),
8134 : NoLock) != NIL)
8135 : {
8136 12 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8137 4 : ereport(ERROR,
8138 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8139 : errmsg("constraint must be added to child tables too"),
8140 : errhint("Do not specify the ONLY keyword."));
8141 : else
8142 8 : is_no_inherit = true;
8143 : }
8144 :
8145 : /*
8146 : * No constraint exists; we must add one. First determine a name to use,
8147 : * if we haven't already.
8148 : */
8149 348 : if (!recursing)
8150 : {
8151 : Assert(conName == NULL);
8152 223 : conName = ChooseConstraintName(RelationGetRelationName(rel),
8153 : colName, "not_null",
8154 223 : RelationGetNamespace(rel),
8155 : NIL);
8156 : }
8157 :
8158 348 : constraint = makeNotNullConstraint(makeString(colName));
8159 348 : constraint->is_no_inherit = is_no_inherit;
8160 348 : constraint->conname = conName;
8161 :
8162 : /* and do it */
8163 348 : cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
8164 348 : false, !recursing, false, NULL);
8165 348 : ccon = linitial(cooked);
8166 348 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8167 :
8168 : /* Mark pg_attribute.attnotnull for the column and queue validation */
8169 348 : set_attnotnull(wqueue, rel, attnum, true, true);
8170 :
8171 348 : InvokeObjectPostAlterHook(RelationRelationId,
8172 : RelationGetRelid(rel), attnum);
8173 :
8174 : /*
8175 : * Recurse to propagate the constraint to children that don't have one.
8176 : */
8177 348 : if (recurse)
8178 : {
8179 : List *children;
8180 :
8181 332 : children = find_inheritance_children(RelationGetRelid(rel),
8182 : lockmode);
8183 :
8184 817 : foreach_oid(childoid, children)
8185 : {
8186 161 : Relation childrel = table_open(childoid, NoLock);
8187 :
8188 161 : CommandCounterIncrement();
8189 :
8190 161 : ATExecSetNotNull(wqueue, childrel, conName, colName,
8191 : recurse, true, lockmode);
8192 157 : table_close(childrel, NoLock);
8193 : }
8194 : }
8195 :
8196 344 : return address;
8197 : }
8198 :
8199 : /*
8200 : * NotNullImpliedByRelConstraints
8201 : * Does rel's existing constraints imply NOT NULL for the given attribute?
8202 : */
8203 : static bool
8204 816 : NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
8205 : {
8206 816 : NullTest *nnulltest = makeNode(NullTest);
8207 :
8208 1632 : nnulltest->arg = (Expr *) makeVar(1,
8209 816 : attr->attnum,
8210 : attr->atttypid,
8211 : attr->atttypmod,
8212 : attr->attcollation,
8213 : 0);
8214 816 : nnulltest->nulltesttype = IS_NOT_NULL;
8215 :
8216 : /*
8217 : * argisrow = false is correct even for a composite column, because
8218 : * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
8219 : * case, just IS DISTINCT FROM NULL.
8220 : */
8221 816 : nnulltest->argisrow = false;
8222 816 : nnulltest->location = -1;
8223 :
8224 816 : if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
8225 : {
8226 32 : ereport(DEBUG1,
8227 : (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
8228 : RelationGetRelationName(rel), NameStr(attr->attname))));
8229 32 : return true;
8230 : }
8231 :
8232 784 : return false;
8233 : }
8234 :
8235 : /*
8236 : * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
8237 : *
8238 : * Return the address of the affected column.
8239 : */
8240 : static ObjectAddress
8241 383 : ATExecColumnDefault(Relation rel, const char *colName,
8242 : Node *newDefault, LOCKMODE lockmode)
8243 : {
8244 383 : TupleDesc tupdesc = RelationGetDescr(rel);
8245 : AttrNumber attnum;
8246 : ObjectAddress address;
8247 :
8248 : /*
8249 : * get the number of the attribute
8250 : */
8251 383 : attnum = get_attnum(RelationGetRelid(rel), colName);
8252 383 : if (attnum == InvalidAttrNumber)
8253 20 : ereport(ERROR,
8254 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8255 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8256 : colName, RelationGetRelationName(rel))));
8257 :
8258 : /* Prevent them from altering a system attribute */
8259 363 : if (attnum <= 0)
8260 0 : ereport(ERROR,
8261 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8262 : errmsg("cannot alter system column \"%s\"",
8263 : colName)));
8264 :
8265 363 : if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
8266 12 : ereport(ERROR,
8267 : (errcode(ERRCODE_SYNTAX_ERROR),
8268 : errmsg("column \"%s\" of relation \"%s\" is an identity column",
8269 : colName, RelationGetRelationName(rel)),
8270 : /* translator: %s is an SQL ALTER command */
8271 : newDefault ? 0 : errhint("Use %s instead.",
8272 : "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
8273 :
8274 351 : if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
8275 8 : ereport(ERROR,
8276 : (errcode(ERRCODE_SYNTAX_ERROR),
8277 : errmsg("column \"%s\" of relation \"%s\" is a generated column",
8278 : colName, RelationGetRelationName(rel)),
8279 : newDefault ?
8280 : /* translator: %s is an SQL ALTER command */
8281 : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
8282 : (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
8283 : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
8284 :
8285 : /*
8286 : * Remove any old default for the column. We use RESTRICT here for
8287 : * safety, but at present we do not expect anything to depend on the
8288 : * default.
8289 : *
8290 : * We treat removing the existing default as an internal operation when it
8291 : * is preparatory to adding a new default, but as a user-initiated
8292 : * operation when the user asked for a drop.
8293 : */
8294 343 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8295 : newDefault != NULL);
8296 :
8297 343 : if (newDefault)
8298 : {
8299 : /* SET DEFAULT */
8300 : RawColumnDefault *rawEnt;
8301 :
8302 227 : rawEnt = palloc_object(RawColumnDefault);
8303 227 : rawEnt->attnum = attnum;
8304 227 : rawEnt->raw_default = newDefault;
8305 227 : rawEnt->generated = '\0';
8306 :
8307 : /*
8308 : * This function is intended for CREATE TABLE, so it processes a
8309 : * _list_ of defaults, but we just do one.
8310 : */
8311 227 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8312 : false, true, false, NULL);
8313 : }
8314 :
8315 339 : ObjectAddressSubSet(address, RelationRelationId,
8316 : RelationGetRelid(rel), attnum);
8317 339 : return address;
8318 : }
8319 :
8320 : /*
8321 : * Add a pre-cooked default expression.
8322 : *
8323 : * Return the address of the affected column.
8324 : */
8325 : static ObjectAddress
8326 53 : ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
8327 : Node *newDefault)
8328 : {
8329 : ObjectAddress address;
8330 :
8331 : /* We assume no checking is required */
8332 :
8333 : /*
8334 : * Remove any old default for the column. We use RESTRICT here for
8335 : * safety, but at present we do not expect anything to depend on the
8336 : * default. (In ordinary cases, there could not be a default in place
8337 : * anyway, but it's possible when combining LIKE with inheritance.)
8338 : */
8339 53 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8340 : true);
8341 :
8342 53 : (void) StoreAttrDefault(rel, attnum, newDefault, true);
8343 :
8344 53 : ObjectAddressSubSet(address, RelationRelationId,
8345 : RelationGetRelid(rel), attnum);
8346 53 : return address;
8347 : }
8348 :
8349 : /*
8350 : * ALTER TABLE ALTER COLUMN ADD IDENTITY
8351 : *
8352 : * Return the address of the affected column.
8353 : */
8354 : static ObjectAddress
8355 103 : ATExecAddIdentity(Relation rel, const char *colName,
8356 : Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
8357 : {
8358 : Relation attrelation;
8359 : HeapTuple tuple;
8360 : Form_pg_attribute attTup;
8361 : AttrNumber attnum;
8362 : ObjectAddress address;
8363 103 : ColumnDef *cdef = castNode(ColumnDef, def);
8364 : bool ispartitioned;
8365 :
8366 103 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8367 103 : if (ispartitioned && !recurse)
8368 4 : ereport(ERROR,
8369 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8370 : errmsg("cannot add identity to a column of only the partitioned table"),
8371 : errhint("Do not specify the ONLY keyword.")));
8372 :
8373 99 : if (rel->rd_rel->relispartition && !recursing)
8374 8 : ereport(ERROR,
8375 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8376 : errmsg("cannot add identity to a column of a partition"));
8377 :
8378 91 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8379 :
8380 91 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8381 91 : if (!HeapTupleIsValid(tuple))
8382 0 : ereport(ERROR,
8383 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8384 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8385 : colName, RelationGetRelationName(rel))));
8386 91 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8387 91 : attnum = attTup->attnum;
8388 :
8389 : /* Can't alter a system attribute */
8390 91 : if (attnum <= 0)
8391 0 : ereport(ERROR,
8392 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8393 : errmsg("cannot alter system column \"%s\"",
8394 : colName)));
8395 :
8396 : /*
8397 : * Creating a column as identity implies NOT NULL, so adding the identity
8398 : * to an existing column that is not NOT NULL would create a state that
8399 : * cannot be reproduced without contortions.
8400 : */
8401 91 : if (!attTup->attnotnull)
8402 4 : ereport(ERROR,
8403 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8404 : errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
8405 : colName, RelationGetRelationName(rel))));
8406 :
8407 : /*
8408 : * On the other hand, if a not-null constraint exists, then verify that
8409 : * it's compatible.
8410 : */
8411 87 : if (attTup->attnotnull)
8412 : {
8413 : HeapTuple contup;
8414 : Form_pg_constraint conForm;
8415 :
8416 87 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel),
8417 : attnum);
8418 87 : if (!HeapTupleIsValid(contup))
8419 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
8420 : colName, RelationGetRelationName(rel));
8421 :
8422 87 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
8423 87 : if (!conForm->convalidated)
8424 4 : ereport(ERROR,
8425 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8426 : errmsg("incompatible NOT VALID constraint \"%s\" on relation \"%s\"",
8427 : NameStr(conForm->conname), RelationGetRelationName(rel)),
8428 : errhint("You might need to validate it using %s.",
8429 : "ALTER TABLE ... VALIDATE CONSTRAINT"));
8430 : }
8431 :
8432 83 : if (attTup->attidentity)
8433 12 : ereport(ERROR,
8434 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8435 : errmsg("column \"%s\" of relation \"%s\" is already an identity column",
8436 : colName, RelationGetRelationName(rel))));
8437 :
8438 71 : if (attTup->atthasdef)
8439 4 : ereport(ERROR,
8440 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8441 : errmsg("column \"%s\" of relation \"%s\" already has a default value",
8442 : colName, RelationGetRelationName(rel))));
8443 :
8444 67 : attTup->attidentity = cdef->identity;
8445 67 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8446 :
8447 67 : InvokeObjectPostAlterHook(RelationRelationId,
8448 : RelationGetRelid(rel),
8449 : attTup->attnum);
8450 67 : ObjectAddressSubSet(address, RelationRelationId,
8451 : RelationGetRelid(rel), attnum);
8452 67 : heap_freetuple(tuple);
8453 :
8454 67 : table_close(attrelation, RowExclusiveLock);
8455 :
8456 : /*
8457 : * Recurse to propagate the identity column to partitions. Identity is
8458 : * not inherited in regular inheritance children.
8459 : */
8460 67 : if (recurse && ispartitioned)
8461 : {
8462 : List *children;
8463 : ListCell *lc;
8464 :
8465 6 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8466 :
8467 10 : foreach(lc, children)
8468 : {
8469 : Relation childrel;
8470 :
8471 4 : childrel = table_open(lfirst_oid(lc), NoLock);
8472 4 : ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
8473 4 : table_close(childrel, NoLock);
8474 : }
8475 : }
8476 :
8477 67 : return address;
8478 : }
8479 :
8480 : /*
8481 : * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
8482 : *
8483 : * Return the address of the affected column.
8484 : */
8485 : static ObjectAddress
8486 49 : ATExecSetIdentity(Relation rel, const char *colName, Node *def,
8487 : LOCKMODE lockmode, bool recurse, bool recursing)
8488 : {
8489 : ListCell *option;
8490 49 : DefElem *generatedEl = NULL;
8491 : HeapTuple tuple;
8492 : Form_pg_attribute attTup;
8493 : AttrNumber attnum;
8494 : Relation attrelation;
8495 : ObjectAddress address;
8496 : bool ispartitioned;
8497 :
8498 49 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8499 49 : if (ispartitioned && !recurse)
8500 4 : ereport(ERROR,
8501 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8502 : errmsg("cannot change identity column of only the partitioned table"),
8503 : errhint("Do not specify the ONLY keyword.")));
8504 :
8505 45 : if (rel->rd_rel->relispartition && !recursing)
8506 8 : ereport(ERROR,
8507 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8508 : errmsg("cannot change identity column of a partition"));
8509 :
8510 66 : foreach(option, castNode(List, def))
8511 : {
8512 29 : DefElem *defel = lfirst_node(DefElem, option);
8513 :
8514 29 : if (strcmp(defel->defname, "generated") == 0)
8515 : {
8516 29 : if (generatedEl)
8517 0 : ereport(ERROR,
8518 : (errcode(ERRCODE_SYNTAX_ERROR),
8519 : errmsg("conflicting or redundant options")));
8520 29 : generatedEl = defel;
8521 : }
8522 : else
8523 0 : elog(ERROR, "option \"%s\" not recognized",
8524 : defel->defname);
8525 : }
8526 :
8527 : /*
8528 : * Even if there is nothing to change here, we run all the checks. There
8529 : * will be a subsequent ALTER SEQUENCE that relies on everything being
8530 : * there.
8531 : */
8532 :
8533 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8534 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8535 37 : if (!HeapTupleIsValid(tuple))
8536 0 : ereport(ERROR,
8537 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8538 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8539 : colName, RelationGetRelationName(rel))));
8540 :
8541 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8542 37 : attnum = attTup->attnum;
8543 :
8544 37 : if (attnum <= 0)
8545 0 : ereport(ERROR,
8546 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8547 : errmsg("cannot alter system column \"%s\"",
8548 : colName)));
8549 :
8550 37 : if (!attTup->attidentity)
8551 4 : ereport(ERROR,
8552 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8553 : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8554 : colName, RelationGetRelationName(rel))));
8555 :
8556 33 : if (generatedEl)
8557 : {
8558 29 : attTup->attidentity = defGetInt32(generatedEl);
8559 29 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8560 :
8561 29 : InvokeObjectPostAlterHook(RelationRelationId,
8562 : RelationGetRelid(rel),
8563 : attTup->attnum);
8564 29 : ObjectAddressSubSet(address, RelationRelationId,
8565 : RelationGetRelid(rel), attnum);
8566 : }
8567 : else
8568 4 : address = InvalidObjectAddress;
8569 :
8570 33 : heap_freetuple(tuple);
8571 33 : table_close(attrelation, RowExclusiveLock);
8572 :
8573 : /*
8574 : * Recurse to propagate the identity change to partitions. Identity is not
8575 : * inherited in regular inheritance children.
8576 : */
8577 33 : if (generatedEl && recurse && ispartitioned)
8578 : {
8579 : List *children;
8580 : ListCell *lc;
8581 :
8582 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8583 :
8584 12 : foreach(lc, children)
8585 : {
8586 : Relation childrel;
8587 :
8588 8 : childrel = table_open(lfirst_oid(lc), NoLock);
8589 8 : ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
8590 8 : table_close(childrel, NoLock);
8591 : }
8592 : }
8593 :
8594 33 : return address;
8595 : }
8596 :
8597 : /*
8598 : * ALTER TABLE ALTER COLUMN DROP IDENTITY
8599 : *
8600 : * Return the address of the affected column.
8601 : */
8602 : static ObjectAddress
8603 61 : ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
8604 : bool recurse, bool recursing)
8605 : {
8606 : HeapTuple tuple;
8607 : Form_pg_attribute attTup;
8608 : AttrNumber attnum;
8609 : Relation attrelation;
8610 : ObjectAddress address;
8611 : Oid seqid;
8612 : ObjectAddress seqaddress;
8613 : bool ispartitioned;
8614 :
8615 61 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8616 61 : if (ispartitioned && !recurse)
8617 4 : ereport(ERROR,
8618 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8619 : errmsg("cannot drop identity from a column of only the partitioned table"),
8620 : errhint("Do not specify the ONLY keyword.")));
8621 :
8622 57 : if (rel->rd_rel->relispartition && !recursing)
8623 4 : ereport(ERROR,
8624 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8625 : errmsg("cannot drop identity from a column of a partition"));
8626 :
8627 53 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8628 53 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8629 53 : if (!HeapTupleIsValid(tuple))
8630 0 : ereport(ERROR,
8631 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8632 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8633 : colName, RelationGetRelationName(rel))));
8634 :
8635 53 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8636 53 : attnum = attTup->attnum;
8637 :
8638 53 : if (attnum <= 0)
8639 0 : ereport(ERROR,
8640 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8641 : errmsg("cannot alter system column \"%s\"",
8642 : colName)));
8643 :
8644 53 : if (!attTup->attidentity)
8645 : {
8646 8 : if (!missing_ok)
8647 4 : ereport(ERROR,
8648 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8649 : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8650 : colName, RelationGetRelationName(rel))));
8651 : else
8652 : {
8653 4 : ereport(NOTICE,
8654 : (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
8655 : colName, RelationGetRelationName(rel))));
8656 4 : heap_freetuple(tuple);
8657 4 : table_close(attrelation, RowExclusiveLock);
8658 4 : return InvalidObjectAddress;
8659 : }
8660 : }
8661 :
8662 45 : attTup->attidentity = '\0';
8663 45 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8664 :
8665 45 : InvokeObjectPostAlterHook(RelationRelationId,
8666 : RelationGetRelid(rel),
8667 : attTup->attnum);
8668 45 : ObjectAddressSubSet(address, RelationRelationId,
8669 : RelationGetRelid(rel), attnum);
8670 45 : heap_freetuple(tuple);
8671 :
8672 45 : table_close(attrelation, RowExclusiveLock);
8673 :
8674 : /*
8675 : * Recurse to drop the identity from column in partitions. Identity is
8676 : * not inherited in regular inheritance children so ignore them.
8677 : */
8678 45 : if (recurse && ispartitioned)
8679 : {
8680 : List *children;
8681 : ListCell *lc;
8682 :
8683 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8684 :
8685 8 : foreach(lc, children)
8686 : {
8687 : Relation childrel;
8688 :
8689 4 : childrel = table_open(lfirst_oid(lc), NoLock);
8690 4 : ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
8691 4 : table_close(childrel, NoLock);
8692 : }
8693 : }
8694 :
8695 45 : if (!recursing)
8696 : {
8697 : /* drop the internal sequence */
8698 21 : seqid = getIdentitySequence(rel, attnum, false);
8699 21 : deleteDependencyRecordsForClass(RelationRelationId, seqid,
8700 : RelationRelationId, DEPENDENCY_INTERNAL);
8701 21 : CommandCounterIncrement();
8702 21 : seqaddress.classId = RelationRelationId;
8703 21 : seqaddress.objectId = seqid;
8704 21 : seqaddress.objectSubId = 0;
8705 21 : performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8706 : }
8707 :
8708 45 : return address;
8709 : }
8710 :
8711 : /*
8712 : * ALTER TABLE ALTER COLUMN SET EXPRESSION
8713 : *
8714 : * Return the address of the affected column.
8715 : */
8716 : static ObjectAddress
8717 169 : ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
8718 : Node *newExpr, LOCKMODE lockmode)
8719 : {
8720 : HeapTuple tuple;
8721 : Form_pg_attribute attTup;
8722 : AttrNumber attnum;
8723 : char attgenerated;
8724 : bool rewrite;
8725 : Oid attrdefoid;
8726 : ObjectAddress address;
8727 : Expr *defval;
8728 : NewColumnValue *newval;
8729 : RawColumnDefault *rawEnt;
8730 :
8731 169 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8732 169 : if (!HeapTupleIsValid(tuple))
8733 0 : ereport(ERROR,
8734 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8735 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8736 : colName, RelationGetRelationName(rel))));
8737 :
8738 169 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8739 :
8740 169 : attnum = attTup->attnum;
8741 169 : if (attnum <= 0)
8742 0 : ereport(ERROR,
8743 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8744 : errmsg("cannot alter system column \"%s\"",
8745 : colName)));
8746 :
8747 169 : attgenerated = attTup->attgenerated;
8748 169 : if (!attgenerated)
8749 8 : ereport(ERROR,
8750 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8751 : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8752 : colName, RelationGetRelationName(rel))));
8753 :
8754 161 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
8755 16 : tab->verify_new_notnull = true;
8756 :
8757 : /*
8758 : * We need to prevent this because a change of expression could affect a
8759 : * row filter and inject expressions that are not permitted in a row
8760 : * filter. XXX We could try to have a more precise check to catch only
8761 : * publications with row filters, or even re-verify the row filter
8762 : * expressions.
8763 : */
8764 237 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
8765 76 : GetRelationIncludedPublications(RelationGetRelid(rel)) != NIL)
8766 4 : ereport(ERROR,
8767 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8768 : errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
8769 : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8770 : colName, RelationGetRelationName(rel))));
8771 :
8772 157 : rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
8773 :
8774 157 : ReleaseSysCache(tuple);
8775 :
8776 157 : if (rewrite)
8777 : {
8778 : /*
8779 : * Clear all the missing values if we're rewriting the table, since
8780 : * this renders them pointless.
8781 : */
8782 85 : RelationClearMissing(rel);
8783 :
8784 : /* make sure we don't conflict with later attribute modifications */
8785 85 : CommandCounterIncrement();
8786 : }
8787 :
8788 : /*
8789 : * Find everything that depends on the column (constraints, indexes, etc),
8790 : * and record enough information to let us recreate the objects.
8791 : */
8792 157 : RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
8793 :
8794 : /*
8795 : * Drop the dependency records of the GENERATED expression, in particular
8796 : * its INTERNAL dependency on the column, which would otherwise cause
8797 : * dependency.c to refuse to perform the deletion.
8798 : */
8799 157 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8800 157 : if (!OidIsValid(attrdefoid))
8801 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8802 : RelationGetRelid(rel), attnum);
8803 157 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8804 :
8805 : /* Make above changes visible */
8806 157 : CommandCounterIncrement();
8807 :
8808 : /*
8809 : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8810 : * safety, but at present we do not expect anything to depend on the
8811 : * expression.
8812 : */
8813 157 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8814 : false, false);
8815 :
8816 : /* Prepare to store the new expression, in the catalogs */
8817 157 : rawEnt = palloc_object(RawColumnDefault);
8818 157 : rawEnt->attnum = attnum;
8819 157 : rawEnt->raw_default = newExpr;
8820 157 : rawEnt->generated = attgenerated;
8821 :
8822 : /* Store the generated expression */
8823 157 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8824 : false, true, false, NULL);
8825 :
8826 : /* Make above new expression visible */
8827 157 : CommandCounterIncrement();
8828 :
8829 157 : if (rewrite)
8830 : {
8831 : /* Prepare for table rewrite */
8832 85 : defval = (Expr *) build_column_default(rel, attnum);
8833 :
8834 85 : newval = palloc0_object(NewColumnValue);
8835 85 : newval->attnum = attnum;
8836 85 : newval->expr = expression_planner(defval);
8837 85 : newval->is_generated = true;
8838 :
8839 85 : tab->newvals = lappend(tab->newvals, newval);
8840 85 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
8841 : }
8842 :
8843 : /* Drop any pg_statistic entry for the column */
8844 157 : RemoveStatistics(RelationGetRelid(rel), attnum);
8845 :
8846 157 : InvokeObjectPostAlterHook(RelationRelationId,
8847 : RelationGetRelid(rel), attnum);
8848 :
8849 157 : ObjectAddressSubSet(address, RelationRelationId,
8850 : RelationGetRelid(rel), attnum);
8851 157 : return address;
8852 : }
8853 :
8854 : /*
8855 : * ALTER TABLE ALTER COLUMN DROP EXPRESSION
8856 : */
8857 : static void
8858 57 : ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
8859 : {
8860 : /*
8861 : * Reject ONLY if there are child tables. We could implement this, but it
8862 : * is a bit complicated. GENERATED clauses must be attached to the column
8863 : * definition and cannot be added later like DEFAULT, so if a child table
8864 : * has a generation expression that the parent does not have, the child
8865 : * column will necessarily be an attislocal column. So to implement ONLY
8866 : * here, we'd need extra code to update attislocal of the direct child
8867 : * tables, somewhat similar to how DROP COLUMN does it, so that the
8868 : * resulting state can be properly dumped and restored.
8869 : */
8870 73 : if (!recurse &&
8871 16 : find_inheritance_children(RelationGetRelid(rel), lockmode))
8872 8 : ereport(ERROR,
8873 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8874 : errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
8875 :
8876 : /*
8877 : * Cannot drop generation expression from inherited columns.
8878 : */
8879 49 : if (!recursing)
8880 : {
8881 : HeapTuple tuple;
8882 : Form_pg_attribute attTup;
8883 :
8884 41 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
8885 41 : if (!HeapTupleIsValid(tuple))
8886 0 : ereport(ERROR,
8887 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8888 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8889 : cmd->name, RelationGetRelationName(rel))));
8890 :
8891 41 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8892 :
8893 41 : if (attTup->attinhcount > 0)
8894 8 : ereport(ERROR,
8895 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8896 : errmsg("cannot drop generation expression from inherited column")));
8897 : }
8898 41 : }
8899 :
8900 : /*
8901 : * Return the address of the affected column.
8902 : */
8903 : static ObjectAddress
8904 37 : ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
8905 : {
8906 : HeapTuple tuple;
8907 : Form_pg_attribute attTup;
8908 : AttrNumber attnum;
8909 : Relation attrelation;
8910 : Oid attrdefoid;
8911 : ObjectAddress address;
8912 :
8913 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8914 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8915 37 : if (!HeapTupleIsValid(tuple))
8916 0 : ereport(ERROR,
8917 : (errcode(ERRCODE_UNDEFINED_COLUMN),
8918 : errmsg("column \"%s\" of relation \"%s\" does not exist",
8919 : colName, RelationGetRelationName(rel))));
8920 :
8921 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8922 37 : attnum = attTup->attnum;
8923 :
8924 37 : if (attnum <= 0)
8925 0 : ereport(ERROR,
8926 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8927 : errmsg("cannot alter system column \"%s\"",
8928 : colName)));
8929 :
8930 : /*
8931 : * TODO: This could be done, but it would need a table rewrite to
8932 : * materialize the generated values. Note that for the time being, we
8933 : * still error with missing_ok, so that we don't silently leave the column
8934 : * as generated.
8935 : */
8936 37 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
8937 8 : ereport(ERROR,
8938 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8939 : errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
8940 : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8941 : colName, RelationGetRelationName(rel))));
8942 :
8943 29 : if (!attTup->attgenerated)
8944 : {
8945 16 : if (!missing_ok)
8946 8 : ereport(ERROR,
8947 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8948 : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8949 : colName, RelationGetRelationName(rel))));
8950 : else
8951 : {
8952 8 : ereport(NOTICE,
8953 : (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
8954 : colName, RelationGetRelationName(rel))));
8955 8 : heap_freetuple(tuple);
8956 8 : table_close(attrelation, RowExclusiveLock);
8957 8 : return InvalidObjectAddress;
8958 : }
8959 : }
8960 :
8961 : /*
8962 : * Mark the column as no longer generated. (The atthasdef flag needs to
8963 : * get cleared too, but RemoveAttrDefault will handle that.)
8964 : */
8965 13 : attTup->attgenerated = '\0';
8966 13 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8967 :
8968 13 : InvokeObjectPostAlterHook(RelationRelationId,
8969 : RelationGetRelid(rel),
8970 : attnum);
8971 13 : heap_freetuple(tuple);
8972 :
8973 13 : table_close(attrelation, RowExclusiveLock);
8974 :
8975 : /*
8976 : * Drop the dependency records of the GENERATED expression, in particular
8977 : * its INTERNAL dependency on the column, which would otherwise cause
8978 : * dependency.c to refuse to perform the deletion.
8979 : */
8980 13 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8981 13 : if (!OidIsValid(attrdefoid))
8982 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8983 : RelationGetRelid(rel), attnum);
8984 13 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8985 :
8986 : /* Make above changes visible */
8987 13 : CommandCounterIncrement();
8988 :
8989 : /*
8990 : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8991 : * safety, but at present we do not expect anything to depend on the
8992 : * default.
8993 : */
8994 13 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8995 : false, false);
8996 :
8997 13 : ObjectAddressSubSet(address, RelationRelationId,
8998 : RelationGetRelid(rel), attnum);
8999 13 : return address;
9000 : }
9001 :
9002 : /*
9003 : * ALTER TABLE ALTER COLUMN SET STATISTICS
9004 : *
9005 : * Return value is the address of the modified column
9006 : */
9007 : static ObjectAddress
9008 111 : ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
9009 : {
9010 111 : int newtarget = 0;
9011 : bool newtarget_default;
9012 : Relation attrelation;
9013 : HeapTuple tuple,
9014 : newtuple;
9015 : Form_pg_attribute attrtuple;
9016 : AttrNumber attnum;
9017 : ObjectAddress address;
9018 : Datum repl_val[Natts_pg_attribute];
9019 : bool repl_null[Natts_pg_attribute];
9020 : bool repl_repl[Natts_pg_attribute];
9021 :
9022 : /*
9023 : * We allow referencing columns by numbers only for indexes, since table
9024 : * column numbers could contain gaps if columns are later dropped.
9025 : */
9026 111 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
9027 69 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
9028 : !colName)
9029 0 : ereport(ERROR,
9030 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9031 : errmsg("cannot refer to non-index column by number")));
9032 :
9033 : /* -1 was used in previous versions for the default setting */
9034 111 : if (newValue && intVal(newValue) != -1)
9035 : {
9036 80 : newtarget = intVal(newValue);
9037 80 : newtarget_default = false;
9038 : }
9039 : else
9040 31 : newtarget_default = true;
9041 :
9042 111 : if (!newtarget_default)
9043 : {
9044 : /*
9045 : * Limit target to a sane range
9046 : */
9047 80 : if (newtarget < 0)
9048 : {
9049 0 : ereport(ERROR,
9050 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9051 : errmsg("statistics target %d is too low",
9052 : newtarget)));
9053 : }
9054 80 : else if (newtarget > MAX_STATISTICS_TARGET)
9055 : {
9056 0 : newtarget = MAX_STATISTICS_TARGET;
9057 0 : ereport(WARNING,
9058 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9059 : errmsg("lowering statistics target to %d",
9060 : newtarget)));
9061 : }
9062 : }
9063 :
9064 111 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9065 :
9066 111 : if (colName)
9067 : {
9068 69 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9069 :
9070 69 : if (!HeapTupleIsValid(tuple))
9071 8 : ereport(ERROR,
9072 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9073 : errmsg("column \"%s\" of relation \"%s\" does not exist",
9074 : colName, RelationGetRelationName(rel))));
9075 : }
9076 : else
9077 : {
9078 42 : tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
9079 :
9080 42 : if (!HeapTupleIsValid(tuple))
9081 8 : ereport(ERROR,
9082 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9083 : errmsg("column number %d of relation \"%s\" does not exist",
9084 : colNum, RelationGetRelationName(rel))));
9085 : }
9086 :
9087 95 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9088 :
9089 95 : attnum = attrtuple->attnum;
9090 95 : if (attnum <= 0)
9091 0 : ereport(ERROR,
9092 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9093 : errmsg("cannot alter system column \"%s\"",
9094 : colName)));
9095 :
9096 : /*
9097 : * Prevent this as long as the ANALYZE code skips virtual generated
9098 : * columns.
9099 : */
9100 95 : if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
9101 0 : ereport(ERROR,
9102 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9103 : errmsg("cannot alter statistics on virtual generated column \"%s\"",
9104 : colName)));
9105 :
9106 95 : if (rel->rd_rel->relkind == RELKIND_INDEX ||
9107 61 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
9108 : {
9109 34 : if (attnum > rel->rd_index->indnkeyatts)
9110 4 : ereport(ERROR,
9111 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9112 : errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
9113 : NameStr(attrtuple->attname), RelationGetRelationName(rel))));
9114 30 : else if (rel->rd_index->indkey.values[attnum - 1] != 0)
9115 12 : ereport(ERROR,
9116 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9117 : errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
9118 : NameStr(attrtuple->attname), RelationGetRelationName(rel)),
9119 : errhint("Alter statistics on table column instead.")));
9120 : }
9121 :
9122 : /* Build new tuple. */
9123 79 : memset(repl_null, false, sizeof(repl_null));
9124 79 : memset(repl_repl, false, sizeof(repl_repl));
9125 79 : if (!newtarget_default)
9126 48 : repl_val[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(newtarget);
9127 : else
9128 31 : repl_null[Anum_pg_attribute_attstattarget - 1] = true;
9129 79 : repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
9130 79 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9131 : repl_val, repl_null, repl_repl);
9132 79 : CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
9133 :
9134 79 : InvokeObjectPostAlterHook(RelationRelationId,
9135 : RelationGetRelid(rel),
9136 : attrtuple->attnum);
9137 79 : ObjectAddressSubSet(address, RelationRelationId,
9138 : RelationGetRelid(rel), attnum);
9139 :
9140 79 : heap_freetuple(newtuple);
9141 :
9142 79 : ReleaseSysCache(tuple);
9143 :
9144 79 : table_close(attrelation, RowExclusiveLock);
9145 :
9146 79 : return address;
9147 : }
9148 :
9149 : /*
9150 : * Return value is the address of the modified column
9151 : */
9152 : static ObjectAddress
9153 21 : ATExecSetOptions(Relation rel, const char *colName, Node *options,
9154 : bool isReset, LOCKMODE lockmode)
9155 : {
9156 : Relation attrelation;
9157 : HeapTuple tuple,
9158 : newtuple;
9159 : Form_pg_attribute attrtuple;
9160 : AttrNumber attnum;
9161 : Datum datum,
9162 : newOptions;
9163 : bool isnull;
9164 : ObjectAddress address;
9165 : Datum repl_val[Natts_pg_attribute];
9166 : bool repl_null[Natts_pg_attribute];
9167 : bool repl_repl[Natts_pg_attribute];
9168 :
9169 21 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9170 :
9171 21 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9172 :
9173 21 : if (!HeapTupleIsValid(tuple))
9174 0 : ereport(ERROR,
9175 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9176 : errmsg("column \"%s\" of relation \"%s\" does not exist",
9177 : colName, RelationGetRelationName(rel))));
9178 21 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9179 :
9180 21 : attnum = attrtuple->attnum;
9181 21 : if (attnum <= 0)
9182 0 : ereport(ERROR,
9183 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9184 : errmsg("cannot alter system column \"%s\"",
9185 : colName)));
9186 :
9187 : /* Generate new proposed attoptions (text array) */
9188 21 : datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
9189 : &isnull);
9190 21 : newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9191 : castNode(List, options), NULL, NULL,
9192 : false, isReset);
9193 : /* Validate new options */
9194 21 : (void) attribute_reloptions(newOptions, true);
9195 :
9196 : /* Build new tuple. */
9197 21 : memset(repl_null, false, sizeof(repl_null));
9198 21 : memset(repl_repl, false, sizeof(repl_repl));
9199 21 : if (newOptions != (Datum) 0)
9200 21 : repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
9201 : else
9202 0 : repl_null[Anum_pg_attribute_attoptions - 1] = true;
9203 21 : repl_repl[Anum_pg_attribute_attoptions - 1] = true;
9204 21 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9205 : repl_val, repl_null, repl_repl);
9206 :
9207 : /* Update system catalog. */
9208 21 : CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
9209 :
9210 21 : InvokeObjectPostAlterHook(RelationRelationId,
9211 : RelationGetRelid(rel),
9212 : attrtuple->attnum);
9213 21 : ObjectAddressSubSet(address, RelationRelationId,
9214 : RelationGetRelid(rel), attnum);
9215 :
9216 21 : heap_freetuple(newtuple);
9217 :
9218 21 : ReleaseSysCache(tuple);
9219 :
9220 21 : table_close(attrelation, RowExclusiveLock);
9221 :
9222 21 : return address;
9223 : }
9224 :
9225 : /*
9226 : * Helper function for ATExecSetStorage and ATExecSetCompression
9227 : *
9228 : * Set the attstorage and/or attcompression fields for index columns
9229 : * associated with the specified table column.
9230 : */
9231 : static void
9232 209 : SetIndexStorageProperties(Relation rel, Relation attrelation,
9233 : AttrNumber attnum,
9234 : bool setstorage, char newstorage,
9235 : bool setcompression, char newcompression,
9236 : LOCKMODE lockmode)
9237 : {
9238 : ListCell *lc;
9239 :
9240 267 : foreach(lc, RelationGetIndexList(rel))
9241 : {
9242 58 : Oid indexoid = lfirst_oid(lc);
9243 : Relation indrel;
9244 58 : AttrNumber indattnum = 0;
9245 : HeapTuple tuple;
9246 :
9247 58 : indrel = index_open(indexoid, lockmode);
9248 :
9249 97 : for (int i = 0; i < indrel->rd_index->indnatts; i++)
9250 : {
9251 62 : if (indrel->rd_index->indkey.values[i] == attnum)
9252 : {
9253 23 : indattnum = i + 1;
9254 23 : break;
9255 : }
9256 : }
9257 :
9258 58 : if (indattnum == 0)
9259 : {
9260 35 : index_close(indrel, lockmode);
9261 35 : continue;
9262 : }
9263 :
9264 23 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
9265 :
9266 23 : if (HeapTupleIsValid(tuple))
9267 : {
9268 23 : Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9269 :
9270 23 : if (setstorage)
9271 15 : attrtuple->attstorage = newstorage;
9272 :
9273 23 : if (setcompression)
9274 8 : attrtuple->attcompression = newcompression;
9275 :
9276 23 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9277 :
9278 23 : InvokeObjectPostAlterHook(RelationRelationId,
9279 : RelationGetRelid(rel),
9280 : attrtuple->attnum);
9281 :
9282 23 : heap_freetuple(tuple);
9283 : }
9284 :
9285 23 : index_close(indrel, lockmode);
9286 : }
9287 209 : }
9288 :
9289 : /*
9290 : * ALTER TABLE ALTER COLUMN SET STORAGE
9291 : *
9292 : * Return value is the address of the modified column
9293 : */
9294 : static ObjectAddress
9295 173 : ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
9296 : {
9297 : Relation attrelation;
9298 : HeapTuple tuple;
9299 : Form_pg_attribute attrtuple;
9300 : AttrNumber attnum;
9301 : ObjectAddress address;
9302 :
9303 173 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9304 :
9305 173 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9306 :
9307 173 : if (!HeapTupleIsValid(tuple))
9308 8 : ereport(ERROR,
9309 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9310 : errmsg("column \"%s\" of relation \"%s\" does not exist",
9311 : colName, RelationGetRelationName(rel))));
9312 165 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9313 :
9314 165 : attnum = attrtuple->attnum;
9315 165 : if (attnum <= 0)
9316 0 : ereport(ERROR,
9317 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9318 : errmsg("cannot alter system column \"%s\"",
9319 : colName)));
9320 :
9321 165 : attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
9322 :
9323 165 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9324 :
9325 165 : InvokeObjectPostAlterHook(RelationRelationId,
9326 : RelationGetRelid(rel),
9327 : attrtuple->attnum);
9328 :
9329 : /*
9330 : * Apply the change to indexes as well (only for simple index columns,
9331 : * matching behavior of index.c ConstructTupleDescriptor()).
9332 : */
9333 165 : SetIndexStorageProperties(rel, attrelation, attnum,
9334 165 : true, attrtuple->attstorage,
9335 : false, 0,
9336 : lockmode);
9337 :
9338 165 : heap_freetuple(tuple);
9339 :
9340 165 : table_close(attrelation, RowExclusiveLock);
9341 :
9342 165 : ObjectAddressSubSet(address, RelationRelationId,
9343 : RelationGetRelid(rel), attnum);
9344 165 : return address;
9345 : }
9346 :
9347 :
9348 : /*
9349 : * ALTER TABLE DROP COLUMN
9350 : *
9351 : * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
9352 : * because we have to decide at runtime whether to recurse or not depending
9353 : * on whether attinhcount goes to zero or not. (We can't check this in a
9354 : * static pre-pass because it won't handle multiple inheritance situations
9355 : * correctly.)
9356 : */
9357 : static void
9358 1147 : ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
9359 : AlterTableCmd *cmd, LOCKMODE lockmode,
9360 : AlterTableUtilityContext *context)
9361 : {
9362 1147 : if (rel->rd_rel->reloftype && !recursing)
9363 4 : ereport(ERROR,
9364 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9365 : errmsg("cannot drop column from typed table")));
9366 :
9367 1143 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
9368 54 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
9369 :
9370 1139 : if (recurse)
9371 981 : cmd->recurse = true;
9372 1139 : }
9373 :
9374 : /*
9375 : * Drops column 'colName' from relation 'rel' and returns the address of the
9376 : * dropped column. The column is also dropped (or marked as no longer
9377 : * inherited from relation) from the relation's inheritance children, if any.
9378 : *
9379 : * In the recursive invocations for inheritance child relations, instead of
9380 : * dropping the column directly (if to be dropped at all), its object address
9381 : * is added to 'addrs', which must be non-NULL in such invocations. All
9382 : * columns are dropped at the same time after all the children have been
9383 : * checked recursively.
9384 : */
9385 : static ObjectAddress
9386 1512 : ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
9387 : DropBehavior behavior,
9388 : bool recurse, bool recursing,
9389 : bool missing_ok, LOCKMODE lockmode,
9390 : ObjectAddresses *addrs)
9391 : {
9392 : HeapTuple tuple;
9393 : Form_pg_attribute targetatt;
9394 : AttrNumber attnum;
9395 : List *children;
9396 : ObjectAddress object;
9397 : bool is_expr;
9398 :
9399 : /* At top level, permission check was done in ATPrepCmd, else do it */
9400 1512 : if (recursing)
9401 373 : ATSimplePermissions(AT_DropColumn, rel,
9402 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9403 :
9404 : /* Initialize addrs on the first invocation */
9405 : Assert(!recursing || addrs != NULL);
9406 :
9407 : /* since this function recurses, it could be driven to stack overflow */
9408 1512 : check_stack_depth();
9409 :
9410 1512 : if (!recursing)
9411 1139 : addrs = new_object_addresses();
9412 :
9413 : /*
9414 : * get the number of the attribute
9415 : */
9416 1512 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9417 1512 : if (!HeapTupleIsValid(tuple))
9418 : {
9419 40 : if (!missing_ok)
9420 : {
9421 24 : ereport(ERROR,
9422 : (errcode(ERRCODE_UNDEFINED_COLUMN),
9423 : errmsg("column \"%s\" of relation \"%s\" does not exist",
9424 : colName, RelationGetRelationName(rel))));
9425 : }
9426 : else
9427 : {
9428 16 : ereport(NOTICE,
9429 : (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
9430 : colName, RelationGetRelationName(rel))));
9431 16 : return InvalidObjectAddress;
9432 : }
9433 : }
9434 1472 : targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
9435 :
9436 1472 : attnum = targetatt->attnum;
9437 :
9438 : /* Can't drop a system attribute */
9439 1472 : if (attnum <= 0)
9440 4 : ereport(ERROR,
9441 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9442 : errmsg("cannot drop system column \"%s\"",
9443 : colName)));
9444 :
9445 : /*
9446 : * Don't drop inherited columns, unless recursing (presumably from a drop
9447 : * of the parent column)
9448 : */
9449 1468 : if (targetatt->attinhcount > 0 && !recursing)
9450 32 : ereport(ERROR,
9451 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9452 : errmsg("cannot drop inherited column \"%s\"",
9453 : colName)));
9454 :
9455 : /*
9456 : * Don't drop columns used in the partition key, either. (If we let this
9457 : * go through, the key column's dependencies would cause a cascaded drop
9458 : * of the whole table, which is surely not what the user expected.)
9459 : */
9460 1436 : if (has_partition_attrs(rel,
9461 : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
9462 : &is_expr))
9463 20 : ereport(ERROR,
9464 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9465 : errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
9466 : colName, RelationGetRelationName(rel))));
9467 :
9468 1416 : ReleaseSysCache(tuple);
9469 :
9470 : /*
9471 : * Propagate to children as appropriate. Unlike most other ALTER
9472 : * routines, we have to do this one level of recursion at a time; we can't
9473 : * use find_all_inheritors to do it in one pass.
9474 : */
9475 : children =
9476 1416 : find_inheritance_children(RelationGetRelid(rel), lockmode);
9477 :
9478 1416 : if (children)
9479 : {
9480 : Relation attr_rel;
9481 : ListCell *child;
9482 :
9483 : /*
9484 : * In case of a partitioned table, the column must be dropped from the
9485 : * partitions as well.
9486 : */
9487 204 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
9488 4 : ereport(ERROR,
9489 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9490 : errmsg("cannot drop column from only the partitioned table when partitions exist"),
9491 : errhint("Do not specify the ONLY keyword.")));
9492 :
9493 200 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
9494 593 : foreach(child, children)
9495 : {
9496 397 : Oid childrelid = lfirst_oid(child);
9497 : Relation childrel;
9498 : Form_pg_attribute childatt;
9499 :
9500 : /* find_inheritance_children already got lock */
9501 397 : childrel = table_open(childrelid, NoLock);
9502 397 : CheckAlterTableIsSafe(childrel);
9503 :
9504 397 : tuple = SearchSysCacheCopyAttName(childrelid, colName);
9505 397 : if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
9506 0 : elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
9507 : colName, childrelid);
9508 397 : childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9509 :
9510 397 : if (childatt->attinhcount <= 0) /* shouldn't happen */
9511 0 : elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
9512 : childrelid, colName);
9513 :
9514 397 : if (recurse)
9515 : {
9516 : /*
9517 : * If the child column has other definition sources, just
9518 : * decrement its inheritance count; if not, recurse to delete
9519 : * it.
9520 : */
9521 381 : if (childatt->attinhcount == 1 && !childatt->attislocal)
9522 : {
9523 : /* Time to delete this child column, too */
9524 373 : ATExecDropColumn(wqueue, childrel, colName,
9525 : behavior, true, true,
9526 : false, lockmode, addrs);
9527 : }
9528 : else
9529 : {
9530 : /* Child column must survive my deletion */
9531 8 : childatt->attinhcount--;
9532 :
9533 8 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9534 :
9535 : /* Make update visible */
9536 8 : CommandCounterIncrement();
9537 : }
9538 : }
9539 : else
9540 : {
9541 : /*
9542 : * If we were told to drop ONLY in this table (no recursion),
9543 : * we need to mark the inheritors' attributes as locally
9544 : * defined rather than inherited.
9545 : */
9546 16 : childatt->attinhcount--;
9547 16 : childatt->attislocal = true;
9548 :
9549 16 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9550 :
9551 : /* Make update visible */
9552 16 : CommandCounterIncrement();
9553 : }
9554 :
9555 393 : heap_freetuple(tuple);
9556 :
9557 393 : table_close(childrel, NoLock);
9558 : }
9559 196 : table_close(attr_rel, RowExclusiveLock);
9560 : }
9561 :
9562 : /* Add object to delete */
9563 1408 : object.classId = RelationRelationId;
9564 1408 : object.objectId = RelationGetRelid(rel);
9565 1408 : object.objectSubId = attnum;
9566 1408 : add_exact_object_address(&object, addrs);
9567 :
9568 1408 : if (!recursing)
9569 : {
9570 : /* Recursion has ended, drop everything that was collected */
9571 1039 : performMultipleDeletions(addrs, behavior, 0);
9572 995 : free_object_addresses(addrs);
9573 : }
9574 :
9575 1364 : return object;
9576 : }
9577 :
9578 : /*
9579 : * Prepare to add a primary key on a table, by adding not-null constraints
9580 : * on all columns.
9581 : *
9582 : * The not-null constraints for a primary key must cover the whole inheritance
9583 : * hierarchy (failing to ensure that leads to funny corner cases). For the
9584 : * normal case where we're asked to recurse, this routine checks if the
9585 : * not-null constraints exist already, and if not queues a requirement for
9586 : * them to be created by phase 2.
9587 : *
9588 : * For the case where we're asked not to recurse, we verify that a not-null
9589 : * constraint exists on each column of each (direct) child table, throwing an
9590 : * error if not. Not throwing an error would also work, because a not-null
9591 : * constraint would be created anyway, but it'd cause a silent scan of the
9592 : * child table to verify absence of nulls. We prefer to let the user know so
9593 : * that they can add the constraint manually without having to hold
9594 : * AccessExclusiveLock while at it.
9595 : *
9596 : * However, it's also important that we do not acquire locks on children if
9597 : * the not-null constraints already exist on the parent, to avoid risking
9598 : * deadlocks during parallel pg_restore of PKs on partitioned tables.
9599 : */
9600 : static void
9601 10379 : ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
9602 : bool recurse, LOCKMODE lockmode,
9603 : AlterTableUtilityContext *context)
9604 : {
9605 : Constraint *pkconstr;
9606 10379 : List *children = NIL;
9607 10379 : bool got_children = false;
9608 :
9609 10379 : pkconstr = castNode(Constraint, cmd->def);
9610 10379 : if (pkconstr->contype != CONSTR_PRIMARY)
9611 6122 : return;
9612 :
9613 : /* Verify that columns are not-null, or request that they be made so */
9614 9123 : foreach_node(String, column, pkconstr->keys)
9615 : {
9616 : AlterTableCmd *newcmd;
9617 : Constraint *nnconstr;
9618 : HeapTuple tuple;
9619 :
9620 : /*
9621 : * First check if a suitable constraint exists. If it does, we don't
9622 : * need to request another one. We do need to bail out if it's not
9623 : * valid, though.
9624 : */
9625 649 : tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
9626 649 : if (tuple != NULL)
9627 : {
9628 322 : verifyNotNullPKCompatible(tuple, strVal(column));
9629 :
9630 : /* All good with this one; don't request another */
9631 314 : heap_freetuple(tuple);
9632 314 : continue;
9633 : }
9634 327 : else if (!recurse)
9635 : {
9636 : /*
9637 : * No constraint on this column. Asked not to recurse, we won't
9638 : * create one here, but verify that all children have one.
9639 : */
9640 24 : if (!got_children)
9641 : {
9642 24 : children = find_inheritance_children(RelationGetRelid(rel),
9643 : lockmode);
9644 : /* only search for children on the first time through */
9645 24 : got_children = true;
9646 : }
9647 :
9648 48 : foreach_oid(childrelid, children)
9649 : {
9650 : HeapTuple tup;
9651 :
9652 24 : tup = findNotNullConstraint(childrelid, strVal(column));
9653 24 : if (!tup)
9654 4 : ereport(ERROR,
9655 : errmsg("column \"%s\" of table \"%s\" is not marked NOT NULL",
9656 : strVal(column), get_rel_name(childrelid)));
9657 : /* verify it's good enough */
9658 20 : verifyNotNullPKCompatible(tup, strVal(column));
9659 : }
9660 : }
9661 :
9662 : /* This column is not already not-null, so add it to the queue */
9663 315 : nnconstr = makeNotNullConstraint(column);
9664 :
9665 315 : newcmd = makeNode(AlterTableCmd);
9666 315 : newcmd->subtype = AT_AddConstraint;
9667 : /* note we force recurse=true here; see above */
9668 315 : newcmd->recurse = true;
9669 315 : newcmd->def = (Node *) nnconstr;
9670 :
9671 315 : ATPrepCmd(wqueue, rel, newcmd, true, false, lockmode, context);
9672 : }
9673 : }
9674 :
9675 : /*
9676 : * Verify whether the given not-null constraint is compatible with a
9677 : * primary key. If not, an error is thrown.
9678 : */
9679 : static void
9680 342 : verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
9681 : {
9682 342 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
9683 :
9684 342 : if (conForm->contype != CONSTRAINT_NOTNULL)
9685 0 : elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
9686 :
9687 : /* a NO INHERIT constraint is no good */
9688 342 : if (conForm->connoinherit)
9689 8 : ereport(ERROR,
9690 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9691 : errmsg("cannot create primary key on column \"%s\"", colname),
9692 : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9693 : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9694 : NameStr(conForm->conname), colname,
9695 : get_rel_name(conForm->conrelid), "NO INHERIT"),
9696 : errhint("You might need to make the existing constraint inheritable using %s.",
9697 : "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
9698 :
9699 : /* an unvalidated constraint is no good */
9700 334 : if (!conForm->convalidated)
9701 8 : ereport(ERROR,
9702 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9703 : errmsg("cannot create primary key on column \"%s\"", colname),
9704 : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9705 : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9706 : NameStr(conForm->conname), colname,
9707 : get_rel_name(conForm->conrelid), "NOT VALID"),
9708 : errhint("You might need to validate it using %s.",
9709 : "ALTER TABLE ... VALIDATE CONSTRAINT"));
9710 326 : }
9711 :
9712 : /*
9713 : * ALTER TABLE ADD INDEX
9714 : *
9715 : * There is no such command in the grammar, but parse_utilcmd.c converts
9716 : * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
9717 : * us schedule creation of the index at the appropriate time during ALTER.
9718 : *
9719 : * Return value is the address of the new index.
9720 : */
9721 : static ObjectAddress
9722 1068 : ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
9723 : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9724 : {
9725 : bool check_rights;
9726 : bool skip_build;
9727 : bool quiet;
9728 : ObjectAddress address;
9729 :
9730 : Assert(IsA(stmt, IndexStmt));
9731 : Assert(!stmt->concurrent);
9732 :
9733 : /* The IndexStmt has already been through transformIndexStmt */
9734 : Assert(stmt->transformed);
9735 :
9736 : /* suppress schema rights check when rebuilding existing index */
9737 1068 : check_rights = !is_rebuild;
9738 : /* skip index build if phase 3 will do it or we're reusing an old one */
9739 1068 : skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
9740 : /* suppress notices when rebuilding existing index */
9741 1068 : quiet = is_rebuild;
9742 :
9743 1068 : address = DefineIndex(NULL,
9744 : RelationGetRelid(rel),
9745 : stmt,
9746 : InvalidOid, /* no predefined OID */
9747 : InvalidOid, /* no parent index */
9748 : InvalidOid, /* no parent constraint */
9749 : -1, /* total_parts unknown */
9750 : true, /* is_alter_table */
9751 : check_rights,
9752 : false, /* check_not_in_use - we did it already */
9753 : skip_build,
9754 : quiet);
9755 :
9756 : /*
9757 : * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
9758 : * new index instead of building from scratch. Restore associated fields.
9759 : * This may store InvalidSubTransactionId in both fields, in which case
9760 : * relcache.c will assume it can rebuild the relcache entry. Hence, do
9761 : * this after the CCI that made catalog rows visible to any rebuild. The
9762 : * DROP of the old edition of this index will have scheduled the storage
9763 : * for deletion at commit, so cancel that pending deletion.
9764 : */
9765 955 : if (RelFileNumberIsValid(stmt->oldNumber))
9766 : {
9767 49 : Relation irel = index_open(address.objectId, NoLock);
9768 :
9769 49 : irel->rd_createSubid = stmt->oldCreateSubid;
9770 49 : irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
9771 49 : RelationPreserveStorage(irel->rd_locator, true);
9772 49 : index_close(irel, NoLock);
9773 : }
9774 :
9775 955 : return address;
9776 : }
9777 :
9778 : /*
9779 : * ALTER TABLE ADD STATISTICS
9780 : *
9781 : * This is no such command in the grammar, but we use this internally to add
9782 : * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
9783 : * column type change.
9784 : */
9785 : static ObjectAddress
9786 53 : ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
9787 : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9788 : {
9789 : ObjectAddress address;
9790 :
9791 : Assert(IsA(stmt, CreateStatsStmt));
9792 :
9793 : /* The CreateStatsStmt has already been through transformStatsStmt */
9794 : Assert(stmt->transformed);
9795 :
9796 53 : address = CreateStatistics(stmt, !is_rebuild);
9797 :
9798 53 : return address;
9799 : }
9800 :
9801 : /*
9802 : * ALTER TABLE ADD CONSTRAINT USING INDEX
9803 : *
9804 : * Returns the address of the new constraint.
9805 : */
9806 : static ObjectAddress
9807 6653 : ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
9808 : IndexStmt *stmt, LOCKMODE lockmode)
9809 : {
9810 6653 : Oid index_oid = stmt->indexOid;
9811 : Relation indexRel;
9812 : char *indexName;
9813 : IndexInfo *indexInfo;
9814 : char *constraintName;
9815 : char constraintType;
9816 : ObjectAddress address;
9817 : uint16 flags;
9818 :
9819 : Assert(IsA(stmt, IndexStmt));
9820 : Assert(OidIsValid(index_oid));
9821 : Assert(stmt->isconstraint);
9822 :
9823 : /*
9824 : * Doing this on partitioned tables is not a simple feature to implement,
9825 : * so let's punt for now.
9826 : */
9827 6653 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
9828 4 : ereport(ERROR,
9829 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9830 : errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
9831 :
9832 6649 : indexRel = index_open(index_oid, AccessShareLock);
9833 :
9834 6649 : indexName = pstrdup(RelationGetRelationName(indexRel));
9835 :
9836 6649 : indexInfo = BuildIndexInfo(indexRel);
9837 :
9838 : /* this should have been checked at parse time */
9839 6649 : if (!indexInfo->ii_Unique)
9840 0 : elog(ERROR, "index \"%s\" is not unique", indexName);
9841 :
9842 : /*
9843 : * Determine name to assign to constraint. We require a constraint to
9844 : * have the same name as the underlying index; therefore, use the index's
9845 : * existing name as the default constraint name, and if the user
9846 : * explicitly gives some other name for the constraint, rename the index
9847 : * to match.
9848 : */
9849 6649 : constraintName = stmt->idxname;
9850 6649 : if (constraintName == NULL)
9851 6632 : constraintName = indexName;
9852 17 : else if (strcmp(constraintName, indexName) != 0)
9853 : {
9854 13 : ereport(NOTICE,
9855 : (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
9856 : indexName, constraintName)));
9857 13 : RenameRelationInternal(index_oid, constraintName, false, true);
9858 : }
9859 :
9860 : /* Extra checks needed if making primary key */
9861 6649 : if (stmt->primary)
9862 3721 : index_check_primary_key(rel, indexInfo, true, stmt);
9863 :
9864 : /* Note we currently don't support EXCLUSION constraints here */
9865 6645 : if (stmt->primary)
9866 3717 : constraintType = CONSTRAINT_PRIMARY;
9867 : else
9868 2928 : constraintType = CONSTRAINT_UNIQUE;
9869 :
9870 : /* Create the catalog entries for the constraint */
9871 6645 : flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
9872 : INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
9873 13290 : (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
9874 6645 : (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
9875 6645 : (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
9876 :
9877 6645 : address = index_constraint_create(rel,
9878 : index_oid,
9879 : InvalidOid,
9880 : indexInfo,
9881 : constraintName,
9882 : constraintType,
9883 : flags,
9884 : allowSystemTableMods,
9885 : false); /* is_internal */
9886 :
9887 6645 : index_close(indexRel, NoLock);
9888 :
9889 6645 : return address;
9890 : }
9891 :
9892 : /*
9893 : * ALTER TABLE ADD CONSTRAINT
9894 : *
9895 : * Return value is the address of the new constraint; if no constraint was
9896 : * added, InvalidObjectAddress is returned.
9897 : */
9898 : static ObjectAddress
9899 8303 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9900 : Constraint *newConstraint, bool recurse, bool is_readd,
9901 : LOCKMODE lockmode)
9902 : {
9903 8303 : ObjectAddress address = InvalidObjectAddress;
9904 :
9905 : Assert(IsA(newConstraint, Constraint));
9906 :
9907 : /*
9908 : * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
9909 : * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
9910 : * parse_utilcmd.c).
9911 : */
9912 8303 : switch (newConstraint->contype)
9913 : {
9914 6469 : case CONSTR_CHECK:
9915 : case CONSTR_NOTNULL:
9916 : address =
9917 6469 : ATAddCheckNNConstraint(wqueue, tab, rel,
9918 : newConstraint, recurse, false, is_readd,
9919 : lockmode);
9920 6369 : break;
9921 :
9922 1834 : case CONSTR_FOREIGN:
9923 :
9924 : /*
9925 : * Assign or validate constraint name
9926 : */
9927 1834 : if (newConstraint->conname)
9928 : {
9929 757 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
9930 : RelationGetRelid(rel),
9931 757 : newConstraint->conname))
9932 0 : ereport(ERROR,
9933 : (errcode(ERRCODE_DUPLICATE_OBJECT),
9934 : errmsg("constraint \"%s\" for relation \"%s\" already exists",
9935 : newConstraint->conname,
9936 : RelationGetRelationName(rel))));
9937 : }
9938 : else
9939 1077 : newConstraint->conname =
9940 1077 : ChooseConstraintName(RelationGetRelationName(rel),
9941 1077 : ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
9942 : "fkey",
9943 1077 : RelationGetNamespace(rel),
9944 : NIL);
9945 :
9946 1834 : address = ATAddForeignKeyConstraint(wqueue, tab, rel,
9947 : newConstraint,
9948 : recurse, false,
9949 : lockmode);
9950 1469 : break;
9951 :
9952 0 : default:
9953 0 : elog(ERROR, "unrecognized constraint type: %d",
9954 : (int) newConstraint->contype);
9955 : }
9956 :
9957 7838 : return address;
9958 : }
9959 :
9960 : /*
9961 : * Generate the column-name portion of the constraint name for a new foreign
9962 : * key given the list of column names that reference the referenced
9963 : * table. This will be passed to ChooseConstraintName along with the parent
9964 : * table name and the "fkey" suffix.
9965 : *
9966 : * We know that less than NAMEDATALEN characters will actually be used, so we
9967 : * can truncate the result once we've generated that many.
9968 : *
9969 : * XXX see also ChooseExtendedStatisticNameAddition and
9970 : * ChooseIndexNameAddition.
9971 : */
9972 : static char *
9973 1077 : ChooseForeignKeyConstraintNameAddition(List *colnames)
9974 : {
9975 : char buf[NAMEDATALEN * 2];
9976 1077 : int buflen = 0;
9977 : ListCell *lc;
9978 :
9979 1077 : buf[0] = '\0';
9980 2448 : foreach(lc, colnames)
9981 : {
9982 1371 : const char *name = strVal(lfirst(lc));
9983 :
9984 1371 : if (buflen > 0)
9985 294 : buf[buflen++] = '_'; /* insert _ between names */
9986 :
9987 : /*
9988 : * At this point we have buflen <= NAMEDATALEN. name should be less
9989 : * than NAMEDATALEN already, but use strlcpy for paranoia.
9990 : */
9991 1371 : strlcpy(buf + buflen, name, NAMEDATALEN);
9992 1371 : buflen += strlen(buf + buflen);
9993 1371 : if (buflen >= NAMEDATALEN)
9994 0 : break;
9995 : }
9996 1077 : return pstrdup(buf);
9997 : }
9998 :
9999 : /*
10000 : * Add a check or not-null constraint to a single table and its children.
10001 : * Returns the address of the constraint added to the parent relation,
10002 : * if one gets added, or InvalidObjectAddress otherwise.
10003 : *
10004 : * Subroutine for ATExecAddConstraint.
10005 : *
10006 : * We must recurse to child tables during execution, rather than using
10007 : * ALTER TABLE's normal prep-time recursion. The reason is that all the
10008 : * constraints *must* be given the same name, else they won't be seen as
10009 : * related later. If the user didn't explicitly specify a name, then
10010 : * AddRelationNewConstraints would normally assign different names to the
10011 : * child constraints. To fix that, we must capture the name assigned at
10012 : * the parent table and pass that down.
10013 : */
10014 : static ObjectAddress
10015 7152 : ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10016 : Constraint *constr, bool recurse, bool recursing,
10017 : bool is_readd, LOCKMODE lockmode)
10018 : {
10019 : List *newcons;
10020 : ListCell *lcon;
10021 : List *children;
10022 : ListCell *child;
10023 7152 : ObjectAddress address = InvalidObjectAddress;
10024 :
10025 : /* Guard against stack overflow due to overly deep inheritance tree. */
10026 7152 : check_stack_depth();
10027 :
10028 : /* At top level, permission check was done in ATPrepCmd, else do it */
10029 7152 : if (recursing)
10030 683 : ATSimplePermissions(AT_AddConstraint, rel,
10031 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
10032 :
10033 : /*
10034 : * Call AddRelationNewConstraints to do the work, making sure it works on
10035 : * a copy of the Constraint so transformExpr can't modify the original. It
10036 : * returns a list of cooked constraints.
10037 : *
10038 : * If the constraint ends up getting merged with a pre-existing one, it's
10039 : * omitted from the returned list, which is what we want: we do not need
10040 : * to do any validation work. That can only happen at child tables,
10041 : * though, since we disallow merging at the top level.
10042 : */
10043 7152 : newcons = AddRelationNewConstraints(rel, NIL,
10044 : list_make1(copyObject(constr)),
10045 7152 : recursing || is_readd, /* allow_merge */
10046 : !recursing, /* is_local */
10047 : is_readd, /* is_internal */
10048 14304 : NULL); /* queryString not available
10049 : * here */
10050 :
10051 : /* we don't expect more than one constraint here */
10052 : Assert(list_length(newcons) <= 1);
10053 :
10054 : /* Add each to-be-validated constraint to Phase 3's queue */
10055 13982 : foreach(lcon, newcons)
10056 : {
10057 6926 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
10058 :
10059 6926 : if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
10060 : {
10061 : NewConstraint *newcon;
10062 :
10063 771 : newcon = palloc0_object(NewConstraint);
10064 771 : newcon->name = ccon->name;
10065 771 : newcon->contype = ccon->contype;
10066 771 : newcon->qual = ccon->expr;
10067 :
10068 771 : tab->constraints = lappend(tab->constraints, newcon);
10069 : }
10070 :
10071 : /* Save the actually assigned name if it was defaulted */
10072 6926 : if (constr->conname == NULL)
10073 5504 : constr->conname = ccon->name;
10074 :
10075 : /*
10076 : * If adding a valid not-null constraint, set the pg_attribute flag
10077 : * and tell phase 3 to verify existing rows, if needed. For an
10078 : * invalid constraint, just set attnotnull, without queueing
10079 : * verification.
10080 : */
10081 6926 : if (constr->contype == CONSTR_NOTNULL)
10082 5850 : set_attnotnull(wqueue, rel, ccon->attnum,
10083 5850 : !constr->skip_validation,
10084 5850 : !constr->skip_validation);
10085 :
10086 6926 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
10087 : }
10088 :
10089 : /* At this point we must have a locked-down name to use */
10090 : Assert(newcons == NIL || constr->conname != NULL);
10091 :
10092 : /* Advance command counter in case same table is visited multiple times */
10093 7056 : CommandCounterIncrement();
10094 :
10095 : /*
10096 : * If the constraint got merged with an existing constraint, we're done.
10097 : * We mustn't recurse to child tables in this case, because they've
10098 : * already got the constraint, and visiting them again would lead to an
10099 : * incorrect value for coninhcount.
10100 : */
10101 7056 : if (newcons == NIL)
10102 130 : return address;
10103 :
10104 : /*
10105 : * If adding a NO INHERIT constraint, no need to find our children.
10106 : */
10107 6926 : if (constr->is_no_inherit)
10108 56 : return address;
10109 :
10110 : /*
10111 : * Propagate to children as appropriate. Unlike most other ALTER
10112 : * routines, we have to do this one level of recursion at a time; we can't
10113 : * use find_all_inheritors to do it in one pass.
10114 : */
10115 : children =
10116 6870 : find_inheritance_children(RelationGetRelid(rel), lockmode);
10117 :
10118 : /*
10119 : * Check if ONLY was specified with ALTER TABLE. If so, allow the
10120 : * constraint creation only if there are no children currently. Error out
10121 : * otherwise.
10122 : */
10123 6870 : if (!recurse && children != NIL)
10124 4 : ereport(ERROR,
10125 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10126 : errmsg("constraint must be added to child tables too")));
10127 :
10128 : /*
10129 : * Recurse to create the constraint on each child.
10130 : */
10131 7529 : foreach(child, children)
10132 : {
10133 683 : Oid childrelid = lfirst_oid(child);
10134 : Relation childrel;
10135 : AlteredTableInfo *childtab;
10136 :
10137 : /* find_inheritance_children already got lock */
10138 683 : childrel = table_open(childrelid, NoLock);
10139 683 : CheckAlterTableIsSafe(childrel);
10140 :
10141 : /* Find or create work queue entry for this table */
10142 683 : childtab = ATGetQueueEntry(wqueue, childrel);
10143 :
10144 : /* Recurse to this child */
10145 683 : ATAddCheckNNConstraint(wqueue, childtab, childrel,
10146 : constr, recurse, true, is_readd, lockmode);
10147 :
10148 663 : table_close(childrel, NoLock);
10149 : }
10150 :
10151 6846 : return address;
10152 : }
10153 :
10154 : /*
10155 : * Add a foreign-key constraint to a single table; return the new constraint's
10156 : * address.
10157 : *
10158 : * Subroutine for ATExecAddConstraint. Must already hold exclusive
10159 : * lock on the rel, and have done appropriate validity checks for it.
10160 : * We do permissions checks here, however.
10161 : *
10162 : * When the referenced or referencing tables (or both) are partitioned,
10163 : * multiple pg_constraint rows are required -- one for each partitioned table
10164 : * and each partition on each side (fortunately, not one for every combination
10165 : * thereof). We also need action triggers on each leaf partition on the
10166 : * referenced side, and check triggers on each leaf partition on the
10167 : * referencing side.
10168 : */
10169 : static ObjectAddress
10170 1834 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10171 : Constraint *fkconstraint,
10172 : bool recurse, bool recursing, LOCKMODE lockmode)
10173 : {
10174 : Relation pkrel;
10175 1834 : int16 pkattnum[INDEX_MAX_KEYS] = {0};
10176 1834 : int16 fkattnum[INDEX_MAX_KEYS] = {0};
10177 1834 : Oid pktypoid[INDEX_MAX_KEYS] = {0};
10178 1834 : Oid fktypoid[INDEX_MAX_KEYS] = {0};
10179 1834 : Oid pkcolloid[INDEX_MAX_KEYS] = {0};
10180 1834 : Oid fkcolloid[INDEX_MAX_KEYS] = {0};
10181 1834 : Oid opclasses[INDEX_MAX_KEYS] = {0};
10182 1834 : Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
10183 1834 : Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
10184 1834 : Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
10185 1834 : int16 fkdelsetcols[INDEX_MAX_KEYS] = {0};
10186 : bool with_period;
10187 : bool pk_has_without_overlaps;
10188 : int i;
10189 : int numfks,
10190 : numpks,
10191 : numfkdelsetcols;
10192 : Oid indexOid;
10193 : bool old_check_ok;
10194 : ObjectAddress address;
10195 1834 : ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
10196 :
10197 : /*
10198 : * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
10199 : * delete rows out from under us.
10200 : */
10201 1834 : if (OidIsValid(fkconstraint->old_pktable_oid))
10202 48 : pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
10203 : else
10204 1786 : pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
10205 :
10206 : /*
10207 : * Validity checks (permission checks wait till we have the column
10208 : * numbers)
10209 : */
10210 1830 : if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10211 4 : ereport(ERROR,
10212 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
10213 : errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
10214 : RelationGetRelationName(rel),
10215 : RelationGetRelationName(pkrel)));
10216 :
10217 1826 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10218 236 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10219 0 : ereport(ERROR,
10220 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10221 : errmsg("referenced relation \"%s\" is not a table",
10222 : RelationGetRelationName(pkrel))));
10223 :
10224 1826 : if (!allowSystemTableMods && IsSystemRelation(pkrel))
10225 1 : ereport(ERROR,
10226 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10227 : errmsg("permission denied: \"%s\" is a system catalog",
10228 : RelationGetRelationName(pkrel))));
10229 :
10230 : /*
10231 : * References from permanent or unlogged tables to temp tables, and from
10232 : * permanent tables to unlogged tables, are disallowed because the
10233 : * referenced data can vanish out from under us. References from temp
10234 : * tables to any other table type are also disallowed, because other
10235 : * backends might need to run the RI triggers on the perm table, but they
10236 : * can't reliably see tuples in the local buffers of other backends.
10237 : */
10238 1825 : switch (rel->rd_rel->relpersistence)
10239 : {
10240 1632 : case RELPERSISTENCE_PERMANENT:
10241 1632 : if (!RelationIsPermanent(pkrel))
10242 0 : ereport(ERROR,
10243 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10244 : errmsg("constraints on permanent tables may reference only permanent tables")));
10245 1632 : break;
10246 8 : case RELPERSISTENCE_UNLOGGED:
10247 8 : if (!RelationIsPermanent(pkrel)
10248 8 : && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
10249 0 : ereport(ERROR,
10250 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10251 : errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
10252 8 : break;
10253 185 : case RELPERSISTENCE_TEMP:
10254 185 : if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10255 0 : ereport(ERROR,
10256 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10257 : errmsg("constraints on temporary tables may reference only temporary tables")));
10258 185 : if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
10259 0 : ereport(ERROR,
10260 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10261 : errmsg("constraints on temporary tables must involve temporary tables of this session")));
10262 185 : break;
10263 : }
10264 :
10265 : /*
10266 : * Look up the referencing attributes to make sure they exist, and record
10267 : * their attnums and type and collation OIDs.
10268 : */
10269 1825 : numfks = transformColumnNameList(RelationGetRelid(rel),
10270 : fkconstraint->fk_attrs,
10271 : fkattnum, fktypoid, fkcolloid);
10272 1805 : with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
10273 1805 : if (with_period && !fkconstraint->fk_with_period)
10274 16 : ereport(ERROR,
10275 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10276 : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10277 :
10278 1789 : numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
10279 : fkconstraint->fk_del_set_cols,
10280 : fkdelsetcols, NULL, NULL);
10281 1785 : numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
10282 : numfkdelsetcols,
10283 : fkdelsetcols,
10284 : fkconstraint->fk_del_set_cols);
10285 :
10286 : /*
10287 : * If the attribute list for the referenced table was omitted, lookup the
10288 : * definition of the primary key and use it. Otherwise, validate the
10289 : * supplied attribute list. In either case, discover the index OID and
10290 : * index opclasses, and the attnums and type and collation OIDs of the
10291 : * attributes.
10292 : */
10293 1781 : if (fkconstraint->pk_attrs == NIL)
10294 : {
10295 896 : numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
10296 : &fkconstraint->pk_attrs,
10297 : pkattnum, pktypoid, pkcolloid,
10298 : opclasses, &pk_has_without_overlaps);
10299 :
10300 : /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
10301 896 : if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
10302 16 : ereport(ERROR,
10303 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10304 : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10305 : }
10306 : else
10307 : {
10308 885 : numpks = transformColumnNameList(RelationGetRelid(pkrel),
10309 : fkconstraint->pk_attrs,
10310 : pkattnum, pktypoid, pkcolloid);
10311 :
10312 : /* Since we got pk_attrs, one should be a period. */
10313 865 : if (with_period && !fkconstraint->pk_with_period)
10314 16 : ereport(ERROR,
10315 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10316 : errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
10317 :
10318 : /* Look for an index matching the column list */
10319 849 : indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
10320 : with_period, opclasses, &pk_has_without_overlaps);
10321 : }
10322 :
10323 : /*
10324 : * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
10325 : * must use PERIOD.
10326 : */
10327 1705 : if (pk_has_without_overlaps && !with_period)
10328 8 : ereport(ERROR,
10329 : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10330 : errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
10331 :
10332 : /*
10333 : * Now we can check permissions.
10334 : */
10335 1697 : checkFkeyPermissions(pkrel, pkattnum, numpks);
10336 :
10337 : /*
10338 : * Check some things for generated columns.
10339 : */
10340 3975 : for (i = 0; i < numfks; i++)
10341 : {
10342 2298 : char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
10343 :
10344 2298 : if (attgenerated)
10345 : {
10346 : /*
10347 : * Check restrictions on UPDATE/DELETE actions, per SQL standard
10348 : */
10349 32 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10350 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
10351 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
10352 8 : ereport(ERROR,
10353 : (errcode(ERRCODE_SYNTAX_ERROR),
10354 : errmsg("invalid %s action for foreign key constraint containing generated column",
10355 : "ON UPDATE")));
10356 24 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10357 16 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10358 8 : ereport(ERROR,
10359 : (errcode(ERRCODE_SYNTAX_ERROR),
10360 : errmsg("invalid %s action for foreign key constraint containing generated column",
10361 : "ON DELETE")));
10362 : }
10363 :
10364 : /*
10365 : * FKs on virtual columns are not supported. This would require
10366 : * various additional support in ri_triggers.c, including special
10367 : * handling in ri_NullCheck(), ri_KeysEqual(),
10368 : * RI_FKey_fk_upd_check_required() (since all virtual columns appear
10369 : * as NULL there). Also not really practical as long as you can't
10370 : * index virtual columns.
10371 : */
10372 2282 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
10373 4 : ereport(ERROR,
10374 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10375 : errmsg("foreign key constraints on virtual generated columns are not supported")));
10376 : }
10377 :
10378 : /*
10379 : * Some actions are currently unsupported for foreign keys using PERIOD.
10380 : */
10381 1677 : if (fkconstraint->fk_with_period)
10382 : {
10383 178 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
10384 170 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
10385 158 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10386 146 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
10387 44 : ereport(ERROR,
10388 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10389 : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10390 : "ON UPDATE"));
10391 :
10392 134 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
10393 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
10394 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10395 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10396 4 : ereport(ERROR,
10397 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10398 : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10399 : "ON DELETE"));
10400 : }
10401 :
10402 : /*
10403 : * Look up the equality operators to use in the constraint.
10404 : *
10405 : * Note that we have to be careful about the difference between the actual
10406 : * PK column type and the opclass' declared input type, which might be
10407 : * only binary-compatible with it. The declared opcintype is the right
10408 : * thing to probe pg_amop with.
10409 : */
10410 1629 : if (numfks != numpks)
10411 0 : ereport(ERROR,
10412 : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
10413 : errmsg("number of referencing and referenced columns for foreign key disagree")));
10414 :
10415 : /*
10416 : * On the strength of a previous constraint, we might avoid scanning
10417 : * tables to validate this one. See below.
10418 : */
10419 1629 : old_check_ok = (fkconstraint->old_conpfeqop != NIL);
10420 : Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
10421 :
10422 3555 : for (i = 0; i < numpks; i++)
10423 : {
10424 2086 : Oid pktype = pktypoid[i];
10425 2086 : Oid fktype = fktypoid[i];
10426 : Oid fktyped;
10427 2086 : Oid pkcoll = pkcolloid[i];
10428 2086 : Oid fkcoll = fkcolloid[i];
10429 : HeapTuple cla_ht;
10430 : Form_pg_opclass cla_tup;
10431 : Oid amid;
10432 : Oid opfamily;
10433 : Oid opcintype;
10434 : bool for_overlaps;
10435 : CompareType cmptype;
10436 : Oid pfeqop;
10437 : Oid ppeqop;
10438 : Oid ffeqop;
10439 : int16 eqstrategy;
10440 : Oid pfeqop_right;
10441 :
10442 : /* We need several fields out of the pg_opclass entry */
10443 2086 : cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
10444 2086 : if (!HeapTupleIsValid(cla_ht))
10445 0 : elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
10446 2086 : cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
10447 2086 : amid = cla_tup->opcmethod;
10448 2086 : opfamily = cla_tup->opcfamily;
10449 2086 : opcintype = cla_tup->opcintype;
10450 2086 : ReleaseSysCache(cla_ht);
10451 :
10452 : /*
10453 : * Get strategy number from index AM.
10454 : *
10455 : * For a normal foreign-key constraint, this should not fail, since we
10456 : * already checked that the index is unique and should therefore have
10457 : * appropriate equal operators. For a period foreign key, this could
10458 : * fail if we selected a non-matching exclusion constraint earlier.
10459 : * (XXX Maybe we should do these lookups earlier so we don't end up
10460 : * doing that.)
10461 : */
10462 2086 : for_overlaps = with_period && i == numpks - 1;
10463 2086 : cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
10464 2086 : eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
10465 2086 : if (eqstrategy == InvalidStrategy)
10466 0 : ereport(ERROR,
10467 : errcode(ERRCODE_UNDEFINED_OBJECT),
10468 : for_overlaps
10469 : ? errmsg("could not identify an overlaps operator for foreign key")
10470 : : errmsg("could not identify an equality operator for foreign key"),
10471 : errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
10472 : cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
10473 :
10474 : /*
10475 : * There had better be a primary equality operator for the index.
10476 : * We'll use it for PK = PK comparisons.
10477 : */
10478 2086 : ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
10479 : eqstrategy);
10480 :
10481 2086 : if (!OidIsValid(ppeqop))
10482 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
10483 : eqstrategy, opcintype, opcintype, opfamily);
10484 :
10485 : /*
10486 : * Are there equality operators that take exactly the FK type? Assume
10487 : * we should look through any domain here.
10488 : */
10489 2086 : fktyped = getBaseType(fktype);
10490 :
10491 2086 : pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
10492 : eqstrategy);
10493 2086 : if (OidIsValid(pfeqop))
10494 : {
10495 1637 : pfeqop_right = fktyped;
10496 1637 : ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
10497 : eqstrategy);
10498 : }
10499 : else
10500 : {
10501 : /* keep compiler quiet */
10502 449 : pfeqop_right = InvalidOid;
10503 449 : ffeqop = InvalidOid;
10504 : }
10505 :
10506 2086 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10507 : {
10508 : /*
10509 : * Otherwise, look for an implicit cast from the FK type to the
10510 : * opcintype, and if found, use the primary equality operator.
10511 : * This is a bit tricky because opcintype might be a polymorphic
10512 : * type such as ANYARRAY or ANYENUM; so what we have to test is
10513 : * whether the two actual column types can be concurrently cast to
10514 : * that type. (Otherwise, we'd fail to reject combinations such
10515 : * as int[] and point[].)
10516 : */
10517 : Oid input_typeids[2];
10518 : Oid target_typeids[2];
10519 :
10520 449 : input_typeids[0] = pktype;
10521 449 : input_typeids[1] = fktype;
10522 449 : target_typeids[0] = opcintype;
10523 449 : target_typeids[1] = opcintype;
10524 449 : if (can_coerce_type(2, input_typeids, target_typeids,
10525 : COERCION_IMPLICIT))
10526 : {
10527 297 : pfeqop = ffeqop = ppeqop;
10528 297 : pfeqop_right = opcintype;
10529 : }
10530 : }
10531 :
10532 2086 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10533 152 : ereport(ERROR,
10534 : (errcode(ERRCODE_DATATYPE_MISMATCH),
10535 : errmsg("foreign key constraint \"%s\" cannot be implemented",
10536 : fkconstraint->conname),
10537 : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10538 : "are of incompatible types: %s and %s.",
10539 : strVal(list_nth(fkconstraint->fk_attrs, i)),
10540 : strVal(list_nth(fkconstraint->pk_attrs, i)),
10541 : format_type_be(fktype),
10542 : format_type_be(pktype))));
10543 :
10544 : /*
10545 : * This shouldn't be possible, but better check to make sure we have a
10546 : * consistent state for the check below.
10547 : */
10548 1934 : if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
10549 0 : elog(ERROR, "key columns are not both collatable");
10550 :
10551 1934 : if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
10552 : {
10553 : bool pkcolldet;
10554 : bool fkcolldet;
10555 :
10556 73 : pkcolldet = get_collation_isdeterministic(pkcoll);
10557 73 : fkcolldet = get_collation_isdeterministic(fkcoll);
10558 :
10559 : /*
10560 : * SQL requires that both collations are the same. This is
10561 : * because we need a consistent notion of equality on both
10562 : * columns. We relax this by allowing different collations if
10563 : * they are both deterministic. (This is also for backward
10564 : * compatibility, because PostgreSQL has always allowed this.)
10565 : */
10566 73 : if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
10567 8 : ereport(ERROR,
10568 : (errcode(ERRCODE_COLLATION_MISMATCH),
10569 : errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
10570 : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10571 : "have incompatible collations: \"%s\" and \"%s\". "
10572 : "If either collation is nondeterministic, then both collations have to be the same.",
10573 : strVal(list_nth(fkconstraint->fk_attrs, i)),
10574 : strVal(list_nth(fkconstraint->pk_attrs, i)),
10575 : get_collation_name(fkcoll),
10576 : get_collation_name(pkcoll))));
10577 : }
10578 :
10579 1926 : if (old_check_ok)
10580 : {
10581 : /*
10582 : * When a pfeqop changes, revalidate the constraint. We could
10583 : * permit intra-opfamily changes, but that adds subtle complexity
10584 : * without any concrete benefit for core types. We need not
10585 : * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
10586 : */
10587 4 : old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
10588 4 : old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
10589 : old_pfeqop_item);
10590 : }
10591 1926 : if (old_check_ok)
10592 : {
10593 : Oid old_fktype;
10594 : Oid new_fktype;
10595 : CoercionPathType old_pathtype;
10596 : CoercionPathType new_pathtype;
10597 : Oid old_castfunc;
10598 : Oid new_castfunc;
10599 : Oid old_fkcoll;
10600 : Oid new_fkcoll;
10601 4 : Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
10602 4 : fkattnum[i] - 1);
10603 :
10604 : /*
10605 : * Identify coercion pathways from each of the old and new FK-side
10606 : * column types to the right (foreign) operand type of the pfeqop.
10607 : * We may assume that pg_constraint.conkey is not changing.
10608 : */
10609 4 : old_fktype = attr->atttypid;
10610 4 : new_fktype = fktype;
10611 4 : old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
10612 : &old_castfunc);
10613 4 : new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
10614 : &new_castfunc);
10615 :
10616 4 : old_fkcoll = attr->attcollation;
10617 4 : new_fkcoll = fkcoll;
10618 :
10619 : /*
10620 : * Upon a change to the cast from the FK column to its pfeqop
10621 : * operand, revalidate the constraint. For this evaluation, a
10622 : * binary coercion cast is equivalent to no cast at all. While
10623 : * type implementors should design implicit casts with an eye
10624 : * toward consistency of operations like equality, we cannot
10625 : * assume here that they have done so.
10626 : *
10627 : * A function with a polymorphic argument could change behavior
10628 : * arbitrarily in response to get_fn_expr_argtype(). Therefore,
10629 : * when the cast destination is polymorphic, we only avoid
10630 : * revalidation if the input type has not changed at all. Given
10631 : * just the core data types and operator classes, this requirement
10632 : * prevents no would-be optimizations.
10633 : *
10634 : * If the cast converts from a base type to a domain thereon, then
10635 : * that domain type must be the opcintype of the unique index.
10636 : * Necessarily, the primary key column must then be of the domain
10637 : * type. Since the constraint was previously valid, all values on
10638 : * the foreign side necessarily exist on the primary side and in
10639 : * turn conform to the domain. Consequently, we need not treat
10640 : * domains specially here.
10641 : *
10642 : * If the collation changes, revalidation is required, unless both
10643 : * collations are deterministic, because those share the same
10644 : * notion of equality (because texteq reduces to bitwise
10645 : * equality).
10646 : *
10647 : * We need not directly consider the PK type. It's necessarily
10648 : * binary coercible to the opcintype of the unique index column,
10649 : * and ri_triggers.c will only deal with PK datums in terms of
10650 : * that opcintype. Changing the opcintype also changes pfeqop.
10651 : */
10652 4 : old_check_ok = (new_pathtype == old_pathtype &&
10653 4 : new_castfunc == old_castfunc &&
10654 4 : (!IsPolymorphicType(pfeqop_right) ||
10655 8 : new_fktype == old_fktype) &&
10656 0 : (new_fkcoll == old_fkcoll ||
10657 0 : (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
10658 : }
10659 :
10660 1926 : pfeqoperators[i] = pfeqop;
10661 1926 : ppeqoperators[i] = ppeqop;
10662 1926 : ffeqoperators[i] = ffeqop;
10663 : }
10664 :
10665 : /*
10666 : * For FKs with PERIOD we need additional operators to check whether the
10667 : * referencing row's range is contained by the aggregated ranges of the
10668 : * referenced row(s). For rangetypes and multirangetypes this is
10669 : * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
10670 : * support for now. FKs will look these up at "runtime", but we should
10671 : * make sure the lookup works here, even if we don't use the values.
10672 : */
10673 1469 : if (with_period)
10674 : {
10675 : Oid periodoperoid;
10676 : Oid aggedperiodoperoid;
10677 : Oid intersectoperoid;
10678 :
10679 118 : FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
10680 : &intersectoperoid);
10681 : }
10682 :
10683 : /* First, create the constraint catalog entry itself. */
10684 1469 : address = addFkConstraint(addFkBothSides,
10685 : fkconstraint->conname, fkconstraint, rel, pkrel,
10686 : indexOid,
10687 : InvalidOid, /* no parent constraint */
10688 : numfks,
10689 : pkattnum,
10690 : fkattnum,
10691 : pfeqoperators,
10692 : ppeqoperators,
10693 : ffeqoperators,
10694 : numfkdelsetcols,
10695 : fkdelsetcols,
10696 : false,
10697 : with_period);
10698 :
10699 : /* Next process the action triggers at the referenced side and recurse */
10700 1469 : addFkRecurseReferenced(fkconstraint, rel, pkrel,
10701 : indexOid,
10702 : address.objectId,
10703 : numfks,
10704 : pkattnum,
10705 : fkattnum,
10706 : pfeqoperators,
10707 : ppeqoperators,
10708 : ffeqoperators,
10709 : numfkdelsetcols,
10710 : fkdelsetcols,
10711 : old_check_ok,
10712 : InvalidOid, InvalidOid,
10713 : with_period);
10714 :
10715 : /* Lastly create the check triggers at the referencing side and recurse */
10716 1469 : addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
10717 : indexOid,
10718 : address.objectId,
10719 : numfks,
10720 : pkattnum,
10721 : fkattnum,
10722 : pfeqoperators,
10723 : ppeqoperators,
10724 : ffeqoperators,
10725 : numfkdelsetcols,
10726 : fkdelsetcols,
10727 : old_check_ok,
10728 : lockmode,
10729 : InvalidOid, InvalidOid,
10730 : with_period);
10731 :
10732 : /*
10733 : * Done. Close pk table, but keep lock until we've committed.
10734 : */
10735 1469 : table_close(pkrel, NoLock);
10736 :
10737 1469 : return address;
10738 : }
10739 :
10740 : /*
10741 : * validateFkOnDeleteSetColumns
10742 : * Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
10743 : * column lists are valid.
10744 : *
10745 : * If there are duplicates in the fksetcolsattnums[] array, this silently
10746 : * removes the dups. The new count of numfksetcols is returned.
10747 : */
10748 : static int
10749 1785 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
10750 : int numfksetcols, int16 *fksetcolsattnums,
10751 : List *fksetcols)
10752 : {
10753 1785 : int numcolsout = 0;
10754 :
10755 1805 : for (int i = 0; i < numfksetcols; i++)
10756 : {
10757 24 : int16 setcol_attnum = fksetcolsattnums[i];
10758 24 : bool seen = false;
10759 :
10760 : /* Make sure it's in fkattnums[] */
10761 44 : for (int j = 0; j < numfks; j++)
10762 : {
10763 40 : if (fkattnums[j] == setcol_attnum)
10764 : {
10765 20 : seen = true;
10766 20 : break;
10767 : }
10768 : }
10769 :
10770 24 : if (!seen)
10771 : {
10772 4 : char *col = strVal(list_nth(fksetcols, i));
10773 :
10774 4 : ereport(ERROR,
10775 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
10776 : errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
10777 : }
10778 :
10779 : /* Now check for dups */
10780 20 : seen = false;
10781 20 : for (int j = 0; j < numcolsout; j++)
10782 : {
10783 4 : if (fksetcolsattnums[j] == setcol_attnum)
10784 : {
10785 4 : seen = true;
10786 4 : break;
10787 : }
10788 : }
10789 20 : if (!seen)
10790 16 : fksetcolsattnums[numcolsout++] = setcol_attnum;
10791 : }
10792 1781 : return numcolsout;
10793 : }
10794 :
10795 : /*
10796 : * addFkConstraint
10797 : * Install pg_constraint entries to implement a foreign key constraint.
10798 : * Caller must separately invoke addFkRecurseReferenced and
10799 : * addFkRecurseReferencing, as appropriate, to install pg_trigger entries
10800 : * and (for partitioned tables) recurse to partitions.
10801 : *
10802 : * fkside: the side of the FK (or both) to create. Caller should
10803 : * call addFkRecurseReferenced if this is addFkReferencedSide,
10804 : * addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
10805 : * addFkBothSides.
10806 : * constraintname: the base name for the constraint being added,
10807 : * copied to fkconstraint->conname if the latter is not set
10808 : * fkconstraint: the constraint being added
10809 : * rel: the root referencing relation
10810 : * pkrel: the referenced relation; might be a partition, if recursing
10811 : * indexOid: the OID of the index (on pkrel) implementing this constraint
10812 : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10813 : * top-level constraint
10814 : * numfks: the number of columns in the foreign key
10815 : * pkattnum: the attnum array of referenced attributes
10816 : * fkattnum: the attnum array of referencing attributes
10817 : * pf/pp/ffeqoperators: OID array of operators between columns
10818 : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
10819 : * (...) clause
10820 : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10821 : * NULL/DEFAULT clause
10822 : * with_period: true if this is a temporal FK
10823 : */
10824 : static ObjectAddress
10825 2836 : addFkConstraint(addFkConstraintSides fkside,
10826 : char *constraintname, Constraint *fkconstraint,
10827 : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
10828 : int numfks, int16 *pkattnum,
10829 : int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
10830 : Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
10831 : bool is_internal, bool with_period)
10832 : {
10833 : ObjectAddress address;
10834 : Oid constrOid;
10835 : char *conname;
10836 : bool conislocal;
10837 : int16 coninhcount;
10838 : bool connoinherit;
10839 :
10840 : /*
10841 : * Verify relkind for each referenced partition. At the top level, this
10842 : * is redundant with a previous check, but we need it when recursing.
10843 : */
10844 2836 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10845 589 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10846 0 : ereport(ERROR,
10847 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10848 : errmsg("referenced relation \"%s\" is not a table",
10849 : RelationGetRelationName(pkrel))));
10850 :
10851 : /*
10852 : * Caller supplies us with a constraint name; however, it may be used in
10853 : * this partition, so come up with a different one in that case. Unless
10854 : * truncation to NAMEDATALEN dictates otherwise, the new name will be the
10855 : * supplied name with an underscore and digit(s) appended.
10856 : */
10857 2836 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
10858 : RelationGetRelid(rel),
10859 : constraintname))
10860 811 : conname = ChooseConstraintName(constraintname,
10861 : NULL,
10862 : "",
10863 811 : RelationGetNamespace(rel), NIL);
10864 : else
10865 2025 : conname = constraintname;
10866 :
10867 2836 : if (fkconstraint->conname == NULL)
10868 283 : fkconstraint->conname = pstrdup(conname);
10869 :
10870 2836 : if (OidIsValid(parentConstr))
10871 : {
10872 1367 : conislocal = false;
10873 1367 : coninhcount = 1;
10874 1367 : connoinherit = false;
10875 : }
10876 : else
10877 : {
10878 1469 : conislocal = true;
10879 1469 : coninhcount = 0;
10880 :
10881 : /*
10882 : * always inherit for partitioned tables, never for legacy inheritance
10883 : */
10884 1469 : connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
10885 : }
10886 :
10887 : /*
10888 : * Record the FK constraint in pg_constraint.
10889 : */
10890 2836 : constrOid = CreateConstraintEntry(conname,
10891 2836 : RelationGetNamespace(rel),
10892 : CONSTRAINT_FOREIGN,
10893 2836 : fkconstraint->deferrable,
10894 2836 : fkconstraint->initdeferred,
10895 2836 : fkconstraint->is_enforced,
10896 2836 : fkconstraint->initially_valid,
10897 : parentConstr,
10898 : RelationGetRelid(rel),
10899 : fkattnum,
10900 : numfks,
10901 : numfks,
10902 : InvalidOid, /* not a domain constraint */
10903 : indexOid,
10904 : RelationGetRelid(pkrel),
10905 : pkattnum,
10906 : pfeqoperators,
10907 : ppeqoperators,
10908 : ffeqoperators,
10909 : numfks,
10910 2836 : fkconstraint->fk_upd_action,
10911 2836 : fkconstraint->fk_del_action,
10912 : fkdelsetcols,
10913 : numfkdelsetcols,
10914 2836 : fkconstraint->fk_matchtype,
10915 : NULL, /* no exclusion constraint */
10916 : NULL, /* no check constraint */
10917 : NULL,
10918 : conislocal, /* islocal */
10919 : coninhcount, /* inhcount */
10920 : connoinherit, /* conNoInherit */
10921 : with_period, /* conPeriod */
10922 : is_internal); /* is_internal */
10923 :
10924 2836 : ObjectAddressSet(address, ConstraintRelationId, constrOid);
10925 :
10926 : /*
10927 : * In partitioning cases, create the dependency entries for this
10928 : * constraint. (For non-partitioned cases, relevant entries were created
10929 : * by CreateConstraintEntry.)
10930 : *
10931 : * On the referenced side, we need the constraint to have an internal
10932 : * dependency on its parent constraint; this means that this constraint
10933 : * cannot be dropped on its own -- only through the parent constraint. It
10934 : * also means the containing partition cannot be dropped on its own, but
10935 : * it can be detached, at which point this dependency is removed (after
10936 : * verifying that no rows are referenced via this FK.)
10937 : *
10938 : * When processing the referencing side, we link the constraint via the
10939 : * special partitioning dependencies: the parent constraint is the primary
10940 : * dependent, and the partition on which the foreign key exists is the
10941 : * secondary dependency. That way, this constraint is dropped if either
10942 : * of these objects is.
10943 : *
10944 : * Note that this is only necessary for the subsidiary pg_constraint rows
10945 : * in partitions; the topmost row doesn't need any of this.
10946 : */
10947 2836 : if (OidIsValid(parentConstr))
10948 : {
10949 : ObjectAddress referenced;
10950 :
10951 1367 : ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
10952 :
10953 : Assert(fkside != addFkBothSides);
10954 1367 : if (fkside == addFkReferencedSide)
10955 807 : recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
10956 : else
10957 : {
10958 560 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
10959 560 : ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
10960 560 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
10961 : }
10962 : }
10963 :
10964 : /* make new constraint visible, in case we add more */
10965 2836 : CommandCounterIncrement();
10966 :
10967 2836 : return address;
10968 : }
10969 :
10970 : /*
10971 : * addFkRecurseReferenced
10972 : * Recursive helper for the referenced side of foreign key creation,
10973 : * which creates the action triggers and recurses
10974 : *
10975 : * If the referenced relation is a plain relation, create the necessary action
10976 : * triggers that implement the constraint. If the referenced relation is a
10977 : * partitioned table, then we create a pg_constraint row referencing the parent
10978 : * of the referencing side for it and recurse on this routine for each
10979 : * partition.
10980 : *
10981 : * fkconstraint: the constraint being added
10982 : * rel: the root referencing relation
10983 : * pkrel: the referenced relation; might be a partition, if recursing
10984 : * indexOid: the OID of the index (on pkrel) implementing this constraint
10985 : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10986 : * top-level constraint
10987 : * numfks: the number of columns in the foreign key
10988 : * pkattnum: the attnum array of referenced attributes
10989 : * fkattnum: the attnum array of referencing attributes
10990 : * numfkdelsetcols: the number of columns in the ON DELETE SET
10991 : * NULL/DEFAULT (...) clause
10992 : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10993 : * NULL/DEFAULT clause
10994 : * pf/pp/ffeqoperators: OID array of operators between columns
10995 : * old_check_ok: true if this constraint replaces an existing one that
10996 : * was already validated (thus this one doesn't need validation)
10997 : * parentDelTrigger and parentUpdTrigger: when recursively called on a
10998 : * partition, the OIDs of the parent action triggers for DELETE and
10999 : * UPDATE respectively.
11000 : * with_period: true if this is a temporal FK
11001 : */
11002 : static void
11003 2348 : addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
11004 : Relation pkrel, Oid indexOid, Oid parentConstr,
11005 : int numfks,
11006 : int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
11007 : Oid *ppeqoperators, Oid *ffeqoperators,
11008 : int numfkdelsetcols, int16 *fkdelsetcols,
11009 : bool old_check_ok,
11010 : Oid parentDelTrigger, Oid parentUpdTrigger,
11011 : bool with_period)
11012 : {
11013 2348 : Oid deleteTriggerOid = InvalidOid,
11014 2348 : updateTriggerOid = InvalidOid;
11015 :
11016 : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11017 : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11018 :
11019 : /*
11020 : * Create action triggers to enforce the constraint, or skip them if the
11021 : * constraint is NOT ENFORCED.
11022 : */
11023 2348 : if (fkconstraint->is_enforced)
11024 2295 : createForeignKeyActionTriggers(RelationGetRelid(rel),
11025 : RelationGetRelid(pkrel),
11026 : fkconstraint,
11027 : parentConstr, indexOid,
11028 : parentDelTrigger, parentUpdTrigger,
11029 : &deleteTriggerOid, &updateTriggerOid);
11030 :
11031 : /*
11032 : * If the referenced table is partitioned, recurse on ourselves to handle
11033 : * each partition. We need one pg_constraint row created for each
11034 : * partition in addition to the pg_constraint row for the parent table.
11035 : */
11036 2348 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11037 : {
11038 373 : PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
11039 :
11040 1048 : for (int i = 0; i < pd->nparts; i++)
11041 : {
11042 : Relation partRel;
11043 : AttrMap *map;
11044 : AttrNumber *mapped_pkattnum;
11045 : Oid partIndexId;
11046 : ObjectAddress address;
11047 :
11048 : /* XXX would it be better to acquire these locks beforehand? */
11049 675 : partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
11050 :
11051 : /*
11052 : * Map the attribute numbers in the referenced side of the FK
11053 : * definition to match the partition's column layout.
11054 : */
11055 675 : map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
11056 : RelationGetDescr(pkrel),
11057 : false);
11058 675 : if (map)
11059 : {
11060 89 : mapped_pkattnum = palloc_array(AttrNumber, numfks);
11061 186 : for (int j = 0; j < numfks; j++)
11062 97 : mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
11063 : }
11064 : else
11065 586 : mapped_pkattnum = pkattnum;
11066 :
11067 : /* Determine the index to use at this level */
11068 675 : partIndexId = index_get_partition(partRel, indexOid);
11069 675 : if (!OidIsValid(partIndexId))
11070 0 : elog(ERROR, "index for %u not found in partition %s",
11071 : indexOid, RelationGetRelationName(partRel));
11072 :
11073 : /* Create entry at this level ... */
11074 675 : address = addFkConstraint(addFkReferencedSide,
11075 : fkconstraint->conname, fkconstraint, rel,
11076 : partRel, partIndexId, parentConstr,
11077 : numfks, mapped_pkattnum,
11078 : fkattnum, pfeqoperators, ppeqoperators,
11079 : ffeqoperators, numfkdelsetcols,
11080 : fkdelsetcols, true, with_period);
11081 : /* ... and recurse to our children */
11082 675 : addFkRecurseReferenced(fkconstraint, rel, partRel,
11083 : partIndexId, address.objectId, numfks,
11084 : mapped_pkattnum, fkattnum,
11085 : pfeqoperators, ppeqoperators, ffeqoperators,
11086 : numfkdelsetcols, fkdelsetcols,
11087 : old_check_ok,
11088 : deleteTriggerOid, updateTriggerOid,
11089 : with_period);
11090 :
11091 : /* Done -- clean up (but keep the lock) */
11092 675 : table_close(partRel, NoLock);
11093 675 : if (map)
11094 : {
11095 89 : pfree(mapped_pkattnum);
11096 89 : free_attrmap(map);
11097 : }
11098 : }
11099 : }
11100 2348 : }
11101 :
11102 : /*
11103 : * addFkRecurseReferencing
11104 : * Recursive helper for the referencing side of foreign key creation,
11105 : * which creates the check triggers and recurses
11106 : *
11107 : * If the referencing relation is a plain relation, create the necessary check
11108 : * triggers that implement the constraint, and set up for Phase 3 constraint
11109 : * verification. If the referencing relation is a partitioned table, then
11110 : * we create a pg_constraint row for it and recurse on this routine for each
11111 : * partition.
11112 : *
11113 : * We assume that the referenced relation is locked against concurrent
11114 : * deletions. If it's a partitioned relation, every partition must be so
11115 : * locked.
11116 : *
11117 : * wqueue: the ALTER TABLE work queue; NULL when not running as part
11118 : * of an ALTER TABLE sequence.
11119 : * fkconstraint: the constraint being added
11120 : * rel: the referencing relation; might be a partition, if recursing
11121 : * pkrel: the root referenced relation
11122 : * indexOid: the OID of the index (on pkrel) implementing this constraint
11123 : * parentConstr: the OID of the parent constraint (there is always one)
11124 : * numfks: the number of columns in the foreign key
11125 : * pkattnum: the attnum array of referenced attributes
11126 : * fkattnum: the attnum array of referencing attributes
11127 : * pf/pp/ffeqoperators: OID array of operators between columns
11128 : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
11129 : * (...) clause
11130 : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
11131 : * NULL/DEFAULT clause
11132 : * old_check_ok: true if this constraint replaces an existing one that
11133 : * was already validated (thus this one doesn't need validation)
11134 : * lockmode: the lockmode to acquire on partitions when recursing
11135 : * parentInsTrigger and parentUpdTrigger: when being recursively called on
11136 : * a partition, the OIDs of the parent check triggers for INSERT and
11137 : * UPDATE respectively.
11138 : * with_period: true if this is a temporal FK
11139 : */
11140 : static void
11141 2029 : addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
11142 : Relation pkrel, Oid indexOid, Oid parentConstr,
11143 : int numfks, int16 *pkattnum, int16 *fkattnum,
11144 : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
11145 : int numfkdelsetcols, int16 *fkdelsetcols,
11146 : bool old_check_ok, LOCKMODE lockmode,
11147 : Oid parentInsTrigger, Oid parentUpdTrigger,
11148 : bool with_period)
11149 : {
11150 2029 : Oid insertTriggerOid = InvalidOid,
11151 2029 : updateTriggerOid = InvalidOid;
11152 :
11153 : Assert(OidIsValid(parentConstr));
11154 : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11155 : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11156 :
11157 2029 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11158 0 : ereport(ERROR,
11159 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11160 : errmsg("foreign key constraints are not supported on foreign tables")));
11161 :
11162 : /*
11163 : * Add check triggers if the constraint is ENFORCED, and if needed,
11164 : * schedule them to be checked in Phase 3.
11165 : *
11166 : * If the relation is partitioned, drill down to do it to its partitions.
11167 : */
11168 2029 : if (fkconstraint->is_enforced)
11169 1992 : createForeignKeyCheckTriggers(RelationGetRelid(rel),
11170 : RelationGetRelid(pkrel),
11171 : fkconstraint,
11172 : parentConstr,
11173 : indexOid,
11174 : parentInsTrigger, parentUpdTrigger,
11175 : &insertTriggerOid, &updateTriggerOid);
11176 :
11177 2029 : if (rel->rd_rel->relkind == RELKIND_RELATION)
11178 : {
11179 : /*
11180 : * Tell Phase 3 to check that the constraint is satisfied by existing
11181 : * rows. We can skip this during table creation, when constraint is
11182 : * specified as NOT ENFORCED, or when requested explicitly by
11183 : * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
11184 : * recreating a constraint following a SET DATA TYPE operation that
11185 : * did not impugn its validity.
11186 : */
11187 1706 : if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
11188 599 : fkconstraint->is_enforced)
11189 : {
11190 : NewConstraint *newcon;
11191 : AlteredTableInfo *tab;
11192 :
11193 599 : tab = ATGetQueueEntry(wqueue, rel);
11194 :
11195 599 : newcon = palloc0_object(NewConstraint);
11196 599 : newcon->name = get_constraint_name(parentConstr);
11197 599 : newcon->contype = CONSTR_FOREIGN;
11198 599 : newcon->refrelid = RelationGetRelid(pkrel);
11199 599 : newcon->refindid = indexOid;
11200 599 : newcon->conid = parentConstr;
11201 599 : newcon->conwithperiod = fkconstraint->fk_with_period;
11202 599 : newcon->qual = (Node *) fkconstraint;
11203 :
11204 599 : tab->constraints = lappend(tab->constraints, newcon);
11205 : }
11206 : }
11207 323 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11208 : {
11209 323 : PartitionDesc pd = RelationGetPartitionDesc(rel, true);
11210 : Relation trigrel;
11211 :
11212 : /*
11213 : * Triggers of the foreign keys will be manipulated a bunch of times
11214 : * in the loop below. To avoid repeatedly opening/closing the trigger
11215 : * catalog relation, we open it here and pass it to the subroutines
11216 : * called below.
11217 : */
11218 323 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11219 :
11220 : /*
11221 : * Recurse to take appropriate action on each partition; either we
11222 : * find an existing constraint to reparent to ours, or we create a new
11223 : * one.
11224 : */
11225 608 : for (int i = 0; i < pd->nparts; i++)
11226 : {
11227 289 : Relation partition = table_open(pd->oids[i], lockmode);
11228 : List *partFKs;
11229 : AttrMap *attmap;
11230 : AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
11231 : bool attached;
11232 : ObjectAddress address;
11233 :
11234 289 : CheckAlterTableIsSafe(partition);
11235 :
11236 285 : attmap = build_attrmap_by_name(RelationGetDescr(partition),
11237 : RelationGetDescr(rel),
11238 : false);
11239 714 : for (int j = 0; j < numfks; j++)
11240 429 : mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
11241 :
11242 : /* Check whether an existing constraint can be repurposed */
11243 285 : partFKs = copyObject(RelationGetFKeyList(partition));
11244 285 : attached = false;
11245 581 : foreach_node(ForeignKeyCacheInfo, fk, partFKs)
11246 : {
11247 19 : if (tryAttachPartitionForeignKey(wqueue,
11248 : fk,
11249 : partition,
11250 : parentConstr,
11251 : numfks,
11252 : mapped_fkattnum,
11253 : pkattnum,
11254 : pfeqoperators,
11255 : insertTriggerOid,
11256 : updateTriggerOid,
11257 : trigrel))
11258 : {
11259 8 : attached = true;
11260 8 : break;
11261 : }
11262 : }
11263 285 : if (attached)
11264 : {
11265 8 : table_close(partition, NoLock);
11266 8 : continue;
11267 : }
11268 :
11269 : /*
11270 : * No luck finding a good constraint to reuse; create our own.
11271 : */
11272 277 : address = addFkConstraint(addFkReferencingSide,
11273 : fkconstraint->conname, fkconstraint,
11274 : partition, pkrel, indexOid, parentConstr,
11275 : numfks, pkattnum,
11276 : mapped_fkattnum, pfeqoperators,
11277 : ppeqoperators, ffeqoperators,
11278 : numfkdelsetcols, fkdelsetcols, true,
11279 : with_period);
11280 :
11281 : /* call ourselves to finalize the creation and we're done */
11282 277 : addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
11283 : indexOid,
11284 : address.objectId,
11285 : numfks,
11286 : pkattnum,
11287 : mapped_fkattnum,
11288 : pfeqoperators,
11289 : ppeqoperators,
11290 : ffeqoperators,
11291 : numfkdelsetcols,
11292 : fkdelsetcols,
11293 : old_check_ok,
11294 : lockmode,
11295 : insertTriggerOid,
11296 : updateTriggerOid,
11297 : with_period);
11298 :
11299 277 : table_close(partition, NoLock);
11300 : }
11301 :
11302 319 : table_close(trigrel, RowExclusiveLock);
11303 : }
11304 2025 : }
11305 :
11306 : /*
11307 : * CloneForeignKeyConstraints
11308 : * Clone foreign keys from a partitioned table to a newly acquired
11309 : * partition.
11310 : *
11311 : * partitionRel is a partition of parentRel, so we can be certain that it has
11312 : * the same columns with the same datatypes. The columns may be in different
11313 : * order, though.
11314 : *
11315 : * wqueue must be passed to set up phase 3 constraint checking, unless the
11316 : * referencing-side partition is known to be empty (such as in CREATE TABLE /
11317 : * PARTITION OF).
11318 : */
11319 : static void
11320 8022 : CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
11321 : Relation partitionRel)
11322 : {
11323 : /* This only works for declarative partitioning */
11324 : Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
11325 :
11326 : /*
11327 : * First, clone constraints where the parent is on the referencing side.
11328 : */
11329 8022 : CloneFkReferencing(wqueue, parentRel, partitionRel);
11330 :
11331 : /*
11332 : * Clone constraints for which the parent is on the referenced side.
11333 : */
11334 8010 : CloneFkReferenced(parentRel, partitionRel);
11335 8010 : }
11336 :
11337 : /*
11338 : * CloneFkReferenced
11339 : * Subroutine for CloneForeignKeyConstraints
11340 : *
11341 : * Find all the FKs that have the parent relation on the referenced side;
11342 : * clone those constraints to the given partition. This is to be called
11343 : * when the partition is being created or attached.
11344 : *
11345 : * This recurses to partitions, if the relation being attached is partitioned.
11346 : * Recursion is done by calling addFkRecurseReferenced.
11347 : */
11348 : static void
11349 8010 : CloneFkReferenced(Relation parentRel, Relation partitionRel)
11350 : {
11351 : Relation pg_constraint;
11352 : AttrMap *attmap;
11353 : ListCell *cell;
11354 : SysScanDesc scan;
11355 : ScanKeyData key[2];
11356 : HeapTuple tuple;
11357 8010 : List *clone = NIL;
11358 : Relation trigrel;
11359 :
11360 : /*
11361 : * Search for any constraints where this partition's parent is in the
11362 : * referenced side. However, we must not clone any constraint whose
11363 : * parent constraint is also going to be cloned, to avoid duplicates. So
11364 : * do it in two steps: first construct the list of constraints to clone,
11365 : * then go over that list cloning those whose parents are not in the list.
11366 : * (We must not rely on the parent being seen first, since the catalog
11367 : * scan could return children first.)
11368 : */
11369 8010 : pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11370 8010 : ScanKeyInit(&key[0],
11371 : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
11372 : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
11373 8010 : ScanKeyInit(&key[1],
11374 : Anum_pg_constraint_contype, BTEqualStrategyNumber,
11375 : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
11376 : /* This is a seqscan, as we don't have a usable index ... */
11377 8010 : scan = systable_beginscan(pg_constraint, InvalidOid, true,
11378 : NULL, 2, key);
11379 8290 : while ((tuple = systable_getnext(scan)) != NULL)
11380 : {
11381 280 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11382 :
11383 280 : clone = lappend_oid(clone, constrForm->oid);
11384 : }
11385 8010 : systable_endscan(scan);
11386 8010 : table_close(pg_constraint, RowShareLock);
11387 :
11388 : /*
11389 : * Triggers of the foreign keys will be manipulated a bunch of times in
11390 : * the loop below. To avoid repeatedly opening/closing the trigger
11391 : * catalog relation, we open it here and pass it to the subroutines called
11392 : * below.
11393 : */
11394 8010 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11395 :
11396 8010 : attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
11397 : RelationGetDescr(parentRel),
11398 : false);
11399 8290 : foreach(cell, clone)
11400 : {
11401 280 : Oid constrOid = lfirst_oid(cell);
11402 : Form_pg_constraint constrForm;
11403 : Relation fkRel;
11404 : Oid indexOid;
11405 : Oid partIndexId;
11406 : int numfks;
11407 : AttrNumber conkey[INDEX_MAX_KEYS];
11408 : AttrNumber mapped_confkey[INDEX_MAX_KEYS];
11409 : AttrNumber confkey[INDEX_MAX_KEYS];
11410 : Oid conpfeqop[INDEX_MAX_KEYS];
11411 : Oid conppeqop[INDEX_MAX_KEYS];
11412 : Oid conffeqop[INDEX_MAX_KEYS];
11413 : int numfkdelsetcols;
11414 : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11415 : Constraint *fkconstraint;
11416 : ObjectAddress address;
11417 280 : Oid deleteTriggerOid = InvalidOid,
11418 280 : updateTriggerOid = InvalidOid;
11419 :
11420 280 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
11421 280 : if (!HeapTupleIsValid(tuple))
11422 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
11423 280 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11424 :
11425 : /*
11426 : * As explained above: don't try to clone a constraint for which we're
11427 : * going to clone the parent.
11428 : */
11429 280 : if (list_member_oid(clone, constrForm->conparentid))
11430 : {
11431 148 : ReleaseSysCache(tuple);
11432 148 : continue;
11433 : }
11434 :
11435 : /* We need the same lock level that CreateTrigger will acquire */
11436 132 : fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
11437 :
11438 132 : indexOid = constrForm->conindid;
11439 132 : DeconstructFkConstraintRow(tuple,
11440 : &numfks,
11441 : conkey,
11442 : confkey,
11443 : conpfeqop,
11444 : conppeqop,
11445 : conffeqop,
11446 : &numfkdelsetcols,
11447 : confdelsetcols);
11448 :
11449 292 : for (int i = 0; i < numfks; i++)
11450 160 : mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
11451 :
11452 132 : fkconstraint = makeNode(Constraint);
11453 132 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11454 132 : fkconstraint->conname = NameStr(constrForm->conname);
11455 132 : fkconstraint->deferrable = constrForm->condeferrable;
11456 132 : fkconstraint->initdeferred = constrForm->condeferred;
11457 132 : fkconstraint->location = -1;
11458 132 : fkconstraint->pktable = NULL;
11459 : /* ->fk_attrs determined below */
11460 132 : fkconstraint->pk_attrs = NIL;
11461 132 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11462 132 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11463 132 : fkconstraint->fk_del_action = constrForm->confdeltype;
11464 132 : fkconstraint->fk_del_set_cols = NIL;
11465 132 : fkconstraint->old_conpfeqop = NIL;
11466 132 : fkconstraint->old_pktable_oid = InvalidOid;
11467 132 : fkconstraint->is_enforced = constrForm->conenforced;
11468 132 : fkconstraint->skip_validation = false;
11469 132 : fkconstraint->initially_valid = constrForm->convalidated;
11470 :
11471 : /* set up colnames that are used to generate the constraint name */
11472 292 : for (int i = 0; i < numfks; i++)
11473 : {
11474 : Form_pg_attribute att;
11475 :
11476 160 : att = TupleDescAttr(RelationGetDescr(fkRel),
11477 160 : conkey[i] - 1);
11478 160 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11479 160 : makeString(NameStr(att->attname)));
11480 : }
11481 :
11482 : /*
11483 : * Add the new foreign key constraint pointing to the new partition.
11484 : * Because this new partition appears in the referenced side of the
11485 : * constraint, we don't need to set up for Phase 3 check.
11486 : */
11487 132 : partIndexId = index_get_partition(partitionRel, indexOid);
11488 132 : if (!OidIsValid(partIndexId))
11489 0 : elog(ERROR, "index for %u not found in partition %s",
11490 : indexOid, RelationGetRelationName(partitionRel));
11491 :
11492 : /*
11493 : * Get the "action" triggers belonging to the constraint to pass as
11494 : * parent OIDs for similar triggers that will be created on the
11495 : * partition in addFkRecurseReferenced().
11496 : */
11497 132 : if (constrForm->conenforced)
11498 128 : GetForeignKeyActionTriggers(trigrel, constrOid,
11499 : constrForm->confrelid, constrForm->conrelid,
11500 : &deleteTriggerOid, &updateTriggerOid);
11501 :
11502 : /* Add this constraint ... */
11503 132 : address = addFkConstraint(addFkReferencedSide,
11504 : fkconstraint->conname, fkconstraint, fkRel,
11505 : partitionRel, partIndexId, constrOid,
11506 : numfks, mapped_confkey,
11507 : conkey, conpfeqop, conppeqop, conffeqop,
11508 : numfkdelsetcols, confdelsetcols, false,
11509 132 : constrForm->conperiod);
11510 : /* ... and recurse */
11511 132 : addFkRecurseReferenced(fkconstraint,
11512 : fkRel,
11513 : partitionRel,
11514 : partIndexId,
11515 : address.objectId,
11516 : numfks,
11517 : mapped_confkey,
11518 : conkey,
11519 : conpfeqop,
11520 : conppeqop,
11521 : conffeqop,
11522 : numfkdelsetcols,
11523 : confdelsetcols,
11524 : true,
11525 : deleteTriggerOid,
11526 : updateTriggerOid,
11527 132 : constrForm->conperiod);
11528 :
11529 132 : table_close(fkRel, NoLock);
11530 132 : ReleaseSysCache(tuple);
11531 : }
11532 :
11533 8010 : table_close(trigrel, RowExclusiveLock);
11534 8010 : }
11535 :
11536 : /*
11537 : * CloneFkReferencing
11538 : * Subroutine for CloneForeignKeyConstraints
11539 : *
11540 : * For each FK constraint of the parent relation in the given list, find an
11541 : * equivalent constraint in its partition relation that can be reparented;
11542 : * if one cannot be found, create a new constraint in the partition as its
11543 : * child.
11544 : *
11545 : * If wqueue is given, it is used to set up phase-3 verification for each
11546 : * cloned constraint; omit it if such verification is not needed
11547 : * (example: the partition is being created anew).
11548 : */
11549 : static void
11550 8022 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
11551 : {
11552 : AttrMap *attmap;
11553 : List *partFKs;
11554 8022 : List *clone = NIL;
11555 : ListCell *cell;
11556 : Relation trigrel;
11557 :
11558 : /* obtain a list of constraints that we need to clone */
11559 8881 : foreach(cell, RelationGetFKeyList(parentRel))
11560 : {
11561 863 : ForeignKeyCacheInfo *fk = lfirst(cell);
11562 :
11563 : /*
11564 : * Refuse to attach a table as partition that this partitioned table
11565 : * already has a foreign key to. This isn't useful schema, which is
11566 : * proven by the fact that there have been no user complaints that
11567 : * it's already impossible to achieve this in the opposite direction,
11568 : * i.e., creating a foreign key that references a partition. This
11569 : * restriction allows us to dodge some complexities around
11570 : * pg_constraint and pg_trigger row creations that would be needed
11571 : * during ATTACH/DETACH for this kind of relationship.
11572 : */
11573 863 : if (fk->confrelid == RelationGetRelid(partRel))
11574 4 : ereport(ERROR,
11575 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11576 : errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
11577 : RelationGetRelationName(partRel),
11578 : get_constraint_name(fk->conoid))));
11579 :
11580 859 : clone = lappend_oid(clone, fk->conoid);
11581 : }
11582 :
11583 : /*
11584 : * Silently do nothing if there's nothing to do. In particular, this
11585 : * avoids throwing a spurious error for foreign tables.
11586 : */
11587 8018 : if (clone == NIL)
11588 7663 : return;
11589 :
11590 355 : if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11591 0 : ereport(ERROR,
11592 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11593 : errmsg("foreign key constraints are not supported on foreign tables")));
11594 :
11595 : /*
11596 : * Triggers of the foreign keys will be manipulated a bunch of times in
11597 : * the loop below. To avoid repeatedly opening/closing the trigger
11598 : * catalog relation, we open it here and pass it to the subroutines called
11599 : * below.
11600 : */
11601 355 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11602 :
11603 : /*
11604 : * The constraint key may differ, if the columns in the partition are
11605 : * different. This map is used to convert them.
11606 : */
11607 355 : attmap = build_attrmap_by_name(RelationGetDescr(partRel),
11608 : RelationGetDescr(parentRel),
11609 : false);
11610 :
11611 355 : partFKs = copyObject(RelationGetFKeyList(partRel));
11612 :
11613 1206 : foreach(cell, clone)
11614 : {
11615 859 : Oid parentConstrOid = lfirst_oid(cell);
11616 : Form_pg_constraint constrForm;
11617 : Relation pkrel;
11618 : HeapTuple tuple;
11619 : int numfks;
11620 : AttrNumber conkey[INDEX_MAX_KEYS];
11621 : AttrNumber mapped_conkey[INDEX_MAX_KEYS];
11622 : AttrNumber confkey[INDEX_MAX_KEYS];
11623 : Oid conpfeqop[INDEX_MAX_KEYS];
11624 : Oid conppeqop[INDEX_MAX_KEYS];
11625 : Oid conffeqop[INDEX_MAX_KEYS];
11626 : int numfkdelsetcols;
11627 : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11628 : Constraint *fkconstraint;
11629 : bool attached;
11630 : Oid indexOid;
11631 : ObjectAddress address;
11632 : ListCell *lc;
11633 859 : Oid insertTriggerOid = InvalidOid,
11634 859 : updateTriggerOid = InvalidOid;
11635 : bool with_period;
11636 :
11637 859 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
11638 859 : if (!HeapTupleIsValid(tuple))
11639 0 : elog(ERROR, "cache lookup failed for constraint %u",
11640 : parentConstrOid);
11641 859 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11642 :
11643 : /* Don't clone constraints whose parents are being cloned */
11644 859 : if (list_member_oid(clone, constrForm->conparentid))
11645 : {
11646 472 : ReleaseSysCache(tuple);
11647 572 : continue;
11648 : }
11649 :
11650 : /*
11651 : * Need to prevent concurrent deletions. If pkrel is a partitioned
11652 : * relation, that means to lock all partitions.
11653 : */
11654 387 : pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
11655 387 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11656 164 : (void) find_all_inheritors(RelationGetRelid(pkrel),
11657 : ShareRowExclusiveLock, NULL);
11658 :
11659 387 : DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
11660 : conpfeqop, conppeqop, conffeqop,
11661 : &numfkdelsetcols, confdelsetcols);
11662 930 : for (int i = 0; i < numfks; i++)
11663 543 : mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
11664 :
11665 : /*
11666 : * Get the "check" triggers belonging to the constraint, if it is
11667 : * ENFORCED, to pass as parent OIDs for similar triggers that will be
11668 : * created on the partition in addFkRecurseReferencing(). They are
11669 : * also passed to tryAttachPartitionForeignKey() below to simply
11670 : * assign as parents to the partition's existing "check" triggers,
11671 : * that is, if the corresponding constraints is deemed attachable to
11672 : * the parent constraint.
11673 : */
11674 387 : if (constrForm->conenforced)
11675 379 : GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
11676 : constrForm->confrelid, constrForm->conrelid,
11677 : &insertTriggerOid, &updateTriggerOid);
11678 :
11679 : /*
11680 : * Before creating a new constraint, see whether any existing FKs are
11681 : * fit for the purpose. If one is, attach the parent constraint to
11682 : * it, and don't clone anything. This way we avoid the expensive
11683 : * verification step and don't end up with a duplicate FK, and we
11684 : * don't need to recurse to partitions for this constraint.
11685 : */
11686 387 : attached = false;
11687 447 : foreach(lc, partFKs)
11688 : {
11689 164 : ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
11690 :
11691 164 : if (tryAttachPartitionForeignKey(wqueue,
11692 : fk,
11693 : partRel,
11694 : parentConstrOid,
11695 : numfks,
11696 : mapped_conkey,
11697 : confkey,
11698 : conpfeqop,
11699 : insertTriggerOid,
11700 : updateTriggerOid,
11701 : trigrel))
11702 : {
11703 100 : attached = true;
11704 100 : table_close(pkrel, NoLock);
11705 100 : break;
11706 : }
11707 : }
11708 383 : if (attached)
11709 : {
11710 100 : ReleaseSysCache(tuple);
11711 100 : continue;
11712 : }
11713 :
11714 : /* No dice. Set up to create our own constraint */
11715 283 : fkconstraint = makeNode(Constraint);
11716 283 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11717 : /* ->conname determined below */
11718 283 : fkconstraint->deferrable = constrForm->condeferrable;
11719 283 : fkconstraint->initdeferred = constrForm->condeferred;
11720 283 : fkconstraint->location = -1;
11721 283 : fkconstraint->pktable = NULL;
11722 : /* ->fk_attrs determined below */
11723 283 : fkconstraint->pk_attrs = NIL;
11724 283 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11725 283 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11726 283 : fkconstraint->fk_del_action = constrForm->confdeltype;
11727 283 : fkconstraint->fk_del_set_cols = NIL;
11728 283 : fkconstraint->old_conpfeqop = NIL;
11729 283 : fkconstraint->old_pktable_oid = InvalidOid;
11730 283 : fkconstraint->is_enforced = constrForm->conenforced;
11731 283 : fkconstraint->skip_validation = false;
11732 283 : fkconstraint->initially_valid = constrForm->convalidated;
11733 646 : for (int i = 0; i < numfks; i++)
11734 : {
11735 : Form_pg_attribute att;
11736 :
11737 363 : att = TupleDescAttr(RelationGetDescr(partRel),
11738 363 : mapped_conkey[i] - 1);
11739 363 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11740 363 : makeString(NameStr(att->attname)));
11741 : }
11742 :
11743 283 : indexOid = constrForm->conindid;
11744 283 : with_period = constrForm->conperiod;
11745 :
11746 : /* Create the pg_constraint entry at this level */
11747 283 : address = addFkConstraint(addFkReferencingSide,
11748 283 : NameStr(constrForm->conname), fkconstraint,
11749 : partRel, pkrel, indexOid, parentConstrOid,
11750 : numfks, confkey,
11751 : mapped_conkey, conpfeqop,
11752 : conppeqop, conffeqop,
11753 : numfkdelsetcols, confdelsetcols,
11754 : false, with_period);
11755 :
11756 : /* Done with the cloned constraint's tuple */
11757 283 : ReleaseSysCache(tuple);
11758 :
11759 : /* Create the check triggers, and recurse to partitions, if any */
11760 283 : addFkRecurseReferencing(wqueue,
11761 : fkconstraint,
11762 : partRel,
11763 : pkrel,
11764 : indexOid,
11765 : address.objectId,
11766 : numfks,
11767 : confkey,
11768 : mapped_conkey,
11769 : conpfeqop,
11770 : conppeqop,
11771 : conffeqop,
11772 : numfkdelsetcols,
11773 : confdelsetcols,
11774 : false, /* no old check exists */
11775 : AccessExclusiveLock,
11776 : insertTriggerOid,
11777 : updateTriggerOid,
11778 : with_period);
11779 279 : table_close(pkrel, NoLock);
11780 : }
11781 :
11782 347 : table_close(trigrel, RowExclusiveLock);
11783 : }
11784 :
11785 : /*
11786 : * When the parent of a partition receives [the referencing side of] a foreign
11787 : * key, we must propagate that foreign key to the partition. However, the
11788 : * partition might already have an equivalent foreign key; this routine
11789 : * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
11790 : * by the other parameters. If they are equivalent, create the link between
11791 : * the two constraints and return true.
11792 : *
11793 : * If the given FK does not match the one defined by rest of the params,
11794 : * return false.
11795 : */
11796 : static bool
11797 183 : tryAttachPartitionForeignKey(List **wqueue,
11798 : ForeignKeyCacheInfo *fk,
11799 : Relation partition,
11800 : Oid parentConstrOid,
11801 : int numfks,
11802 : AttrNumber *mapped_conkey,
11803 : AttrNumber *confkey,
11804 : Oid *conpfeqop,
11805 : Oid parentInsTrigger,
11806 : Oid parentUpdTrigger,
11807 : Relation trigrel)
11808 : {
11809 : HeapTuple parentConstrTup;
11810 : Form_pg_constraint parentConstr;
11811 : HeapTuple partcontup;
11812 : Form_pg_constraint partConstr;
11813 :
11814 183 : parentConstrTup = SearchSysCache1(CONSTROID,
11815 : ObjectIdGetDatum(parentConstrOid));
11816 183 : if (!HeapTupleIsValid(parentConstrTup))
11817 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11818 183 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11819 :
11820 : /*
11821 : * Do some quick & easy initial checks. If any of these fail, we cannot
11822 : * use this constraint.
11823 : */
11824 183 : if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
11825 : {
11826 0 : ReleaseSysCache(parentConstrTup);
11827 0 : return false;
11828 : }
11829 505 : for (int i = 0; i < numfks; i++)
11830 : {
11831 324 : if (fk->conkey[i] != mapped_conkey[i] ||
11832 322 : fk->confkey[i] != confkey[i] ||
11833 322 : fk->conpfeqop[i] != conpfeqop[i])
11834 : {
11835 2 : ReleaseSysCache(parentConstrTup);
11836 2 : return false;
11837 : }
11838 : }
11839 :
11840 : /* Looks good so far; perform more extensive checks. */
11841 181 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
11842 181 : if (!HeapTupleIsValid(partcontup))
11843 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
11844 181 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11845 :
11846 : /*
11847 : * An error should be raised if the constraint enforceability is
11848 : * different. Returning false without raising an error, as we do for other
11849 : * attributes, could lead to a duplicate constraint with the same
11850 : * enforceability as the parent. While this may be acceptable, it may not
11851 : * be ideal. Therefore, it's better to raise an error and allow the user
11852 : * to correct the enforceability before proceeding.
11853 : */
11854 181 : if (partConstr->conenforced != parentConstr->conenforced)
11855 4 : ereport(ERROR,
11856 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
11857 : errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
11858 : NameStr(parentConstr->conname),
11859 : NameStr(partConstr->conname),
11860 : RelationGetRelationName(partition))));
11861 :
11862 177 : if (OidIsValid(partConstr->conparentid) ||
11863 158 : partConstr->condeferrable != parentConstr->condeferrable ||
11864 140 : partConstr->condeferred != parentConstr->condeferred ||
11865 140 : partConstr->confupdtype != parentConstr->confupdtype ||
11866 117 : partConstr->confdeltype != parentConstr->confdeltype ||
11867 117 : partConstr->confmatchtype != parentConstr->confmatchtype)
11868 : {
11869 69 : ReleaseSysCache(parentConstrTup);
11870 69 : ReleaseSysCache(partcontup);
11871 69 : return false;
11872 : }
11873 :
11874 108 : ReleaseSysCache(parentConstrTup);
11875 108 : ReleaseSysCache(partcontup);
11876 :
11877 : /* Looks good! Attach this constraint. */
11878 108 : AttachPartitionForeignKey(wqueue, partition, fk->conoid,
11879 : parentConstrOid, parentInsTrigger,
11880 : parentUpdTrigger, trigrel);
11881 :
11882 108 : return true;
11883 : }
11884 :
11885 : /*
11886 : * AttachPartitionForeignKey
11887 : *
11888 : * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
11889 : * attaching the constraint, removing redundant triggers and entries from
11890 : * pg_constraint, and setting the constraint's parent.
11891 : */
11892 : static void
11893 108 : AttachPartitionForeignKey(List **wqueue,
11894 : Relation partition,
11895 : Oid partConstrOid,
11896 : Oid parentConstrOid,
11897 : Oid parentInsTrigger,
11898 : Oid parentUpdTrigger,
11899 : Relation trigrel)
11900 : {
11901 : HeapTuple parentConstrTup;
11902 : Form_pg_constraint parentConstr;
11903 : HeapTuple partcontup;
11904 : Form_pg_constraint partConstr;
11905 : bool queueValidation;
11906 : Oid partConstrFrelid;
11907 : Oid partConstrRelid;
11908 : bool parentConstrIsEnforced;
11909 :
11910 : /* Fetch the parent constraint tuple */
11911 108 : parentConstrTup = SearchSysCache1(CONSTROID,
11912 : ObjectIdGetDatum(parentConstrOid));
11913 108 : if (!HeapTupleIsValid(parentConstrTup))
11914 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11915 108 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11916 108 : parentConstrIsEnforced = parentConstr->conenforced;
11917 :
11918 : /* Fetch the child constraint tuple */
11919 108 : partcontup = SearchSysCache1(CONSTROID,
11920 : ObjectIdGetDatum(partConstrOid));
11921 108 : if (!HeapTupleIsValid(partcontup))
11922 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11923 108 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11924 108 : partConstrFrelid = partConstr->confrelid;
11925 108 : partConstrRelid = partConstr->conrelid;
11926 :
11927 : /*
11928 : * If the referenced table is partitioned, then the partition we're
11929 : * attaching now has extra pg_constraint rows and action triggers that are
11930 : * no longer needed. Remove those.
11931 : */
11932 108 : if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
11933 : {
11934 24 : Relation pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11935 :
11936 24 : RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
11937 : partConstrRelid);
11938 :
11939 24 : table_close(pg_constraint, RowShareLock);
11940 : }
11941 :
11942 : /*
11943 : * Will we need to validate this constraint? A valid parent constraint
11944 : * implies that all child constraints have been validated, so if this one
11945 : * isn't, we must trigger phase 3 validation.
11946 : */
11947 108 : queueValidation = parentConstr->convalidated && !partConstr->convalidated;
11948 :
11949 108 : ReleaseSysCache(partcontup);
11950 108 : ReleaseSysCache(parentConstrTup);
11951 :
11952 : /*
11953 : * The action triggers in the new partition become redundant -- the parent
11954 : * table already has equivalent ones, and those will be able to reach the
11955 : * partition. Remove the ones in the partition. We identify them because
11956 : * they have our constraint OID, as well as being on the referenced rel.
11957 : */
11958 108 : DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
11959 : partConstrRelid);
11960 :
11961 108 : ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
11962 : RelationGetRelid(partition));
11963 :
11964 : /*
11965 : * Like the constraint, attach partition's "check" triggers to the
11966 : * corresponding parent triggers if the constraint is ENFORCED. NOT
11967 : * ENFORCED constraints do not have these triggers.
11968 : */
11969 108 : if (parentConstrIsEnforced)
11970 : {
11971 : Oid insertTriggerOid,
11972 : updateTriggerOid;
11973 :
11974 100 : GetForeignKeyCheckTriggers(trigrel,
11975 : partConstrOid, partConstrFrelid, partConstrRelid,
11976 : &insertTriggerOid, &updateTriggerOid);
11977 : Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
11978 100 : TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
11979 : RelationGetRelid(partition));
11980 : Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
11981 100 : TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
11982 : RelationGetRelid(partition));
11983 : }
11984 :
11985 : /*
11986 : * We updated this pg_constraint row above to set its parent; validating
11987 : * it will cause its convalidated flag to change, so we need CCI here. In
11988 : * addition, we need it unconditionally for the rare case where the parent
11989 : * table has *two* identical constraints; when reaching this function for
11990 : * the second one, we must have made our changes visible, otherwise we
11991 : * would try to attach both to this one.
11992 : */
11993 108 : CommandCounterIncrement();
11994 :
11995 : /* If validation is needed, put it in the queue now. */
11996 108 : if (queueValidation)
11997 : {
11998 : Relation conrel;
11999 : Oid confrelid;
12000 :
12001 12 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12002 :
12003 12 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
12004 12 : if (!HeapTupleIsValid(partcontup))
12005 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
12006 :
12007 12 : confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
12008 :
12009 : /* Use the same lock as for AT_ValidateConstraint */
12010 12 : QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
12011 : partcontup, ShareUpdateExclusiveLock);
12012 12 : ReleaseSysCache(partcontup);
12013 12 : table_close(conrel, RowExclusiveLock);
12014 : }
12015 108 : }
12016 :
12017 : /*
12018 : * RemoveInheritedConstraint
12019 : *
12020 : * Removes the constraint and its associated trigger from the specified
12021 : * relation, which inherited the given constraint.
12022 : */
12023 : static void
12024 24 : RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
12025 : Oid conrelid)
12026 : {
12027 : ObjectAddresses *objs;
12028 : HeapTuple consttup;
12029 : ScanKeyData key;
12030 : SysScanDesc scan;
12031 : HeapTuple trigtup;
12032 :
12033 24 : ScanKeyInit(&key,
12034 : Anum_pg_constraint_conrelid,
12035 : BTEqualStrategyNumber, F_OIDEQ,
12036 : ObjectIdGetDatum(conrelid));
12037 :
12038 24 : scan = systable_beginscan(conrel,
12039 : ConstraintRelidTypidNameIndexId,
12040 : true, NULL, 1, &key);
12041 24 : objs = new_object_addresses();
12042 216 : while ((consttup = systable_getnext(scan)) != NULL)
12043 : {
12044 192 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
12045 :
12046 192 : if (conform->conparentid != conoid)
12047 140 : continue;
12048 : else
12049 : {
12050 : ObjectAddress addr;
12051 : SysScanDesc scan2;
12052 : ScanKeyData key2;
12053 : int n PG_USED_FOR_ASSERTS_ONLY;
12054 :
12055 52 : ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
12056 52 : add_exact_object_address(&addr, objs);
12057 :
12058 : /*
12059 : * First we must delete the dependency record that binds the
12060 : * constraint records together.
12061 : */
12062 52 : n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
12063 : conform->oid,
12064 : DEPENDENCY_INTERNAL,
12065 : ConstraintRelationId,
12066 : conoid);
12067 : Assert(n == 1); /* actually only one is expected */
12068 :
12069 : /*
12070 : * Now search for the triggers for this constraint and set them up
12071 : * for deletion too
12072 : */
12073 52 : ScanKeyInit(&key2,
12074 : Anum_pg_trigger_tgconstraint,
12075 : BTEqualStrategyNumber, F_OIDEQ,
12076 : ObjectIdGetDatum(conform->oid));
12077 52 : scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
12078 : true, NULL, 1, &key2);
12079 156 : while ((trigtup = systable_getnext(scan2)) != NULL)
12080 : {
12081 104 : ObjectAddressSet(addr, TriggerRelationId,
12082 : ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
12083 104 : add_exact_object_address(&addr, objs);
12084 : }
12085 52 : systable_endscan(scan2);
12086 : }
12087 : }
12088 : /* make the dependency deletions visible */
12089 24 : CommandCounterIncrement();
12090 24 : performMultipleDeletions(objs, DROP_RESTRICT,
12091 : PERFORM_DELETION_INTERNAL);
12092 24 : systable_endscan(scan);
12093 24 : }
12094 :
12095 : /*
12096 : * DropForeignKeyConstraintTriggers
12097 : *
12098 : * The subroutine for tryAttachPartitionForeignKey handles the deletion of
12099 : * action triggers for the foreign key constraint.
12100 : *
12101 : * If valid confrelid and conrelid values are not provided, the respective
12102 : * trigger check will be skipped, and the trigger will be considered for
12103 : * removal.
12104 : */
12105 : static void
12106 160 : DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
12107 : Oid conrelid)
12108 : {
12109 : ScanKeyData key;
12110 : SysScanDesc scan;
12111 : HeapTuple trigtup;
12112 :
12113 160 : ScanKeyInit(&key,
12114 : Anum_pg_trigger_tgconstraint,
12115 : BTEqualStrategyNumber, F_OIDEQ,
12116 : ObjectIdGetDatum(conoid));
12117 160 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12118 : NULL, 1, &key);
12119 696 : while ((trigtup = systable_getnext(scan)) != NULL)
12120 : {
12121 536 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12122 : ObjectAddress trigger;
12123 :
12124 : /* Invalid if trigger is not for a referential integrity constraint */
12125 536 : if (!OidIsValid(trgform->tgconstrrelid))
12126 200 : continue;
12127 536 : if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
12128 200 : continue;
12129 336 : if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
12130 0 : continue;
12131 :
12132 : /* We should be dropping trigger related to foreign key constraint */
12133 : Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
12134 : trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
12135 : trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
12136 : trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
12137 : trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
12138 : trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
12139 : trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
12140 : trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
12141 : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
12142 : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
12143 : trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
12144 : trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
12145 :
12146 : /*
12147 : * The constraint is originally set up to contain this trigger as an
12148 : * implementation object, so there's a dependency record that links
12149 : * the two; however, since the trigger is no longer needed, we remove
12150 : * the dependency link in order to be able to drop the trigger while
12151 : * keeping the constraint intact.
12152 : */
12153 336 : deleteDependencyRecordsFor(TriggerRelationId,
12154 : trgform->oid,
12155 : false);
12156 : /* make dependency deletion visible to performDeletion */
12157 336 : CommandCounterIncrement();
12158 336 : ObjectAddressSet(trigger, TriggerRelationId,
12159 : trgform->oid);
12160 336 : performDeletion(&trigger, DROP_RESTRICT, 0);
12161 : /* make trigger drop visible, in case the loop iterates */
12162 336 : CommandCounterIncrement();
12163 : }
12164 :
12165 160 : systable_endscan(scan);
12166 160 : }
12167 :
12168 : /*
12169 : * GetForeignKeyActionTriggers
12170 : * Returns delete and update "action" triggers of the given relation
12171 : * belonging to the given constraint
12172 : */
12173 : static void
12174 128 : GetForeignKeyActionTriggers(Relation trigrel,
12175 : Oid conoid, Oid confrelid, Oid conrelid,
12176 : Oid *deleteTriggerOid,
12177 : Oid *updateTriggerOid)
12178 : {
12179 : ScanKeyData key;
12180 : SysScanDesc scan;
12181 : HeapTuple trigtup;
12182 :
12183 128 : *deleteTriggerOid = *updateTriggerOid = InvalidOid;
12184 128 : ScanKeyInit(&key,
12185 : Anum_pg_trigger_tgconstraint,
12186 : BTEqualStrategyNumber, F_OIDEQ,
12187 : ObjectIdGetDatum(conoid));
12188 :
12189 128 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12190 : NULL, 1, &key);
12191 262 : while ((trigtup = systable_getnext(scan)) != NULL)
12192 : {
12193 262 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12194 :
12195 262 : if (trgform->tgconstrrelid != conrelid)
12196 6 : continue;
12197 256 : if (trgform->tgrelid != confrelid)
12198 0 : continue;
12199 : /* Only ever look at "action" triggers on the PK side. */
12200 256 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
12201 0 : continue;
12202 256 : if (TRIGGER_FOR_DELETE(trgform->tgtype))
12203 : {
12204 : Assert(*deleteTriggerOid == InvalidOid);
12205 128 : *deleteTriggerOid = trgform->oid;
12206 : }
12207 128 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12208 : {
12209 : Assert(*updateTriggerOid == InvalidOid);
12210 128 : *updateTriggerOid = trgform->oid;
12211 : }
12212 : #ifndef USE_ASSERT_CHECKING
12213 : /* In an assert-enabled build, continue looking to find duplicates */
12214 256 : if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
12215 128 : break;
12216 : #endif
12217 : }
12218 :
12219 128 : if (!OidIsValid(*deleteTriggerOid))
12220 0 : elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
12221 : conoid);
12222 128 : if (!OidIsValid(*updateTriggerOid))
12223 0 : elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
12224 : conoid);
12225 :
12226 128 : systable_endscan(scan);
12227 128 : }
12228 :
12229 : /*
12230 : * GetForeignKeyCheckTriggers
12231 : * Returns insert and update "check" triggers of the given relation
12232 : * belonging to the given constraint
12233 : */
12234 : static void
12235 551 : GetForeignKeyCheckTriggers(Relation trigrel,
12236 : Oid conoid, Oid confrelid, Oid conrelid,
12237 : Oid *insertTriggerOid,
12238 : Oid *updateTriggerOid)
12239 : {
12240 : ScanKeyData key;
12241 : SysScanDesc scan;
12242 : HeapTuple trigtup;
12243 :
12244 551 : *insertTriggerOid = *updateTriggerOid = InvalidOid;
12245 551 : ScanKeyInit(&key,
12246 : Anum_pg_trigger_tgconstraint,
12247 : BTEqualStrategyNumber, F_OIDEQ,
12248 : ObjectIdGetDatum(conoid));
12249 :
12250 551 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12251 : NULL, 1, &key);
12252 1768 : while ((trigtup = systable_getnext(scan)) != NULL)
12253 : {
12254 1768 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12255 :
12256 1768 : if (trgform->tgconstrrelid != confrelid)
12257 594 : continue;
12258 1174 : if (trgform->tgrelid != conrelid)
12259 0 : continue;
12260 : /* Only ever look at "check" triggers on the FK side. */
12261 1174 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
12262 72 : continue;
12263 1102 : if (TRIGGER_FOR_INSERT(trgform->tgtype))
12264 : {
12265 : Assert(*insertTriggerOid == InvalidOid);
12266 551 : *insertTriggerOid = trgform->oid;
12267 : }
12268 551 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12269 : {
12270 : Assert(*updateTriggerOid == InvalidOid);
12271 551 : *updateTriggerOid = trgform->oid;
12272 : }
12273 : #ifndef USE_ASSERT_CHECKING
12274 : /* In an assert-enabled build, continue looking to find duplicates. */
12275 1102 : if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
12276 551 : break;
12277 : #endif
12278 : }
12279 :
12280 551 : if (!OidIsValid(*insertTriggerOid))
12281 0 : elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
12282 : conoid);
12283 551 : if (!OidIsValid(*updateTriggerOid))
12284 0 : elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
12285 : conoid);
12286 :
12287 551 : systable_endscan(scan);
12288 551 : }
12289 :
12290 : /*
12291 : * ALTER TABLE ALTER CONSTRAINT
12292 : *
12293 : * Update the attributes of a constraint.
12294 : *
12295 : * Currently works for Foreign Key, Check, and not null constraints.
12296 : *
12297 : * If the constraint is modified, returns its address; otherwise, return
12298 : * InvalidObjectAddress.
12299 : */
12300 : static ObjectAddress
12301 296 : ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
12302 : bool recurse, LOCKMODE lockmode)
12303 : {
12304 : Relation conrel;
12305 : Relation tgrel;
12306 : SysScanDesc scan;
12307 : ScanKeyData skey[3];
12308 : HeapTuple contuple;
12309 : Form_pg_constraint currcon;
12310 : ObjectAddress address;
12311 :
12312 : /*
12313 : * Disallow altering ONLY a partitioned table, as it would make no sense.
12314 : * This is okay for legacy inheritance.
12315 : */
12316 296 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
12317 0 : ereport(ERROR,
12318 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12319 : errmsg("constraint must be altered in child tables too"),
12320 : errhint("Do not specify the ONLY keyword."));
12321 :
12322 :
12323 296 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12324 296 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
12325 :
12326 : /*
12327 : * Find and check the target constraint
12328 : */
12329 296 : ScanKeyInit(&skey[0],
12330 : Anum_pg_constraint_conrelid,
12331 : BTEqualStrategyNumber, F_OIDEQ,
12332 : ObjectIdGetDatum(RelationGetRelid(rel)));
12333 296 : ScanKeyInit(&skey[1],
12334 : Anum_pg_constraint_contypid,
12335 : BTEqualStrategyNumber, F_OIDEQ,
12336 : ObjectIdGetDatum(InvalidOid));
12337 296 : ScanKeyInit(&skey[2],
12338 : Anum_pg_constraint_conname,
12339 : BTEqualStrategyNumber, F_NAMEEQ,
12340 296 : CStringGetDatum(cmdcon->conname));
12341 296 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12342 : true, NULL, 3, skey);
12343 :
12344 : /* There can be at most one matching row */
12345 296 : if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
12346 4 : ereport(ERROR,
12347 : (errcode(ERRCODE_UNDEFINED_OBJECT),
12348 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12349 : cmdcon->conname, RelationGetRelationName(rel))));
12350 :
12351 292 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12352 292 : if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
12353 0 : ereport(ERROR,
12354 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12355 : errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
12356 : cmdcon->conname, RelationGetRelationName(rel))));
12357 292 : if (cmdcon->alterEnforceability &&
12358 156 : (currcon->contype != CONSTRAINT_FOREIGN && currcon->contype != CONSTRAINT_CHECK))
12359 8 : ereport(ERROR,
12360 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12361 : errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
12362 : cmdcon->conname, RelationGetRelationName(rel)),
12363 : errhint("Only foreign key and check constraints can change enforceability.")));
12364 284 : if (cmdcon->alterInheritability &&
12365 64 : currcon->contype != CONSTRAINT_NOTNULL)
12366 16 : ereport(ERROR,
12367 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
12368 : errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
12369 : cmdcon->conname, RelationGetRelationName(rel)));
12370 268 : if (cmdcon->alterInheritability &&
12371 48 : cmdcon->noinherit && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12372 4 : ereport(ERROR,
12373 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12374 : errmsg("not-null constraint \"%s\" on partitioned table \"%s\" cannot be NO INHERIT",
12375 : cmdcon->conname, RelationGetRelationName(rel)));
12376 :
12377 : /* Refuse to modify inheritability of inherited constraints */
12378 264 : if (cmdcon->alterInheritability &&
12379 44 : cmdcon->noinherit && currcon->coninhcount > 0)
12380 4 : ereport(ERROR,
12381 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12382 : errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
12383 : NameStr(currcon->conname),
12384 : RelationGetRelationName(rel)));
12385 :
12386 : /*
12387 : * If it's not the topmost constraint, raise an error.
12388 : *
12389 : * Altering a non-topmost constraint leaves some triggers untouched, since
12390 : * they are not directly connected to this constraint; also, pg_dump would
12391 : * ignore the deferrability status of the individual constraint, since it
12392 : * only dumps topmost constraints. Avoid these problems by refusing this
12393 : * operation and telling the user to alter the parent constraint instead.
12394 : */
12395 260 : if (OidIsValid(currcon->conparentid))
12396 : {
12397 : HeapTuple tp;
12398 8 : Oid parent = currcon->conparentid;
12399 8 : char *ancestorname = NULL;
12400 8 : char *ancestortable = NULL;
12401 :
12402 : /* Loop to find the topmost constraint */
12403 16 : while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
12404 : {
12405 16 : Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
12406 :
12407 : /* If no parent, this is the constraint we want */
12408 16 : if (!OidIsValid(contup->conparentid))
12409 : {
12410 8 : ancestorname = pstrdup(NameStr(contup->conname));
12411 8 : ancestortable = get_rel_name(contup->conrelid);
12412 8 : ReleaseSysCache(tp);
12413 8 : break;
12414 : }
12415 :
12416 8 : parent = contup->conparentid;
12417 8 : ReleaseSysCache(tp);
12418 : }
12419 :
12420 8 : ereport(ERROR,
12421 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12422 : errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
12423 : cmdcon->conname, RelationGetRelationName(rel)),
12424 : ancestorname && ancestortable ?
12425 : errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
12426 : cmdcon->conname, ancestorname, ancestortable) : 0,
12427 : errhint("You may alter the constraint it derives from instead.")));
12428 : }
12429 :
12430 252 : address = InvalidObjectAddress;
12431 :
12432 : /*
12433 : * Do the actual catalog work, and recurse if necessary.
12434 : */
12435 252 : if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
12436 : contuple, recurse, lockmode))
12437 232 : ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
12438 :
12439 240 : systable_endscan(scan);
12440 :
12441 240 : table_close(tgrel, RowExclusiveLock);
12442 240 : table_close(conrel, RowExclusiveLock);
12443 :
12444 240 : return address;
12445 : }
12446 :
12447 : /*
12448 : * A subroutine of ATExecAlterConstraint that calls the respective routines for
12449 : * altering constraint's enforceability, deferrability or inheritability.
12450 : */
12451 : static bool
12452 252 : ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
12453 : Relation conrel, Relation tgrel, Relation rel,
12454 : HeapTuple contuple, bool recurse,
12455 : LOCKMODE lockmode)
12456 : {
12457 : Form_pg_constraint currcon;
12458 252 : bool changed = false;
12459 252 : List *otherrelids = NIL;
12460 :
12461 252 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12462 :
12463 : /*
12464 : * Do the catalog work for the enforceability or deferrability change,
12465 : * recurse if necessary.
12466 : *
12467 : * Note that even if deferrability is requested to be altered along with
12468 : * enforceability, we don't need to explicitly update multiple entries in
12469 : * pg_trigger related to deferrability.
12470 : *
12471 : * Modifying foreign key enforceability involves either creating or
12472 : * dropping the trigger, during which the deferrability setting will be
12473 : * adjusted automatically.
12474 : */
12475 252 : if (cmdcon->alterEnforceability)
12476 : {
12477 148 : if (currcon->contype == CONSTRAINT_FOREIGN)
12478 60 : changed = ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
12479 : currcon->conrelid,
12480 : currcon->confrelid,
12481 : contuple, lockmode,
12482 : InvalidOid, InvalidOid,
12483 : InvalidOid, InvalidOid);
12484 88 : else if (currcon->contype == CONSTRAINT_CHECK)
12485 88 : changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel,
12486 : contuple, recurse, false,
12487 : lockmode);
12488 : }
12489 168 : else if (cmdcon->alterDeferrability &&
12490 64 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
12491 : contuple, recurse, &otherrelids,
12492 : lockmode))
12493 : {
12494 : /*
12495 : * AlterConstrUpdateConstraintEntry already invalidated relcache for
12496 : * the relations having the constraint itself; here we also invalidate
12497 : * for relations that have any triggers that are part of the
12498 : * constraint.
12499 : */
12500 204 : foreach_oid(relid, otherrelids)
12501 76 : CacheInvalidateRelcacheByRelid(relid);
12502 :
12503 64 : changed = true;
12504 : }
12505 :
12506 : /*
12507 : * Do the catalog work for the inheritability change.
12508 : */
12509 280 : if (cmdcon->alterInheritability &&
12510 40 : ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
12511 : lockmode))
12512 36 : changed = true;
12513 :
12514 240 : return changed;
12515 : }
12516 :
12517 : /*
12518 : * Returns true if the foreign key constraint's enforceability is altered.
12519 : *
12520 : * Depending on whether the constraint is being set to ENFORCED or NOT
12521 : * ENFORCED, it creates or drops the trigger accordingly.
12522 : *
12523 : * Note that we must recurse even when trying to change a constraint to not
12524 : * enforced if it is already not enforced, in case descendant constraints
12525 : * might be enforced and need to be changed to not enforced. Conversely, we
12526 : * should do nothing if a constraint is being set to enforced and is already
12527 : * enforced, as descendant constraints cannot be different in that case.
12528 : */
12529 : static bool
12530 128 : ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12531 : Relation conrel, Relation tgrel,
12532 : Oid fkrelid, Oid pkrelid,
12533 : HeapTuple contuple, LOCKMODE lockmode,
12534 : Oid ReferencedParentDelTrigger,
12535 : Oid ReferencedParentUpdTrigger,
12536 : Oid ReferencingParentInsTrigger,
12537 : Oid ReferencingParentUpdTrigger)
12538 : {
12539 : Form_pg_constraint currcon;
12540 : Oid conoid;
12541 : Relation rel;
12542 128 : bool changed = false;
12543 :
12544 : /* Since this function recurses, it could be driven to stack overflow */
12545 128 : check_stack_depth();
12546 :
12547 : Assert(cmdcon->alterEnforceability);
12548 :
12549 128 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12550 128 : conoid = currcon->oid;
12551 :
12552 : /* Should be foreign key constraint */
12553 : Assert(currcon->contype == CONSTRAINT_FOREIGN);
12554 :
12555 128 : rel = table_open(currcon->conrelid, lockmode);
12556 :
12557 128 : if (currcon->conenforced != cmdcon->is_enforced)
12558 : {
12559 124 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12560 124 : changed = true;
12561 : }
12562 :
12563 : /* Drop triggers */
12564 128 : if (!cmdcon->is_enforced)
12565 : {
12566 : /*
12567 : * When setting a constraint to NOT ENFORCED, the constraint triggers
12568 : * need to be dropped. Therefore, we must process the child relations
12569 : * first, followed by the parent, to account for dependencies.
12570 : */
12571 92 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12572 40 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12573 12 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12574 : fkrelid, pkrelid, contuple,
12575 : lockmode, InvalidOid, InvalidOid,
12576 : InvalidOid, InvalidOid);
12577 :
12578 : /* Drop all the triggers */
12579 52 : DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
12580 : }
12581 76 : else if (changed) /* Create triggers */
12582 : {
12583 76 : Oid ReferencedDelTriggerOid = InvalidOid,
12584 76 : ReferencedUpdTriggerOid = InvalidOid,
12585 76 : ReferencingInsTriggerOid = InvalidOid,
12586 76 : ReferencingUpdTriggerOid = InvalidOid;
12587 :
12588 : /* Prepare the minimal information required for trigger creation. */
12589 76 : Constraint *fkconstraint = makeNode(Constraint);
12590 :
12591 76 : fkconstraint->conname = pstrdup(NameStr(currcon->conname));
12592 76 : fkconstraint->fk_matchtype = currcon->confmatchtype;
12593 76 : fkconstraint->fk_upd_action = currcon->confupdtype;
12594 76 : fkconstraint->fk_del_action = currcon->confdeltype;
12595 76 : fkconstraint->deferrable = currcon->condeferrable;
12596 76 : fkconstraint->initdeferred = currcon->condeferred;
12597 :
12598 : /* Create referenced triggers */
12599 76 : if (currcon->conrelid == fkrelid)
12600 48 : createForeignKeyActionTriggers(currcon->conrelid,
12601 : currcon->confrelid,
12602 : fkconstraint,
12603 : conoid,
12604 : currcon->conindid,
12605 : ReferencedParentDelTrigger,
12606 : ReferencedParentUpdTrigger,
12607 : &ReferencedDelTriggerOid,
12608 : &ReferencedUpdTriggerOid);
12609 :
12610 : /* Create referencing triggers */
12611 76 : if (currcon->confrelid == pkrelid)
12612 64 : createForeignKeyCheckTriggers(currcon->conrelid,
12613 : pkrelid,
12614 : fkconstraint,
12615 : conoid,
12616 : currcon->conindid,
12617 : ReferencingParentInsTrigger,
12618 : ReferencingParentUpdTrigger,
12619 : &ReferencingInsTriggerOid,
12620 : &ReferencingUpdTriggerOid);
12621 :
12622 : /*
12623 : * Tell Phase 3 to check that the constraint is satisfied by existing
12624 : * rows. Only applies to leaf partitions, and (for constraints that
12625 : * reference a partitioned table) only if this is not one of the
12626 : * pg_constraint rows that exist solely to support action triggers.
12627 : */
12628 76 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12629 64 : currcon->confrelid == pkrelid)
12630 : {
12631 : AlteredTableInfo *tab;
12632 : NewConstraint *newcon;
12633 :
12634 52 : newcon = palloc0_object(NewConstraint);
12635 52 : newcon->name = fkconstraint->conname;
12636 52 : newcon->contype = CONSTR_FOREIGN;
12637 52 : newcon->refrelid = currcon->confrelid;
12638 52 : newcon->refindid = currcon->conindid;
12639 52 : newcon->conid = currcon->oid;
12640 52 : newcon->qual = (Node *) fkconstraint;
12641 :
12642 : /* Find or create work queue entry for this table */
12643 52 : tab = ATGetQueueEntry(wqueue, rel);
12644 52 : tab->constraints = lappend(tab->constraints, newcon);
12645 : }
12646 :
12647 : /*
12648 : * If the table at either end of the constraint is partitioned, we
12649 : * need to recurse and create triggers for each constraint that is a
12650 : * child of this one.
12651 : */
12652 140 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12653 64 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12654 20 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12655 : fkrelid, pkrelid, contuple,
12656 : lockmode,
12657 : ReferencedDelTriggerOid,
12658 : ReferencedUpdTriggerOid,
12659 : ReferencingInsTriggerOid,
12660 : ReferencingUpdTriggerOid);
12661 : }
12662 :
12663 128 : table_close(rel, NoLock);
12664 :
12665 128 : return changed;
12666 : }
12667 :
12668 : /*
12669 : * Returns true if the CHECK constraint's enforceability is altered.
12670 : */
12671 : static bool
12672 236 : ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12673 : Relation conrel, HeapTuple contuple,
12674 : bool recurse, bool recursing, LOCKMODE lockmode)
12675 : {
12676 : Form_pg_constraint currcon;
12677 : Relation rel;
12678 236 : bool changed = false;
12679 236 : List *children = NIL;
12680 :
12681 : /* Since this function recurses, it could be driven to stack overflow */
12682 236 : check_stack_depth();
12683 :
12684 : Assert(cmdcon->alterEnforceability);
12685 :
12686 236 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12687 :
12688 : Assert(currcon->contype == CONSTRAINT_CHECK);
12689 :
12690 : /*
12691 : * Parent relation already locked by caller, children will be locked by
12692 : * find_all_inheritors. So NoLock is fine here.
12693 : */
12694 236 : rel = table_open(currcon->conrelid, NoLock);
12695 :
12696 236 : if (currcon->conenforced != cmdcon->is_enforced)
12697 : {
12698 196 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12699 196 : changed = true;
12700 : }
12701 :
12702 : /*
12703 : * Note that we must recurse even when trying to change a check constraint
12704 : * to not enforced if it is already not enforced, in case descendant
12705 : * constraints might be enforced and need to be changed to not enforced.
12706 : * Conversely, we should do nothing if a constraint is being set to
12707 : * enforced and is already enforced, as descendant constraints cannot be
12708 : * different in that case.
12709 : */
12710 236 : if (!cmdcon->is_enforced || changed)
12711 : {
12712 : /*
12713 : * If we're recursing, the parent has already done this, so skip it.
12714 : * Also, if the constraint is a NO INHERIT constraint, we shouldn't
12715 : * try to look for it in the children.
12716 : */
12717 220 : if (!recursing && !currcon->connoinherit)
12718 84 : children = find_all_inheritors(RelationGetRelid(rel),
12719 : lockmode, NULL);
12720 :
12721 664 : foreach_oid(childoid, children)
12722 : {
12723 240 : if (childoid == RelationGetRelid(rel))
12724 84 : continue;
12725 :
12726 : /*
12727 : * If we are told not to recurse, there had better not be any
12728 : * child tables, because we can't change constraint enforceability
12729 : * on the parent unless we have changed enforceability for all
12730 : * child.
12731 : */
12732 156 : if (!recurse)
12733 8 : ereport(ERROR,
12734 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12735 : errmsg("constraint must be altered on child tables too"),
12736 : errhint("Do not specify the ONLY keyword."));
12737 :
12738 148 : AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel,
12739 : childoid, false, true,
12740 : lockmode);
12741 : }
12742 : }
12743 :
12744 : /*
12745 : * Tell Phase 3 to check that the constraint is satisfied by existing
12746 : * rows. We only need do this when altering the constraint from NOT
12747 : * ENFORCED to ENFORCED.
12748 : */
12749 228 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12750 180 : !currcon->conenforced &&
12751 128 : cmdcon->is_enforced)
12752 : {
12753 : AlteredTableInfo *tab;
12754 : NewConstraint *newcon;
12755 : Datum val;
12756 : char *conbin;
12757 :
12758 116 : newcon = palloc0_object(NewConstraint);
12759 116 : newcon->name = pstrdup(NameStr(currcon->conname));
12760 116 : newcon->contype = CONSTR_CHECK;
12761 :
12762 116 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
12763 : Anum_pg_constraint_conbin);
12764 116 : conbin = TextDatumGetCString(val);
12765 116 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
12766 :
12767 : /* Find or create work queue entry for this table */
12768 116 : tab = ATGetQueueEntry(wqueue, rel);
12769 116 : tab->constraints = lappend(tab->constraints, newcon);
12770 : }
12771 :
12772 228 : table_close(rel, NoLock);
12773 :
12774 228 : return changed;
12775 : }
12776 :
12777 : /*
12778 : * Invokes ATExecAlterCheckConstrEnforceability for each CHECK constraint that
12779 : * is a child of the specified constraint.
12780 : *
12781 : * We rely on the parent and child tables having identical CHECK constraint
12782 : * names to retrieve the child's pg_constraint tuple.
12783 : *
12784 : * The arguments to this function have the same meaning as the arguments to
12785 : * ATExecAlterCheckConstrEnforceability.
12786 : */
12787 : static void
12788 148 : AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12789 : Relation conrel, Oid conrelid,
12790 : bool recurse, bool recursing,
12791 : LOCKMODE lockmode)
12792 : {
12793 : SysScanDesc pscan;
12794 : HeapTuple childtup;
12795 : ScanKeyData skey[3];
12796 :
12797 148 : ScanKeyInit(&skey[0],
12798 : Anum_pg_constraint_conrelid,
12799 : BTEqualStrategyNumber, F_OIDEQ,
12800 : ObjectIdGetDatum(conrelid));
12801 148 : ScanKeyInit(&skey[1],
12802 : Anum_pg_constraint_contypid,
12803 : BTEqualStrategyNumber, F_OIDEQ,
12804 : ObjectIdGetDatum(InvalidOid));
12805 148 : ScanKeyInit(&skey[2],
12806 : Anum_pg_constraint_conname,
12807 : BTEqualStrategyNumber, F_NAMEEQ,
12808 148 : CStringGetDatum(cmdcon->conname));
12809 :
12810 148 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
12811 : NULL, 3, skey);
12812 :
12813 148 : if (!HeapTupleIsValid(childtup = systable_getnext(pscan)))
12814 0 : ereport(ERROR,
12815 : errcode(ERRCODE_UNDEFINED_OBJECT),
12816 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12817 : cmdcon->conname, get_rel_name(conrelid)));
12818 :
12819 148 : ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup,
12820 : recurse, recursing, lockmode);
12821 :
12822 148 : systable_endscan(pscan);
12823 148 : }
12824 :
12825 : /*
12826 : * Returns true if the constraint's deferrability is altered.
12827 : *
12828 : * *otherrelids is appended OIDs of relations containing affected triggers.
12829 : *
12830 : * Note that we must recurse even when the values are correct, in case
12831 : * indirect descendants have had their constraints altered locally.
12832 : * (This could be avoided if we forbade altering constraints in partitions
12833 : * but existing releases don't do that.)
12834 : */
12835 : static bool
12836 108 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
12837 : Relation conrel, Relation tgrel, Relation rel,
12838 : HeapTuple contuple, bool recurse,
12839 : List **otherrelids, LOCKMODE lockmode)
12840 : {
12841 : Form_pg_constraint currcon;
12842 : Oid refrelid;
12843 108 : bool changed = false;
12844 :
12845 : /* since this function recurses, it could be driven to stack overflow */
12846 108 : check_stack_depth();
12847 :
12848 : Assert(cmdcon->alterDeferrability);
12849 :
12850 108 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12851 108 : refrelid = currcon->confrelid;
12852 :
12853 : /* Should be foreign key constraint */
12854 : Assert(currcon->contype == CONSTRAINT_FOREIGN);
12855 :
12856 : /*
12857 : * If called to modify a constraint that's already in the desired state,
12858 : * silently do nothing.
12859 : */
12860 108 : if (currcon->condeferrable != cmdcon->deferrable ||
12861 4 : currcon->condeferred != cmdcon->initdeferred)
12862 : {
12863 108 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12864 108 : changed = true;
12865 :
12866 : /*
12867 : * Now we need to update the multiple entries in pg_trigger that
12868 : * implement the constraint.
12869 : */
12870 108 : AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
12871 108 : cmdcon->deferrable,
12872 108 : cmdcon->initdeferred, otherrelids);
12873 : }
12874 :
12875 : /*
12876 : * If the table at either end of the constraint is partitioned, we need to
12877 : * handle every constraint that is a child of this one.
12878 : */
12879 108 : if (recurse && changed &&
12880 200 : (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12881 92 : get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
12882 28 : AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
12883 : contuple, recurse, otherrelids,
12884 : lockmode);
12885 :
12886 108 : return changed;
12887 : }
12888 :
12889 : /*
12890 : * Returns true if the constraint's inheritability is altered.
12891 : */
12892 : static bool
12893 40 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
12894 : Relation conrel, Relation rel,
12895 : HeapTuple contuple, LOCKMODE lockmode)
12896 : {
12897 : Form_pg_constraint currcon;
12898 : AttrNumber colNum;
12899 : char *colName;
12900 : List *children;
12901 :
12902 : Assert(cmdcon->alterInheritability);
12903 :
12904 40 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12905 :
12906 : /* The current implementation only works for NOT NULL constraints */
12907 : Assert(currcon->contype == CONSTRAINT_NOTNULL);
12908 :
12909 : /*
12910 : * If called to modify a constraint that's already in the desired state,
12911 : * silently do nothing.
12912 : */
12913 40 : if (cmdcon->noinherit == currcon->connoinherit)
12914 0 : return false;
12915 :
12916 40 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12917 40 : CommandCounterIncrement();
12918 :
12919 : /* Fetch the column number and name */
12920 40 : colNum = extractNotNullColumn(contuple);
12921 40 : colName = get_attname(currcon->conrelid, colNum, false);
12922 :
12923 : /*
12924 : * Propagate the change to children. For this subcommand type we don't
12925 : * recursively affect children, just the immediate level.
12926 : */
12927 40 : children = find_inheritance_children(RelationGetRelid(rel),
12928 : lockmode);
12929 128 : foreach_oid(childoid, children)
12930 : {
12931 : ObjectAddress addr;
12932 :
12933 56 : if (cmdcon->noinherit)
12934 : {
12935 : HeapTuple childtup;
12936 : Form_pg_constraint childcon;
12937 :
12938 20 : childtup = findNotNullConstraint(childoid, colName);
12939 20 : if (!childtup)
12940 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
12941 : colName, childoid);
12942 20 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
12943 : Assert(childcon->coninhcount > 0);
12944 20 : childcon->coninhcount--;
12945 20 : childcon->conislocal = true;
12946 20 : CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
12947 20 : heap_freetuple(childtup);
12948 : }
12949 : else
12950 : {
12951 36 : Relation childrel = table_open(childoid, NoLock);
12952 :
12953 36 : addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
12954 : colName, true, true, lockmode);
12955 32 : if (OidIsValid(addr.objectId))
12956 32 : CommandCounterIncrement();
12957 32 : table_close(childrel, NoLock);
12958 : }
12959 : }
12960 :
12961 36 : return true;
12962 : }
12963 :
12964 : /*
12965 : * A subroutine of ATExecAlterConstrDeferrability that updated constraint
12966 : * trigger's deferrability.
12967 : *
12968 : * The arguments to this function have the same meaning as the arguments to
12969 : * ATExecAlterConstrDeferrability.
12970 : */
12971 : static void
12972 108 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
12973 : bool deferrable, bool initdeferred,
12974 : List **otherrelids)
12975 : {
12976 : HeapTuple tgtuple;
12977 : ScanKeyData tgkey;
12978 : SysScanDesc tgscan;
12979 :
12980 108 : ScanKeyInit(&tgkey,
12981 : Anum_pg_trigger_tgconstraint,
12982 : BTEqualStrategyNumber, F_OIDEQ,
12983 : ObjectIdGetDatum(conoid));
12984 108 : tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
12985 : NULL, 1, &tgkey);
12986 420 : while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
12987 : {
12988 312 : Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
12989 : Form_pg_trigger copy_tg;
12990 : HeapTuple tgCopyTuple;
12991 :
12992 : /*
12993 : * Remember OIDs of other relation(s) involved in FK constraint.
12994 : * (Note: it's likely that we could skip forcing a relcache inval for
12995 : * other rels that don't have a trigger whose properties change, but
12996 : * let's be conservative.)
12997 : */
12998 312 : if (tgform->tgrelid != RelationGetRelid(rel))
12999 152 : *otherrelids = list_append_unique_oid(*otherrelids,
13000 : tgform->tgrelid);
13001 :
13002 : /*
13003 : * Update enable status and deferrability of RI_FKey_noaction_del,
13004 : * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
13005 : * triggers, but not others; see createForeignKeyActionTriggers and
13006 : * CreateFKCheckTrigger.
13007 : */
13008 312 : if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
13009 248 : tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
13010 172 : tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
13011 92 : tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
13012 12 : continue;
13013 :
13014 300 : tgCopyTuple = heap_copytuple(tgtuple);
13015 300 : copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
13016 :
13017 300 : copy_tg->tgdeferrable = deferrable;
13018 300 : copy_tg->tginitdeferred = initdeferred;
13019 300 : CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
13020 :
13021 300 : InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
13022 :
13023 300 : heap_freetuple(tgCopyTuple);
13024 : }
13025 :
13026 108 : systable_endscan(tgscan);
13027 108 : }
13028 :
13029 : /*
13030 : * Invokes ATExecAlterFKConstrEnforceability for each foreign key constraint
13031 : * that is a child of the specified constraint.
13032 : *
13033 : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13034 : * list of child relations and recursing; instead it uses the conparentid
13035 : * relationships. This may need to be reconsidered.
13036 : *
13037 : * The arguments to this function have the same meaning as the arguments to
13038 : * ATExecAlterFKConstrEnforceability.
13039 : */
13040 : static void
13041 32 : AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13042 : Relation conrel, Relation tgrel,
13043 : Oid fkrelid, Oid pkrelid,
13044 : HeapTuple contuple, LOCKMODE lockmode,
13045 : Oid ReferencedParentDelTrigger,
13046 : Oid ReferencedParentUpdTrigger,
13047 : Oid ReferencingParentInsTrigger,
13048 : Oid ReferencingParentUpdTrigger)
13049 : {
13050 : Form_pg_constraint currcon;
13051 : Oid conoid;
13052 : ScanKeyData pkey;
13053 : SysScanDesc pscan;
13054 : HeapTuple childtup;
13055 :
13056 32 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13057 32 : conoid = currcon->oid;
13058 :
13059 32 : ScanKeyInit(&pkey,
13060 : Anum_pg_constraint_conparentid,
13061 : BTEqualStrategyNumber, F_OIDEQ,
13062 : ObjectIdGetDatum(conoid));
13063 :
13064 32 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13065 : true, NULL, 1, &pkey);
13066 :
13067 100 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13068 68 : ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
13069 : pkrelid, childtup, lockmode,
13070 : ReferencedParentDelTrigger,
13071 : ReferencedParentUpdTrigger,
13072 : ReferencingParentInsTrigger,
13073 : ReferencingParentUpdTrigger);
13074 :
13075 32 : systable_endscan(pscan);
13076 32 : }
13077 :
13078 : /*
13079 : * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
13080 : * the specified constraint.
13081 : *
13082 : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13083 : * list of child relations and recursing; instead it uses the conparentid
13084 : * relationships. This may need to be reconsidered.
13085 : *
13086 : * The arguments to this function have the same meaning as the arguments to
13087 : * ATExecAlterConstrDeferrability.
13088 : */
13089 : static void
13090 28 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13091 : Relation conrel, Relation tgrel, Relation rel,
13092 : HeapTuple contuple, bool recurse,
13093 : List **otherrelids, LOCKMODE lockmode)
13094 : {
13095 : Form_pg_constraint currcon;
13096 : Oid conoid;
13097 : ScanKeyData pkey;
13098 : SysScanDesc pscan;
13099 : HeapTuple childtup;
13100 :
13101 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13102 28 : conoid = currcon->oid;
13103 :
13104 28 : ScanKeyInit(&pkey,
13105 : Anum_pg_constraint_conparentid,
13106 : BTEqualStrategyNumber, F_OIDEQ,
13107 : ObjectIdGetDatum(conoid));
13108 :
13109 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13110 : true, NULL, 1, &pkey);
13111 :
13112 72 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13113 : {
13114 44 : Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13115 : Relation childrel;
13116 :
13117 44 : childrel = table_open(childcon->conrelid, lockmode);
13118 :
13119 44 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
13120 : childtup, recurse, otherrelids, lockmode);
13121 44 : table_close(childrel, NoLock);
13122 : }
13123 :
13124 28 : systable_endscan(pscan);
13125 28 : }
13126 :
13127 : /*
13128 : * Update the constraint entry for the given ATAlterConstraint command, and
13129 : * invoke the appropriate hooks.
13130 : */
13131 : static void
13132 468 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
13133 : HeapTuple contuple)
13134 : {
13135 : HeapTuple copyTuple;
13136 : Form_pg_constraint copy_con;
13137 :
13138 : Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
13139 : cmdcon->alterInheritability);
13140 :
13141 468 : copyTuple = heap_copytuple(contuple);
13142 468 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13143 :
13144 468 : if (cmdcon->alterEnforceability)
13145 : {
13146 320 : copy_con->conenforced = cmdcon->is_enforced;
13147 :
13148 : /*
13149 : * NB: The convalidated status is irrelevant when the constraint is
13150 : * set to NOT ENFORCED, but for consistency, it should still be set
13151 : * appropriately. Similarly, if the constraint is later changed to
13152 : * ENFORCED, validation will be performed during phase 3, so it makes
13153 : * sense to mark it as valid in that case.
13154 : */
13155 320 : copy_con->convalidated = cmdcon->is_enforced;
13156 : }
13157 468 : if (cmdcon->alterDeferrability)
13158 : {
13159 112 : copy_con->condeferrable = cmdcon->deferrable;
13160 112 : copy_con->condeferred = cmdcon->initdeferred;
13161 : }
13162 468 : if (cmdcon->alterInheritability)
13163 40 : copy_con->connoinherit = cmdcon->noinherit;
13164 :
13165 468 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13166 468 : InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
13167 :
13168 : /* Make new constraint flags visible to others */
13169 468 : CacheInvalidateRelcacheByRelid(copy_con->conrelid);
13170 :
13171 468 : heap_freetuple(copyTuple);
13172 468 : }
13173 :
13174 : /*
13175 : * ALTER TABLE VALIDATE CONSTRAINT
13176 : *
13177 : * XXX The reason we handle recursion here rather than at Phase 1 is because
13178 : * there's no good way to skip recursing when handling foreign keys: there is
13179 : * no need to lock children in that case, yet we wouldn't be able to avoid
13180 : * doing so at that level.
13181 : *
13182 : * Return value is the address of the validated constraint. If the constraint
13183 : * was already validated, InvalidObjectAddress is returned.
13184 : */
13185 : static ObjectAddress
13186 347 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
13187 : bool recurse, bool recursing, LOCKMODE lockmode)
13188 : {
13189 : Relation conrel;
13190 : SysScanDesc scan;
13191 : ScanKeyData skey[3];
13192 : HeapTuple tuple;
13193 : Form_pg_constraint con;
13194 : ObjectAddress address;
13195 :
13196 347 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
13197 :
13198 : /*
13199 : * Find and check the target constraint
13200 : */
13201 347 : ScanKeyInit(&skey[0],
13202 : Anum_pg_constraint_conrelid,
13203 : BTEqualStrategyNumber, F_OIDEQ,
13204 : ObjectIdGetDatum(RelationGetRelid(rel)));
13205 347 : ScanKeyInit(&skey[1],
13206 : Anum_pg_constraint_contypid,
13207 : BTEqualStrategyNumber, F_OIDEQ,
13208 : ObjectIdGetDatum(InvalidOid));
13209 347 : ScanKeyInit(&skey[2],
13210 : Anum_pg_constraint_conname,
13211 : BTEqualStrategyNumber, F_NAMEEQ,
13212 : CStringGetDatum(constrName));
13213 347 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
13214 : true, NULL, 3, skey);
13215 :
13216 : /* There can be at most one matching row */
13217 347 : if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
13218 0 : ereport(ERROR,
13219 : (errcode(ERRCODE_UNDEFINED_OBJECT),
13220 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
13221 : constrName, RelationGetRelationName(rel))));
13222 :
13223 347 : con = (Form_pg_constraint) GETSTRUCT(tuple);
13224 347 : if (con->contype != CONSTRAINT_FOREIGN &&
13225 170 : con->contype != CONSTRAINT_CHECK &&
13226 74 : con->contype != CONSTRAINT_NOTNULL)
13227 0 : ereport(ERROR,
13228 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
13229 : errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
13230 : constrName, RelationGetRelationName(rel)),
13231 : errdetail("This operation is not supported for this type of constraint."));
13232 :
13233 347 : if (!con->conenforced)
13234 4 : ereport(ERROR,
13235 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13236 : errmsg("cannot validate NOT ENFORCED constraint")));
13237 :
13238 343 : if (!con->convalidated)
13239 : {
13240 331 : if (con->contype == CONSTRAINT_FOREIGN)
13241 : {
13242 173 : QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
13243 : tuple, lockmode);
13244 : }
13245 158 : else if (con->contype == CONSTRAINT_CHECK)
13246 : {
13247 84 : QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
13248 : tuple, recurse, recursing, lockmode);
13249 : }
13250 74 : else if (con->contype == CONSTRAINT_NOTNULL)
13251 : {
13252 74 : QueueNNConstraintValidation(wqueue, conrel, rel,
13253 : tuple, recurse, recursing, lockmode);
13254 : }
13255 :
13256 331 : ObjectAddressSet(address, ConstraintRelationId, con->oid);
13257 : }
13258 : else
13259 12 : address = InvalidObjectAddress; /* already validated */
13260 :
13261 343 : systable_endscan(scan);
13262 :
13263 343 : table_close(conrel, RowExclusiveLock);
13264 :
13265 343 : return address;
13266 : }
13267 :
13268 : /*
13269 : * QueueFKConstraintValidation
13270 : *
13271 : * Add an entry to the wqueue to validate the given foreign key constraint in
13272 : * Phase 3 and update the convalidated field in the pg_constraint catalog
13273 : * for the specified relation and all its children.
13274 : */
13275 : static void
13276 225 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
13277 : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
13278 : {
13279 : Form_pg_constraint con;
13280 : AlteredTableInfo *tab;
13281 : HeapTuple copyTuple;
13282 : Form_pg_constraint copy_con;
13283 :
13284 : /* since this function recurses, it could be driven to stack overflow */
13285 225 : check_stack_depth();
13286 :
13287 225 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13288 : Assert(con->contype == CONSTRAINT_FOREIGN);
13289 : Assert(!con->convalidated);
13290 :
13291 : /*
13292 : * Add the validation to phase 3's queue; not needed for partitioned
13293 : * tables themselves, only for their partitions.
13294 : *
13295 : * When the referenced table (pkrelid) is partitioned, the referencing
13296 : * table (fkrel) has one pg_constraint row pointing to each partition
13297 : * thereof. These rows are there only to support action triggers and no
13298 : * table scan is needed, therefore skip this for them as well.
13299 : */
13300 225 : if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
13301 193 : con->confrelid == pkrelid)
13302 : {
13303 : NewConstraint *newcon;
13304 : Constraint *fkconstraint;
13305 :
13306 : /* Queue validation for phase 3 */
13307 181 : fkconstraint = makeNode(Constraint);
13308 : /* for now this is all we need */
13309 181 : fkconstraint->conname = pstrdup(NameStr(con->conname));
13310 :
13311 181 : newcon = palloc0_object(NewConstraint);
13312 181 : newcon->name = fkconstraint->conname;
13313 181 : newcon->contype = CONSTR_FOREIGN;
13314 181 : newcon->refrelid = con->confrelid;
13315 181 : newcon->refindid = con->conindid;
13316 181 : newcon->conid = con->oid;
13317 181 : newcon->qual = (Node *) fkconstraint;
13318 :
13319 : /* Find or create work queue entry for this table */
13320 181 : tab = ATGetQueueEntry(wqueue, fkrel);
13321 181 : tab->constraints = lappend(tab->constraints, newcon);
13322 : }
13323 :
13324 : /*
13325 : * If the table at either end of the constraint is partitioned, we need to
13326 : * recurse and handle every unvalidated constraint that is a child of this
13327 : * constraint.
13328 : */
13329 418 : if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13330 193 : get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
13331 : {
13332 : ScanKeyData pkey;
13333 : SysScanDesc pscan;
13334 : HeapTuple childtup;
13335 :
13336 52 : ScanKeyInit(&pkey,
13337 : Anum_pg_constraint_conparentid,
13338 : BTEqualStrategyNumber, F_OIDEQ,
13339 : ObjectIdGetDatum(con->oid));
13340 :
13341 52 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13342 : true, NULL, 1, &pkey);
13343 :
13344 104 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13345 : {
13346 : Form_pg_constraint childcon;
13347 : Relation childrel;
13348 :
13349 52 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13350 :
13351 : /*
13352 : * If the child constraint has already been validated, no further
13353 : * action is required for it or its descendants, as they are all
13354 : * valid.
13355 : */
13356 52 : if (childcon->convalidated)
13357 12 : continue;
13358 :
13359 40 : childrel = table_open(childcon->conrelid, lockmode);
13360 :
13361 : /*
13362 : * NB: Note that pkrelid should be passed as-is during recursion,
13363 : * as it is required to identify the root referenced table.
13364 : */
13365 40 : QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
13366 : childtup, lockmode);
13367 40 : table_close(childrel, NoLock);
13368 : }
13369 :
13370 52 : systable_endscan(pscan);
13371 : }
13372 :
13373 : /*
13374 : * Now mark the pg_constraint row as validated (even if we didn't check,
13375 : * notably the ones for partitions on the referenced side).
13376 : *
13377 : * We rely on transaction abort to roll back this change if phase 3
13378 : * ultimately finds violating rows. This is a bit ugly.
13379 : */
13380 225 : copyTuple = heap_copytuple(contuple);
13381 225 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13382 225 : copy_con->convalidated = true;
13383 225 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13384 :
13385 225 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13386 :
13387 225 : heap_freetuple(copyTuple);
13388 225 : }
13389 :
13390 : /*
13391 : * QueueCheckConstraintValidation
13392 : *
13393 : * Add an entry to the wqueue to validate the given check constraint in Phase 3
13394 : * and update the convalidated field in the pg_constraint catalog for the
13395 : * specified relation and all its inheriting children.
13396 : */
13397 : static void
13398 84 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13399 : char *constrName, HeapTuple contuple,
13400 : bool recurse, bool recursing, LOCKMODE lockmode)
13401 : {
13402 : Form_pg_constraint con;
13403 : AlteredTableInfo *tab;
13404 : HeapTuple copyTuple;
13405 : Form_pg_constraint copy_con;
13406 :
13407 84 : List *children = NIL;
13408 : ListCell *child;
13409 : NewConstraint *newcon;
13410 : Datum val;
13411 : char *conbin;
13412 :
13413 84 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13414 : Assert(con->contype == CONSTRAINT_CHECK);
13415 :
13416 : /*
13417 : * If we're recursing, the parent has already done this, so skip it. Also,
13418 : * if the constraint is a NO INHERIT constraint, we shouldn't try to look
13419 : * for it in the children.
13420 : */
13421 84 : if (!recursing && !con->connoinherit)
13422 48 : children = find_all_inheritors(RelationGetRelid(rel),
13423 : lockmode, NULL);
13424 :
13425 : /*
13426 : * For CHECK constraints, we must ensure that we only mark the constraint
13427 : * as validated on the parent if it's already validated on the children.
13428 : *
13429 : * We recurse before validating on the parent, to reduce risk of
13430 : * deadlocks.
13431 : */
13432 164 : foreach(child, children)
13433 : {
13434 80 : Oid childoid = lfirst_oid(child);
13435 : Relation childrel;
13436 :
13437 80 : if (childoid == RelationGetRelid(rel))
13438 48 : continue;
13439 :
13440 : /*
13441 : * If we are told not to recurse, there had better not be any child
13442 : * tables, because we can't mark the constraint on the parent valid
13443 : * unless it is valid for all child tables.
13444 : */
13445 32 : if (!recurse)
13446 0 : ereport(ERROR,
13447 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13448 : errmsg("constraint must be validated on child tables too")));
13449 :
13450 : /* find_all_inheritors already got lock */
13451 32 : childrel = table_open(childoid, NoLock);
13452 :
13453 32 : ATExecValidateConstraint(wqueue, childrel, constrName, false,
13454 : true, lockmode);
13455 32 : table_close(childrel, NoLock);
13456 : }
13457 :
13458 : /* Queue validation for phase 3 */
13459 84 : newcon = palloc0_object(NewConstraint);
13460 84 : newcon->name = constrName;
13461 84 : newcon->contype = CONSTR_CHECK;
13462 84 : newcon->refrelid = InvalidOid;
13463 84 : newcon->refindid = InvalidOid;
13464 84 : newcon->conid = con->oid;
13465 :
13466 84 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
13467 : Anum_pg_constraint_conbin);
13468 84 : conbin = TextDatumGetCString(val);
13469 84 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
13470 :
13471 : /* Find or create work queue entry for this table */
13472 84 : tab = ATGetQueueEntry(wqueue, rel);
13473 84 : tab->constraints = lappend(tab->constraints, newcon);
13474 :
13475 : /*
13476 : * Invalidate relcache so that others see the new validated constraint.
13477 : */
13478 84 : CacheInvalidateRelcache(rel);
13479 :
13480 : /*
13481 : * Now update the catalog, while we have the door open.
13482 : */
13483 84 : copyTuple = heap_copytuple(contuple);
13484 84 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13485 84 : copy_con->convalidated = true;
13486 84 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13487 :
13488 84 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13489 :
13490 84 : heap_freetuple(copyTuple);
13491 84 : }
13492 :
13493 : /*
13494 : * QueueNNConstraintValidation
13495 : *
13496 : * Add an entry to the wqueue to validate the given not-null constraint in
13497 : * Phase 3 and update the convalidated field in the pg_constraint catalog for
13498 : * the specified relation and all its inheriting children.
13499 : */
13500 : static void
13501 74 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13502 : HeapTuple contuple, bool recurse, bool recursing,
13503 : LOCKMODE lockmode)
13504 : {
13505 : Form_pg_constraint con;
13506 : AlteredTableInfo *tab;
13507 : HeapTuple copyTuple;
13508 : Form_pg_constraint copy_con;
13509 74 : List *children = NIL;
13510 : AttrNumber attnum;
13511 : char *colname;
13512 :
13513 74 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13514 : Assert(con->contype == CONSTRAINT_NOTNULL);
13515 :
13516 74 : attnum = extractNotNullColumn(contuple);
13517 :
13518 : /*
13519 : * If we're recursing, we've already done this for parent, so skip it.
13520 : * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
13521 : * look for it in the children.
13522 : *
13523 : * We recurse before validating on the parent, to reduce risk of
13524 : * deadlocks.
13525 : */
13526 74 : if (!recursing && !con->connoinherit)
13527 50 : children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
13528 :
13529 74 : colname = get_attname(RelationGetRelid(rel), attnum, false);
13530 250 : foreach_oid(childoid, children)
13531 : {
13532 : Relation childrel;
13533 : HeapTuple contup;
13534 : Form_pg_constraint childcon;
13535 : char *conname;
13536 :
13537 102 : if (childoid == RelationGetRelid(rel))
13538 50 : continue;
13539 :
13540 : /*
13541 : * If we are told not to recurse, there had better not be any child
13542 : * tables, because we can't mark the constraint on the parent valid
13543 : * unless it is valid for all child tables.
13544 : */
13545 52 : if (!recurse)
13546 0 : ereport(ERROR,
13547 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13548 : errmsg("constraint must be validated on child tables too"));
13549 :
13550 : /*
13551 : * The column on child might have a different attnum, so search by
13552 : * column name.
13553 : */
13554 52 : contup = findNotNullConstraint(childoid, colname);
13555 52 : if (!contup)
13556 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
13557 : colname, get_rel_name(childoid));
13558 52 : childcon = (Form_pg_constraint) GETSTRUCT(contup);
13559 52 : if (childcon->convalidated)
13560 28 : continue;
13561 :
13562 : /* find_all_inheritors already got lock */
13563 24 : childrel = table_open(childoid, NoLock);
13564 24 : conname = pstrdup(NameStr(childcon->conname));
13565 :
13566 : /* XXX improve ATExecValidateConstraint API to avoid double search */
13567 24 : ATExecValidateConstraint(wqueue, childrel, conname,
13568 : false, true, lockmode);
13569 24 : table_close(childrel, NoLock);
13570 : }
13571 :
13572 : /* Set attnotnull appropriately without queueing another validation */
13573 74 : set_attnotnull(NULL, rel, attnum, true, false);
13574 :
13575 74 : tab = ATGetQueueEntry(wqueue, rel);
13576 74 : tab->verify_new_notnull = true;
13577 :
13578 : /*
13579 : * Invalidate relcache so that others see the new validated constraint.
13580 : */
13581 74 : CacheInvalidateRelcache(rel);
13582 :
13583 : /*
13584 : * Now update the catalogs, while we have the door open.
13585 : */
13586 74 : copyTuple = heap_copytuple(contuple);
13587 74 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13588 74 : copy_con->convalidated = true;
13589 74 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13590 :
13591 74 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13592 :
13593 74 : heap_freetuple(copyTuple);
13594 74 : }
13595 :
13596 : /*
13597 : * transformColumnNameList - transform list of column names
13598 : *
13599 : * Lookup each name and return its attnum and, optionally, type and collation
13600 : * OIDs
13601 : *
13602 : * Note: the name of this function suggests that it's general-purpose,
13603 : * but actually it's only used to look up names appearing in foreign-key
13604 : * clauses. The error messages would need work to use it in other cases,
13605 : * and perhaps the validity checks as well.
13606 : */
13607 : static int
13608 4499 : transformColumnNameList(Oid relId, List *colList,
13609 : int16 *attnums, Oid *atttypids, Oid *attcollids)
13610 : {
13611 : ListCell *l;
13612 : int attnum;
13613 :
13614 4499 : attnum = 0;
13615 8191 : foreach(l, colList)
13616 : {
13617 3736 : char *attname = strVal(lfirst(l));
13618 : HeapTuple atttuple;
13619 : Form_pg_attribute attform;
13620 :
13621 3736 : atttuple = SearchSysCacheAttName(relId, attname);
13622 3736 : if (!HeapTupleIsValid(atttuple))
13623 36 : ereport(ERROR,
13624 : (errcode(ERRCODE_UNDEFINED_COLUMN),
13625 : errmsg("column \"%s\" referenced in foreign key constraint does not exist",
13626 : attname)));
13627 3700 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
13628 3700 : if (attform->attnum < 0)
13629 8 : ereport(ERROR,
13630 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13631 : errmsg("system columns cannot be used in foreign keys")));
13632 3692 : if (attnum >= INDEX_MAX_KEYS)
13633 0 : ereport(ERROR,
13634 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
13635 : errmsg("cannot have more than %d keys in a foreign key",
13636 : INDEX_MAX_KEYS)));
13637 3692 : attnums[attnum] = attform->attnum;
13638 3692 : if (atttypids != NULL)
13639 3668 : atttypids[attnum] = attform->atttypid;
13640 3692 : if (attcollids != NULL)
13641 3668 : attcollids[attnum] = attform->attcollation;
13642 3692 : ReleaseSysCache(atttuple);
13643 3692 : attnum++;
13644 : }
13645 :
13646 4455 : return attnum;
13647 : }
13648 :
13649 : /*
13650 : * transformFkeyGetPrimaryKey -
13651 : *
13652 : * Look up the names, attnums, types, and collations of the primary key attributes
13653 : * for the pkrel. Also return the index OID and index opclasses of the
13654 : * index supporting the primary key. Also return whether the index has
13655 : * WITHOUT OVERLAPS.
13656 : *
13657 : * All parameters except pkrel are output parameters. Also, the function
13658 : * return value is the number of attributes in the primary key.
13659 : *
13660 : * Used when the column list in the REFERENCES specification is omitted.
13661 : */
13662 : static int
13663 896 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
13664 : List **attnamelist,
13665 : int16 *attnums, Oid *atttypids, Oid *attcollids,
13666 : Oid *opclasses, bool *pk_has_without_overlaps)
13667 : {
13668 : List *indexoidlist;
13669 : ListCell *indexoidscan;
13670 896 : HeapTuple indexTuple = NULL;
13671 896 : Form_pg_index indexStruct = NULL;
13672 : Datum indclassDatum;
13673 : oidvector *indclass;
13674 : int i;
13675 :
13676 : /*
13677 : * Get the list of index OIDs for the table from the relcache, and look up
13678 : * each one in the pg_index syscache until we find one marked primary key
13679 : * (hopefully there isn't more than one such). Insist it's valid, too.
13680 : */
13681 896 : *indexOid = InvalidOid;
13682 :
13683 896 : indexoidlist = RelationGetIndexList(pkrel);
13684 :
13685 900 : foreach(indexoidscan, indexoidlist)
13686 : {
13687 900 : Oid indexoid = lfirst_oid(indexoidscan);
13688 :
13689 900 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13690 900 : if (!HeapTupleIsValid(indexTuple))
13691 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
13692 900 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13693 900 : if (indexStruct->indisprimary && indexStruct->indisvalid)
13694 : {
13695 : /*
13696 : * Refuse to use a deferrable primary key. This is per SQL spec,
13697 : * and there would be a lot of interesting semantic problems if we
13698 : * tried to allow it.
13699 : */
13700 896 : if (!indexStruct->indimmediate)
13701 0 : ereport(ERROR,
13702 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13703 : errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
13704 : RelationGetRelationName(pkrel))));
13705 :
13706 896 : *indexOid = indexoid;
13707 896 : break;
13708 : }
13709 4 : ReleaseSysCache(indexTuple);
13710 : }
13711 :
13712 896 : list_free(indexoidlist);
13713 :
13714 : /*
13715 : * Check that we found it
13716 : */
13717 896 : if (!OidIsValid(*indexOid))
13718 0 : ereport(ERROR,
13719 : (errcode(ERRCODE_UNDEFINED_OBJECT),
13720 : errmsg("there is no primary key for referenced table \"%s\"",
13721 : RelationGetRelationName(pkrel))));
13722 :
13723 : /* Must get indclass the hard way */
13724 896 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13725 : Anum_pg_index_indclass);
13726 896 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
13727 :
13728 : /*
13729 : * Now build the list of PK attributes from the indkey definition (we
13730 : * assume a primary key cannot have expressional elements)
13731 : */
13732 896 : *attnamelist = NIL;
13733 2108 : for (i = 0; i < indexStruct->indnkeyatts; i++)
13734 : {
13735 1212 : int pkattno = indexStruct->indkey.values[i];
13736 :
13737 1212 : attnums[i] = pkattno;
13738 1212 : atttypids[i] = attnumTypeId(pkrel, pkattno);
13739 1212 : attcollids[i] = attnumCollationId(pkrel, pkattno);
13740 1212 : opclasses[i] = indclass->values[i];
13741 1212 : *attnamelist = lappend(*attnamelist,
13742 1212 : makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
13743 : }
13744 :
13745 896 : *pk_has_without_overlaps = indexStruct->indisexclusion;
13746 :
13747 896 : ReleaseSysCache(indexTuple);
13748 :
13749 896 : return i;
13750 : }
13751 :
13752 : /*
13753 : * transformFkeyCheckAttrs -
13754 : *
13755 : * Validate that the 'attnums' columns in the 'pkrel' relation are valid to
13756 : * reference as part of a foreign key constraint.
13757 : *
13758 : * Returns the OID of the unique index supporting the constraint and
13759 : * populates the caller-provided 'opclasses' array with the opclasses
13760 : * associated with the index columns. Also sets whether the index
13761 : * uses WITHOUT OVERLAPS.
13762 : *
13763 : * Raises an ERROR on validation failure.
13764 : */
13765 : static Oid
13766 849 : transformFkeyCheckAttrs(Relation pkrel,
13767 : int numattrs, int16 *attnums,
13768 : bool with_period, Oid *opclasses,
13769 : bool *pk_has_without_overlaps)
13770 : {
13771 849 : Oid indexoid = InvalidOid;
13772 849 : bool found = false;
13773 849 : bool found_deferrable = false;
13774 : List *indexoidlist;
13775 : ListCell *indexoidscan;
13776 : int i,
13777 : j;
13778 :
13779 : /*
13780 : * Reject duplicate appearances of columns in the referenced-columns list.
13781 : * Such a case is forbidden by the SQL standard, and even if we thought it
13782 : * useful to allow it, there would be ambiguity about how to match the
13783 : * list to unique indexes (in particular, it'd be unclear which index
13784 : * opclass goes with which FK column).
13785 : */
13786 1991 : for (i = 0; i < numattrs; i++)
13787 : {
13788 1517 : for (j = i + 1; j < numattrs; j++)
13789 : {
13790 375 : if (attnums[i] == attnums[j])
13791 16 : ereport(ERROR,
13792 : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
13793 : errmsg("foreign key referenced-columns list must not contain duplicates")));
13794 : }
13795 : }
13796 :
13797 : /*
13798 : * Get the list of index OIDs for the table from the relcache, and look up
13799 : * each one in the pg_index syscache, and match unique indexes to the list
13800 : * of attnums we are given.
13801 : */
13802 833 : indexoidlist = RelationGetIndexList(pkrel);
13803 :
13804 952 : foreach(indexoidscan, indexoidlist)
13805 : {
13806 : HeapTuple indexTuple;
13807 : Form_pg_index indexStruct;
13808 :
13809 944 : indexoid = lfirst_oid(indexoidscan);
13810 944 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13811 944 : if (!HeapTupleIsValid(indexTuple))
13812 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
13813 944 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13814 :
13815 : /*
13816 : * Must have the right number of columns; must be unique (or if
13817 : * temporal then exclusion instead) and not a partial index; forget it
13818 : * if there are any expressions, too. Invalid indexes are out as well.
13819 : */
13820 944 : if (indexStruct->indnkeyatts == numattrs &&
13821 863 : (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
13822 1726 : indexStruct->indisvalid &&
13823 1726 : heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
13824 863 : heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
13825 : {
13826 : Datum indclassDatum;
13827 : oidvector *indclass;
13828 :
13829 : /* Must get indclass the hard way */
13830 863 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13831 : Anum_pg_index_indclass);
13832 863 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
13833 :
13834 : /*
13835 : * The given attnum list may match the index columns in any order.
13836 : * Check for a match, and extract the appropriate opclasses while
13837 : * we're at it.
13838 : *
13839 : * We know that attnums[] is duplicate-free per the test at the
13840 : * start of this function, and we checked above that the number of
13841 : * index columns agrees, so if we find a match for each attnums[]
13842 : * entry then we must have a one-to-one match in some order.
13843 : */
13844 1997 : for (i = 0; i < numattrs; i++)
13845 : {
13846 1172 : found = false;
13847 1569 : for (j = 0; j < numattrs; j++)
13848 : {
13849 1531 : if (attnums[i] == indexStruct->indkey.values[j])
13850 : {
13851 1134 : opclasses[i] = indclass->values[j];
13852 1134 : found = true;
13853 1134 : break;
13854 : }
13855 : }
13856 1172 : if (!found)
13857 38 : break;
13858 : }
13859 : /* The last attribute in the index must be the PERIOD FK part */
13860 863 : if (found && with_period)
13861 : {
13862 80 : int16 periodattnum = attnums[numattrs - 1];
13863 :
13864 80 : found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
13865 : }
13866 :
13867 : /*
13868 : * Refuse to use a deferrable unique/primary key. This is per SQL
13869 : * spec, and there would be a lot of interesting semantic problems
13870 : * if we tried to allow it.
13871 : */
13872 863 : if (found && !indexStruct->indimmediate)
13873 : {
13874 : /*
13875 : * Remember that we found an otherwise matching index, so that
13876 : * we can generate a more appropriate error message.
13877 : */
13878 0 : found_deferrable = true;
13879 0 : found = false;
13880 : }
13881 :
13882 : /* We need to know whether the index has WITHOUT OVERLAPS */
13883 863 : if (found)
13884 825 : *pk_has_without_overlaps = indexStruct->indisexclusion;
13885 : }
13886 944 : ReleaseSysCache(indexTuple);
13887 944 : if (found)
13888 825 : break;
13889 : }
13890 :
13891 833 : if (!found)
13892 : {
13893 8 : if (found_deferrable)
13894 0 : ereport(ERROR,
13895 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13896 : errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
13897 : RelationGetRelationName(pkrel))));
13898 : else
13899 8 : ereport(ERROR,
13900 : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
13901 : errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
13902 : RelationGetRelationName(pkrel))));
13903 : }
13904 :
13905 825 : list_free(indexoidlist);
13906 :
13907 825 : return indexoid;
13908 : }
13909 :
13910 : /*
13911 : * findFkeyCast -
13912 : *
13913 : * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
13914 : * Caller has equal regard for binary coercibility and for an exact match.
13915 : */
13916 : static CoercionPathType
13917 8 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
13918 : {
13919 : CoercionPathType ret;
13920 :
13921 8 : if (targetTypeId == sourceTypeId)
13922 : {
13923 8 : ret = COERCION_PATH_RELABELTYPE;
13924 8 : *funcid = InvalidOid;
13925 : }
13926 : else
13927 : {
13928 0 : ret = find_coercion_pathway(targetTypeId, sourceTypeId,
13929 : COERCION_IMPLICIT, funcid);
13930 0 : if (ret == COERCION_PATH_NONE)
13931 : /* A previously-relied-upon cast is now gone. */
13932 0 : elog(ERROR, "could not find cast from %u to %u",
13933 : sourceTypeId, targetTypeId);
13934 : }
13935 :
13936 8 : return ret;
13937 : }
13938 :
13939 : /*
13940 : * Permissions checks on the referenced table for ADD FOREIGN KEY
13941 : *
13942 : * Note: we have already checked that the user owns the referencing table,
13943 : * else we'd have failed much earlier; no additional checks are needed for it.
13944 : */
13945 : static void
13946 1697 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
13947 : {
13948 1697 : Oid roleid = GetUserId();
13949 : AclResult aclresult;
13950 : int i;
13951 :
13952 : /* Okay if we have relation-level REFERENCES permission */
13953 1697 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
13954 : ACL_REFERENCES);
13955 1697 : if (aclresult == ACLCHECK_OK)
13956 1697 : return;
13957 : /* Else we must have REFERENCES on each column */
13958 0 : for (i = 0; i < natts; i++)
13959 : {
13960 0 : aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
13961 : roleid, ACL_REFERENCES);
13962 0 : if (aclresult != ACLCHECK_OK)
13963 0 : aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
13964 0 : RelationGetRelationName(rel));
13965 : }
13966 : }
13967 :
13968 : /*
13969 : * Scan the existing rows in a table to verify they meet a proposed FK
13970 : * constraint.
13971 : *
13972 : * Caller must have opened and locked both relations appropriately.
13973 : */
13974 : static void
13975 828 : validateForeignKeyConstraint(char *conname,
13976 : Relation rel,
13977 : Relation pkrel,
13978 : Oid pkindOid,
13979 : Oid constraintOid,
13980 : bool hasperiod)
13981 : {
13982 : TupleTableSlot *slot;
13983 : TableScanDesc scan;
13984 828 : Trigger trig = {0};
13985 : Snapshot snapshot;
13986 : MemoryContext oldcxt;
13987 : MemoryContext perTupCxt;
13988 :
13989 828 : ereport(DEBUG1,
13990 : (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
13991 :
13992 : /*
13993 : * Build a trigger call structure; we'll need it either way.
13994 : */
13995 828 : trig.tgoid = InvalidOid;
13996 828 : trig.tgname = conname;
13997 828 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
13998 828 : trig.tgisinternal = true;
13999 828 : trig.tgconstrrelid = RelationGetRelid(pkrel);
14000 828 : trig.tgconstrindid = pkindOid;
14001 828 : trig.tgconstraint = constraintOid;
14002 828 : trig.tgdeferrable = false;
14003 828 : trig.tginitdeferred = false;
14004 : /* we needn't fill in remaining fields */
14005 :
14006 : /*
14007 : * See if we can do it with a single LEFT JOIN query. A false result
14008 : * indicates we must proceed with the fire-the-trigger method. We can't do
14009 : * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
14010 : * left joins.
14011 : */
14012 828 : if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
14013 698 : return;
14014 :
14015 : /*
14016 : * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
14017 : * if that tuple had just been inserted. If any of those fail, it should
14018 : * ereport(ERROR) and that's that.
14019 : */
14020 71 : snapshot = RegisterSnapshot(GetLatestSnapshot());
14021 71 : slot = table_slot_create(rel, NULL);
14022 71 : scan = table_beginscan(rel, snapshot, 0, NULL,
14023 : SO_NONE);
14024 71 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
14025 : "validateForeignKeyConstraint",
14026 : ALLOCSET_SMALL_SIZES);
14027 71 : oldcxt = MemoryContextSwitchTo(perTupCxt);
14028 :
14029 127 : while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
14030 : {
14031 68 : LOCAL_FCINFO(fcinfo, 0);
14032 68 : TriggerData trigdata = {0};
14033 :
14034 68 : CHECK_FOR_INTERRUPTS();
14035 :
14036 : /*
14037 : * Make a call to the trigger function
14038 : *
14039 : * No parameters are passed, but we do set a context
14040 : */
14041 340 : MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
14042 :
14043 : /*
14044 : * We assume RI_FKey_check_ins won't look at flinfo...
14045 : */
14046 68 : trigdata.type = T_TriggerData;
14047 68 : trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
14048 68 : trigdata.tg_relation = rel;
14049 68 : trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
14050 68 : trigdata.tg_trigslot = slot;
14051 68 : trigdata.tg_trigger = &trig;
14052 :
14053 68 : fcinfo->context = (Node *) &trigdata;
14054 :
14055 68 : RI_FKey_check_ins(fcinfo);
14056 :
14057 56 : MemoryContextReset(perTupCxt);
14058 : }
14059 :
14060 59 : MemoryContextSwitchTo(oldcxt);
14061 59 : MemoryContextDelete(perTupCxt);
14062 59 : table_endscan(scan);
14063 59 : UnregisterSnapshot(snapshot);
14064 59 : ExecDropSingleTupleTableSlot(slot);
14065 : }
14066 :
14067 : /*
14068 : * CreateFKCheckTrigger
14069 : * Creates the insert (on_insert=true) or update "check" trigger that
14070 : * implements a given foreign key
14071 : *
14072 : * Returns the OID of the so created trigger.
14073 : */
14074 : static Oid
14075 4112 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14076 : Oid constraintOid, Oid indexOid, Oid parentTrigOid,
14077 : bool on_insert)
14078 : {
14079 : ObjectAddress trigAddress;
14080 : CreateTrigStmt *fk_trigger;
14081 :
14082 : /*
14083 : * Note: for a self-referential FK (referencing and referenced tables are
14084 : * the same), it is important that the ON UPDATE action fires before the
14085 : * CHECK action, since both triggers will fire on the same row during an
14086 : * UPDATE event; otherwise the CHECK trigger will be checking a non-final
14087 : * state of the row. Triggers fire in name order, so we ensure this by
14088 : * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
14089 : * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
14090 : */
14091 4112 : fk_trigger = makeNode(CreateTrigStmt);
14092 4112 : fk_trigger->replace = false;
14093 4112 : fk_trigger->isconstraint = true;
14094 4112 : fk_trigger->trigname = "RI_ConstraintTrigger_c";
14095 4112 : fk_trigger->relation = NULL;
14096 :
14097 : /* Either ON INSERT or ON UPDATE */
14098 4112 : if (on_insert)
14099 : {
14100 2056 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
14101 2056 : fk_trigger->events = TRIGGER_TYPE_INSERT;
14102 : }
14103 : else
14104 : {
14105 2056 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
14106 2056 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14107 : }
14108 :
14109 4112 : fk_trigger->args = NIL;
14110 4112 : fk_trigger->row = true;
14111 4112 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14112 4112 : fk_trigger->columns = NIL;
14113 4112 : fk_trigger->whenClause = NULL;
14114 4112 : fk_trigger->transitionRels = NIL;
14115 4112 : fk_trigger->deferrable = fkconstraint->deferrable;
14116 4112 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14117 4112 : fk_trigger->constrrel = NULL;
14118 :
14119 4112 : trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
14120 : constraintOid, indexOid, InvalidOid,
14121 : parentTrigOid, NULL, true, false);
14122 :
14123 : /* Make changes-so-far visible */
14124 4112 : CommandCounterIncrement();
14125 :
14126 4112 : return trigAddress.objectId;
14127 : }
14128 :
14129 : /*
14130 : * createForeignKeyActionTriggers
14131 : * Create the referenced-side "action" triggers that implement a foreign
14132 : * key.
14133 : *
14134 : * Returns the OIDs of the so created triggers in *deleteTrigOid and
14135 : * *updateTrigOid.
14136 : */
14137 : static void
14138 2343 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14139 : Oid constraintOid, Oid indexOid,
14140 : Oid parentDelTrigger, Oid parentUpdTrigger,
14141 : Oid *deleteTrigOid, Oid *updateTrigOid)
14142 : {
14143 : CreateTrigStmt *fk_trigger;
14144 : ObjectAddress trigAddress;
14145 :
14146 : /*
14147 : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14148 : * DELETE action on the referenced table.
14149 : */
14150 2343 : fk_trigger = makeNode(CreateTrigStmt);
14151 2343 : fk_trigger->replace = false;
14152 2343 : fk_trigger->isconstraint = true;
14153 2343 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14154 2343 : fk_trigger->relation = NULL;
14155 2343 : fk_trigger->args = NIL;
14156 2343 : fk_trigger->row = true;
14157 2343 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14158 2343 : fk_trigger->events = TRIGGER_TYPE_DELETE;
14159 2343 : fk_trigger->columns = NIL;
14160 2343 : fk_trigger->whenClause = NULL;
14161 2343 : fk_trigger->transitionRels = NIL;
14162 2343 : fk_trigger->constrrel = NULL;
14163 :
14164 2343 : switch (fkconstraint->fk_del_action)
14165 : {
14166 1914 : case FKCONSTR_ACTION_NOACTION:
14167 1914 : fk_trigger->deferrable = fkconstraint->deferrable;
14168 1914 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14169 1914 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
14170 1914 : break;
14171 20 : case FKCONSTR_ACTION_RESTRICT:
14172 20 : fk_trigger->deferrable = false;
14173 20 : fk_trigger->initdeferred = false;
14174 20 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
14175 20 : break;
14176 306 : case FKCONSTR_ACTION_CASCADE:
14177 306 : fk_trigger->deferrable = false;
14178 306 : fk_trigger->initdeferred = false;
14179 306 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
14180 306 : break;
14181 63 : case FKCONSTR_ACTION_SETNULL:
14182 63 : fk_trigger->deferrable = false;
14183 63 : fk_trigger->initdeferred = false;
14184 63 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
14185 63 : break;
14186 40 : case FKCONSTR_ACTION_SETDEFAULT:
14187 40 : fk_trigger->deferrable = false;
14188 40 : fk_trigger->initdeferred = false;
14189 40 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
14190 40 : break;
14191 0 : default:
14192 0 : elog(ERROR, "unrecognized FK action type: %d",
14193 : (int) fkconstraint->fk_del_action);
14194 : break;
14195 : }
14196 :
14197 2343 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14198 : constraintOid, indexOid, InvalidOid,
14199 : parentDelTrigger, NULL, true, false);
14200 2343 : if (deleteTrigOid)
14201 2343 : *deleteTrigOid = trigAddress.objectId;
14202 :
14203 : /* Make changes-so-far visible */
14204 2343 : CommandCounterIncrement();
14205 :
14206 : /*
14207 : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14208 : * UPDATE action on the referenced table.
14209 : */
14210 2343 : fk_trigger = makeNode(CreateTrigStmt);
14211 2343 : fk_trigger->replace = false;
14212 2343 : fk_trigger->isconstraint = true;
14213 2343 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14214 2343 : fk_trigger->relation = NULL;
14215 2343 : fk_trigger->args = NIL;
14216 2343 : fk_trigger->row = true;
14217 2343 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14218 2343 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14219 2343 : fk_trigger->columns = NIL;
14220 2343 : fk_trigger->whenClause = NULL;
14221 2343 : fk_trigger->transitionRels = NIL;
14222 2343 : fk_trigger->constrrel = NULL;
14223 :
14224 2343 : switch (fkconstraint->fk_upd_action)
14225 : {
14226 2039 : case FKCONSTR_ACTION_NOACTION:
14227 2039 : fk_trigger->deferrable = fkconstraint->deferrable;
14228 2039 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14229 2039 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
14230 2039 : break;
14231 24 : case FKCONSTR_ACTION_RESTRICT:
14232 24 : fk_trigger->deferrable = false;
14233 24 : fk_trigger->initdeferred = false;
14234 24 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
14235 24 : break;
14236 211 : case FKCONSTR_ACTION_CASCADE:
14237 211 : fk_trigger->deferrable = false;
14238 211 : fk_trigger->initdeferred = false;
14239 211 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
14240 211 : break;
14241 41 : case FKCONSTR_ACTION_SETNULL:
14242 41 : fk_trigger->deferrable = false;
14243 41 : fk_trigger->initdeferred = false;
14244 41 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
14245 41 : break;
14246 28 : case FKCONSTR_ACTION_SETDEFAULT:
14247 28 : fk_trigger->deferrable = false;
14248 28 : fk_trigger->initdeferred = false;
14249 28 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
14250 28 : break;
14251 0 : default:
14252 0 : elog(ERROR, "unrecognized FK action type: %d",
14253 : (int) fkconstraint->fk_upd_action);
14254 : break;
14255 : }
14256 :
14257 2343 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14258 : constraintOid, indexOid, InvalidOid,
14259 : parentUpdTrigger, NULL, true, false);
14260 2343 : if (updateTrigOid)
14261 2343 : *updateTrigOid = trigAddress.objectId;
14262 2343 : }
14263 :
14264 : /*
14265 : * createForeignKeyCheckTriggers
14266 : * Create the referencing-side "check" triggers that implement a foreign
14267 : * key.
14268 : *
14269 : * Returns the OIDs of the so created triggers in *insertTrigOid and
14270 : * *updateTrigOid.
14271 : */
14272 : static void
14273 2056 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
14274 : Constraint *fkconstraint, Oid constraintOid,
14275 : Oid indexOid,
14276 : Oid parentInsTrigger, Oid parentUpdTrigger,
14277 : Oid *insertTrigOid, Oid *updateTrigOid)
14278 : {
14279 2056 : *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14280 : constraintOid, indexOid,
14281 : parentInsTrigger, true);
14282 2056 : *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14283 : constraintOid, indexOid,
14284 : parentUpdTrigger, false);
14285 2056 : }
14286 :
14287 : /*
14288 : * ALTER TABLE DROP CONSTRAINT
14289 : *
14290 : * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
14291 : */
14292 : static void
14293 574 : ATExecDropConstraint(Relation rel, const char *constrName,
14294 : DropBehavior behavior, bool recurse,
14295 : bool missing_ok, LOCKMODE lockmode)
14296 : {
14297 : Relation conrel;
14298 : SysScanDesc scan;
14299 : ScanKeyData skey[3];
14300 : HeapTuple tuple;
14301 574 : bool found = false;
14302 :
14303 574 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14304 :
14305 : /*
14306 : * Find and drop the target constraint
14307 : */
14308 574 : ScanKeyInit(&skey[0],
14309 : Anum_pg_constraint_conrelid,
14310 : BTEqualStrategyNumber, F_OIDEQ,
14311 : ObjectIdGetDatum(RelationGetRelid(rel)));
14312 574 : ScanKeyInit(&skey[1],
14313 : Anum_pg_constraint_contypid,
14314 : BTEqualStrategyNumber, F_OIDEQ,
14315 : ObjectIdGetDatum(InvalidOid));
14316 574 : ScanKeyInit(&skey[2],
14317 : Anum_pg_constraint_conname,
14318 : BTEqualStrategyNumber, F_NAMEEQ,
14319 : CStringGetDatum(constrName));
14320 574 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14321 : true, NULL, 3, skey);
14322 :
14323 : /* There can be at most one matching row */
14324 574 : if (HeapTupleIsValid(tuple = systable_getnext(scan)))
14325 : {
14326 550 : dropconstraint_internal(rel, tuple, behavior, recurse, false,
14327 : missing_ok, lockmode);
14328 426 : found = true;
14329 : }
14330 :
14331 450 : systable_endscan(scan);
14332 :
14333 450 : if (!found)
14334 : {
14335 24 : if (!missing_ok)
14336 16 : ereport(ERROR,
14337 : errcode(ERRCODE_UNDEFINED_OBJECT),
14338 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14339 : constrName, RelationGetRelationName(rel)));
14340 : else
14341 8 : ereport(NOTICE,
14342 : errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
14343 : constrName, RelationGetRelationName(rel)));
14344 : }
14345 :
14346 434 : table_close(conrel, RowExclusiveLock);
14347 434 : }
14348 :
14349 : /*
14350 : * Remove a constraint, using its pg_constraint tuple
14351 : *
14352 : * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
14353 : * DROP NOT NULL.
14354 : *
14355 : * Returns the address of the constraint being removed.
14356 : */
14357 : static ObjectAddress
14358 854 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
14359 : bool recurse, bool recursing, bool missing_ok,
14360 : LOCKMODE lockmode)
14361 : {
14362 : Relation conrel;
14363 : Form_pg_constraint con;
14364 : ObjectAddress conobj;
14365 : List *children;
14366 854 : bool is_no_inherit_constraint = false;
14367 : char *constrName;
14368 854 : char *colname = NULL;
14369 :
14370 : /* Guard against stack overflow due to overly deep inheritance tree. */
14371 854 : check_stack_depth();
14372 :
14373 : /* At top level, permission check was done in ATPrepCmd, else do it */
14374 854 : if (recursing)
14375 159 : ATSimplePermissions(AT_DropConstraint, rel,
14376 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
14377 :
14378 850 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14379 :
14380 850 : con = (Form_pg_constraint) GETSTRUCT(constraintTup);
14381 850 : constrName = NameStr(con->conname);
14382 :
14383 : /* Don't allow drop of inherited constraints */
14384 850 : if (con->coninhcount > 0 && !recursing)
14385 104 : ereport(ERROR,
14386 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14387 : errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
14388 : constrName, RelationGetRelationName(rel))));
14389 :
14390 : /*
14391 : * Reset pg_constraint.attnotnull, if this is a not-null constraint.
14392 : *
14393 : * While doing that, we're in a good position to disallow dropping a not-
14394 : * null constraint underneath a primary key, a replica identity index, or
14395 : * a generated identity column.
14396 : */
14397 746 : if (con->contype == CONSTRAINT_NOTNULL)
14398 : {
14399 207 : Relation attrel = table_open(AttributeRelationId, RowExclusiveLock);
14400 207 : AttrNumber attnum = extractNotNullColumn(constraintTup);
14401 : Bitmapset *pkattrs;
14402 : Bitmapset *irattrs;
14403 : HeapTuple atttup;
14404 : Form_pg_attribute attForm;
14405 :
14406 : /* save column name for recursion step */
14407 207 : colname = get_attname(RelationGetRelid(rel), attnum, false);
14408 :
14409 : /*
14410 : * Disallow if it's in the primary key. For partitioned tables we
14411 : * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
14412 : * return NULL if the primary key is invalid; but we still need to
14413 : * protect not-null constraints under such a constraint, so check the
14414 : * slow way.
14415 : */
14416 207 : pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
14417 :
14418 207 : if (pkattrs == NULL &&
14419 187 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14420 : {
14421 12 : Oid pkindex = RelationGetPrimaryKeyIndex(rel, true);
14422 :
14423 12 : if (OidIsValid(pkindex))
14424 : {
14425 0 : Relation pk = relation_open(pkindex, AccessShareLock);
14426 :
14427 0 : pkattrs = NULL;
14428 0 : for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
14429 0 : pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
14430 :
14431 0 : relation_close(pk, AccessShareLock);
14432 : }
14433 : }
14434 :
14435 227 : if (pkattrs &&
14436 20 : bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
14437 16 : ereport(ERROR,
14438 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14439 : errmsg("column \"%s\" is in a primary key",
14440 : get_attname(RelationGetRelid(rel), attnum, false)));
14441 :
14442 : /* Disallow if it's in the replica identity */
14443 191 : irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
14444 191 : if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
14445 8 : ereport(ERROR,
14446 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14447 : errmsg("column \"%s\" is in index used as replica identity",
14448 : get_attname(RelationGetRelid(rel), attnum, false)));
14449 :
14450 : /* Disallow if it's a GENERATED AS IDENTITY column */
14451 183 : atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
14452 183 : if (!HeapTupleIsValid(atttup))
14453 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
14454 : attnum, RelationGetRelid(rel));
14455 183 : attForm = (Form_pg_attribute) GETSTRUCT(atttup);
14456 183 : if (attForm->attidentity != '\0')
14457 0 : ereport(ERROR,
14458 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14459 : errmsg("column \"%s\" of relation \"%s\" is an identity column",
14460 : get_attname(RelationGetRelid(rel), attnum,
14461 : false),
14462 : RelationGetRelationName(rel)));
14463 :
14464 : /* All good -- reset attnotnull if needed */
14465 183 : if (attForm->attnotnull)
14466 : {
14467 183 : attForm->attnotnull = false;
14468 183 : CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
14469 : }
14470 :
14471 183 : table_close(attrel, RowExclusiveLock);
14472 : }
14473 :
14474 722 : is_no_inherit_constraint = con->connoinherit;
14475 :
14476 : /*
14477 : * If it's a foreign-key constraint, we'd better lock the referenced table
14478 : * and check that that's not in use, just as we've already done for the
14479 : * constrained table (else we might, eg, be dropping a trigger that has
14480 : * unfired events). But we can/must skip that in the self-referential
14481 : * case.
14482 : */
14483 722 : if (con->contype == CONSTRAINT_FOREIGN &&
14484 112 : con->confrelid != RelationGetRelid(rel))
14485 : {
14486 : Relation frel;
14487 :
14488 : /* Must match lock taken by RemoveTriggerById: */
14489 112 : frel = table_open(con->confrelid, AccessExclusiveLock);
14490 112 : CheckAlterTableIsSafe(frel);
14491 108 : table_close(frel, NoLock);
14492 : }
14493 :
14494 : /*
14495 : * Perform the actual constraint deletion
14496 : */
14497 718 : ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
14498 718 : performDeletion(&conobj, behavior, 0);
14499 :
14500 : /*
14501 : * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
14502 : * are dropped via the dependency mechanism, so we're done here.
14503 : */
14504 694 : if (con->contype != CONSTRAINT_CHECK &&
14505 417 : con->contype != CONSTRAINT_NOTNULL &&
14506 234 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14507 : {
14508 52 : table_close(conrel, RowExclusiveLock);
14509 52 : return conobj;
14510 : }
14511 :
14512 : /*
14513 : * Propagate to children as appropriate. Unlike most other ALTER
14514 : * routines, we have to do this one level of recursion at a time; we can't
14515 : * use find_all_inheritors to do it in one pass.
14516 : */
14517 642 : if (!is_no_inherit_constraint)
14518 452 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
14519 : else
14520 190 : children = NIL;
14521 :
14522 1559 : foreach_oid(childrelid, children)
14523 : {
14524 : Relation childrel;
14525 : HeapTuple tuple;
14526 : Form_pg_constraint childcon;
14527 :
14528 : /* find_inheritance_children already got lock */
14529 283 : childrel = table_open(childrelid, NoLock);
14530 283 : CheckAlterTableIsSafe(childrel);
14531 :
14532 : /*
14533 : * We search for not-null constraints by column name, and others by
14534 : * constraint name.
14535 : */
14536 283 : if (con->contype == CONSTRAINT_NOTNULL)
14537 : {
14538 98 : tuple = findNotNullConstraint(childrelid, colname);
14539 98 : if (!HeapTupleIsValid(tuple))
14540 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
14541 : colname, RelationGetRelid(childrel));
14542 : }
14543 : else
14544 : {
14545 : SysScanDesc scan;
14546 : ScanKeyData skey[3];
14547 :
14548 185 : ScanKeyInit(&skey[0],
14549 : Anum_pg_constraint_conrelid,
14550 : BTEqualStrategyNumber, F_OIDEQ,
14551 : ObjectIdGetDatum(childrelid));
14552 185 : ScanKeyInit(&skey[1],
14553 : Anum_pg_constraint_contypid,
14554 : BTEqualStrategyNumber, F_OIDEQ,
14555 : ObjectIdGetDatum(InvalidOid));
14556 185 : ScanKeyInit(&skey[2],
14557 : Anum_pg_constraint_conname,
14558 : BTEqualStrategyNumber, F_NAMEEQ,
14559 : CStringGetDatum(constrName));
14560 185 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14561 : true, NULL, 3, skey);
14562 : /* There can only be one, so no need to loop */
14563 185 : tuple = systable_getnext(scan);
14564 185 : if (!HeapTupleIsValid(tuple))
14565 0 : ereport(ERROR,
14566 : (errcode(ERRCODE_UNDEFINED_OBJECT),
14567 : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14568 : constrName,
14569 : RelationGetRelationName(childrel))));
14570 185 : tuple = heap_copytuple(tuple);
14571 185 : systable_endscan(scan);
14572 : }
14573 :
14574 283 : childcon = (Form_pg_constraint) GETSTRUCT(tuple);
14575 :
14576 : /* Right now only CHECK and not-null constraints can be inherited */
14577 283 : if (childcon->contype != CONSTRAINT_CHECK &&
14578 98 : childcon->contype != CONSTRAINT_NOTNULL)
14579 0 : elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
14580 :
14581 283 : if (childcon->coninhcount <= 0) /* shouldn't happen */
14582 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
14583 : childrelid, NameStr(childcon->conname));
14584 :
14585 283 : if (recurse)
14586 : {
14587 : /*
14588 : * If the child constraint has other definition sources, just
14589 : * decrement its inheritance count; if not, recurse to delete it.
14590 : */
14591 215 : if (childcon->coninhcount == 1 && !childcon->conislocal)
14592 : {
14593 : /* Time to delete this child constraint, too */
14594 159 : dropconstraint_internal(childrel, tuple, behavior,
14595 : recurse, true, missing_ok,
14596 : lockmode);
14597 : }
14598 : else
14599 : {
14600 : /* Child constraint must survive my deletion */
14601 56 : childcon->coninhcount--;
14602 56 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14603 :
14604 : /* Make update visible */
14605 56 : CommandCounterIncrement();
14606 : }
14607 : }
14608 : else
14609 : {
14610 : /*
14611 : * If we were told to drop ONLY in this table (no recursion) and
14612 : * there are no further parents for this constraint, we need to
14613 : * mark the inheritors' constraints as locally defined rather than
14614 : * inherited.
14615 : */
14616 68 : childcon->coninhcount--;
14617 68 : if (childcon->coninhcount == 0)
14618 68 : childcon->conislocal = true;
14619 :
14620 68 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14621 :
14622 : /* Make update visible */
14623 68 : CommandCounterIncrement();
14624 : }
14625 :
14626 279 : heap_freetuple(tuple);
14627 :
14628 279 : table_close(childrel, NoLock);
14629 : }
14630 :
14631 638 : table_close(conrel, RowExclusiveLock);
14632 :
14633 638 : return conobj;
14634 : }
14635 :
14636 : /*
14637 : * ALTER COLUMN TYPE
14638 : *
14639 : * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
14640 : * TYPE during phase 1 --- the AlterTableCmd passed in here is already
14641 : * transformed (and must be, because we rely on some transformed fields).
14642 : *
14643 : * The point of this is that the execution of all ALTER COLUMN TYPEs for a
14644 : * table will be done "in parallel" during phase 3, so all the USING
14645 : * expressions should be parsed assuming the original column types. Also,
14646 : * this allows a USING expression to refer to a field that will be dropped.
14647 : *
14648 : * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
14649 : * the first two execution steps in phase 2; they must not see the effects
14650 : * of any other subcommand types, since the USING expressions are parsed
14651 : * against the unmodified table's state.
14652 : */
14653 : static void
14654 948 : ATPrepAlterColumnType(List **wqueue,
14655 : AlteredTableInfo *tab, Relation rel,
14656 : bool recurse, bool recursing,
14657 : AlterTableCmd *cmd, LOCKMODE lockmode,
14658 : AlterTableUtilityContext *context)
14659 : {
14660 948 : char *colName = cmd->name;
14661 948 : ColumnDef *def = (ColumnDef *) cmd->def;
14662 948 : TypeName *typeName = def->typeName;
14663 948 : Node *transform = def->cooked_default;
14664 : HeapTuple tuple;
14665 : Form_pg_attribute attTup;
14666 : AttrNumber attnum;
14667 : Oid targettype;
14668 : int32 targettypmod;
14669 : Oid targetcollid;
14670 : NewColumnValue *newval;
14671 948 : ParseState *pstate = make_parsestate(NULL);
14672 : AclResult aclresult;
14673 : bool is_expr;
14674 :
14675 948 : pstate->p_sourcetext = context->queryString;
14676 :
14677 948 : if (rel->rd_rel->reloftype && !recursing)
14678 4 : ereport(ERROR,
14679 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14680 : errmsg("cannot alter column type of typed table"),
14681 : parser_errposition(pstate, def->location)));
14682 :
14683 : /* lookup the attribute so we can check inheritance status */
14684 944 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
14685 944 : if (!HeapTupleIsValid(tuple))
14686 0 : ereport(ERROR,
14687 : (errcode(ERRCODE_UNDEFINED_COLUMN),
14688 : errmsg("column \"%s\" of relation \"%s\" does not exist",
14689 : colName, RelationGetRelationName(rel)),
14690 : parser_errposition(pstate, def->location)));
14691 944 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
14692 944 : attnum = attTup->attnum;
14693 :
14694 : /* Can't alter a system attribute */
14695 944 : if (attnum <= 0)
14696 4 : ereport(ERROR,
14697 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14698 : errmsg("cannot alter system column \"%s\"", colName),
14699 : parser_errposition(pstate, def->location)));
14700 :
14701 : /*
14702 : * Cannot specify USING when altering type of a generated column, because
14703 : * that would violate the generation expression.
14704 : */
14705 940 : if (attTup->attgenerated && def->cooked_default)
14706 8 : ereport(ERROR,
14707 : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
14708 : errmsg("cannot specify USING when altering type of generated column"),
14709 : errdetail("Column \"%s\" is a generated column.", colName),
14710 : parser_errposition(pstate, def->location)));
14711 :
14712 : /*
14713 : * Don't alter inherited columns. At outer level, there had better not be
14714 : * any inherited definition; when recursing, we assume this was checked at
14715 : * the parent level (see below).
14716 : */
14717 932 : if (attTup->attinhcount > 0 && !recursing)
14718 4 : ereport(ERROR,
14719 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14720 : errmsg("cannot alter inherited column \"%s\"", colName),
14721 : parser_errposition(pstate, def->location)));
14722 :
14723 : /* Don't alter columns used in the partition key */
14724 928 : if (has_partition_attrs(rel,
14725 : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
14726 : &is_expr))
14727 12 : ereport(ERROR,
14728 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14729 : errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
14730 : colName, RelationGetRelationName(rel)),
14731 : parser_errposition(pstate, def->location)));
14732 :
14733 : /* Look up the target type */
14734 916 : typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
14735 :
14736 912 : aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
14737 912 : if (aclresult != ACLCHECK_OK)
14738 8 : aclcheck_error_type(aclresult, targettype);
14739 :
14740 : /* And the collation */
14741 904 : targetcollid = GetColumnDefCollation(pstate, def, targettype);
14742 :
14743 : /* make sure datatype is legal for a column */
14744 1800 : CheckAttributeType(colName, targettype, targetcollid,
14745 900 : list_make1_oid(rel->rd_rel->reltype),
14746 900 : (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
14747 :
14748 892 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14749 : {
14750 : /* do nothing */
14751 : }
14752 868 : else if (tab->relkind == RELKIND_RELATION ||
14753 133 : tab->relkind == RELKIND_PARTITIONED_TABLE)
14754 : {
14755 : /*
14756 : * Set up an expression to transform the old data value to the new
14757 : * type. If a USING option was given, use the expression as
14758 : * transformed by transformAlterTableStmt, else just take the old
14759 : * value and try to coerce it. We do this first so that type
14760 : * incompatibility can be detected before we waste effort, and because
14761 : * we need the expression to be parsed against the original table row
14762 : * type.
14763 : */
14764 779 : if (!transform)
14765 : {
14766 628 : transform = (Node *) makeVar(1, attnum,
14767 : attTup->atttypid, attTup->atttypmod,
14768 : attTup->attcollation,
14769 : 0);
14770 : }
14771 :
14772 779 : transform = coerce_to_target_type(pstate,
14773 : transform, exprType(transform),
14774 : targettype, targettypmod,
14775 : COERCION_ASSIGNMENT,
14776 : COERCE_IMPLICIT_CAST,
14777 : -1);
14778 779 : if (transform == NULL)
14779 : {
14780 : /* error text depends on whether USING was specified or not */
14781 15 : if (def->cooked_default != NULL)
14782 4 : ereport(ERROR,
14783 : (errcode(ERRCODE_DATATYPE_MISMATCH),
14784 : errmsg("result of USING clause for column \"%s\""
14785 : " cannot be cast automatically to type %s",
14786 : colName, format_type_be(targettype)),
14787 : errhint("You might need to add an explicit cast.")));
14788 : else
14789 11 : ereport(ERROR,
14790 : (errcode(ERRCODE_DATATYPE_MISMATCH),
14791 : errmsg("column \"%s\" cannot be cast automatically to type %s",
14792 : colName, format_type_be(targettype)),
14793 : !attTup->attgenerated ?
14794 : /* translator: USING is SQL, don't translate it */
14795 : errhint("You might need to specify \"USING %s::%s\".",
14796 : quote_identifier(colName),
14797 : format_type_with_typemod(targettype,
14798 : targettypmod)) : 0));
14799 : }
14800 :
14801 : /* Fix collations after all else */
14802 764 : assign_expr_collations(pstate, transform);
14803 :
14804 : /* Expand virtual generated columns in the expr. */
14805 764 : transform = expand_generated_columns_in_expr(transform, rel, 1);
14806 :
14807 : /* Plan the expr now so we can accurately assess the need to rewrite. */
14808 764 : transform = (Node *) expression_planner((Expr *) transform);
14809 :
14810 : /*
14811 : * Add a work queue item to make ATRewriteTable update the column
14812 : * contents.
14813 : */
14814 764 : newval = palloc0_object(NewColumnValue);
14815 764 : newval->attnum = attnum;
14816 764 : newval->expr = (Expr *) transform;
14817 764 : newval->is_generated = false;
14818 :
14819 764 : tab->newvals = lappend(tab->newvals, newval);
14820 1396 : if (ATColumnChangeRequiresRewrite(transform, attnum))
14821 632 : tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
14822 : }
14823 89 : else if (transform)
14824 8 : ereport(ERROR,
14825 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14826 : errmsg("\"%s\" is not a table",
14827 : RelationGetRelationName(rel))));
14828 :
14829 869 : if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14830 : {
14831 : /*
14832 : * For relations or columns without storage, do this check now.
14833 : * Regular tables will check it later when the table is being
14834 : * rewritten.
14835 : */
14836 149 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
14837 : }
14838 :
14839 837 : ReleaseSysCache(tuple);
14840 :
14841 : /*
14842 : * Recurse manually by queueing a new command for each child, if
14843 : * necessary. We cannot apply ATSimpleRecursion here because we need to
14844 : * remap attribute numbers in the USING expression, if any.
14845 : *
14846 : * If we are told not to recurse, there had better not be any child
14847 : * tables; else the alter would put them out of step.
14848 : */
14849 837 : if (recurse)
14850 : {
14851 666 : Oid relid = RelationGetRelid(rel);
14852 : List *child_oids,
14853 : *child_numparents;
14854 : ListCell *lo,
14855 : *li;
14856 :
14857 666 : child_oids = find_all_inheritors(relid, lockmode,
14858 : &child_numparents);
14859 :
14860 : /*
14861 : * find_all_inheritors does the recursive search of the inheritance
14862 : * hierarchy, so all we have to do is process all of the relids in the
14863 : * list that it returns.
14864 : */
14865 1470 : forboth(lo, child_oids, li, child_numparents)
14866 : {
14867 820 : Oid childrelid = lfirst_oid(lo);
14868 820 : int numparents = lfirst_int(li);
14869 : Relation childrel;
14870 : HeapTuple childtuple;
14871 : Form_pg_attribute childattTup;
14872 :
14873 820 : if (childrelid == relid)
14874 666 : continue;
14875 :
14876 : /* find_all_inheritors already got lock */
14877 154 : childrel = relation_open(childrelid, NoLock);
14878 154 : CheckAlterTableIsSafe(childrel);
14879 :
14880 : /*
14881 : * Verify that the child doesn't have any inherited definitions of
14882 : * this column that came from outside this inheritance hierarchy.
14883 : * (renameatt makes a similar test, though in a different way
14884 : * because of its different recursion mechanism.)
14885 : */
14886 154 : childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
14887 : colName);
14888 154 : if (!HeapTupleIsValid(childtuple))
14889 0 : ereport(ERROR,
14890 : (errcode(ERRCODE_UNDEFINED_COLUMN),
14891 : errmsg("column \"%s\" of relation \"%s\" does not exist",
14892 : colName, RelationGetRelationName(childrel))));
14893 154 : childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
14894 :
14895 154 : if (childattTup->attinhcount > numparents)
14896 4 : ereport(ERROR,
14897 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14898 : errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
14899 : colName, RelationGetRelationName(childrel))));
14900 :
14901 150 : ReleaseSysCache(childtuple);
14902 :
14903 : /*
14904 : * Remap the attribute numbers. If no USING expression was
14905 : * specified, there is no need for this step.
14906 : */
14907 150 : if (def->cooked_default)
14908 : {
14909 : AttrMap *attmap;
14910 : bool found_whole_row;
14911 :
14912 : /* create a copy to scribble on */
14913 52 : cmd = copyObject(cmd);
14914 :
14915 52 : attmap = build_attrmap_by_name(RelationGetDescr(childrel),
14916 : RelationGetDescr(rel),
14917 : false);
14918 104 : ((ColumnDef *) cmd->def)->cooked_default =
14919 52 : map_variable_attnos(def->cooked_default,
14920 : 1, 0,
14921 : attmap,
14922 : InvalidOid, &found_whole_row);
14923 52 : if (found_whole_row)
14924 4 : ereport(ERROR,
14925 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14926 : errmsg("cannot convert whole-row table reference"),
14927 : errdetail("USING expression contains a whole-row table reference.")));
14928 48 : pfree(attmap);
14929 : }
14930 146 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
14931 138 : relation_close(childrel, NoLock);
14932 : }
14933 : }
14934 204 : else if (!recursing &&
14935 33 : find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
14936 0 : ereport(ERROR,
14937 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14938 : errmsg("type of inherited column \"%s\" must be changed in child tables too",
14939 : colName)));
14940 :
14941 821 : if (tab->relkind == RELKIND_COMPOSITE_TYPE)
14942 33 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
14943 817 : }
14944 :
14945 : /*
14946 : * When the data type of a column is changed, a rewrite might not be required
14947 : * if the new type is sufficiently identical to the old one, and the USING
14948 : * clause isn't trying to insert some other value. It's safe to skip the
14949 : * rewrite in these cases:
14950 : *
14951 : * - the old type is binary coercible to the new type
14952 : * - the new type is an unconstrained domain over the old type
14953 : * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
14954 : *
14955 : * In the case of a constrained domain, we could get by with scanning the
14956 : * table and checking the constraint rather than actually rewriting it, but we
14957 : * don't currently try to do that.
14958 : */
14959 : static bool
14960 764 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
14961 : {
14962 : Assert(expr != NULL);
14963 :
14964 : for (;;)
14965 : {
14966 : /* only one varno, so no need to check that */
14967 840 : if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
14968 132 : return false;
14969 708 : else if (IsA(expr, RelabelType))
14970 68 : expr = (Node *) ((RelabelType *) expr)->arg;
14971 640 : else if (IsA(expr, CoerceToDomain))
14972 : {
14973 4 : CoerceToDomain *d = (CoerceToDomain *) expr;
14974 :
14975 4 : if (DomainHasConstraints(d->resulttype, NULL))
14976 4 : return true;
14977 0 : expr = (Node *) d->arg;
14978 : }
14979 636 : else if (IsA(expr, FuncExpr))
14980 : {
14981 503 : FuncExpr *f = (FuncExpr *) expr;
14982 :
14983 503 : switch (f->funcid)
14984 : {
14985 12 : case F_TIMESTAMPTZ_TIMESTAMP:
14986 : case F_TIMESTAMP_TIMESTAMPTZ:
14987 12 : if (TimestampTimestampTzRequiresRewrite())
14988 4 : return true;
14989 : else
14990 8 : expr = linitial(f->args);
14991 8 : break;
14992 491 : default:
14993 491 : return true;
14994 : }
14995 : }
14996 : else
14997 133 : return true;
14998 : }
14999 : }
15000 :
15001 : /*
15002 : * ALTER COLUMN .. SET DATA TYPE
15003 : *
15004 : * Return the address of the modified column.
15005 : */
15006 : static ObjectAddress
15007 793 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
15008 : AlterTableCmd *cmd, LOCKMODE lockmode)
15009 : {
15010 793 : char *colName = cmd->name;
15011 793 : ColumnDef *def = (ColumnDef *) cmd->def;
15012 793 : TypeName *typeName = def->typeName;
15013 : HeapTuple heapTup;
15014 : Form_pg_attribute attTup,
15015 : attOldTup;
15016 : AttrNumber attnum;
15017 : HeapTuple typeTuple;
15018 : Form_pg_type tform;
15019 : Oid targettype;
15020 : int32 targettypmod;
15021 : Oid targetcollid;
15022 : Node *defaultexpr;
15023 : Relation attrelation;
15024 : Relation depRel;
15025 : ScanKeyData key[3];
15026 : SysScanDesc scan;
15027 : HeapTuple depTup;
15028 : ObjectAddress address;
15029 :
15030 : /*
15031 : * Clear all the missing values if we're rewriting the table, since this
15032 : * renders them pointless.
15033 : */
15034 793 : if (tab->rewrite)
15035 : {
15036 : Relation newrel;
15037 :
15038 592 : newrel = table_open(RelationGetRelid(rel), NoLock);
15039 592 : RelationClearMissing(newrel);
15040 592 : relation_close(newrel, NoLock);
15041 : /* make sure we don't conflict with later attribute modifications */
15042 592 : CommandCounterIncrement();
15043 : }
15044 :
15045 793 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
15046 :
15047 : /* Look up the target column */
15048 793 : heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
15049 793 : if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
15050 0 : ereport(ERROR,
15051 : (errcode(ERRCODE_UNDEFINED_COLUMN),
15052 : errmsg("column \"%s\" of relation \"%s\" does not exist",
15053 : colName, RelationGetRelationName(rel))));
15054 793 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15055 793 : attnum = attTup->attnum;
15056 793 : attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
15057 :
15058 : /* Check for multiple ALTER TYPE on same column --- can't cope */
15059 793 : if (attTup->atttypid != attOldTup->atttypid ||
15060 793 : attTup->atttypmod != attOldTup->atttypmod)
15061 0 : ereport(ERROR,
15062 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15063 : errmsg("cannot alter type of column \"%s\" twice",
15064 : colName)));
15065 :
15066 : /* Look up the target type (should not fail, since prep found it) */
15067 793 : typeTuple = typenameType(NULL, typeName, &targettypmod);
15068 793 : tform = (Form_pg_type) GETSTRUCT(typeTuple);
15069 793 : targettype = tform->oid;
15070 : /* And the collation */
15071 793 : targetcollid = GetColumnDefCollation(NULL, def, targettype);
15072 :
15073 : /*
15074 : * If there is a default expression for the column, get it and ensure we
15075 : * can coerce it to the new datatype. (We must do this before changing
15076 : * the column type, because build_column_default itself will try to
15077 : * coerce, and will not issue the error message we want if it fails.)
15078 : *
15079 : * We remove any implicit coercion steps at the top level of the old
15080 : * default expression; this has been agreed to satisfy the principle of
15081 : * least surprise. (The conversion to the new column type should act like
15082 : * it started from what the user sees as the stored expression, and the
15083 : * implicit coercions aren't going to be shown.)
15084 : */
15085 793 : if (attTup->atthasdef)
15086 : {
15087 64 : defaultexpr = build_column_default(rel, attnum);
15088 : Assert(defaultexpr);
15089 64 : defaultexpr = strip_implicit_coercions(defaultexpr);
15090 64 : defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
15091 : defaultexpr, exprType(defaultexpr),
15092 : targettype, targettypmod,
15093 : COERCION_ASSIGNMENT,
15094 : COERCE_IMPLICIT_CAST,
15095 : -1);
15096 64 : if (defaultexpr == NULL)
15097 : {
15098 4 : if (attTup->attgenerated)
15099 0 : ereport(ERROR,
15100 : (errcode(ERRCODE_DATATYPE_MISMATCH),
15101 : errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
15102 : colName, format_type_be(targettype))));
15103 : else
15104 4 : ereport(ERROR,
15105 : (errcode(ERRCODE_DATATYPE_MISMATCH),
15106 : errmsg("default for column \"%s\" cannot be cast automatically to type %s",
15107 : colName, format_type_be(targettype))));
15108 : }
15109 : }
15110 : else
15111 729 : defaultexpr = NULL;
15112 :
15113 : /*
15114 : * Find everything that depends on the column (constraints, indexes, etc),
15115 : * and record enough information to let us recreate the objects.
15116 : *
15117 : * The actual recreation does not happen here, but only after we have
15118 : * performed all the individual ALTER TYPE operations. We have to save
15119 : * the info before executing ALTER TYPE, though, else the deparser will
15120 : * get confused.
15121 : */
15122 789 : RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
15123 :
15124 : /*
15125 : * Now scan for dependencies of this column on other things. The only
15126 : * things we should find are the dependency on the column datatype and
15127 : * possibly a collation dependency. Those can be removed.
15128 : */
15129 765 : depRel = table_open(DependRelationId, RowExclusiveLock);
15130 :
15131 765 : ScanKeyInit(&key[0],
15132 : Anum_pg_depend_classid,
15133 : BTEqualStrategyNumber, F_OIDEQ,
15134 : ObjectIdGetDatum(RelationRelationId));
15135 765 : ScanKeyInit(&key[1],
15136 : Anum_pg_depend_objid,
15137 : BTEqualStrategyNumber, F_OIDEQ,
15138 : ObjectIdGetDatum(RelationGetRelid(rel)));
15139 765 : ScanKeyInit(&key[2],
15140 : Anum_pg_depend_objsubid,
15141 : BTEqualStrategyNumber, F_INT4EQ,
15142 : Int32GetDatum((int32) attnum));
15143 :
15144 765 : scan = systable_beginscan(depRel, DependDependerIndexId, true,
15145 : NULL, 3, key);
15146 :
15147 767 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15148 : {
15149 2 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15150 : ObjectAddress foundObject;
15151 :
15152 2 : foundObject.classId = foundDep->refclassid;
15153 2 : foundObject.objectId = foundDep->refobjid;
15154 2 : foundObject.objectSubId = foundDep->refobjsubid;
15155 :
15156 2 : if (foundDep->deptype != DEPENDENCY_NORMAL)
15157 0 : elog(ERROR, "found unexpected dependency type '%c'",
15158 : foundDep->deptype);
15159 2 : if (!(foundDep->refclassid == TypeRelationId &&
15160 2 : foundDep->refobjid == attTup->atttypid) &&
15161 0 : !(foundDep->refclassid == CollationRelationId &&
15162 0 : foundDep->refobjid == attTup->attcollation))
15163 0 : elog(ERROR, "found unexpected dependency for column: %s",
15164 : getObjectDescription(&foundObject, false));
15165 :
15166 2 : CatalogTupleDelete(depRel, &depTup->t_self);
15167 : }
15168 :
15169 765 : systable_endscan(scan);
15170 :
15171 765 : table_close(depRel, RowExclusiveLock);
15172 :
15173 : /*
15174 : * Here we go --- change the recorded column type and collation. (Note
15175 : * heapTup is a copy of the syscache entry, so okay to scribble on.) First
15176 : * fix up the missing value if any.
15177 : */
15178 765 : if (attTup->atthasmissing)
15179 : {
15180 : Datum missingval;
15181 : bool missingNull;
15182 :
15183 : /* if rewrite is true the missing value should already be cleared */
15184 : Assert(tab->rewrite == 0);
15185 :
15186 : /* Get the missing value datum */
15187 4 : missingval = heap_getattr(heapTup,
15188 : Anum_pg_attribute_attmissingval,
15189 : attrelation->rd_att,
15190 : &missingNull);
15191 :
15192 : /* if it's a null array there is nothing to do */
15193 :
15194 4 : if (!missingNull)
15195 : {
15196 : /*
15197 : * Get the datum out of the array and repack it in a new array
15198 : * built with the new type data. We assume that since the table
15199 : * doesn't need rewriting, the actual Datum doesn't need to be
15200 : * changed, only the array metadata.
15201 : */
15202 :
15203 4 : int one = 1;
15204 : bool isNull;
15205 4 : Datum valuesAtt[Natts_pg_attribute] = {0};
15206 4 : bool nullsAtt[Natts_pg_attribute] = {0};
15207 4 : bool replacesAtt[Natts_pg_attribute] = {0};
15208 : HeapTuple newTup;
15209 :
15210 8 : missingval = array_get_element(missingval,
15211 : 1,
15212 : &one,
15213 : 0,
15214 4 : attTup->attlen,
15215 4 : attTup->attbyval,
15216 4 : attTup->attalign,
15217 : &isNull);
15218 4 : missingval = PointerGetDatum(construct_array(&missingval,
15219 : 1,
15220 : targettype,
15221 : tform->typlen,
15222 : tform->typbyval,
15223 : tform->typalign));
15224 :
15225 4 : valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
15226 4 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
15227 4 : nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
15228 :
15229 4 : newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
15230 : valuesAtt, nullsAtt, replacesAtt);
15231 4 : heap_freetuple(heapTup);
15232 4 : heapTup = newTup;
15233 4 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15234 : }
15235 : }
15236 :
15237 765 : attTup->atttypid = targettype;
15238 765 : attTup->atttypmod = targettypmod;
15239 765 : attTup->attcollation = targetcollid;
15240 765 : if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
15241 0 : ereport(ERROR,
15242 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
15243 : errmsg("too many array dimensions"));
15244 765 : attTup->attndims = list_length(typeName->arrayBounds);
15245 765 : attTup->attlen = tform->typlen;
15246 765 : attTup->attbyval = tform->typbyval;
15247 765 : attTup->attalign = tform->typalign;
15248 765 : attTup->attstorage = tform->typstorage;
15249 765 : attTup->attcompression = InvalidCompressionMethod;
15250 :
15251 765 : ReleaseSysCache(typeTuple);
15252 :
15253 765 : CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
15254 :
15255 765 : table_close(attrelation, RowExclusiveLock);
15256 :
15257 : /* Install dependencies on new datatype and collation */
15258 765 : add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
15259 765 : add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
15260 :
15261 : /*
15262 : * Drop any pg_statistic entry for the column, since it's now wrong type
15263 : */
15264 765 : RemoveStatistics(RelationGetRelid(rel), attnum);
15265 :
15266 765 : InvokeObjectPostAlterHook(RelationRelationId,
15267 : RelationGetRelid(rel), attnum);
15268 :
15269 : /*
15270 : * Update the default, if present, by brute force --- remove and re-add
15271 : * the default. Probably unsafe to take shortcuts, since the new version
15272 : * may well have additional dependencies. (It's okay to do this now,
15273 : * rather than after other ALTER TYPE commands, since the default won't
15274 : * depend on other column types.)
15275 : */
15276 765 : if (defaultexpr)
15277 : {
15278 : /*
15279 : * If it's a GENERATED default, drop its dependency records, in
15280 : * particular its INTERNAL dependency on the column, which would
15281 : * otherwise cause dependency.c to refuse to perform the deletion.
15282 : */
15283 60 : if (attTup->attgenerated)
15284 : {
15285 28 : Oid attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
15286 :
15287 28 : if (!OidIsValid(attrdefoid))
15288 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
15289 : RelationGetRelid(rel), attnum);
15290 28 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
15291 : }
15292 :
15293 : /*
15294 : * Make updates-so-far visible, particularly the new pg_attribute row
15295 : * which will be updated again.
15296 : */
15297 60 : CommandCounterIncrement();
15298 :
15299 : /*
15300 : * We use RESTRICT here for safety, but at present we do not expect
15301 : * anything to depend on the default.
15302 : */
15303 60 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
15304 : true);
15305 :
15306 60 : (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
15307 : }
15308 :
15309 765 : ObjectAddressSubSet(address, RelationRelationId,
15310 : RelationGetRelid(rel), attnum);
15311 :
15312 : /* Cleanup */
15313 765 : heap_freetuple(heapTup);
15314 :
15315 765 : return address;
15316 : }
15317 :
15318 : /*
15319 : * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
15320 : * that depends on the column (constraints, indexes, etc), and record enough
15321 : * information to let us recreate the objects.
15322 : */
15323 : static void
15324 946 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
15325 : Relation rel, AttrNumber attnum, const char *colName)
15326 : {
15327 : Relation depRel;
15328 : ScanKeyData key[3];
15329 : SysScanDesc scan;
15330 : HeapTuple depTup;
15331 :
15332 : Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
15333 :
15334 946 : depRel = table_open(DependRelationId, RowExclusiveLock);
15335 :
15336 946 : ScanKeyInit(&key[0],
15337 : Anum_pg_depend_refclassid,
15338 : BTEqualStrategyNumber, F_OIDEQ,
15339 : ObjectIdGetDatum(RelationRelationId));
15340 946 : ScanKeyInit(&key[1],
15341 : Anum_pg_depend_refobjid,
15342 : BTEqualStrategyNumber, F_OIDEQ,
15343 : ObjectIdGetDatum(RelationGetRelid(rel)));
15344 946 : ScanKeyInit(&key[2],
15345 : Anum_pg_depend_refobjsubid,
15346 : BTEqualStrategyNumber, F_INT4EQ,
15347 : Int32GetDatum((int32) attnum));
15348 :
15349 946 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15350 : NULL, 3, key);
15351 :
15352 1925 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15353 : {
15354 1003 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15355 : ObjectAddress foundObject;
15356 :
15357 1003 : foundObject.classId = foundDep->classid;
15358 1003 : foundObject.objectId = foundDep->objid;
15359 1003 : foundObject.objectSubId = foundDep->objsubid;
15360 :
15361 1003 : switch (foundObject.classId)
15362 : {
15363 193 : case RelationRelationId:
15364 : {
15365 193 : char relKind = get_rel_relkind(foundObject.objectId);
15366 :
15367 193 : if (relKind == RELKIND_INDEX ||
15368 : relKind == RELKIND_PARTITIONED_INDEX)
15369 : {
15370 : Assert(foundObject.objectSubId == 0);
15371 168 : RememberIndexForRebuilding(foundObject.objectId, tab);
15372 : }
15373 25 : else if (relKind == RELKIND_SEQUENCE)
15374 : {
15375 : /*
15376 : * This must be a SERIAL column's sequence. We need
15377 : * not do anything to it.
15378 : */
15379 : Assert(foundObject.objectSubId == 0);
15380 : }
15381 : else
15382 : {
15383 : /* Not expecting any other direct dependencies... */
15384 0 : elog(ERROR, "unexpected object depending on column: %s",
15385 : getObjectDescription(&foundObject, false));
15386 : }
15387 193 : break;
15388 : }
15389 :
15390 516 : case ConstraintRelationId:
15391 : Assert(foundObject.objectSubId == 0);
15392 516 : RememberConstraintForRebuilding(foundObject.objectId, tab);
15393 516 : break;
15394 :
15395 0 : case ProcedureRelationId:
15396 :
15397 : /*
15398 : * A new-style SQL function can depend on a column, if that
15399 : * column is referenced in the parsed function body. Ideally
15400 : * we'd automatically update the function by deparsing and
15401 : * reparsing it, but that's risky and might well fail anyhow.
15402 : * FIXME someday.
15403 : *
15404 : * This is only a problem for AT_AlterColumnType, not
15405 : * AT_SetExpression.
15406 : */
15407 0 : if (subtype == AT_AlterColumnType)
15408 0 : ereport(ERROR,
15409 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15410 : errmsg("cannot alter type of a column used by a function or procedure"),
15411 : errdetail("%s depends on column \"%s\"",
15412 : getObjectDescription(&foundObject, false),
15413 : colName)));
15414 0 : break;
15415 :
15416 8 : case RewriteRelationId:
15417 :
15418 : /*
15419 : * View/rule bodies have pretty much the same issues as
15420 : * function bodies. FIXME someday.
15421 : */
15422 8 : if (subtype == AT_AlterColumnType)
15423 8 : ereport(ERROR,
15424 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15425 : errmsg("cannot alter type of a column used by a view or rule"),
15426 : errdetail("%s depends on column \"%s\"",
15427 : getObjectDescription(&foundObject, false),
15428 : colName)));
15429 0 : break;
15430 :
15431 0 : case TriggerRelationId:
15432 :
15433 : /*
15434 : * A trigger can depend on a column because the column is
15435 : * specified as an update target, or because the column is
15436 : * used in the trigger's WHEN condition. The first case would
15437 : * not require any extra work, but the second case would
15438 : * require updating the WHEN expression, which has the same
15439 : * issues as above. Since we can't easily tell which case
15440 : * applies, we punt for both. FIXME someday.
15441 : */
15442 0 : if (subtype == AT_AlterColumnType)
15443 0 : ereport(ERROR,
15444 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15445 : errmsg("cannot alter type of a column used in a trigger definition"),
15446 : errdetail("%s depends on column \"%s\"",
15447 : getObjectDescription(&foundObject, false),
15448 : colName)));
15449 0 : break;
15450 :
15451 0 : case PolicyRelationId:
15452 :
15453 : /*
15454 : * A policy can depend on a column because the column is
15455 : * specified in the policy's USING or WITH CHECK qual
15456 : * expressions. It might be possible to rewrite and recheck
15457 : * the policy expression, but punt for now. It's certainly
15458 : * easy enough to remove and recreate the policy; still, FIXME
15459 : * someday.
15460 : */
15461 0 : if (subtype == AT_AlterColumnType)
15462 0 : ereport(ERROR,
15463 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15464 : errmsg("cannot alter type of a column used in a policy definition"),
15465 : errdetail("%s depends on column \"%s\"",
15466 : getObjectDescription(&foundObject, false),
15467 : colName)));
15468 0 : break;
15469 :
15470 233 : case AttrDefaultRelationId:
15471 : {
15472 233 : ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
15473 :
15474 450 : if (col.objectId == RelationGetRelid(rel) &&
15475 233 : col.objectSubId == attnum)
15476 : {
15477 : /*
15478 : * Ignore the column's own default expression. The
15479 : * caller deals with it.
15480 : */
15481 : }
15482 : else
15483 : {
15484 : /*
15485 : * This must be a reference from the expression of a
15486 : * generated column elsewhere in the same table.
15487 : * Changing the type/generated expression of a column
15488 : * that is used by a generated column is not allowed
15489 : * by SQL standard, so just punt for now. It might be
15490 : * doable with some thinking and effort.
15491 : */
15492 16 : if (subtype == AT_AlterColumnType)
15493 16 : ereport(ERROR,
15494 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15495 : errmsg("cannot alter type of a column used by a generated column"),
15496 : errdetail("Column \"%s\" is used by generated column \"%s\".",
15497 : colName,
15498 : get_attname(col.objectId,
15499 : col.objectSubId,
15500 : false))));
15501 : }
15502 217 : break;
15503 : }
15504 :
15505 53 : case StatisticExtRelationId:
15506 :
15507 : /*
15508 : * Give the extended-stats machinery a chance to fix anything
15509 : * that this column type change would break.
15510 : */
15511 53 : RememberStatisticsForRebuilding(foundObject.objectId, tab);
15512 53 : break;
15513 :
15514 0 : case PublicationRelRelationId:
15515 :
15516 : /*
15517 : * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
15518 : * clause. Same issues as above. FIXME someday.
15519 : */
15520 0 : if (subtype == AT_AlterColumnType)
15521 0 : ereport(ERROR,
15522 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15523 : errmsg("cannot alter type of a column used by a publication WHERE clause"),
15524 : errdetail("%s depends on column \"%s\"",
15525 : getObjectDescription(&foundObject, false),
15526 : colName)));
15527 0 : break;
15528 :
15529 0 : default:
15530 :
15531 : /*
15532 : * We don't expect any other sorts of objects to depend on a
15533 : * column.
15534 : */
15535 0 : elog(ERROR, "unexpected object depending on column: %s",
15536 : getObjectDescription(&foundObject, false));
15537 : break;
15538 : }
15539 : }
15540 :
15541 922 : systable_endscan(scan);
15542 922 : table_close(depRel, NoLock);
15543 922 : }
15544 :
15545 : /*
15546 : * Subroutine for ATExecAlterColumnType: remember that a replica identity
15547 : * needs to be reset.
15548 : */
15549 : static void
15550 307 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
15551 : {
15552 307 : if (!get_index_isreplident(indoid))
15553 295 : return;
15554 :
15555 12 : if (tab->replicaIdentityIndex)
15556 0 : elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
15557 :
15558 12 : tab->replicaIdentityIndex = get_rel_name(indoid);
15559 : }
15560 :
15561 : /*
15562 : * Subroutine for ATExecAlterColumnType: remember any clustered index.
15563 : */
15564 : static void
15565 307 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
15566 : {
15567 307 : if (!get_index_isclustered(indoid))
15568 295 : return;
15569 :
15570 12 : if (tab->clusterOnIndex)
15571 0 : elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
15572 :
15573 12 : tab->clusterOnIndex = get_rel_name(indoid);
15574 : }
15575 :
15576 : /*
15577 : * Subroutine for ATExecAlterColumnType: remember that a constraint needs
15578 : * to be rebuilt (which we might already know).
15579 : */
15580 : static void
15581 524 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
15582 : {
15583 : /*
15584 : * This de-duplication check is critical for two independent reasons: we
15585 : * mustn't try to recreate the same constraint twice, and if a constraint
15586 : * depends on more than one column whose type is to be altered, we must
15587 : * capture its definition string before applying any of the column type
15588 : * changes. ruleutils.c will get confused if we ask again later.
15589 : */
15590 524 : if (!list_member_oid(tab->changedConstraintOids, conoid))
15591 : {
15592 : /* OK, capture the constraint's existing definition string */
15593 452 : char *defstring = pg_get_constraintdef_command(conoid);
15594 : Oid indoid;
15595 :
15596 : /*
15597 : * It is critical to create not-null constraints ahead of primary key
15598 : * indexes; otherwise, the not-null constraint would be created by the
15599 : * primary key, and the constraint name would be wrong.
15600 : */
15601 452 : if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
15602 : {
15603 163 : tab->changedConstraintOids = lcons_oid(conoid,
15604 : tab->changedConstraintOids);
15605 163 : tab->changedConstraintDefs = lcons(defstring,
15606 : tab->changedConstraintDefs);
15607 : }
15608 : else
15609 : {
15610 :
15611 289 : tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
15612 : conoid);
15613 289 : tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
15614 : defstring);
15615 : }
15616 :
15617 : /*
15618 : * For the index of a constraint, if any, remember if it is used for
15619 : * the table's replica identity or if it is a clustered index, so that
15620 : * ATPostAlterTypeCleanup() can queue up commands necessary to restore
15621 : * those properties.
15622 : */
15623 452 : indoid = get_constraint_index(conoid);
15624 452 : if (OidIsValid(indoid))
15625 : {
15626 152 : RememberReplicaIdentityForRebuilding(indoid, tab);
15627 152 : RememberClusterOnForRebuilding(indoid, tab);
15628 : }
15629 : }
15630 524 : }
15631 :
15632 : /*
15633 : * Subroutine for ATExecAlterColumnType: remember that an index needs
15634 : * to be rebuilt (which we might already know).
15635 : */
15636 : static void
15637 168 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
15638 : {
15639 : /*
15640 : * This de-duplication check is critical for two independent reasons: we
15641 : * mustn't try to recreate the same index twice, and if an index depends
15642 : * on more than one column whose type is to be altered, we must capture
15643 : * its definition string before applying any of the column type changes.
15644 : * ruleutils.c will get confused if we ask again later.
15645 : */
15646 168 : if (!list_member_oid(tab->changedIndexOids, indoid))
15647 : {
15648 : /*
15649 : * Before adding it as an index-to-rebuild, we'd better see if it
15650 : * belongs to a constraint, and if so rebuild the constraint instead.
15651 : * Typically this check fails, because constraint indexes normally
15652 : * have only dependencies on their constraint. But it's possible for
15653 : * such an index to also have direct dependencies on table columns,
15654 : * for example with a partial exclusion constraint.
15655 : */
15656 163 : Oid conoid = get_index_constraint(indoid);
15657 :
15658 163 : if (OidIsValid(conoid))
15659 : {
15660 8 : RememberConstraintForRebuilding(conoid, tab);
15661 : }
15662 : else
15663 : {
15664 : /* OK, capture the index's existing definition string */
15665 155 : char *defstring = pg_get_indexdef_string(indoid);
15666 :
15667 155 : tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
15668 : indoid);
15669 155 : tab->changedIndexDefs = lappend(tab->changedIndexDefs,
15670 : defstring);
15671 :
15672 : /*
15673 : * Remember if this index is used for the table's replica identity
15674 : * or if it is a clustered index, so that ATPostAlterTypeCleanup()
15675 : * can queue up commands necessary to restore those properties.
15676 : */
15677 155 : RememberReplicaIdentityForRebuilding(indoid, tab);
15678 155 : RememberClusterOnForRebuilding(indoid, tab);
15679 : }
15680 : }
15681 168 : }
15682 :
15683 : /*
15684 : * Subroutine for ATExecAlterColumnType: remember that a statistics object
15685 : * needs to be rebuilt (which we might already know).
15686 : */
15687 : static void
15688 53 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
15689 : {
15690 : /*
15691 : * This de-duplication check is critical for two independent reasons: we
15692 : * mustn't try to recreate the same statistics object twice, and if the
15693 : * statistics object depends on more than one column whose type is to be
15694 : * altered, we must capture its definition string before applying any of
15695 : * the type changes. ruleutils.c will get confused if we ask again later.
15696 : */
15697 53 : if (!list_member_oid(tab->changedStatisticsOids, stxoid))
15698 : {
15699 : /* OK, capture the statistics object's existing definition string */
15700 53 : char *defstring = pg_get_statisticsobjdef_string(stxoid);
15701 :
15702 53 : tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
15703 : stxoid);
15704 53 : tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
15705 : defstring);
15706 : }
15707 53 : }
15708 :
15709 : /*
15710 : * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
15711 : * operations for a particular relation. We have to drop and recreate all the
15712 : * indexes and constraints that depend on the altered columns. We do the
15713 : * actual dropping here, but re-creation is managed by adding work queue
15714 : * entries to do those steps later.
15715 : */
15716 : static void
15717 890 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
15718 : {
15719 : ObjectAddress obj;
15720 : ObjectAddresses *objects;
15721 : ListCell *def_item;
15722 : ListCell *oid_item;
15723 :
15724 : /*
15725 : * Collect all the constraints and indexes to drop so we can process them
15726 : * in a single call. That way we don't have to worry about dependencies
15727 : * among them.
15728 : */
15729 890 : objects = new_object_addresses();
15730 :
15731 : /*
15732 : * Re-parse the index and constraint definitions, and attach them to the
15733 : * appropriate work queue entries. We do this before dropping because in
15734 : * the case of a constraint on another table, we might not yet have
15735 : * exclusive lock on the table the constraint is attached to, and we need
15736 : * to get that before reparsing/dropping. (That's possible at least for
15737 : * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
15738 : * requires a dependency on the target table's composite type in the other
15739 : * table's constraint expressions.)
15740 : *
15741 : * We can't rely on the output of deparsing to tell us which relation to
15742 : * operate on, because concurrent activity might have made the name
15743 : * resolve differently. Instead, we've got to use the OID of the
15744 : * constraint or index we're processing to figure out which relation to
15745 : * operate on.
15746 : */
15747 1342 : forboth(oid_item, tab->changedConstraintOids,
15748 : def_item, tab->changedConstraintDefs)
15749 : {
15750 452 : Oid oldId = lfirst_oid(oid_item);
15751 : HeapTuple tup;
15752 : Form_pg_constraint con;
15753 : Oid relid;
15754 : Oid confrelid;
15755 : bool conislocal;
15756 :
15757 452 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
15758 452 : if (!HeapTupleIsValid(tup)) /* should not happen */
15759 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
15760 452 : con = (Form_pg_constraint) GETSTRUCT(tup);
15761 452 : if (OidIsValid(con->conrelid))
15762 443 : relid = con->conrelid;
15763 : else
15764 : {
15765 : /* must be a domain constraint */
15766 9 : relid = get_typ_typrelid(getBaseType(con->contypid));
15767 9 : if (!OidIsValid(relid))
15768 0 : elog(ERROR, "could not identify relation associated with constraint %u", oldId);
15769 : }
15770 452 : confrelid = con->confrelid;
15771 452 : conislocal = con->conislocal;
15772 452 : ReleaseSysCache(tup);
15773 :
15774 452 : ObjectAddressSet(obj, ConstraintRelationId, oldId);
15775 452 : add_exact_object_address(&obj, objects);
15776 :
15777 : /*
15778 : * If the constraint is inherited (only), we don't want to inject a
15779 : * new definition here; it'll get recreated when
15780 : * ATAddCheckNNConstraint recurses from adding the parent table's
15781 : * constraint. But we had to carry the info this far so that we can
15782 : * drop the constraint below.
15783 : */
15784 452 : if (!conislocal)
15785 34 : continue;
15786 :
15787 : /*
15788 : * When rebuilding another table's constraint that references the
15789 : * table we're modifying, we might not yet have any lock on the other
15790 : * table, so get one now. We'll need AccessExclusiveLock for the DROP
15791 : * CONSTRAINT step, so there's no value in asking for anything weaker.
15792 : */
15793 418 : if (relid != tab->relid)
15794 36 : LockRelationOid(relid, AccessExclusiveLock);
15795 :
15796 418 : ATPostAlterTypeParse(oldId, relid, confrelid,
15797 418 : (char *) lfirst(def_item),
15798 418 : wqueue, lockmode, tab->rewrite);
15799 : }
15800 1045 : forboth(oid_item, tab->changedIndexOids,
15801 : def_item, tab->changedIndexDefs)
15802 : {
15803 155 : Oid oldId = lfirst_oid(oid_item);
15804 : Oid relid;
15805 :
15806 155 : relid = IndexGetRelation(oldId, false);
15807 :
15808 : /*
15809 : * As above, make sure we have lock on the index's table if it's not
15810 : * the same table.
15811 : */
15812 155 : if (relid != tab->relid)
15813 12 : LockRelationOid(relid, AccessExclusiveLock);
15814 :
15815 155 : ATPostAlterTypeParse(oldId, relid, InvalidOid,
15816 155 : (char *) lfirst(def_item),
15817 155 : wqueue, lockmode, tab->rewrite);
15818 :
15819 155 : ObjectAddressSet(obj, RelationRelationId, oldId);
15820 155 : add_exact_object_address(&obj, objects);
15821 : }
15822 :
15823 : /* add dependencies for new statistics */
15824 943 : forboth(oid_item, tab->changedStatisticsOids,
15825 : def_item, tab->changedStatisticsDefs)
15826 : {
15827 53 : Oid oldId = lfirst_oid(oid_item);
15828 : Oid relid;
15829 :
15830 53 : relid = StatisticsGetRelation(oldId, false);
15831 :
15832 : /*
15833 : * As above, make sure we have lock on the statistics object's table
15834 : * if it's not the same table. However, we take
15835 : * ShareUpdateExclusiveLock here, aligning with the lock level used in
15836 : * CreateStatistics and RemoveStatisticsById.
15837 : *
15838 : * CAUTION: this should be done after all cases that grab
15839 : * AccessExclusiveLock, else we risk causing deadlock due to needing
15840 : * to promote our table lock.
15841 : */
15842 53 : if (relid != tab->relid)
15843 12 : LockRelationOid(relid, ShareUpdateExclusiveLock);
15844 :
15845 53 : ATPostAlterTypeParse(oldId, relid, InvalidOid,
15846 53 : (char *) lfirst(def_item),
15847 53 : wqueue, lockmode, tab->rewrite);
15848 :
15849 53 : ObjectAddressSet(obj, StatisticExtRelationId, oldId);
15850 53 : add_exact_object_address(&obj, objects);
15851 : }
15852 :
15853 : /*
15854 : * Queue up command to restore replica identity index marking
15855 : */
15856 890 : if (tab->replicaIdentityIndex)
15857 : {
15858 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
15859 12 : ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
15860 :
15861 12 : subcmd->identity_type = REPLICA_IDENTITY_INDEX;
15862 12 : subcmd->name = tab->replicaIdentityIndex;
15863 12 : cmd->subtype = AT_ReplicaIdentity;
15864 12 : cmd->def = (Node *) subcmd;
15865 :
15866 : /* do it after indexes and constraints */
15867 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
15868 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15869 : }
15870 :
15871 : /*
15872 : * Queue up command to restore marking of index used for cluster.
15873 : */
15874 890 : if (tab->clusterOnIndex)
15875 : {
15876 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
15877 :
15878 12 : cmd->subtype = AT_ClusterOn;
15879 12 : cmd->name = tab->clusterOnIndex;
15880 :
15881 : /* do it after indexes and constraints */
15882 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
15883 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
15884 : }
15885 :
15886 : /*
15887 : * It should be okay to use DROP_RESTRICT here, since nothing else should
15888 : * be depending on these objects.
15889 : */
15890 890 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
15891 :
15892 890 : free_object_addresses(objects);
15893 :
15894 : /*
15895 : * The objects will get recreated during subsequent passes over the work
15896 : * queue.
15897 : */
15898 890 : }
15899 :
15900 : /*
15901 : * Parse the previously-saved definition string for a constraint, index or
15902 : * statistics object against the newly-established column data type(s), and
15903 : * queue up the resulting command parsetrees for execution.
15904 : *
15905 : * This might fail if, for example, you have a WHERE clause that uses an
15906 : * operator that's not available for the new column type.
15907 : */
15908 : static void
15909 626 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, char *cmd,
15910 : List **wqueue, LOCKMODE lockmode, bool rewrite)
15911 : {
15912 : List *raw_parsetree_list;
15913 : List *querytree_list;
15914 : ListCell *list_item;
15915 : Relation rel;
15916 :
15917 : /*
15918 : * We expect that we will get only ALTER TABLE and CREATE INDEX
15919 : * statements. Hence, there is no need to pass them through
15920 : * parse_analyze_*() or the rewriter, but instead we need to pass them
15921 : * through parse_utilcmd.c to make them ready for execution.
15922 : */
15923 626 : raw_parsetree_list = raw_parser(cmd, RAW_PARSE_DEFAULT);
15924 626 : querytree_list = NIL;
15925 1252 : foreach(list_item, raw_parsetree_list)
15926 : {
15927 626 : RawStmt *rs = lfirst_node(RawStmt, list_item);
15928 626 : Node *stmt = rs->stmt;
15929 :
15930 626 : if (IsA(stmt, IndexStmt))
15931 155 : querytree_list = lappend(querytree_list,
15932 155 : transformIndexStmt(oldRelId,
15933 : (IndexStmt *) stmt,
15934 : cmd));
15935 471 : else if (IsA(stmt, AlterTableStmt))
15936 : {
15937 : List *beforeStmts;
15938 : List *afterStmts;
15939 :
15940 409 : stmt = (Node *) transformAlterTableStmt(oldRelId,
15941 : (AlterTableStmt *) stmt,
15942 : cmd,
15943 : &beforeStmts,
15944 : &afterStmts);
15945 409 : querytree_list = list_concat(querytree_list, beforeStmts);
15946 409 : querytree_list = lappend(querytree_list, stmt);
15947 409 : querytree_list = list_concat(querytree_list, afterStmts);
15948 : }
15949 62 : else if (IsA(stmt, CreateStatsStmt))
15950 53 : querytree_list = lappend(querytree_list,
15951 53 : transformStatsStmt(oldRelId,
15952 : (CreateStatsStmt *) stmt,
15953 : cmd));
15954 : else
15955 9 : querytree_list = lappend(querytree_list, stmt);
15956 : }
15957 :
15958 : /* Caller should already have acquired whatever lock we need. */
15959 626 : rel = relation_open(oldRelId, NoLock);
15960 :
15961 : /*
15962 : * Attach each generated command to the proper place in the work queue.
15963 : * Note this could result in creation of entirely new work-queue entries.
15964 : *
15965 : * Also note that we have to tweak the command subtypes, because it turns
15966 : * out that re-creation of indexes and constraints has to act a bit
15967 : * differently from initial creation.
15968 : */
15969 1252 : foreach(list_item, querytree_list)
15970 : {
15971 626 : Node *stm = (Node *) lfirst(list_item);
15972 : AlteredTableInfo *tab;
15973 :
15974 626 : tab = ATGetQueueEntry(wqueue, rel);
15975 :
15976 626 : if (IsA(stm, IndexStmt))
15977 : {
15978 155 : IndexStmt *stmt = (IndexStmt *) stm;
15979 : AlterTableCmd *newcmd;
15980 :
15981 155 : if (!rewrite)
15982 41 : TryReuseIndex(oldId, stmt);
15983 155 : stmt->reset_default_tblspc = true;
15984 : /* keep the index's comment */
15985 155 : stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
15986 :
15987 155 : newcmd = makeNode(AlterTableCmd);
15988 155 : newcmd->subtype = AT_ReAddIndex;
15989 155 : newcmd->def = (Node *) stmt;
15990 155 : tab->subcmds[AT_PASS_OLD_INDEX] =
15991 155 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
15992 : }
15993 471 : else if (IsA(stm, AlterTableStmt))
15994 : {
15995 409 : AlterTableStmt *stmt = (AlterTableStmt *) stm;
15996 : ListCell *lcmd;
15997 :
15998 818 : foreach(lcmd, stmt->cmds)
15999 : {
16000 409 : AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
16001 :
16002 409 : if (cmd->subtype == AT_AddIndex)
16003 : {
16004 : IndexStmt *indstmt;
16005 : Oid indoid;
16006 :
16007 152 : indstmt = castNode(IndexStmt, cmd->def);
16008 152 : indoid = get_constraint_index(oldId);
16009 :
16010 152 : if (!rewrite)
16011 32 : TryReuseIndex(indoid, indstmt);
16012 : /* keep any comment on the index */
16013 152 : indstmt->idxcomment = GetComment(indoid,
16014 : RelationRelationId, 0);
16015 152 : indstmt->reset_default_tblspc = true;
16016 :
16017 152 : cmd->subtype = AT_ReAddIndex;
16018 152 : tab->subcmds[AT_PASS_OLD_INDEX] =
16019 152 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
16020 :
16021 : /* recreate any comment on the constraint */
16022 152 : RebuildConstraintComment(tab,
16023 : AT_PASS_OLD_INDEX,
16024 : oldId,
16025 : rel,
16026 : NIL,
16027 152 : indstmt->idxname);
16028 : }
16029 257 : else if (cmd->subtype == AT_AddConstraint)
16030 : {
16031 257 : Constraint *con = castNode(Constraint, cmd->def);
16032 :
16033 257 : con->old_pktable_oid = refRelId;
16034 : /* rewriting neither side of a FK */
16035 257 : if (con->contype == CONSTR_FOREIGN &&
16036 48 : !rewrite && tab->rewrite == 0)
16037 4 : TryReuseForeignKey(oldId, con);
16038 257 : con->reset_default_tblspc = true;
16039 257 : cmd->subtype = AT_ReAddConstraint;
16040 257 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16041 257 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16042 :
16043 : /*
16044 : * Recreate any comment on the constraint. If we have
16045 : * recreated a primary key, then transformTableConstraint
16046 : * has added an unnamed not-null constraint here; skip
16047 : * this in that case.
16048 : */
16049 257 : if (con->conname)
16050 257 : RebuildConstraintComment(tab,
16051 : AT_PASS_OLD_CONSTR,
16052 : oldId,
16053 : rel,
16054 : NIL,
16055 257 : con->conname);
16056 : else
16057 : Assert(con->contype == CONSTR_NOTNULL);
16058 : }
16059 : else
16060 0 : elog(ERROR, "unexpected statement subtype: %d",
16061 : (int) cmd->subtype);
16062 : }
16063 : }
16064 62 : else if (IsA(stm, AlterDomainStmt))
16065 : {
16066 9 : AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
16067 :
16068 9 : if (stmt->subtype == AD_AddConstraint)
16069 : {
16070 9 : Constraint *con = castNode(Constraint, stmt->def);
16071 9 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16072 :
16073 9 : cmd->subtype = AT_ReAddDomainConstraint;
16074 9 : cmd->def = (Node *) stmt;
16075 9 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16076 9 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16077 :
16078 : /* recreate any comment on the constraint */
16079 9 : RebuildConstraintComment(tab,
16080 : AT_PASS_OLD_CONSTR,
16081 : oldId,
16082 : NULL,
16083 : stmt->typeName,
16084 9 : con->conname);
16085 : }
16086 : else
16087 0 : elog(ERROR, "unexpected statement subtype: %d",
16088 : (int) stmt->subtype);
16089 : }
16090 53 : else if (IsA(stm, CreateStatsStmt))
16091 : {
16092 53 : CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
16093 : AlterTableCmd *newcmd;
16094 :
16095 : /* keep the statistics object's comment */
16096 53 : stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
16097 :
16098 53 : newcmd = makeNode(AlterTableCmd);
16099 53 : newcmd->subtype = AT_ReAddStatistics;
16100 53 : newcmd->def = (Node *) stmt;
16101 53 : tab->subcmds[AT_PASS_MISC] =
16102 53 : lappend(tab->subcmds[AT_PASS_MISC], newcmd);
16103 : }
16104 : else
16105 0 : elog(ERROR, "unexpected statement type: %d",
16106 : (int) nodeTag(stm));
16107 : }
16108 :
16109 626 : relation_close(rel, NoLock);
16110 626 : }
16111 :
16112 : /*
16113 : * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
16114 : * for a table or domain constraint that is being rebuilt.
16115 : *
16116 : * objid is the OID of the constraint.
16117 : * Pass "rel" for a table constraint, or "domname" (domain's qualified name
16118 : * as a string list) for a domain constraint.
16119 : * (We could dig that info, as well as the conname, out of the pg_constraint
16120 : * entry; but callers already have them so might as well pass them.)
16121 : */
16122 : static void
16123 418 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
16124 : Relation rel, List *domname,
16125 : const char *conname)
16126 : {
16127 : CommentStmt *cmd;
16128 : char *comment_str;
16129 : AlterTableCmd *newcmd;
16130 :
16131 : /* Look for comment for object wanted, and leave if none */
16132 418 : comment_str = GetComment(objid, ConstraintRelationId, 0);
16133 418 : if (comment_str == NULL)
16134 358 : return;
16135 :
16136 : /* Build CommentStmt node, copying all input data for safety */
16137 60 : cmd = makeNode(CommentStmt);
16138 60 : if (rel)
16139 : {
16140 52 : cmd->objtype = OBJECT_TABCONSTRAINT;
16141 52 : cmd->object = (Node *)
16142 52 : list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
16143 : makeString(pstrdup(RelationGetRelationName(rel))),
16144 : makeString(pstrdup(conname)));
16145 : }
16146 : else
16147 : {
16148 8 : cmd->objtype = OBJECT_DOMCONSTRAINT;
16149 8 : cmd->object = (Node *)
16150 8 : list_make2(makeTypeNameFromNameList(copyObject(domname)),
16151 : makeString(pstrdup(conname)));
16152 : }
16153 60 : cmd->comment = comment_str;
16154 :
16155 : /* Append it to list of commands */
16156 60 : newcmd = makeNode(AlterTableCmd);
16157 60 : newcmd->subtype = AT_ReAddComment;
16158 60 : newcmd->def = (Node *) cmd;
16159 60 : tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
16160 : }
16161 :
16162 : /*
16163 : * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
16164 : * for the real analysis, then mutates the IndexStmt based on that verdict.
16165 : */
16166 : static void
16167 73 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
16168 : {
16169 73 : if (CheckIndexCompatible(oldId,
16170 73 : stmt->accessMethod,
16171 73 : stmt->indexParams,
16172 73 : stmt->excludeOpNames,
16173 73 : stmt->iswithoutoverlaps))
16174 : {
16175 69 : Relation irel = index_open(oldId, NoLock);
16176 :
16177 : /* If it's a partitioned index, there is no storage to share. */
16178 69 : if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
16179 : {
16180 49 : stmt->oldNumber = irel->rd_locator.relNumber;
16181 49 : stmt->oldCreateSubid = irel->rd_createSubid;
16182 49 : stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
16183 : }
16184 69 : index_close(irel, NoLock);
16185 : }
16186 73 : }
16187 :
16188 : /*
16189 : * Subroutine for ATPostAlterTypeParse().
16190 : *
16191 : * Stash the old P-F equality operator into the Constraint node, for possible
16192 : * use by ATAddForeignKeyConstraint() in determining whether revalidation of
16193 : * this constraint can be skipped.
16194 : */
16195 : static void
16196 4 : TryReuseForeignKey(Oid oldId, Constraint *con)
16197 : {
16198 : HeapTuple tup;
16199 : Datum adatum;
16200 : ArrayType *arr;
16201 : Oid *rawarr;
16202 : int numkeys;
16203 : int i;
16204 :
16205 : Assert(con->contype == CONSTR_FOREIGN);
16206 : Assert(con->old_conpfeqop == NIL); /* already prepared this node */
16207 :
16208 4 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16209 4 : if (!HeapTupleIsValid(tup)) /* should not happen */
16210 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16211 :
16212 4 : adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
16213 : Anum_pg_constraint_conpfeqop);
16214 4 : arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
16215 4 : numkeys = ARR_DIMS(arr)[0];
16216 : /* test follows the one in ri_FetchConstraintInfo() */
16217 4 : if (ARR_NDIM(arr) != 1 ||
16218 4 : ARR_HASNULL(arr) ||
16219 4 : ARR_ELEMTYPE(arr) != OIDOID)
16220 0 : elog(ERROR, "conpfeqop is not a 1-D Oid array");
16221 4 : rawarr = (Oid *) ARR_DATA_PTR(arr);
16222 :
16223 : /* stash a List of the operator Oids in our Constraint node */
16224 8 : for (i = 0; i < numkeys; i++)
16225 4 : con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
16226 :
16227 4 : ReleaseSysCache(tup);
16228 4 : }
16229 :
16230 : /*
16231 : * ALTER COLUMN .. OPTIONS ( ... )
16232 : *
16233 : * Returns the address of the modified column
16234 : */
16235 : static ObjectAddress
16236 94 : ATExecAlterColumnGenericOptions(Relation rel,
16237 : const char *colName,
16238 : List *options,
16239 : LOCKMODE lockmode)
16240 : {
16241 : Relation ftrel;
16242 : Relation attrel;
16243 : ForeignServer *server;
16244 : ForeignDataWrapper *fdw;
16245 : HeapTuple tuple;
16246 : HeapTuple newtuple;
16247 : bool isnull;
16248 : Datum repl_val[Natts_pg_attribute];
16249 : bool repl_null[Natts_pg_attribute];
16250 : bool repl_repl[Natts_pg_attribute];
16251 : Datum datum;
16252 : Form_pg_foreign_table fttableform;
16253 : Form_pg_attribute atttableform;
16254 : AttrNumber attnum;
16255 : ObjectAddress address;
16256 :
16257 94 : if (options == NIL)
16258 0 : return InvalidObjectAddress;
16259 :
16260 : /* First, determine FDW validator associated to the foreign table. */
16261 94 : ftrel = table_open(ForeignTableRelationId, AccessShareLock);
16262 94 : tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
16263 94 : if (!HeapTupleIsValid(tuple))
16264 0 : ereport(ERROR,
16265 : (errcode(ERRCODE_UNDEFINED_OBJECT),
16266 : errmsg("foreign table \"%s\" does not exist",
16267 : RelationGetRelationName(rel))));
16268 94 : fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
16269 94 : server = GetForeignServer(fttableform->ftserver);
16270 94 : fdw = GetForeignDataWrapper(server->fdwid);
16271 :
16272 94 : table_close(ftrel, AccessShareLock);
16273 94 : ReleaseSysCache(tuple);
16274 :
16275 94 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
16276 94 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
16277 94 : if (!HeapTupleIsValid(tuple))
16278 0 : ereport(ERROR,
16279 : (errcode(ERRCODE_UNDEFINED_COLUMN),
16280 : errmsg("column \"%s\" of relation \"%s\" does not exist",
16281 : colName, RelationGetRelationName(rel))));
16282 :
16283 : /* Prevent them from altering a system attribute */
16284 94 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
16285 94 : attnum = atttableform->attnum;
16286 94 : if (attnum <= 0)
16287 4 : ereport(ERROR,
16288 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16289 : errmsg("cannot alter system column \"%s\"", colName)));
16290 :
16291 :
16292 : /* Initialize buffers for new tuple values */
16293 90 : memset(repl_val, 0, sizeof(repl_val));
16294 90 : memset(repl_null, false, sizeof(repl_null));
16295 90 : memset(repl_repl, false, sizeof(repl_repl));
16296 :
16297 : /* Extract the current options */
16298 90 : datum = SysCacheGetAttr(ATTNAME,
16299 : tuple,
16300 : Anum_pg_attribute_attfdwoptions,
16301 : &isnull);
16302 90 : if (isnull)
16303 84 : datum = PointerGetDatum(NULL);
16304 :
16305 : /* Transform the options */
16306 90 : datum = transformGenericOptions(AttributeRelationId,
16307 : datum,
16308 : options,
16309 : fdw->fdwvalidator);
16310 :
16311 90 : if (DatumGetPointer(datum) != NULL)
16312 90 : repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
16313 : else
16314 0 : repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
16315 :
16316 90 : repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
16317 :
16318 : /* Everything looks good - update the tuple */
16319 :
16320 90 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
16321 : repl_val, repl_null, repl_repl);
16322 :
16323 90 : CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
16324 :
16325 90 : InvokeObjectPostAlterHook(RelationRelationId,
16326 : RelationGetRelid(rel),
16327 : atttableform->attnum);
16328 90 : ObjectAddressSubSet(address, RelationRelationId,
16329 : RelationGetRelid(rel), attnum);
16330 :
16331 90 : ReleaseSysCache(tuple);
16332 :
16333 90 : table_close(attrel, RowExclusiveLock);
16334 :
16335 90 : heap_freetuple(newtuple);
16336 :
16337 90 : return address;
16338 : }
16339 :
16340 : /*
16341 : * ALTER TABLE OWNER
16342 : *
16343 : * recursing is true if we are recursing from a table to its indexes,
16344 : * sequences, or toast table. We don't allow the ownership of those things to
16345 : * be changed separately from the parent table. Also, we can skip permission
16346 : * checks (this is necessary not just an optimization, else we'd fail to
16347 : * handle toast tables properly).
16348 : *
16349 : * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
16350 : * free-standing composite type.
16351 : */
16352 : void
16353 1358 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
16354 : {
16355 : Relation target_rel;
16356 : Relation class_rel;
16357 : HeapTuple tuple;
16358 : Form_pg_class tuple_class;
16359 :
16360 : /*
16361 : * Get exclusive lock till end of transaction on the target table. Use
16362 : * relation_open so that we can work on indexes and sequences.
16363 : */
16364 1358 : target_rel = relation_open(relationOid, lockmode);
16365 :
16366 : /* Get its pg_class tuple, too */
16367 1358 : class_rel = table_open(RelationRelationId, RowExclusiveLock);
16368 :
16369 1358 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16370 1358 : if (!HeapTupleIsValid(tuple))
16371 0 : elog(ERROR, "cache lookup failed for relation %u", relationOid);
16372 1358 : tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16373 :
16374 : /* Can we change the ownership of this tuple? */
16375 1358 : switch (tuple_class->relkind)
16376 : {
16377 1139 : case RELKIND_RELATION:
16378 : case RELKIND_VIEW:
16379 : case RELKIND_MATVIEW:
16380 : case RELKIND_FOREIGN_TABLE:
16381 : case RELKIND_PARTITIONED_TABLE:
16382 : case RELKIND_PROPGRAPH:
16383 : /* ok to change owner */
16384 1139 : break;
16385 92 : case RELKIND_INDEX:
16386 92 : if (!recursing)
16387 : {
16388 : /*
16389 : * Because ALTER INDEX OWNER used to be allowed, and in fact
16390 : * is generated by old versions of pg_dump, we give a warning
16391 : * and do nothing rather than erroring out. Also, to avoid
16392 : * unnecessary chatter while restoring those old dumps, say
16393 : * nothing at all if the command would be a no-op anyway.
16394 : */
16395 0 : if (tuple_class->relowner != newOwnerId)
16396 0 : ereport(WARNING,
16397 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16398 : errmsg("cannot change owner of index \"%s\"",
16399 : NameStr(tuple_class->relname)),
16400 : errhint("Change the ownership of the index's table instead.")));
16401 : /* quick hack to exit via the no-op path */
16402 0 : newOwnerId = tuple_class->relowner;
16403 : }
16404 92 : break;
16405 14 : case RELKIND_PARTITIONED_INDEX:
16406 14 : if (recursing)
16407 14 : break;
16408 0 : ereport(ERROR,
16409 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16410 : errmsg("cannot change owner of index \"%s\"",
16411 : NameStr(tuple_class->relname)),
16412 : errhint("Change the ownership of the index's table instead.")));
16413 : break;
16414 65 : case RELKIND_SEQUENCE:
16415 65 : if (!recursing &&
16416 35 : tuple_class->relowner != newOwnerId)
16417 : {
16418 : /* if it's an owned sequence, disallow changing it by itself */
16419 : Oid tableId;
16420 : int32 colId;
16421 :
16422 0 : if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16423 0 : sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16424 0 : ereport(ERROR,
16425 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16426 : errmsg("cannot change owner of sequence \"%s\"",
16427 : NameStr(tuple_class->relname)),
16428 : errdetail("Sequence \"%s\" is linked to table \"%s\".",
16429 : NameStr(tuple_class->relname),
16430 : get_rel_name(tableId))));
16431 : }
16432 65 : break;
16433 5 : case RELKIND_COMPOSITE_TYPE:
16434 5 : if (recursing)
16435 5 : break;
16436 0 : ereport(ERROR,
16437 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16438 : errmsg("\"%s\" is a composite type",
16439 : NameStr(tuple_class->relname)),
16440 : /* translator: %s is an SQL ALTER command */
16441 : errhint("Use %s instead.",
16442 : "ALTER TYPE")));
16443 : break;
16444 43 : case RELKIND_TOASTVALUE:
16445 43 : if (recursing)
16446 43 : break;
16447 : pg_fallthrough;
16448 : default:
16449 0 : ereport(ERROR,
16450 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16451 : errmsg("cannot change owner of relation \"%s\"",
16452 : NameStr(tuple_class->relname)),
16453 : errdetail_relkind_not_supported(tuple_class->relkind)));
16454 : }
16455 :
16456 : /*
16457 : * If the new owner is the same as the existing owner, consider the
16458 : * command to have succeeded. This is for dump restoration purposes.
16459 : */
16460 1358 : if (tuple_class->relowner != newOwnerId)
16461 : {
16462 : Datum repl_val[Natts_pg_class];
16463 : bool repl_null[Natts_pg_class];
16464 : bool repl_repl[Natts_pg_class];
16465 : Acl *newAcl;
16466 : Datum aclDatum;
16467 : bool isNull;
16468 : HeapTuple newtuple;
16469 :
16470 : /* skip permission checks when recursing to index or toast table */
16471 426 : if (!recursing)
16472 : {
16473 : /* Superusers can always do it */
16474 216 : if (!superuser())
16475 : {
16476 28 : Oid namespaceOid = tuple_class->relnamespace;
16477 : AclResult aclresult;
16478 :
16479 : /* Otherwise, must be owner of the existing object */
16480 28 : if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16481 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
16482 0 : RelationGetRelationName(target_rel));
16483 :
16484 : /* Must be able to become new owner */
16485 28 : check_can_set_role(GetUserId(), newOwnerId);
16486 :
16487 : /* New owner must have CREATE privilege on namespace */
16488 20 : aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16489 : ACL_CREATE);
16490 20 : if (aclresult != ACLCHECK_OK)
16491 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
16492 0 : get_namespace_name(namespaceOid));
16493 : }
16494 : }
16495 :
16496 418 : memset(repl_null, false, sizeof(repl_null));
16497 418 : memset(repl_repl, false, sizeof(repl_repl));
16498 :
16499 418 : repl_repl[Anum_pg_class_relowner - 1] = true;
16500 418 : repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16501 :
16502 : /*
16503 : * Determine the modified ACL for the new owner. This is only
16504 : * necessary when the ACL is non-null.
16505 : */
16506 418 : aclDatum = SysCacheGetAttr(RELOID, tuple,
16507 : Anum_pg_class_relacl,
16508 : &isNull);
16509 418 : if (!isNull)
16510 : {
16511 60 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
16512 : tuple_class->relowner, newOwnerId);
16513 60 : repl_repl[Anum_pg_class_relacl - 1] = true;
16514 60 : repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16515 : }
16516 :
16517 418 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16518 :
16519 418 : CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16520 :
16521 418 : heap_freetuple(newtuple);
16522 :
16523 : /*
16524 : * We must similarly update any per-column ACLs to reflect the new
16525 : * owner; for neatness reasons that's split out as a subroutine.
16526 : */
16527 418 : change_owner_fix_column_acls(relationOid,
16528 : tuple_class->relowner,
16529 : newOwnerId);
16530 :
16531 : /*
16532 : * Update owner dependency reference, if any. A composite type has
16533 : * none, because it's tracked for the pg_type entry instead of here;
16534 : * indexes and TOAST tables don't have their own entries either.
16535 : */
16536 418 : if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16537 413 : tuple_class->relkind != RELKIND_INDEX &&
16538 321 : tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16539 307 : tuple_class->relkind != RELKIND_TOASTVALUE)
16540 264 : changeDependencyOnOwner(RelationRelationId, relationOid,
16541 : newOwnerId);
16542 :
16543 : /*
16544 : * Also change the ownership of the table's row type, if it has one
16545 : */
16546 418 : if (OidIsValid(tuple_class->reltype))
16547 244 : AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16548 :
16549 : /*
16550 : * If we are operating on a table or materialized view, also change
16551 : * the ownership of any indexes and sequences that belong to the
16552 : * relation, as well as its toast table (if it has one).
16553 : */
16554 418 : if (tuple_class->relkind == RELKIND_RELATION ||
16555 230 : tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16556 193 : tuple_class->relkind == RELKIND_MATVIEW ||
16557 193 : tuple_class->relkind == RELKIND_TOASTVALUE)
16558 : {
16559 : List *index_oid_list;
16560 : ListCell *i;
16561 :
16562 : /* Find all the indexes belonging to this relation */
16563 268 : index_oid_list = RelationGetIndexList(target_rel);
16564 :
16565 : /* For each index, recursively change its ownership */
16566 374 : foreach(i, index_oid_list)
16567 106 : ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16568 :
16569 268 : list_free(index_oid_list);
16570 : }
16571 :
16572 : /* If it has a toast table, recurse to change its ownership */
16573 418 : if (tuple_class->reltoastrelid != InvalidOid)
16574 43 : ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16575 : true, lockmode);
16576 :
16577 : /* If it has dependent sequences, recurse to change them too */
16578 418 : change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16579 : }
16580 :
16581 1350 : InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16582 :
16583 1350 : ReleaseSysCache(tuple);
16584 1350 : table_close(class_rel, RowExclusiveLock);
16585 1350 : relation_close(target_rel, NoLock);
16586 1350 : }
16587 :
16588 : /*
16589 : * change_owner_fix_column_acls
16590 : *
16591 : * Helper function for ATExecChangeOwner. Scan the columns of the table
16592 : * and fix any non-null column ACLs to reflect the new owner.
16593 : */
16594 : static void
16595 418 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
16596 : {
16597 : Relation attRelation;
16598 : SysScanDesc scan;
16599 : ScanKeyData key[1];
16600 : HeapTuple attributeTuple;
16601 :
16602 418 : attRelation = table_open(AttributeRelationId, RowExclusiveLock);
16603 418 : ScanKeyInit(&key[0],
16604 : Anum_pg_attribute_attrelid,
16605 : BTEqualStrategyNumber, F_OIDEQ,
16606 : ObjectIdGetDatum(relationOid));
16607 418 : scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
16608 : true, NULL, 1, key);
16609 2947 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
16610 : {
16611 2529 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
16612 : Datum repl_val[Natts_pg_attribute];
16613 : bool repl_null[Natts_pg_attribute];
16614 : bool repl_repl[Natts_pg_attribute];
16615 : Acl *newAcl;
16616 : Datum aclDatum;
16617 : bool isNull;
16618 : HeapTuple newtuple;
16619 :
16620 : /* Ignore dropped columns */
16621 2529 : if (att->attisdropped)
16622 2528 : continue;
16623 :
16624 2529 : aclDatum = heap_getattr(attributeTuple,
16625 : Anum_pg_attribute_attacl,
16626 : RelationGetDescr(attRelation),
16627 : &isNull);
16628 : /* Null ACLs do not require changes */
16629 2529 : if (isNull)
16630 2528 : continue;
16631 :
16632 1 : memset(repl_null, false, sizeof(repl_null));
16633 1 : memset(repl_repl, false, sizeof(repl_repl));
16634 :
16635 1 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
16636 : oldOwnerId, newOwnerId);
16637 1 : repl_repl[Anum_pg_attribute_attacl - 1] = true;
16638 1 : repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
16639 :
16640 1 : newtuple = heap_modify_tuple(attributeTuple,
16641 : RelationGetDescr(attRelation),
16642 : repl_val, repl_null, repl_repl);
16643 :
16644 1 : CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
16645 :
16646 1 : heap_freetuple(newtuple);
16647 : }
16648 418 : systable_endscan(scan);
16649 418 : table_close(attRelation, RowExclusiveLock);
16650 418 : }
16651 :
16652 : /*
16653 : * change_owner_recurse_to_sequences
16654 : *
16655 : * Helper function for ATExecChangeOwner. Examines pg_depend searching
16656 : * for sequences that are dependent on serial columns, and changes their
16657 : * ownership.
16658 : */
16659 : static void
16660 418 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
16661 : {
16662 : Relation depRel;
16663 : SysScanDesc scan;
16664 : ScanKeyData key[2];
16665 : HeapTuple tup;
16666 :
16667 : /*
16668 : * SERIAL sequences are those having an auto dependency on one of the
16669 : * table's columns (we don't care *which* column, exactly).
16670 : */
16671 418 : depRel = table_open(DependRelationId, AccessShareLock);
16672 :
16673 418 : ScanKeyInit(&key[0],
16674 : Anum_pg_depend_refclassid,
16675 : BTEqualStrategyNumber, F_OIDEQ,
16676 : ObjectIdGetDatum(RelationRelationId));
16677 418 : ScanKeyInit(&key[1],
16678 : Anum_pg_depend_refobjid,
16679 : BTEqualStrategyNumber, F_OIDEQ,
16680 : ObjectIdGetDatum(relationOid));
16681 : /* we leave refobjsubid unspecified */
16682 :
16683 418 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
16684 : NULL, 2, key);
16685 :
16686 1348 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
16687 : {
16688 930 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
16689 : Relation seqRel;
16690 :
16691 : /* skip dependencies other than auto dependencies on columns */
16692 930 : if (depForm->refobjsubid == 0 ||
16693 400 : depForm->classid != RelationRelationId ||
16694 124 : depForm->objsubid != 0 ||
16695 124 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
16696 806 : continue;
16697 :
16698 : /* Use relation_open just in case it's an index */
16699 124 : seqRel = relation_open(depForm->objid, lockmode);
16700 :
16701 : /* skip non-sequence relations */
16702 124 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
16703 : {
16704 : /* No need to keep the lock */
16705 107 : relation_close(seqRel, lockmode);
16706 107 : continue;
16707 : }
16708 :
16709 : /* We don't need to close the sequence while we alter it. */
16710 17 : ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
16711 :
16712 : /* Now we can close it. Keep the lock till end of transaction. */
16713 17 : relation_close(seqRel, NoLock);
16714 : }
16715 :
16716 418 : systable_endscan(scan);
16717 :
16718 418 : relation_close(depRel, AccessShareLock);
16719 418 : }
16720 :
16721 : /*
16722 : * ALTER TABLE CLUSTER ON
16723 : *
16724 : * The only thing we have to do is to change the indisclustered bits.
16725 : *
16726 : * Return the address of the new clustering index.
16727 : */
16728 : static ObjectAddress
16729 39 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
16730 : {
16731 : Oid indexOid;
16732 : ObjectAddress address;
16733 :
16734 39 : indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
16735 :
16736 39 : if (!OidIsValid(indexOid))
16737 0 : ereport(ERROR,
16738 : (errcode(ERRCODE_UNDEFINED_OBJECT),
16739 : errmsg("index \"%s\" for table \"%s\" does not exist",
16740 : indexName, RelationGetRelationName(rel))));
16741 :
16742 : /* Check index is valid to cluster on */
16743 39 : check_index_is_clusterable(rel, indexOid, lockmode);
16744 :
16745 : /* And do the work */
16746 39 : mark_index_clustered(rel, indexOid, false);
16747 :
16748 39 : ObjectAddressSet(address,
16749 : RelationRelationId, indexOid);
16750 :
16751 39 : return address;
16752 : }
16753 :
16754 : /*
16755 : * ALTER TABLE SET WITHOUT CLUSTER
16756 : *
16757 : * We have to find any indexes on the table that have indisclustered bit
16758 : * set and turn it off.
16759 : */
16760 : static void
16761 8 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
16762 : {
16763 8 : mark_index_clustered(rel, InvalidOid, false);
16764 8 : }
16765 :
16766 : /*
16767 : * Preparation phase for SET ACCESS METHOD
16768 : *
16769 : * Check that the access method exists and determine whether a change is
16770 : * actually needed.
16771 : */
16772 : static void
16773 73 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
16774 : {
16775 : Oid amoid;
16776 :
16777 : /*
16778 : * Look up the access method name and check that it differs from the
16779 : * table's current AM. If DEFAULT was specified for a partitioned table
16780 : * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
16781 : */
16782 73 : if (amname != NULL)
16783 49 : amoid = get_table_am_oid(amname, false);
16784 24 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
16785 12 : amoid = InvalidOid;
16786 : else
16787 12 : amoid = get_table_am_oid(default_table_access_method, false);
16788 :
16789 : /* if it's a match, phase 3 doesn't need to do anything */
16790 73 : if (rel->rd_rel->relam == amoid)
16791 8 : return;
16792 :
16793 : /* Save info for Phase 3 to do the real work */
16794 65 : tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
16795 65 : tab->newAccessMethod = amoid;
16796 65 : tab->chgAccessMethod = true;
16797 : }
16798 :
16799 : /*
16800 : * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
16801 : * storage that have an interest in preserving AM.
16802 : *
16803 : * Since these have no storage, setting the access method is a catalog only
16804 : * operation.
16805 : */
16806 : static void
16807 29 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
16808 : {
16809 : Relation pg_class;
16810 : Oid oldAccessMethodId;
16811 : HeapTuple tuple;
16812 : Form_pg_class rd_rel;
16813 29 : Oid reloid = RelationGetRelid(rel);
16814 :
16815 : /*
16816 : * Shouldn't be called on relations having storage; these are processed in
16817 : * phase 3.
16818 : */
16819 : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
16820 :
16821 : /* Get a modifiable copy of the relation's pg_class row. */
16822 29 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
16823 :
16824 29 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
16825 29 : if (!HeapTupleIsValid(tuple))
16826 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
16827 29 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
16828 :
16829 : /* Update the pg_class row. */
16830 29 : oldAccessMethodId = rd_rel->relam;
16831 29 : rd_rel->relam = newAccessMethodId;
16832 :
16833 : /* Leave if no update required */
16834 29 : if (rd_rel->relam == oldAccessMethodId)
16835 : {
16836 0 : heap_freetuple(tuple);
16837 0 : table_close(pg_class, RowExclusiveLock);
16838 0 : return;
16839 : }
16840 :
16841 29 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
16842 :
16843 : /*
16844 : * Update the dependency on the new access method. No dependency is added
16845 : * if the new access method is InvalidOid (default case). Be very careful
16846 : * that this has to compare the previous value stored in pg_class with the
16847 : * new one.
16848 : */
16849 29 : if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
16850 13 : {
16851 : ObjectAddress relobj,
16852 : referenced;
16853 :
16854 : /*
16855 : * New access method is defined and there was no dependency
16856 : * previously, so record a new one.
16857 : */
16858 13 : ObjectAddressSet(relobj, RelationRelationId, reloid);
16859 13 : ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
16860 13 : recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
16861 : }
16862 16 : else if (OidIsValid(oldAccessMethodId) &&
16863 16 : !OidIsValid(rd_rel->relam))
16864 : {
16865 : /*
16866 : * There was an access method defined, and no new one, so just remove
16867 : * the existing dependency.
16868 : */
16869 8 : deleteDependencyRecordsForClass(RelationRelationId, reloid,
16870 : AccessMethodRelationId,
16871 : DEPENDENCY_NORMAL);
16872 : }
16873 : else
16874 : {
16875 : Assert(OidIsValid(oldAccessMethodId) &&
16876 : OidIsValid(rd_rel->relam));
16877 :
16878 : /* Both are valid, so update the dependency */
16879 8 : changeDependencyFor(RelationRelationId, reloid,
16880 : AccessMethodRelationId,
16881 : oldAccessMethodId, rd_rel->relam);
16882 : }
16883 :
16884 : /* make the relam and dependency changes visible */
16885 29 : CommandCounterIncrement();
16886 :
16887 29 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
16888 :
16889 29 : heap_freetuple(tuple);
16890 29 : table_close(pg_class, RowExclusiveLock);
16891 : }
16892 :
16893 : /*
16894 : * ALTER TABLE SET TABLESPACE
16895 : */
16896 : static void
16897 111 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
16898 : {
16899 : Oid tablespaceId;
16900 :
16901 : /* Check that the tablespace exists */
16902 111 : tablespaceId = get_tablespace_oid(tablespacename, false);
16903 :
16904 : /* Check permissions except when moving to database's default */
16905 111 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
16906 : {
16907 : AclResult aclresult;
16908 :
16909 44 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
16910 44 : if (aclresult != ACLCHECK_OK)
16911 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
16912 : }
16913 :
16914 : /* Save info for Phase 3 to do the real work */
16915 111 : if (OidIsValid(tab->newTableSpace))
16916 0 : ereport(ERROR,
16917 : (errcode(ERRCODE_SYNTAX_ERROR),
16918 : errmsg("cannot have multiple SET TABLESPACE subcommands")));
16919 :
16920 111 : tab->newTableSpace = tablespaceId;
16921 111 : }
16922 :
16923 : /*
16924 : * Set, reset, or replace reloptions.
16925 : */
16926 : static void
16927 632 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
16928 : LOCKMODE lockmode)
16929 : {
16930 : Oid relid;
16931 : Relation pgclass;
16932 : HeapTuple tuple;
16933 : HeapTuple newtuple;
16934 : Datum datum;
16935 : Datum newOptions;
16936 : Datum repl_val[Natts_pg_class];
16937 : bool repl_null[Natts_pg_class];
16938 : bool repl_repl[Natts_pg_class];
16939 632 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
16940 :
16941 632 : if (defList == NIL && operation != AT_ReplaceRelOptions)
16942 0 : return; /* nothing to do */
16943 :
16944 632 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
16945 :
16946 : /* Fetch heap tuple */
16947 632 : relid = RelationGetRelid(rel);
16948 632 : tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
16949 632 : if (!HeapTupleIsValid(tuple))
16950 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
16951 :
16952 632 : if (operation == AT_ReplaceRelOptions)
16953 : {
16954 : /*
16955 : * If we're supposed to replace the reloptions list, we just pretend
16956 : * there were none before.
16957 : */
16958 137 : datum = (Datum) 0;
16959 : }
16960 : else
16961 : {
16962 : bool isnull;
16963 :
16964 : /* Get the old reloptions */
16965 495 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
16966 : &isnull);
16967 495 : if (isnull)
16968 306 : datum = (Datum) 0;
16969 : }
16970 :
16971 : /* Generate new proposed reloptions (text array) */
16972 632 : newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
16973 : operation == AT_ResetRelOptions);
16974 :
16975 : /* Validate */
16976 628 : switch (rel->rd_rel->relkind)
16977 : {
16978 348 : case RELKIND_RELATION:
16979 : case RELKIND_MATVIEW:
16980 348 : (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
16981 348 : break;
16982 4 : case RELKIND_PARTITIONED_TABLE:
16983 4 : (void) partitioned_table_reloptions(newOptions, true);
16984 0 : break;
16985 205 : case RELKIND_VIEW:
16986 205 : (void) view_reloptions(newOptions, true);
16987 193 : break;
16988 71 : case RELKIND_INDEX:
16989 : case RELKIND_PARTITIONED_INDEX:
16990 71 : (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
16991 57 : break;
16992 0 : case RELKIND_TOASTVALUE:
16993 : /* fall through to error -- shouldn't ever get here */
16994 : default:
16995 0 : ereport(ERROR,
16996 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16997 : errmsg("cannot set options for relation \"%s\"",
16998 : RelationGetRelationName(rel)),
16999 : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
17000 : break;
17001 : }
17002 :
17003 : /* Special-case validation of view options */
17004 598 : if (rel->rd_rel->relkind == RELKIND_VIEW)
17005 : {
17006 193 : Query *view_query = get_view_query(rel);
17007 193 : List *view_options = untransformRelOptions(newOptions);
17008 : ListCell *cell;
17009 193 : bool check_option = false;
17010 :
17011 261 : foreach(cell, view_options)
17012 : {
17013 68 : DefElem *defel = (DefElem *) lfirst(cell);
17014 :
17015 68 : if (strcmp(defel->defname, "check_option") == 0)
17016 16 : check_option = true;
17017 : }
17018 :
17019 : /*
17020 : * If the check option is specified, look to see if the view is
17021 : * actually auto-updatable or not.
17022 : */
17023 193 : if (check_option)
17024 : {
17025 : const char *view_updatable_error =
17026 16 : view_query_is_auto_updatable(view_query, true);
17027 :
17028 16 : if (view_updatable_error)
17029 0 : ereport(ERROR,
17030 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17031 : errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
17032 : errhint("%s", _(view_updatable_error))));
17033 : }
17034 : }
17035 :
17036 : /*
17037 : * All we need do here is update the pg_class row; the new options will be
17038 : * propagated into relcaches during post-commit cache inval.
17039 : */
17040 598 : memset(repl_val, 0, sizeof(repl_val));
17041 598 : memset(repl_null, false, sizeof(repl_null));
17042 598 : memset(repl_repl, false, sizeof(repl_repl));
17043 :
17044 598 : if (newOptions != (Datum) 0)
17045 396 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17046 : else
17047 202 : repl_null[Anum_pg_class_reloptions - 1] = true;
17048 :
17049 598 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17050 :
17051 598 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17052 : repl_val, repl_null, repl_repl);
17053 :
17054 598 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17055 598 : UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
17056 :
17057 598 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17058 :
17059 598 : heap_freetuple(newtuple);
17060 :
17061 598 : ReleaseSysCache(tuple);
17062 :
17063 : /* repeat the whole exercise for the toast table, if there's one */
17064 598 : if (OidIsValid(rel->rd_rel->reltoastrelid))
17065 : {
17066 : Relation toastrel;
17067 182 : Oid toastid = rel->rd_rel->reltoastrelid;
17068 :
17069 182 : toastrel = table_open(toastid, lockmode);
17070 :
17071 : /* Fetch heap tuple */
17072 182 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
17073 182 : if (!HeapTupleIsValid(tuple))
17074 0 : elog(ERROR, "cache lookup failed for relation %u", toastid);
17075 :
17076 182 : if (operation == AT_ReplaceRelOptions)
17077 : {
17078 : /*
17079 : * If we're supposed to replace the reloptions list, we just
17080 : * pretend there were none before.
17081 : */
17082 0 : datum = (Datum) 0;
17083 : }
17084 : else
17085 : {
17086 : bool isnull;
17087 :
17088 : /* Get the old reloptions */
17089 182 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
17090 : &isnull);
17091 182 : if (isnull)
17092 158 : datum = (Datum) 0;
17093 : }
17094 :
17095 182 : newOptions = transformRelOptions(datum, defList, "toast", validnsps,
17096 : false, operation == AT_ResetRelOptions);
17097 :
17098 182 : (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
17099 :
17100 182 : memset(repl_val, 0, sizeof(repl_val));
17101 182 : memset(repl_null, false, sizeof(repl_null));
17102 182 : memset(repl_repl, false, sizeof(repl_repl));
17103 :
17104 182 : if (newOptions != (Datum) 0)
17105 28 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17106 : else
17107 154 : repl_null[Anum_pg_class_reloptions - 1] = true;
17108 :
17109 182 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17110 :
17111 182 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17112 : repl_val, repl_null, repl_repl);
17113 :
17114 182 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17115 :
17116 182 : InvokeObjectPostAlterHookArg(RelationRelationId,
17117 : RelationGetRelid(toastrel), 0,
17118 : InvalidOid, true);
17119 :
17120 182 : heap_freetuple(newtuple);
17121 :
17122 182 : ReleaseSysCache(tuple);
17123 :
17124 182 : table_close(toastrel, NoLock);
17125 : }
17126 :
17127 598 : table_close(pgclass, RowExclusiveLock);
17128 : }
17129 :
17130 : /*
17131 : * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
17132 : * rewriting to be done, so we just want to copy the data as fast as possible.
17133 : */
17134 : static void
17135 113 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
17136 : {
17137 : Relation rel;
17138 : Oid reltoastrelid;
17139 : RelFileNumber newrelfilenumber;
17140 : RelFileLocator newrlocator;
17141 113 : List *reltoastidxids = NIL;
17142 : ListCell *lc;
17143 :
17144 : /*
17145 : * Need lock here in case we are recursing to toast table or index
17146 : */
17147 113 : rel = relation_open(tableOid, lockmode);
17148 :
17149 : /* Check first if relation can be moved to new tablespace */
17150 113 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17151 : {
17152 5 : InvokeObjectPostAlterHook(RelationRelationId,
17153 : RelationGetRelid(rel), 0);
17154 5 : relation_close(rel, NoLock);
17155 5 : return;
17156 : }
17157 :
17158 108 : reltoastrelid = rel->rd_rel->reltoastrelid;
17159 : /* Fetch the list of indexes on toast relation if necessary */
17160 108 : if (OidIsValid(reltoastrelid))
17161 : {
17162 13 : Relation toastRel = relation_open(reltoastrelid, lockmode);
17163 :
17164 13 : reltoastidxids = RelationGetIndexList(toastRel);
17165 13 : relation_close(toastRel, lockmode);
17166 : }
17167 :
17168 : /*
17169 : * Relfilenumbers are not unique in databases across tablespaces, so we
17170 : * need to allocate a new one in the new tablespace.
17171 : */
17172 108 : newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
17173 108 : rel->rd_rel->relpersistence);
17174 :
17175 : /* Open old and new relation */
17176 108 : newrlocator = rel->rd_locator;
17177 108 : newrlocator.relNumber = newrelfilenumber;
17178 108 : newrlocator.spcOid = newTableSpace;
17179 :
17180 : /* hand off to AM to actually create new rel storage and copy the data */
17181 108 : if (rel->rd_rel->relkind == RELKIND_INDEX)
17182 : {
17183 41 : index_copy_data(rel, newrlocator);
17184 : }
17185 : else
17186 : {
17187 : Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
17188 67 : table_relation_copy_data(rel, &newrlocator);
17189 : }
17190 :
17191 : /*
17192 : * Update the pg_class row.
17193 : *
17194 : * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
17195 : * executed on pg_class or its indexes (the above copy wouldn't contain
17196 : * the updated pg_class entry), but that's forbidden with
17197 : * CheckRelationTableSpaceMove().
17198 : */
17199 108 : SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
17200 :
17201 108 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17202 :
17203 108 : RelationAssumeNewRelfilelocator(rel);
17204 :
17205 108 : relation_close(rel, NoLock);
17206 :
17207 : /* Make sure the reltablespace change is visible */
17208 108 : CommandCounterIncrement();
17209 :
17210 : /* Move associated toast relation and/or indexes, too */
17211 108 : if (OidIsValid(reltoastrelid))
17212 13 : ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
17213 121 : foreach(lc, reltoastidxids)
17214 13 : ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
17215 :
17216 : /* Clean up */
17217 108 : list_free(reltoastidxids);
17218 : }
17219 :
17220 : /*
17221 : * Special handling of ALTER TABLE SET TABLESPACE for relations with no
17222 : * storage that have an interest in preserving tablespace.
17223 : *
17224 : * Since these have no storage the tablespace can be updated with a simple
17225 : * metadata only operation to update the tablespace.
17226 : */
17227 : static void
17228 24 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
17229 : {
17230 : /*
17231 : * Shouldn't be called on relations having storage; these are processed in
17232 : * phase 3.
17233 : */
17234 : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17235 :
17236 : /* check if relation can be moved to its new tablespace */
17237 24 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17238 : {
17239 0 : InvokeObjectPostAlterHook(RelationRelationId,
17240 : RelationGetRelid(rel),
17241 : 0);
17242 0 : return;
17243 : }
17244 :
17245 : /* Update can be done, so change reltablespace */
17246 20 : SetRelationTableSpace(rel, newTableSpace, InvalidOid);
17247 :
17248 20 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17249 :
17250 : /* Make sure the reltablespace change is visible */
17251 20 : CommandCounterIncrement();
17252 : }
17253 :
17254 : /*
17255 : * Alter Table ALL ... SET TABLESPACE
17256 : *
17257 : * Allows a user to move all objects of some type in a given tablespace in the
17258 : * current database to another tablespace. Objects can be chosen based on the
17259 : * owner of the object also, to allow users to move only their objects.
17260 : * The user must have CREATE rights on the new tablespace, as usual. The main
17261 : * permissions handling is done by the lower-level table move function.
17262 : *
17263 : * All to-be-moved objects are locked first. If NOWAIT is specified and the
17264 : * lock can't be acquired then we ereport(ERROR).
17265 : */
17266 : Oid
17267 20 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
17268 : {
17269 20 : List *relations = NIL;
17270 : ListCell *l;
17271 : ScanKeyData key[1];
17272 : Relation rel;
17273 : TableScanDesc scan;
17274 : HeapTuple tuple;
17275 : Oid orig_tablespaceoid;
17276 : Oid new_tablespaceoid;
17277 20 : List *role_oids = roleSpecsToIds(stmt->roles);
17278 :
17279 : /* Ensure we were not asked to move something we can't */
17280 20 : if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17281 8 : stmt->objtype != OBJECT_MATVIEW)
17282 0 : ereport(ERROR,
17283 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17284 : errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17285 :
17286 : /* Get the orig and new tablespace OIDs */
17287 20 : orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17288 20 : new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17289 :
17290 : /* Can't move shared relations in to or out of pg_global */
17291 : /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17292 20 : if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
17293 : new_tablespaceoid == GLOBALTABLESPACE_OID)
17294 0 : ereport(ERROR,
17295 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17296 : errmsg("cannot move relations in to or out of pg_global tablespace")));
17297 :
17298 : /*
17299 : * Must have CREATE rights on the new tablespace, unless it is the
17300 : * database default tablespace (which all users implicitly have CREATE
17301 : * rights on).
17302 : */
17303 20 : if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
17304 : {
17305 : AclResult aclresult;
17306 :
17307 0 : aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
17308 : ACL_CREATE);
17309 0 : if (aclresult != ACLCHECK_OK)
17310 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
17311 0 : get_tablespace_name(new_tablespaceoid));
17312 : }
17313 :
17314 : /*
17315 : * Now that the checks are done, check if we should set either to
17316 : * InvalidOid because it is our database's default tablespace.
17317 : */
17318 20 : if (orig_tablespaceoid == MyDatabaseTableSpace)
17319 0 : orig_tablespaceoid = InvalidOid;
17320 :
17321 20 : if (new_tablespaceoid == MyDatabaseTableSpace)
17322 20 : new_tablespaceoid = InvalidOid;
17323 :
17324 : /* no-op */
17325 20 : if (orig_tablespaceoid == new_tablespaceoid)
17326 0 : return new_tablespaceoid;
17327 :
17328 : /*
17329 : * Walk the list of objects in the tablespace and move them. This will
17330 : * only find objects in our database, of course.
17331 : */
17332 20 : ScanKeyInit(&key[0],
17333 : Anum_pg_class_reltablespace,
17334 : BTEqualStrategyNumber, F_OIDEQ,
17335 : ObjectIdGetDatum(orig_tablespaceoid));
17336 :
17337 20 : rel = table_open(RelationRelationId, AccessShareLock);
17338 20 : scan = table_beginscan_catalog(rel, 1, key);
17339 88 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17340 : {
17341 68 : Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
17342 68 : Oid relOid = relForm->oid;
17343 :
17344 : /*
17345 : * Do not move objects in pg_catalog as part of this, if an admin
17346 : * really wishes to do so, they can issue the individual ALTER
17347 : * commands directly.
17348 : *
17349 : * Also, explicitly avoid any shared tables, temp tables, or TOAST
17350 : * (TOAST will be moved with the main table).
17351 : */
17352 68 : if (IsCatalogNamespace(relForm->relnamespace) ||
17353 136 : relForm->relisshared ||
17354 136 : isAnyTempNamespace(relForm->relnamespace) ||
17355 68 : IsToastNamespace(relForm->relnamespace))
17356 0 : continue;
17357 :
17358 : /* Only move the object type requested */
17359 68 : if ((stmt->objtype == OBJECT_TABLE &&
17360 40 : relForm->relkind != RELKIND_RELATION &&
17361 24 : relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17362 44 : (stmt->objtype == OBJECT_INDEX &&
17363 24 : relForm->relkind != RELKIND_INDEX &&
17364 4 : relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17365 40 : (stmt->objtype == OBJECT_MATVIEW &&
17366 4 : relForm->relkind != RELKIND_MATVIEW))
17367 28 : continue;
17368 :
17369 : /* Check if we are only moving objects owned by certain roles */
17370 40 : if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17371 0 : continue;
17372 :
17373 : /*
17374 : * Handle permissions-checking here since we are locking the tables
17375 : * and also to avoid doing a bunch of work only to fail part-way. Note
17376 : * that permissions will also be checked by AlterTableInternal().
17377 : *
17378 : * Caller must be considered an owner on the table to move it.
17379 : */
17380 40 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17381 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
17382 0 : NameStr(relForm->relname));
17383 :
17384 40 : if (stmt->nowait &&
17385 0 : !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
17386 0 : ereport(ERROR,
17387 : (errcode(ERRCODE_OBJECT_IN_USE),
17388 : errmsg("aborting because lock on relation \"%s.%s\" is not available",
17389 : get_namespace_name(relForm->relnamespace),
17390 : NameStr(relForm->relname))));
17391 : else
17392 40 : LockRelationOid(relOid, AccessExclusiveLock);
17393 :
17394 : /* Add to our list of objects to move */
17395 40 : relations = lappend_oid(relations, relOid);
17396 : }
17397 :
17398 20 : table_endscan(scan);
17399 20 : table_close(rel, AccessShareLock);
17400 :
17401 20 : if (relations == NIL)
17402 8 : ereport(NOTICE,
17403 : (errcode(ERRCODE_NO_DATA_FOUND),
17404 : errmsg("no matching relations in tablespace \"%s\" found",
17405 : orig_tablespaceoid == InvalidOid ? "(database default)" :
17406 : get_tablespace_name(orig_tablespaceoid))));
17407 :
17408 : /* Everything is locked, loop through and move all of the relations. */
17409 60 : foreach(l, relations)
17410 : {
17411 40 : List *cmds = NIL;
17412 40 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
17413 :
17414 40 : cmd->subtype = AT_SetTableSpace;
17415 40 : cmd->name = stmt->new_tablespacename;
17416 :
17417 40 : cmds = lappend(cmds, cmd);
17418 :
17419 40 : EventTriggerAlterTableStart((Node *) stmt);
17420 : /* OID is set by AlterTableInternal */
17421 40 : AlterTableInternal(lfirst_oid(l), cmds, false);
17422 40 : EventTriggerAlterTableEnd();
17423 : }
17424 :
17425 20 : return new_tablespaceoid;
17426 : }
17427 :
17428 : static void
17429 41 : index_copy_data(Relation rel, RelFileLocator newrlocator)
17430 : {
17431 : SMgrRelation dstrel;
17432 :
17433 : /*
17434 : * Since we copy the file directly without looking at the shared buffers,
17435 : * we'd better first flush out any pages of the source relation that are
17436 : * in shared buffers. We assume no new changes will be made while we are
17437 : * holding exclusive lock on the rel.
17438 : */
17439 41 : FlushRelationBuffers(rel);
17440 :
17441 : /*
17442 : * Create and copy all forks of the relation, and schedule unlinking of
17443 : * old physical files.
17444 : *
17445 : * NOTE: any conflict in relfilenumber value will be caught in
17446 : * RelationCreateStorage().
17447 : */
17448 41 : dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
17449 :
17450 : /* copy main fork */
17451 41 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
17452 41 : rel->rd_rel->relpersistence);
17453 :
17454 : /* copy those extra forks that exist */
17455 41 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
17456 164 : forkNum <= MAX_FORKNUM; forkNum++)
17457 : {
17458 123 : if (smgrexists(RelationGetSmgr(rel), forkNum))
17459 : {
17460 0 : smgrcreate(dstrel, forkNum, false);
17461 :
17462 : /*
17463 : * WAL log creation if the relation is persistent, or this is the
17464 : * init fork of an unlogged relation.
17465 : */
17466 0 : if (RelationIsPermanent(rel) ||
17467 0 : (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
17468 : forkNum == INIT_FORKNUM))
17469 0 : log_smgrcreate(&newrlocator, forkNum);
17470 0 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
17471 0 : rel->rd_rel->relpersistence);
17472 : }
17473 : }
17474 :
17475 : /* drop old relation, and close new one */
17476 41 : RelationDropStorage(rel);
17477 41 : smgrclose(dstrel);
17478 41 : }
17479 :
17480 : /*
17481 : * ALTER TABLE ENABLE/DISABLE TRIGGER
17482 : *
17483 : * We just pass this off to trigger.c.
17484 : */
17485 : static void
17486 191 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
17487 : char fires_when, bool skip_system, bool recurse,
17488 : LOCKMODE lockmode)
17489 : {
17490 191 : EnableDisableTrigger(rel, trigname, InvalidOid,
17491 : fires_when, skip_system, recurse,
17492 : lockmode);
17493 :
17494 191 : InvokeObjectPostAlterHook(RelationRelationId,
17495 : RelationGetRelid(rel), 0);
17496 191 : }
17497 :
17498 : /*
17499 : * ALTER TABLE ENABLE/DISABLE RULE
17500 : *
17501 : * We just pass this off to rewriteDefine.c.
17502 : */
17503 : static void
17504 29 : ATExecEnableDisableRule(Relation rel, const char *rulename,
17505 : char fires_when, LOCKMODE lockmode)
17506 : {
17507 29 : EnableDisableRule(rel, rulename, fires_when);
17508 :
17509 29 : InvokeObjectPostAlterHook(RelationRelationId,
17510 : RelationGetRelid(rel), 0);
17511 29 : }
17512 :
17513 : /*
17514 : * Preparation phase of [NO] INHERIT
17515 : *
17516 : * Check the relation defined as a child.
17517 : */
17518 : static void
17519 378 : ATPrepChangeInherit(Relation child_rel)
17520 : {
17521 378 : if (child_rel->rd_rel->reloftype)
17522 8 : ereport(ERROR,
17523 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17524 : errmsg("cannot change inheritance of typed table")));
17525 :
17526 370 : if (child_rel->rd_rel->relispartition)
17527 12 : ereport(ERROR,
17528 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17529 : errmsg("cannot change inheritance of a partition")));
17530 358 : }
17531 :
17532 : /*
17533 : * ALTER TABLE INHERIT
17534 : *
17535 : * Return the address of the new parent relation.
17536 : */
17537 : static ObjectAddress
17538 289 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
17539 : {
17540 : Relation parent_rel;
17541 : List *children;
17542 : ObjectAddress address;
17543 : const char *trigger_name;
17544 :
17545 : /*
17546 : * A self-exclusive lock is needed here. See the similar case in
17547 : * MergeAttributes() for a full explanation.
17548 : */
17549 289 : parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
17550 :
17551 : /*
17552 : * Must be owner of both parent and child -- child was checked by
17553 : * ATSimplePermissions call in ATPrepCmd
17554 : */
17555 289 : ATSimplePermissions(AT_AddInherit, parent_rel,
17556 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
17557 :
17558 : /* Permanent rels cannot inherit from temporary ones */
17559 289 : if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17560 4 : child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
17561 0 : ereport(ERROR,
17562 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17563 : errmsg("cannot inherit from temporary relation \"%s\"",
17564 : RelationGetRelationName(parent_rel))));
17565 :
17566 : /* If parent rel is temp, it must belong to this session */
17567 289 : if (RELATION_IS_OTHER_TEMP(parent_rel))
17568 0 : ereport(ERROR,
17569 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17570 : errmsg("cannot inherit from temporary relation of another session")));
17571 :
17572 : /* Ditto for the child */
17573 289 : if (RELATION_IS_OTHER_TEMP(child_rel))
17574 0 : ereport(ERROR,
17575 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17576 : errmsg("cannot inherit to temporary relation of another session")));
17577 :
17578 : /* Prevent partitioned tables from becoming inheritance parents */
17579 289 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17580 4 : ereport(ERROR,
17581 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17582 : errmsg("cannot inherit from partitioned table \"%s\"",
17583 : parent->relname)));
17584 :
17585 : /* Likewise for partitions */
17586 285 : if (parent_rel->rd_rel->relispartition)
17587 4 : ereport(ERROR,
17588 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17589 : errmsg("cannot inherit from a partition")));
17590 :
17591 : /*
17592 : * Prevent circularity by seeing if proposed parent inherits from child.
17593 : * (In particular, this disallows making a rel inherit from itself.)
17594 : *
17595 : * This is not completely bulletproof because of race conditions: in
17596 : * multi-level inheritance trees, someone else could concurrently be
17597 : * making another inheritance link that closes the loop but does not join
17598 : * either of the rels we have locked. Preventing that seems to require
17599 : * exclusive locks on the entire inheritance tree, which is a cure worse
17600 : * than the disease. find_all_inheritors() will cope with circularity
17601 : * anyway, so don't sweat it too much.
17602 : *
17603 : * We use weakest lock we can on child's children, namely AccessShareLock.
17604 : */
17605 281 : children = find_all_inheritors(RelationGetRelid(child_rel),
17606 : AccessShareLock, NULL);
17607 :
17608 281 : if (list_member_oid(children, RelationGetRelid(parent_rel)))
17609 8 : ereport(ERROR,
17610 : (errcode(ERRCODE_DUPLICATE_TABLE),
17611 : errmsg("circular inheritance not allowed"),
17612 : errdetail("\"%s\" is already a child of \"%s\".",
17613 : parent->relname,
17614 : RelationGetRelationName(child_rel))));
17615 :
17616 : /*
17617 : * If child_rel has row-level triggers with transition tables, we
17618 : * currently don't allow it to become an inheritance child. See also
17619 : * prohibitions in ATExecAttachPartition() and CreateTrigger().
17620 : */
17621 273 : trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
17622 273 : if (trigger_name != NULL)
17623 4 : ereport(ERROR,
17624 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17625 : errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
17626 : trigger_name, RelationGetRelationName(child_rel)),
17627 : errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
17628 :
17629 : /* OK to create inheritance */
17630 269 : CreateInheritance(child_rel, parent_rel, false);
17631 :
17632 209 : ObjectAddressSet(address, RelationRelationId,
17633 : RelationGetRelid(parent_rel));
17634 :
17635 : /* keep our lock on the parent relation until commit */
17636 209 : table_close(parent_rel, NoLock);
17637 :
17638 209 : return address;
17639 : }
17640 :
17641 : /*
17642 : * CreateInheritance
17643 : * Catalog manipulation portion of creating inheritance between a child
17644 : * table and a parent table.
17645 : *
17646 : * This verifies that all the columns and check constraints of the parent
17647 : * appear in the child and that they have the same data types and expressions.
17648 : *
17649 : * Common to ATExecAddInherit() and ATExecAttachPartition().
17650 : */
17651 : static void
17652 2201 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
17653 : {
17654 : Relation catalogRelation;
17655 : SysScanDesc scan;
17656 : ScanKeyData key;
17657 : HeapTuple inheritsTuple;
17658 : int32 inhseqno;
17659 :
17660 : /* Note: get RowExclusiveLock because we will write pg_inherits below. */
17661 2201 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
17662 :
17663 : /*
17664 : * Check for duplicates in the list of parents, and determine the highest
17665 : * inhseqno already present; we'll use the next one for the new parent.
17666 : * Also, if proposed child is a partition, it cannot already be
17667 : * inheriting.
17668 : *
17669 : * Note: we do not reject the case where the child already inherits from
17670 : * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
17671 : */
17672 2201 : ScanKeyInit(&key,
17673 : Anum_pg_inherits_inhrelid,
17674 : BTEqualStrategyNumber, F_OIDEQ,
17675 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
17676 2201 : scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
17677 : true, NULL, 1, &key);
17678 :
17679 : /* inhseqno sequences start at 1 */
17680 2201 : inhseqno = 0;
17681 2244 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
17682 : {
17683 47 : Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
17684 :
17685 47 : if (inh->inhparent == RelationGetRelid(parent_rel))
17686 4 : ereport(ERROR,
17687 : (errcode(ERRCODE_DUPLICATE_TABLE),
17688 : errmsg("relation \"%s\" would be inherited from more than once",
17689 : RelationGetRelationName(parent_rel))));
17690 :
17691 43 : if (inh->inhseqno > inhseqno)
17692 43 : inhseqno = inh->inhseqno;
17693 : }
17694 2197 : systable_endscan(scan);
17695 :
17696 : /* Match up the columns and bump attinhcount as needed */
17697 2197 : MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
17698 :
17699 : /* Match up the constraints and bump coninhcount as needed */
17700 2109 : MergeConstraintsIntoExisting(child_rel, parent_rel);
17701 :
17702 : /*
17703 : * OK, it looks valid. Make the catalog entries that show inheritance.
17704 : */
17705 2069 : StoreCatalogInheritance1(RelationGetRelid(child_rel),
17706 : RelationGetRelid(parent_rel),
17707 : inhseqno + 1,
17708 : catalogRelation,
17709 2069 : parent_rel->rd_rel->relkind ==
17710 : RELKIND_PARTITIONED_TABLE);
17711 :
17712 : /* Now we're done with pg_inherits */
17713 2069 : table_close(catalogRelation, RowExclusiveLock);
17714 2069 : }
17715 :
17716 : /*
17717 : * Obtain the source-text form of the constraint expression for a check
17718 : * constraint, given its pg_constraint tuple
17719 : */
17720 : static char *
17721 272 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
17722 : {
17723 : Form_pg_constraint con;
17724 : bool isnull;
17725 : Datum attr;
17726 : Datum expr;
17727 :
17728 272 : con = (Form_pg_constraint) GETSTRUCT(contup);
17729 272 : attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
17730 272 : if (isnull)
17731 0 : elog(ERROR, "null conbin for constraint %u", con->oid);
17732 :
17733 272 : expr = DirectFunctionCall2(pg_get_expr, attr,
17734 : ObjectIdGetDatum(con->conrelid));
17735 272 : return TextDatumGetCString(expr);
17736 : }
17737 :
17738 : /*
17739 : * Determine whether two check constraints are functionally equivalent
17740 : *
17741 : * The test we apply is to see whether they reverse-compile to the same
17742 : * source string. This insulates us from issues like whether attributes
17743 : * have the same physical column numbers in parent and child relations.
17744 : *
17745 : * Note that we ignore enforceability as there are cases where constraints
17746 : * with differing enforceability are allowed.
17747 : */
17748 : static bool
17749 136 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
17750 : {
17751 136 : Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
17752 136 : Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
17753 :
17754 136 : if (acon->condeferrable != bcon->condeferrable ||
17755 136 : acon->condeferred != bcon->condeferred ||
17756 136 : strcmp(decompile_conbin(a, tupleDesc),
17757 136 : decompile_conbin(b, tupleDesc)) != 0)
17758 4 : return false;
17759 : else
17760 132 : return true;
17761 : }
17762 :
17763 : /*
17764 : * Check columns in child table match up with columns in parent, and increment
17765 : * their attinhcount.
17766 : *
17767 : * Called by CreateInheritance
17768 : *
17769 : * Currently all parent columns must be found in child. Missing columns are an
17770 : * error. One day we might consider creating new columns like CREATE TABLE
17771 : * does. However, that is widely unpopular --- in the common use case of
17772 : * partitioned tables it's a foot-gun.
17773 : *
17774 : * The data type must match exactly. If the parent column is NOT NULL then
17775 : * the child must be as well. Defaults are not compared, however.
17776 : */
17777 : static void
17778 2197 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
17779 : {
17780 : Relation attrrel;
17781 : TupleDesc parent_desc;
17782 :
17783 2197 : attrrel = table_open(AttributeRelationId, RowExclusiveLock);
17784 2197 : parent_desc = RelationGetDescr(parent_rel);
17785 :
17786 7241 : for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
17787 : {
17788 5132 : Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
17789 5132 : char *parent_attname = NameStr(parent_att->attname);
17790 : HeapTuple tuple;
17791 :
17792 : /* Ignore dropped columns in the parent. */
17793 5132 : if (parent_att->attisdropped)
17794 180 : continue;
17795 :
17796 : /* Find same column in child (matching on column name). */
17797 4952 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
17798 4952 : if (HeapTupleIsValid(tuple))
17799 : {
17800 4944 : Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
17801 :
17802 4944 : if (parent_att->atttypid != child_att->atttypid ||
17803 4940 : parent_att->atttypmod != child_att->atttypmod)
17804 8 : ereport(ERROR,
17805 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17806 : errmsg("child table \"%s\" has different type for column \"%s\"",
17807 : RelationGetRelationName(child_rel), parent_attname)));
17808 :
17809 4936 : if (parent_att->attcollation != child_att->attcollation)
17810 4 : ereport(ERROR,
17811 : (errcode(ERRCODE_COLLATION_MISMATCH),
17812 : errmsg("child table \"%s\" has different collation for column \"%s\"",
17813 : RelationGetRelationName(child_rel), parent_attname)));
17814 :
17815 : /*
17816 : * If the parent has a not-null constraint that's not NO INHERIT,
17817 : * make sure the child has one too.
17818 : *
17819 : * Other constraints are checked elsewhere.
17820 : */
17821 4932 : if (parent_att->attnotnull && !child_att->attnotnull)
17822 : {
17823 : HeapTuple contup;
17824 :
17825 32 : contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
17826 32 : parent_att->attnum);
17827 32 : if (HeapTupleIsValid(contup) &&
17828 32 : !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
17829 20 : ereport(ERROR,
17830 : errcode(ERRCODE_DATATYPE_MISMATCH),
17831 : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
17832 : parent_attname, RelationGetRelationName(child_rel)));
17833 : }
17834 :
17835 : /*
17836 : * Child column must be generated if and only if parent column is.
17837 : */
17838 4912 : if (parent_att->attgenerated && !child_att->attgenerated)
17839 24 : ereport(ERROR,
17840 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17841 : errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
17842 4888 : if (child_att->attgenerated && !parent_att->attgenerated)
17843 16 : ereport(ERROR,
17844 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17845 : errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
17846 :
17847 4872 : if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
17848 8 : ereport(ERROR,
17849 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17850 : errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
17851 : errdetail("Parent column is %s, child column is %s.",
17852 : parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
17853 : child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
17854 :
17855 : /*
17856 : * Regular inheritance children are independent enough not to
17857 : * inherit identity columns. But partitions are integral part of
17858 : * a partitioned table and inherit identity column.
17859 : */
17860 4864 : if (ispartition)
17861 4387 : child_att->attidentity = parent_att->attidentity;
17862 :
17863 : /*
17864 : * OK, bump the child column's inheritance count. (If we fail
17865 : * later on, this change will just roll back.)
17866 : */
17867 4864 : if (pg_add_s16_overflow(child_att->attinhcount, 1,
17868 : &child_att->attinhcount))
17869 0 : ereport(ERROR,
17870 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
17871 : errmsg("too many inheritance parents"));
17872 :
17873 : /*
17874 : * In case of partitions, we must enforce that value of attislocal
17875 : * is same in all partitions. (Note: there are only inherited
17876 : * attributes in partitions)
17877 : */
17878 4864 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17879 : {
17880 : Assert(child_att->attinhcount == 1);
17881 4387 : child_att->attislocal = false;
17882 : }
17883 :
17884 4864 : CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
17885 4864 : heap_freetuple(tuple);
17886 : }
17887 : else
17888 : {
17889 8 : ereport(ERROR,
17890 : (errcode(ERRCODE_DATATYPE_MISMATCH),
17891 : errmsg("child table is missing column \"%s\"", parent_attname)));
17892 : }
17893 : }
17894 :
17895 2109 : table_close(attrrel, RowExclusiveLock);
17896 2109 : }
17897 :
17898 : /*
17899 : * Check constraints in child table match up with constraints in parent,
17900 : * and increment their coninhcount.
17901 : *
17902 : * Constraints that are marked ONLY in the parent are ignored.
17903 : *
17904 : * Called by CreateInheritance
17905 : *
17906 : * Currently all constraints in parent must be present in the child. One day we
17907 : * may consider adding new constraints like CREATE TABLE does.
17908 : *
17909 : * XXX This is O(N^2) which may be an issue with tables with hundreds of
17910 : * constraints. As long as tables have more like 10 constraints it shouldn't be
17911 : * a problem though. Even 100 constraints ought not be the end of the world.
17912 : *
17913 : * XXX See MergeWithExistingConstraint too if you change this code.
17914 : */
17915 : static void
17916 2109 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
17917 : {
17918 : Relation constraintrel;
17919 : SysScanDesc parent_scan;
17920 : ScanKeyData parent_key;
17921 : HeapTuple parent_tuple;
17922 2109 : Oid parent_relid = RelationGetRelid(parent_rel);
17923 : AttrMap *attmap;
17924 :
17925 2109 : constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
17926 :
17927 : /* Outer loop scans through the parent's constraint definitions */
17928 2109 : ScanKeyInit(&parent_key,
17929 : Anum_pg_constraint_conrelid,
17930 : BTEqualStrategyNumber, F_OIDEQ,
17931 : ObjectIdGetDatum(parent_relid));
17932 2109 : parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
17933 : true, NULL, 1, &parent_key);
17934 :
17935 2109 : attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
17936 : RelationGetDescr(child_rel),
17937 : true);
17938 :
17939 3720 : while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
17940 : {
17941 1651 : Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
17942 : SysScanDesc child_scan;
17943 : ScanKeyData child_key;
17944 : HeapTuple child_tuple;
17945 : AttrNumber parent_attno;
17946 1651 : bool found = false;
17947 :
17948 1651 : if (parent_con->contype != CONSTRAINT_CHECK &&
17949 1483 : parent_con->contype != CONSTRAINT_NOTNULL)
17950 770 : continue;
17951 :
17952 : /* if the parent's constraint is marked NO INHERIT, it's not inherited */
17953 913 : if (parent_con->connoinherit)
17954 32 : continue;
17955 :
17956 881 : if (parent_con->contype == CONSTRAINT_NOTNULL)
17957 729 : parent_attno = extractNotNullColumn(parent_tuple);
17958 : else
17959 152 : parent_attno = InvalidAttrNumber;
17960 :
17961 : /* Search for a child constraint matching this one */
17962 881 : ScanKeyInit(&child_key,
17963 : Anum_pg_constraint_conrelid,
17964 : BTEqualStrategyNumber, F_OIDEQ,
17965 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
17966 881 : child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
17967 : true, NULL, 1, &child_key);
17968 :
17969 1408 : while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
17970 : {
17971 1392 : Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
17972 : HeapTuple child_copy;
17973 :
17974 1392 : if (child_con->contype != parent_con->contype)
17975 274 : continue;
17976 :
17977 : /*
17978 : * CHECK constraint are matched by constraint name, NOT NULL ones
17979 : * by attribute number.
17980 : */
17981 1118 : if (child_con->contype == CONSTRAINT_CHECK)
17982 : {
17983 262 : if (strcmp(NameStr(parent_con->conname),
17984 199 : NameStr(child_con->conname)) != 0)
17985 63 : continue;
17986 : }
17987 919 : else if (child_con->contype == CONSTRAINT_NOTNULL)
17988 : {
17989 : Form_pg_attribute parent_attr;
17990 : Form_pg_attribute child_attr;
17991 : AttrNumber child_attno;
17992 :
17993 919 : parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
17994 919 : child_attno = extractNotNullColumn(child_tuple);
17995 919 : if (parent_attno != attmap->attnums[child_attno - 1])
17996 190 : continue;
17997 :
17998 729 : child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
17999 : /* there shouldn't be constraints on dropped columns */
18000 729 : if (parent_attr->attisdropped || child_attr->attisdropped)
18001 0 : elog(ERROR, "found not-null constraint on dropped columns");
18002 : }
18003 :
18004 865 : if (child_con->contype == CONSTRAINT_CHECK &&
18005 136 : !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
18006 4 : ereport(ERROR,
18007 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18008 : errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
18009 : RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
18010 :
18011 : /*
18012 : * If the child constraint is "no inherit" then cannot merge
18013 : */
18014 861 : if (child_con->connoinherit)
18015 8 : ereport(ERROR,
18016 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18017 : errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
18018 : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18019 :
18020 : /*
18021 : * If the child constraint is "not valid" then cannot merge with a
18022 : * valid parent constraint
18023 : */
18024 853 : if (parent_con->convalidated && child_con->conenforced &&
18025 773 : !child_con->convalidated)
18026 8 : ereport(ERROR,
18027 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18028 : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
18029 : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18030 :
18031 : /*
18032 : * A NOT ENFORCED child constraint cannot be merged with an
18033 : * ENFORCED parent constraint. However, the reverse is allowed,
18034 : * where the child constraint is ENFORCED.
18035 : */
18036 845 : if (parent_con->conenforced && !child_con->conenforced)
18037 4 : ereport(ERROR,
18038 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18039 : errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
18040 : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18041 :
18042 : /*
18043 : * OK, bump the child constraint's inheritance count. (If we fail
18044 : * later on, this change will just roll back.)
18045 : */
18046 841 : child_copy = heap_copytuple(child_tuple);
18047 841 : child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
18048 :
18049 841 : if (pg_add_s16_overflow(child_con->coninhcount, 1,
18050 : &child_con->coninhcount))
18051 0 : ereport(ERROR,
18052 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18053 : errmsg("too many inheritance parents"));
18054 :
18055 : /*
18056 : * In case of partitions, an inherited constraint must be
18057 : * inherited only once since it cannot have multiple parents and
18058 : * it is never considered local.
18059 : */
18060 841 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18061 : {
18062 : Assert(child_con->coninhcount == 1);
18063 750 : child_con->conislocal = false;
18064 : }
18065 :
18066 841 : CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
18067 841 : heap_freetuple(child_copy);
18068 :
18069 841 : found = true;
18070 841 : break;
18071 : }
18072 :
18073 857 : systable_endscan(child_scan);
18074 :
18075 857 : if (!found)
18076 : {
18077 16 : if (parent_con->contype == CONSTRAINT_NOTNULL)
18078 0 : ereport(ERROR,
18079 : errcode(ERRCODE_DATATYPE_MISMATCH),
18080 : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18081 : get_attname(parent_relid,
18082 : extractNotNullColumn(parent_tuple),
18083 : false),
18084 : RelationGetRelationName(child_rel)));
18085 :
18086 16 : ereport(ERROR,
18087 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18088 : errmsg("child table is missing constraint \"%s\"",
18089 : NameStr(parent_con->conname))));
18090 : }
18091 : }
18092 :
18093 2069 : systable_endscan(parent_scan);
18094 2069 : table_close(constraintrel, RowExclusiveLock);
18095 2069 : }
18096 :
18097 : /*
18098 : * ALTER TABLE NO INHERIT
18099 : *
18100 : * Return value is the address of the relation that is no longer parent.
18101 : */
18102 : static ObjectAddress
18103 69 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
18104 : {
18105 : ObjectAddress address;
18106 : Relation parent_rel;
18107 :
18108 : /*
18109 : * AccessShareLock on the parent is probably enough, seeing that DROP
18110 : * TABLE doesn't lock parent tables at all. We need some lock since we'll
18111 : * be inspecting the parent's schema.
18112 : */
18113 69 : parent_rel = table_openrv(parent, AccessShareLock);
18114 :
18115 : /*
18116 : * We don't bother to check ownership of the parent table --- ownership of
18117 : * the child is presumed enough rights.
18118 : */
18119 :
18120 : /* Off to RemoveInheritance() where most of the work happens */
18121 69 : RemoveInheritance(rel, parent_rel, false);
18122 :
18123 65 : ObjectAddressSet(address, RelationRelationId,
18124 : RelationGetRelid(parent_rel));
18125 :
18126 : /* keep our lock on the parent relation until commit */
18127 65 : table_close(parent_rel, NoLock);
18128 :
18129 65 : return address;
18130 : }
18131 :
18132 : /*
18133 : * MarkInheritDetached
18134 : *
18135 : * Set inhdetachpending for a partition, for ATExecDetachPartition
18136 : * in concurrent mode. While at it, verify that no other partition is
18137 : * already pending detach.
18138 : */
18139 : static void
18140 75 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
18141 : {
18142 : Relation catalogRelation;
18143 : SysScanDesc scan;
18144 : ScanKeyData key;
18145 : HeapTuple inheritsTuple;
18146 75 : bool found = false;
18147 :
18148 : Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18149 :
18150 : /*
18151 : * Find pg_inherits entries by inhparent. (We need to scan them all in
18152 : * order to verify that no other partition is pending detach.)
18153 : */
18154 75 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18155 75 : ScanKeyInit(&key,
18156 : Anum_pg_inherits_inhparent,
18157 : BTEqualStrategyNumber, F_OIDEQ,
18158 : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18159 75 : scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
18160 : true, NULL, 1, &key);
18161 :
18162 294 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18163 : {
18164 : Form_pg_inherits inhForm;
18165 :
18166 145 : inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18167 145 : if (inhForm->inhdetachpending)
18168 1 : ereport(ERROR,
18169 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
18170 : errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
18171 : get_rel_name(inhForm->inhrelid),
18172 : get_namespace_name(parent_rel->rd_rel->relnamespace),
18173 : RelationGetRelationName(parent_rel)),
18174 : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
18175 :
18176 144 : if (inhForm->inhrelid == RelationGetRelid(child_rel))
18177 : {
18178 : HeapTuple newtup;
18179 :
18180 74 : newtup = heap_copytuple(inheritsTuple);
18181 74 : ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
18182 :
18183 74 : CatalogTupleUpdate(catalogRelation,
18184 74 : &inheritsTuple->t_self,
18185 : newtup);
18186 74 : found = true;
18187 74 : heap_freetuple(newtup);
18188 : /* keep looking, to ensure we catch others pending detach */
18189 : }
18190 : }
18191 :
18192 : /* Done */
18193 74 : systable_endscan(scan);
18194 74 : table_close(catalogRelation, RowExclusiveLock);
18195 :
18196 74 : if (!found)
18197 0 : ereport(ERROR,
18198 : (errcode(ERRCODE_UNDEFINED_TABLE),
18199 : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18200 : RelationGetRelationName(child_rel),
18201 : RelationGetRelationName(parent_rel))));
18202 74 : }
18203 :
18204 : /*
18205 : * RemoveInheritance
18206 : *
18207 : * Drop a parent from the child's parents. This just adjusts the attinhcount
18208 : * and attislocal of the columns and removes the pg_inherit and pg_depend
18209 : * entries. expect_detached is passed down to DeleteInheritsTuple, q.v..
18210 : *
18211 : * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
18212 : * up attislocal stays true, which means if a child is ever removed from a
18213 : * parent then its columns will never be automatically dropped which may
18214 : * surprise. But at least we'll never surprise by dropping columns someone
18215 : * isn't expecting to be dropped which would actually mean data loss.
18216 : *
18217 : * coninhcount and conislocal for inherited constraints are adjusted in
18218 : * exactly the same way.
18219 : *
18220 : * Common to ATExecDropInherit() and ATExecDetachPartition().
18221 : */
18222 : static void
18223 782 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
18224 : {
18225 : Relation catalogRelation;
18226 : SysScanDesc scan;
18227 : ScanKeyData key[3];
18228 : HeapTuple attributeTuple,
18229 : constraintTuple;
18230 : AttrMap *attmap;
18231 : List *connames;
18232 : List *nncolumns;
18233 : bool found;
18234 : bool is_partitioning;
18235 :
18236 782 : is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18237 :
18238 782 : found = DeleteInheritsTuple(RelationGetRelid(child_rel),
18239 : RelationGetRelid(parent_rel),
18240 : expect_detached,
18241 782 : RelationGetRelationName(child_rel));
18242 782 : if (!found)
18243 : {
18244 16 : if (is_partitioning)
18245 12 : ereport(ERROR,
18246 : (errcode(ERRCODE_UNDEFINED_TABLE),
18247 : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18248 : RelationGetRelationName(child_rel),
18249 : RelationGetRelationName(parent_rel))));
18250 : else
18251 4 : ereport(ERROR,
18252 : (errcode(ERRCODE_UNDEFINED_TABLE),
18253 : errmsg("relation \"%s\" is not a parent of relation \"%s\"",
18254 : RelationGetRelationName(parent_rel),
18255 : RelationGetRelationName(child_rel))));
18256 : }
18257 :
18258 : /*
18259 : * Search through child columns looking for ones matching parent rel
18260 : */
18261 766 : catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
18262 766 : ScanKeyInit(&key[0],
18263 : Anum_pg_attribute_attrelid,
18264 : BTEqualStrategyNumber, F_OIDEQ,
18265 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18266 766 : scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
18267 : true, NULL, 1, key);
18268 7090 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
18269 : {
18270 6324 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
18271 :
18272 : /* Ignore if dropped or not inherited */
18273 6324 : if (att->attisdropped)
18274 28 : continue;
18275 6296 : if (att->attinhcount <= 0)
18276 4624 : continue;
18277 :
18278 1672 : if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
18279 1672 : NameStr(att->attname)))
18280 : {
18281 : /* Decrement inhcount and possibly set islocal to true */
18282 1636 : HeapTuple copyTuple = heap_copytuple(attributeTuple);
18283 1636 : Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
18284 :
18285 1636 : copy_att->attinhcount--;
18286 1636 : if (copy_att->attinhcount == 0)
18287 1616 : copy_att->attislocal = true;
18288 :
18289 1636 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18290 1636 : heap_freetuple(copyTuple);
18291 : }
18292 : }
18293 766 : systable_endscan(scan);
18294 766 : table_close(catalogRelation, RowExclusiveLock);
18295 :
18296 : /*
18297 : * Likewise, find inherited check and not-null constraints and disinherit
18298 : * them. To do this, we first need a list of the names of the parent's
18299 : * check constraints. (We cheat a bit by only checking for name matches,
18300 : * assuming that the expressions will match.)
18301 : *
18302 : * For NOT NULL columns, we store column numbers to match, mapping them in
18303 : * to the child rel's attribute numbers.
18304 : */
18305 766 : attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
18306 : RelationGetDescr(parent_rel),
18307 : false);
18308 :
18309 766 : catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
18310 766 : ScanKeyInit(&key[0],
18311 : Anum_pg_constraint_conrelid,
18312 : BTEqualStrategyNumber, F_OIDEQ,
18313 : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18314 766 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18315 : true, NULL, 1, key);
18316 :
18317 766 : connames = NIL;
18318 766 : nncolumns = NIL;
18319 :
18320 1463 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18321 : {
18322 697 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18323 :
18324 697 : if (con->connoinherit)
18325 152 : continue;
18326 :
18327 545 : if (con->contype == CONSTRAINT_CHECK)
18328 76 : connames = lappend(connames, pstrdup(NameStr(con->conname)));
18329 545 : if (con->contype == CONSTRAINT_NOTNULL)
18330 : {
18331 249 : AttrNumber parent_attno = extractNotNullColumn(constraintTuple);
18332 :
18333 249 : nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
18334 : }
18335 : }
18336 :
18337 766 : systable_endscan(scan);
18338 :
18339 : /* Now scan the child's constraints to find matches */
18340 766 : ScanKeyInit(&key[0],
18341 : Anum_pg_constraint_conrelid,
18342 : BTEqualStrategyNumber, F_OIDEQ,
18343 : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18344 766 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18345 : true, NULL, 1, key);
18346 :
18347 1459 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18348 : {
18349 693 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18350 693 : bool match = false;
18351 :
18352 : /*
18353 : * Match CHECK constraints by name, not-null constraints by column
18354 : * number, and ignore all others.
18355 : */
18356 693 : if (con->contype == CONSTRAINT_CHECK)
18357 : {
18358 228 : foreach_ptr(char, chkname, connames)
18359 : {
18360 80 : if (con->contype == CONSTRAINT_CHECK &&
18361 80 : strcmp(NameStr(con->conname), chkname) == 0)
18362 : {
18363 76 : match = true;
18364 76 : connames = foreach_delete_current(connames, chkname);
18365 76 : break;
18366 : }
18367 : }
18368 : }
18369 581 : else if (con->contype == CONSTRAINT_NOTNULL)
18370 : {
18371 289 : AttrNumber child_attno = extractNotNullColumn(constraintTuple);
18372 :
18373 582 : foreach_int(prevattno, nncolumns)
18374 : {
18375 253 : if (prevattno == child_attno)
18376 : {
18377 249 : match = true;
18378 249 : nncolumns = foreach_delete_current(nncolumns, prevattno);
18379 249 : break;
18380 : }
18381 : }
18382 : }
18383 : else
18384 292 : continue;
18385 :
18386 401 : if (match)
18387 : {
18388 : /* Decrement inhcount and possibly set islocal to true */
18389 325 : HeapTuple copyTuple = heap_copytuple(constraintTuple);
18390 325 : Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
18391 :
18392 325 : if (copy_con->coninhcount <= 0) /* shouldn't happen */
18393 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
18394 : RelationGetRelid(child_rel), NameStr(copy_con->conname));
18395 :
18396 325 : copy_con->coninhcount--;
18397 325 : if (copy_con->coninhcount == 0)
18398 313 : copy_con->conislocal = true;
18399 :
18400 325 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18401 325 : heap_freetuple(copyTuple);
18402 : }
18403 : }
18404 :
18405 : /* We should have matched all constraints */
18406 766 : if (connames != NIL || nncolumns != NIL)
18407 0 : elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
18408 : list_length(connames) + list_length(nncolumns),
18409 : RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
18410 :
18411 766 : systable_endscan(scan);
18412 766 : table_close(catalogRelation, RowExclusiveLock);
18413 :
18414 766 : drop_parent_dependency(RelationGetRelid(child_rel),
18415 : RelationRelationId,
18416 : RelationGetRelid(parent_rel),
18417 : child_dependency_type(is_partitioning));
18418 :
18419 : /*
18420 : * Post alter hook of this inherits. Since object_access_hook doesn't take
18421 : * multiple object identifiers, we relay oid of parent relation using
18422 : * auxiliary_id argument.
18423 : */
18424 766 : InvokeObjectPostAlterHookArg(InheritsRelationId,
18425 : RelationGetRelid(child_rel), 0,
18426 : RelationGetRelid(parent_rel), false);
18427 766 : }
18428 :
18429 : /*
18430 : * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
18431 : * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
18432 : * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
18433 : * be TypeRelationId). There's no convenient way to do this, so go trawling
18434 : * through pg_depend.
18435 : */
18436 : static void
18437 774 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
18438 : DependencyType deptype)
18439 : {
18440 : Relation catalogRelation;
18441 : SysScanDesc scan;
18442 : ScanKeyData key[3];
18443 : HeapTuple depTuple;
18444 :
18445 774 : catalogRelation = table_open(DependRelationId, RowExclusiveLock);
18446 :
18447 774 : ScanKeyInit(&key[0],
18448 : Anum_pg_depend_classid,
18449 : BTEqualStrategyNumber, F_OIDEQ,
18450 : ObjectIdGetDatum(RelationRelationId));
18451 774 : ScanKeyInit(&key[1],
18452 : Anum_pg_depend_objid,
18453 : BTEqualStrategyNumber, F_OIDEQ,
18454 : ObjectIdGetDatum(relid));
18455 774 : ScanKeyInit(&key[2],
18456 : Anum_pg_depend_objsubid,
18457 : BTEqualStrategyNumber, F_INT4EQ,
18458 : Int32GetDatum(0));
18459 :
18460 774 : scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
18461 : NULL, 3, key);
18462 :
18463 2375 : while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
18464 : {
18465 1601 : Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
18466 :
18467 1601 : if (dep->refclassid == refclassid &&
18468 802 : dep->refobjid == refobjid &&
18469 774 : dep->refobjsubid == 0 &&
18470 774 : dep->deptype == deptype)
18471 774 : CatalogTupleDelete(catalogRelation, &depTuple->t_self);
18472 : }
18473 :
18474 774 : systable_endscan(scan);
18475 774 : table_close(catalogRelation, RowExclusiveLock);
18476 774 : }
18477 :
18478 : /*
18479 : * ALTER TABLE OF
18480 : *
18481 : * Attach a table to a composite type, as though it had been created with CREATE
18482 : * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
18483 : * subject table must not have inheritance parents. These restrictions ensure
18484 : * that you cannot create a configuration impossible with CREATE TABLE OF alone.
18485 : *
18486 : * The address of the type is returned.
18487 : */
18488 : static ObjectAddress
18489 42 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
18490 : {
18491 42 : Oid relid = RelationGetRelid(rel);
18492 : Type typetuple;
18493 : Form_pg_type typeform;
18494 : Oid typeid;
18495 : Relation inheritsRelation,
18496 : relationRelation;
18497 : SysScanDesc scan;
18498 : ScanKeyData key;
18499 : AttrNumber table_attno,
18500 : type_attno;
18501 : TupleDesc typeTupleDesc,
18502 : tableTupleDesc;
18503 : ObjectAddress tableobj,
18504 : typeobj;
18505 : HeapTuple classtuple;
18506 :
18507 : /* Validate the type. */
18508 42 : typetuple = typenameType(NULL, ofTypename, NULL);
18509 42 : check_of_type(typetuple);
18510 42 : typeform = (Form_pg_type) GETSTRUCT(typetuple);
18511 42 : typeid = typeform->oid;
18512 :
18513 : /* Fail if the table has any inheritance parents. */
18514 42 : inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
18515 42 : ScanKeyInit(&key,
18516 : Anum_pg_inherits_inhrelid,
18517 : BTEqualStrategyNumber, F_OIDEQ,
18518 : ObjectIdGetDatum(relid));
18519 42 : scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
18520 : true, NULL, 1, &key);
18521 42 : if (HeapTupleIsValid(systable_getnext(scan)))
18522 4 : ereport(ERROR,
18523 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18524 : errmsg("typed tables cannot inherit")));
18525 38 : systable_endscan(scan);
18526 38 : table_close(inheritsRelation, AccessShareLock);
18527 :
18528 : /*
18529 : * Check the tuple descriptors for compatibility. Unlike inheritance, we
18530 : * require that the order also match. However, attnotnull need not match.
18531 : */
18532 38 : typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
18533 38 : tableTupleDesc = RelationGetDescr(rel);
18534 38 : table_attno = 1;
18535 121 : for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
18536 : {
18537 : Form_pg_attribute type_attr,
18538 : table_attr;
18539 : const char *type_attname,
18540 : *table_attname;
18541 :
18542 : /* Get the next non-dropped type attribute. */
18543 99 : type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
18544 99 : if (type_attr->attisdropped)
18545 29 : continue;
18546 70 : type_attname = NameStr(type_attr->attname);
18547 :
18548 : /* Get the next non-dropped table attribute. */
18549 : do
18550 : {
18551 78 : if (table_attno > tableTupleDesc->natts)
18552 4 : ereport(ERROR,
18553 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18554 : errmsg("table is missing column \"%s\"",
18555 : type_attname)));
18556 74 : table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
18557 74 : table_attno++;
18558 74 : } while (table_attr->attisdropped);
18559 66 : table_attname = NameStr(table_attr->attname);
18560 :
18561 : /* Compare name. */
18562 66 : if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
18563 4 : ereport(ERROR,
18564 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18565 : errmsg("table has column \"%s\" where type requires \"%s\"",
18566 : table_attname, type_attname)));
18567 :
18568 : /* Compare type. */
18569 62 : if (table_attr->atttypid != type_attr->atttypid ||
18570 58 : table_attr->atttypmod != type_attr->atttypmod ||
18571 54 : table_attr->attcollation != type_attr->attcollation)
18572 8 : ereport(ERROR,
18573 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18574 : errmsg("table \"%s\" has different type for column \"%s\"",
18575 : RelationGetRelationName(rel), type_attname)));
18576 : }
18577 22 : ReleaseTupleDesc(typeTupleDesc);
18578 :
18579 : /* Any remaining columns at the end of the table had better be dropped. */
18580 22 : for (; table_attno <= tableTupleDesc->natts; table_attno++)
18581 : {
18582 4 : Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
18583 : table_attno - 1);
18584 :
18585 4 : if (!table_attr->attisdropped)
18586 4 : ereport(ERROR,
18587 : (errcode(ERRCODE_DATATYPE_MISMATCH),
18588 : errmsg("table has extra column \"%s\"",
18589 : NameStr(table_attr->attname))));
18590 : }
18591 :
18592 : /* If the table was already typed, drop the existing dependency. */
18593 18 : if (rel->rd_rel->reloftype)
18594 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
18595 : DEPENDENCY_NORMAL);
18596 :
18597 : /* Record a dependency on the new type. */
18598 18 : tableobj.classId = RelationRelationId;
18599 18 : tableobj.objectId = relid;
18600 18 : tableobj.objectSubId = 0;
18601 18 : typeobj.classId = TypeRelationId;
18602 18 : typeobj.objectId = typeid;
18603 18 : typeobj.objectSubId = 0;
18604 18 : recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
18605 :
18606 : /* Update pg_class.reloftype */
18607 18 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
18608 18 : classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18609 18 : if (!HeapTupleIsValid(classtuple))
18610 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18611 18 : ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
18612 18 : CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
18613 :
18614 18 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
18615 :
18616 18 : heap_freetuple(classtuple);
18617 18 : table_close(relationRelation, RowExclusiveLock);
18618 :
18619 18 : ReleaseSysCache(typetuple);
18620 :
18621 18 : return typeobj;
18622 : }
18623 :
18624 : /*
18625 : * ALTER TABLE NOT OF
18626 : *
18627 : * Detach a typed table from its originating type. Just clear reloftype and
18628 : * remove the dependency.
18629 : */
18630 : static void
18631 4 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
18632 : {
18633 4 : Oid relid = RelationGetRelid(rel);
18634 : Relation relationRelation;
18635 : HeapTuple tuple;
18636 :
18637 4 : if (!OidIsValid(rel->rd_rel->reloftype))
18638 0 : ereport(ERROR,
18639 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18640 : errmsg("\"%s\" is not a typed table",
18641 : RelationGetRelationName(rel))));
18642 :
18643 : /*
18644 : * We don't bother to check ownership of the type --- ownership of the
18645 : * table is presumed enough rights. No lock required on the type, either.
18646 : */
18647 :
18648 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
18649 : DEPENDENCY_NORMAL);
18650 :
18651 : /* Clear pg_class.reloftype */
18652 4 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
18653 4 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18654 4 : if (!HeapTupleIsValid(tuple))
18655 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18656 4 : ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
18657 4 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
18658 :
18659 4 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
18660 :
18661 4 : heap_freetuple(tuple);
18662 4 : table_close(relationRelation, RowExclusiveLock);
18663 4 : }
18664 :
18665 : /*
18666 : * relation_mark_replica_identity: Update a table's replica identity
18667 : *
18668 : * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
18669 : * index. Otherwise, it must be InvalidOid.
18670 : *
18671 : * Caller had better hold an exclusive lock on the relation, as the results
18672 : * of running two of these concurrently wouldn't be pretty.
18673 : */
18674 : static void
18675 286 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
18676 : bool is_internal)
18677 : {
18678 : Relation pg_index;
18679 : Relation pg_class;
18680 : HeapTuple pg_class_tuple;
18681 : HeapTuple pg_index_tuple;
18682 : Form_pg_class pg_class_form;
18683 : Form_pg_index pg_index_form;
18684 : ListCell *index;
18685 :
18686 : /*
18687 : * Check whether relreplident has changed, and update it if so.
18688 : */
18689 286 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
18690 286 : pg_class_tuple = SearchSysCacheCopy1(RELOID,
18691 : ObjectIdGetDatum(RelationGetRelid(rel)));
18692 286 : if (!HeapTupleIsValid(pg_class_tuple))
18693 0 : elog(ERROR, "cache lookup failed for relation \"%s\"",
18694 : RelationGetRelationName(rel));
18695 286 : pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
18696 286 : if (pg_class_form->relreplident != ri_type)
18697 : {
18698 253 : pg_class_form->relreplident = ri_type;
18699 253 : CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
18700 : }
18701 286 : table_close(pg_class, RowExclusiveLock);
18702 286 : heap_freetuple(pg_class_tuple);
18703 :
18704 : /*
18705 : * Update the per-index indisreplident flags correctly.
18706 : */
18707 286 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
18708 757 : foreach(index, RelationGetIndexList(rel))
18709 : {
18710 471 : Oid thisIndexOid = lfirst_oid(index);
18711 471 : bool dirty = false;
18712 :
18713 471 : pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
18714 : ObjectIdGetDatum(thisIndexOid));
18715 471 : if (!HeapTupleIsValid(pg_index_tuple))
18716 0 : elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
18717 471 : pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
18718 :
18719 471 : if (thisIndexOid == indexOid)
18720 : {
18721 : /* Set the bit if not already set. */
18722 153 : if (!pg_index_form->indisreplident)
18723 : {
18724 141 : dirty = true;
18725 141 : pg_index_form->indisreplident = true;
18726 : }
18727 : }
18728 : else
18729 : {
18730 : /* Unset the bit if set. */
18731 318 : if (pg_index_form->indisreplident)
18732 : {
18733 34 : dirty = true;
18734 34 : pg_index_form->indisreplident = false;
18735 : }
18736 : }
18737 :
18738 471 : if (dirty)
18739 : {
18740 175 : CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
18741 175 : InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
18742 : InvalidOid, is_internal);
18743 :
18744 : /*
18745 : * Invalidate the relcache for the table, so that after we commit
18746 : * all sessions will refresh the table's replica identity index
18747 : * before attempting any UPDATE or DELETE on the table. (If we
18748 : * changed the table's pg_class row above, then a relcache inval
18749 : * is already queued due to that; but we might not have.)
18750 : */
18751 175 : CacheInvalidateRelcache(rel);
18752 : }
18753 471 : heap_freetuple(pg_index_tuple);
18754 : }
18755 :
18756 286 : table_close(pg_index, RowExclusiveLock);
18757 286 : }
18758 :
18759 : /*
18760 : * ALTER TABLE <name> REPLICA IDENTITY ...
18761 : */
18762 : static void
18763 318 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
18764 : {
18765 : Oid indexOid;
18766 : Relation indexRel;
18767 : int key;
18768 :
18769 318 : if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
18770 : {
18771 5 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18772 5 : return;
18773 : }
18774 313 : else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
18775 : {
18776 98 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18777 98 : return;
18778 : }
18779 215 : else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
18780 : {
18781 30 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
18782 30 : return;
18783 : }
18784 185 : else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
18785 : {
18786 : /* fallthrough */ ;
18787 : }
18788 : else
18789 0 : elog(ERROR, "unexpected identity type %u", stmt->identity_type);
18790 :
18791 : /* Check that the index exists */
18792 185 : indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
18793 185 : if (!OidIsValid(indexOid))
18794 0 : ereport(ERROR,
18795 : (errcode(ERRCODE_UNDEFINED_OBJECT),
18796 : errmsg("index \"%s\" for table \"%s\" does not exist",
18797 : stmt->name, RelationGetRelationName(rel))));
18798 :
18799 185 : indexRel = index_open(indexOid, ShareLock);
18800 :
18801 : /* Check that the index is on the relation we're altering. */
18802 185 : if (indexRel->rd_index == NULL ||
18803 185 : indexRel->rd_index->indrelid != RelationGetRelid(rel))
18804 4 : ereport(ERROR,
18805 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18806 : errmsg("\"%s\" is not an index for table \"%s\"",
18807 : RelationGetRelationName(indexRel),
18808 : RelationGetRelationName(rel))));
18809 :
18810 : /*
18811 : * The AM must support uniqueness, and the index must in fact be unique.
18812 : * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
18813 : * exclusion), we can use that too.
18814 : */
18815 181 : if ((!indexRel->rd_indam->amcanunique ||
18816 167 : !indexRel->rd_index->indisunique) &&
18817 18 : !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
18818 8 : ereport(ERROR,
18819 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18820 : errmsg("cannot use non-unique index \"%s\" as replica identity",
18821 : RelationGetRelationName(indexRel))));
18822 : /* Deferred indexes are not guaranteed to be always unique. */
18823 173 : if (!indexRel->rd_index->indimmediate)
18824 8 : ereport(ERROR,
18825 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18826 : errmsg("cannot use non-immediate index \"%s\" as replica identity",
18827 : RelationGetRelationName(indexRel))));
18828 : /* Expression indexes aren't supported. */
18829 165 : if (RelationGetIndexExpressions(indexRel) != NIL)
18830 4 : ereport(ERROR,
18831 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18832 : errmsg("cannot use expression index \"%s\" as replica identity",
18833 : RelationGetRelationName(indexRel))));
18834 : /* Predicate indexes aren't supported. */
18835 161 : if (RelationGetIndexPredicate(indexRel) != NIL)
18836 4 : ereport(ERROR,
18837 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18838 : errmsg("cannot use partial index \"%s\" as replica identity",
18839 : RelationGetRelationName(indexRel))));
18840 :
18841 : /* Check index for nullable columns. */
18842 354 : for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
18843 : {
18844 201 : int16 attno = indexRel->rd_index->indkey.values[key];
18845 : Form_pg_attribute attr;
18846 :
18847 : /*
18848 : * Reject any other system columns. (Going forward, we'll disallow
18849 : * indexes containing such columns in the first place, but they might
18850 : * exist in older branches.)
18851 : */
18852 201 : if (attno <= 0)
18853 0 : ereport(ERROR,
18854 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
18855 : errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
18856 : RelationGetRelationName(indexRel), attno)));
18857 :
18858 201 : attr = TupleDescAttr(rel->rd_att, attno - 1);
18859 201 : if (!attr->attnotnull)
18860 4 : ereport(ERROR,
18861 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18862 : errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
18863 : RelationGetRelationName(indexRel),
18864 : NameStr(attr->attname))));
18865 : }
18866 :
18867 : /* This index is suitable for use as a replica identity. Mark it. */
18868 153 : relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
18869 :
18870 153 : index_close(indexRel, NoLock);
18871 : }
18872 :
18873 : /*
18874 : * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
18875 : */
18876 : static void
18877 246 : ATExecSetRowSecurity(Relation rel, bool rls)
18878 : {
18879 : Relation pg_class;
18880 : Oid relid;
18881 : HeapTuple tuple;
18882 :
18883 246 : relid = RelationGetRelid(rel);
18884 :
18885 : /* Pull the record for this relation and update it */
18886 246 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
18887 :
18888 246 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18889 :
18890 246 : if (!HeapTupleIsValid(tuple))
18891 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18892 :
18893 246 : ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
18894 246 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
18895 :
18896 246 : InvokeObjectPostAlterHook(RelationRelationId,
18897 : RelationGetRelid(rel), 0);
18898 :
18899 246 : table_close(pg_class, RowExclusiveLock);
18900 246 : heap_freetuple(tuple);
18901 246 : }
18902 :
18903 : /*
18904 : * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
18905 : */
18906 : static void
18907 90 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
18908 : {
18909 : Relation pg_class;
18910 : Oid relid;
18911 : HeapTuple tuple;
18912 :
18913 90 : relid = RelationGetRelid(rel);
18914 :
18915 90 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
18916 :
18917 90 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
18918 :
18919 90 : if (!HeapTupleIsValid(tuple))
18920 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
18921 :
18922 90 : ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
18923 90 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
18924 :
18925 90 : InvokeObjectPostAlterHook(RelationRelationId,
18926 : RelationGetRelid(rel), 0);
18927 :
18928 90 : table_close(pg_class, RowExclusiveLock);
18929 90 : heap_freetuple(tuple);
18930 90 : }
18931 :
18932 : /*
18933 : * ALTER FOREIGN TABLE <name> OPTIONS (...)
18934 : */
18935 : static void
18936 33 : ATExecGenericOptions(Relation rel, List *options)
18937 : {
18938 : Relation ftrel;
18939 : ForeignServer *server;
18940 : ForeignDataWrapper *fdw;
18941 : HeapTuple tuple;
18942 : bool isnull;
18943 : Datum repl_val[Natts_pg_foreign_table];
18944 : bool repl_null[Natts_pg_foreign_table];
18945 : bool repl_repl[Natts_pg_foreign_table];
18946 : Datum datum;
18947 : Form_pg_foreign_table tableform;
18948 :
18949 33 : if (options == NIL)
18950 0 : return;
18951 :
18952 33 : ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
18953 :
18954 33 : tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
18955 : ObjectIdGetDatum(rel->rd_id));
18956 33 : if (!HeapTupleIsValid(tuple))
18957 0 : ereport(ERROR,
18958 : (errcode(ERRCODE_UNDEFINED_OBJECT),
18959 : errmsg("foreign table \"%s\" does not exist",
18960 : RelationGetRelationName(rel))));
18961 33 : tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
18962 33 : server = GetForeignServer(tableform->ftserver);
18963 33 : fdw = GetForeignDataWrapper(server->fdwid);
18964 :
18965 33 : memset(repl_val, 0, sizeof(repl_val));
18966 33 : memset(repl_null, false, sizeof(repl_null));
18967 33 : memset(repl_repl, false, sizeof(repl_repl));
18968 :
18969 : /* Extract the current options */
18970 33 : datum = SysCacheGetAttr(FOREIGNTABLEREL,
18971 : tuple,
18972 : Anum_pg_foreign_table_ftoptions,
18973 : &isnull);
18974 33 : if (isnull)
18975 2 : datum = PointerGetDatum(NULL);
18976 :
18977 : /* Transform the options */
18978 33 : datum = transformGenericOptions(ForeignTableRelationId,
18979 : datum,
18980 : options,
18981 : fdw->fdwvalidator);
18982 :
18983 32 : if (DatumGetPointer(datum) != NULL)
18984 32 : repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
18985 : else
18986 0 : repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
18987 :
18988 32 : repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
18989 :
18990 : /* Everything looks good - update the tuple */
18991 :
18992 32 : tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
18993 : repl_val, repl_null, repl_repl);
18994 :
18995 32 : CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
18996 :
18997 : /*
18998 : * Invalidate relcache so that all sessions will refresh any cached plans
18999 : * that might depend on the old options.
19000 : */
19001 32 : CacheInvalidateRelcache(rel);
19002 :
19003 32 : InvokeObjectPostAlterHook(ForeignTableRelationId,
19004 : RelationGetRelid(rel), 0);
19005 :
19006 32 : table_close(ftrel, RowExclusiveLock);
19007 :
19008 32 : heap_freetuple(tuple);
19009 : }
19010 :
19011 : /*
19012 : * ALTER TABLE ALTER COLUMN SET COMPRESSION
19013 : *
19014 : * Return value is the address of the modified column
19015 : */
19016 : static ObjectAddress
19017 48 : ATExecSetCompression(Relation rel,
19018 : const char *column,
19019 : Node *newValue,
19020 : LOCKMODE lockmode)
19021 : {
19022 : Relation attrel;
19023 : HeapTuple tuple;
19024 : Form_pg_attribute atttableform;
19025 : AttrNumber attnum;
19026 : char *compression;
19027 : char cmethod;
19028 : ObjectAddress address;
19029 :
19030 48 : compression = strVal(newValue);
19031 :
19032 48 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
19033 :
19034 : /* copy the cache entry so we can scribble on it below */
19035 48 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
19036 48 : if (!HeapTupleIsValid(tuple))
19037 0 : ereport(ERROR,
19038 : (errcode(ERRCODE_UNDEFINED_COLUMN),
19039 : errmsg("column \"%s\" of relation \"%s\" does not exist",
19040 : column, RelationGetRelationName(rel))));
19041 :
19042 : /* prevent them from altering a system attribute */
19043 48 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
19044 48 : attnum = atttableform->attnum;
19045 48 : if (attnum <= 0)
19046 0 : ereport(ERROR,
19047 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19048 : errmsg("cannot alter system column \"%s\"", column)));
19049 :
19050 : /*
19051 : * Check that column type is compressible, then get the attribute
19052 : * compression method code
19053 : */
19054 48 : cmethod = GetAttributeCompression(atttableform->atttypid, compression);
19055 :
19056 : /* update pg_attribute entry */
19057 44 : atttableform->attcompression = cmethod;
19058 44 : CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
19059 :
19060 44 : InvokeObjectPostAlterHook(RelationRelationId,
19061 : RelationGetRelid(rel),
19062 : attnum);
19063 :
19064 : /*
19065 : * Apply the change to indexes as well (only for simple index columns,
19066 : * matching behavior of index.c ConstructTupleDescriptor()).
19067 : */
19068 44 : SetIndexStorageProperties(rel, attrel, attnum,
19069 : false, 0,
19070 : true, cmethod,
19071 : lockmode);
19072 :
19073 44 : heap_freetuple(tuple);
19074 :
19075 44 : table_close(attrel, RowExclusiveLock);
19076 :
19077 : /* make changes visible */
19078 44 : CommandCounterIncrement();
19079 :
19080 44 : ObjectAddressSubSet(address, RelationRelationId,
19081 : RelationGetRelid(rel), attnum);
19082 44 : return address;
19083 : }
19084 :
19085 :
19086 : /*
19087 : * Preparation phase for SET LOGGED/UNLOGGED
19088 : *
19089 : * This verifies that we're not trying to change a temp table. Also,
19090 : * existing foreign key constraints are checked to avoid ending up with
19091 : * permanent tables referencing unlogged tables.
19092 : */
19093 : static void
19094 67 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
19095 : {
19096 : Relation pg_constraint;
19097 : HeapTuple tuple;
19098 : SysScanDesc scan;
19099 : ScanKeyData skey[1];
19100 :
19101 : /*
19102 : * Disallow changing status for a temp table. Also verify whether we can
19103 : * get away with doing nothing; in such cases we don't need to run the
19104 : * checks below, either.
19105 : */
19106 67 : switch (rel->rd_rel->relpersistence)
19107 : {
19108 0 : case RELPERSISTENCE_TEMP:
19109 0 : ereport(ERROR,
19110 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19111 : errmsg("cannot change logged status of table \"%s\" because it is temporary",
19112 : RelationGetRelationName(rel)),
19113 : errtable(rel)));
19114 : break;
19115 37 : case RELPERSISTENCE_PERMANENT:
19116 37 : if (toLogged)
19117 : /* nothing to do */
19118 8 : return;
19119 33 : break;
19120 30 : case RELPERSISTENCE_UNLOGGED:
19121 30 : if (!toLogged)
19122 : /* nothing to do */
19123 4 : return;
19124 26 : break;
19125 : }
19126 :
19127 : /*
19128 : * Check that the table is not part of any publication when changing to
19129 : * UNLOGGED, as UNLOGGED tables can't be published.
19130 : */
19131 92 : if (!toLogged &&
19132 33 : GetRelationIncludedPublications(RelationGetRelid(rel)) != NIL)
19133 0 : ereport(ERROR,
19134 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19135 : errmsg("cannot change table \"%s\" to unlogged because it is part of a publication",
19136 : RelationGetRelationName(rel)),
19137 : errdetail("Unlogged relations cannot be replicated.")));
19138 :
19139 : /*
19140 : * Check existing foreign key constraints to preserve the invariant that
19141 : * permanent tables cannot reference unlogged ones. Self-referencing
19142 : * foreign keys can safely be ignored.
19143 : */
19144 59 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
19145 :
19146 : /*
19147 : * Scan conrelid if changing to permanent, else confrelid. This also
19148 : * determines whether a useful index exists.
19149 : */
19150 59 : ScanKeyInit(&skey[0],
19151 : toLogged ? Anum_pg_constraint_conrelid :
19152 : Anum_pg_constraint_confrelid,
19153 : BTEqualStrategyNumber, F_OIDEQ,
19154 : ObjectIdGetDatum(RelationGetRelid(rel)));
19155 59 : scan = systable_beginscan(pg_constraint,
19156 : toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
19157 : true, NULL, 1, skey);
19158 :
19159 95 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
19160 : {
19161 44 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
19162 :
19163 44 : if (con->contype == CONSTRAINT_FOREIGN)
19164 : {
19165 : Oid foreignrelid;
19166 : Relation foreignrel;
19167 :
19168 : /* the opposite end of what we used as scankey */
19169 20 : foreignrelid = toLogged ? con->confrelid : con->conrelid;
19170 :
19171 : /* ignore if self-referencing */
19172 20 : if (RelationGetRelid(rel) == foreignrelid)
19173 8 : continue;
19174 :
19175 12 : foreignrel = relation_open(foreignrelid, AccessShareLock);
19176 :
19177 12 : if (toLogged)
19178 : {
19179 4 : if (!RelationIsPermanent(foreignrel))
19180 4 : ereport(ERROR,
19181 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19182 : errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
19183 : RelationGetRelationName(rel),
19184 : RelationGetRelationName(foreignrel)),
19185 : errtableconstraint(rel, NameStr(con->conname))));
19186 : }
19187 : else
19188 : {
19189 8 : if (RelationIsPermanent(foreignrel))
19190 4 : ereport(ERROR,
19191 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19192 : errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
19193 : RelationGetRelationName(rel),
19194 : RelationGetRelationName(foreignrel)),
19195 : errtableconstraint(rel, NameStr(con->conname))));
19196 : }
19197 :
19198 4 : relation_close(foreignrel, AccessShareLock);
19199 : }
19200 : }
19201 :
19202 51 : systable_endscan(scan);
19203 :
19204 51 : table_close(pg_constraint, AccessShareLock);
19205 :
19206 : /* force rewrite if necessary; see comment in ATRewriteTables */
19207 51 : tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
19208 51 : if (toLogged)
19209 22 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
19210 : else
19211 29 : tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
19212 51 : tab->chgPersistence = true;
19213 : }
19214 :
19215 : /*
19216 : * Execute ALTER TABLE SET SCHEMA
19217 : */
19218 : ObjectAddress
19219 88 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
19220 : {
19221 : Relation rel;
19222 : Oid relid;
19223 : Oid oldNspOid;
19224 : Oid nspOid;
19225 : RangeVar *newrv;
19226 : ObjectAddresses *objsMoved;
19227 : ObjectAddress myself;
19228 :
19229 88 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
19230 88 : stmt->missing_ok ? RVR_MISSING_OK : 0,
19231 : RangeVarCallbackForAlterRelation,
19232 : stmt);
19233 :
19234 83 : if (!OidIsValid(relid))
19235 : {
19236 12 : ereport(NOTICE,
19237 : (errmsg("relation \"%s\" does not exist, skipping",
19238 : stmt->relation->relname)));
19239 12 : return InvalidObjectAddress;
19240 : }
19241 :
19242 71 : rel = relation_open(relid, NoLock);
19243 :
19244 71 : oldNspOid = RelationGetNamespace(rel);
19245 :
19246 : /* If it's an owned sequence, disallow moving it by itself. */
19247 71 : if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19248 : {
19249 : Oid tableId;
19250 : int32 colId;
19251 :
19252 6 : if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19253 1 : sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
19254 4 : ereport(ERROR,
19255 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19256 : errmsg("cannot move an owned sequence into another schema"),
19257 : errdetail("Sequence \"%s\" is linked to table \"%s\".",
19258 : RelationGetRelationName(rel),
19259 : get_rel_name(tableId))));
19260 : }
19261 :
19262 : /* Get and lock schema OID and check its permissions. */
19263 67 : newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19264 67 : nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
19265 :
19266 : /* common checks on switching namespaces */
19267 67 : CheckSetNamespace(oldNspOid, nspOid);
19268 :
19269 67 : objsMoved = new_object_addresses();
19270 67 : AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
19271 63 : free_object_addresses(objsMoved);
19272 :
19273 63 : ObjectAddressSet(myself, RelationRelationId, relid);
19274 :
19275 63 : if (oldschema)
19276 63 : *oldschema = oldNspOid;
19277 :
19278 : /* close rel, but keep lock until commit */
19279 63 : relation_close(rel, NoLock);
19280 :
19281 63 : return myself;
19282 : }
19283 :
19284 : /*
19285 : * The guts of relocating a table or materialized view to another namespace:
19286 : * besides moving the relation itself, its dependent objects are relocated to
19287 : * the new schema.
19288 : */
19289 : void
19290 68 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
19291 : ObjectAddresses *objsMoved)
19292 : {
19293 : Relation classRel;
19294 :
19295 : Assert(objsMoved != NULL);
19296 :
19297 : /* OK, modify the pg_class row and pg_depend entry */
19298 68 : classRel = table_open(RelationRelationId, RowExclusiveLock);
19299 :
19300 68 : AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
19301 : nspOid, true, objsMoved);
19302 :
19303 : /* Fix the table's row type too, if it has one */
19304 64 : if (OidIsValid(rel->rd_rel->reltype))
19305 55 : AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
19306 : false, /* isImplicitArray */
19307 : false, /* ignoreDependent */
19308 : false, /* errorOnTableType */
19309 : objsMoved);
19310 :
19311 : /* Fix other dependent stuff */
19312 64 : AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
19313 64 : AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
19314 : objsMoved, AccessExclusiveLock);
19315 64 : AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
19316 : false, objsMoved);
19317 :
19318 64 : table_close(classRel, RowExclusiveLock);
19319 64 : }
19320 :
19321 : /*
19322 : * The guts of relocating a relation to another namespace: fix the pg_class
19323 : * entry, and the pg_depend entry if any. Caller must already have
19324 : * opened and write-locked pg_class.
19325 : */
19326 : void
19327 135 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
19328 : Oid oldNspOid, Oid newNspOid,
19329 : bool hasDependEntry,
19330 : ObjectAddresses *objsMoved)
19331 : {
19332 : HeapTuple classTup;
19333 : Form_pg_class classForm;
19334 : ObjectAddress thisobj;
19335 135 : bool already_done = false;
19336 :
19337 : /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19338 135 : classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
19339 135 : if (!HeapTupleIsValid(classTup))
19340 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
19341 135 : classForm = (Form_pg_class) GETSTRUCT(classTup);
19342 :
19343 : Assert(classForm->relnamespace == oldNspOid);
19344 :
19345 135 : thisobj.classId = RelationRelationId;
19346 135 : thisobj.objectId = relOid;
19347 135 : thisobj.objectSubId = 0;
19348 :
19349 : /*
19350 : * If the object has already been moved, don't move it again. If it's
19351 : * already in the right place, don't move it, but still fire the object
19352 : * access hook.
19353 : */
19354 135 : already_done = object_address_present(&thisobj, objsMoved);
19355 135 : if (!already_done && oldNspOid != newNspOid)
19356 103 : {
19357 107 : ItemPointerData otid = classTup->t_self;
19358 :
19359 : /* check for duplicate name (more friendly than unique-index failure) */
19360 107 : if (get_relname_relid(NameStr(classForm->relname),
19361 : newNspOid) != InvalidOid)
19362 4 : ereport(ERROR,
19363 : (errcode(ERRCODE_DUPLICATE_TABLE),
19364 : errmsg("relation \"%s\" already exists in schema \"%s\"",
19365 : NameStr(classForm->relname),
19366 : get_namespace_name(newNspOid))));
19367 :
19368 : /* classTup is a copy, so OK to scribble on */
19369 103 : classForm->relnamespace = newNspOid;
19370 :
19371 103 : CatalogTupleUpdate(classRel, &otid, classTup);
19372 103 : UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19373 :
19374 :
19375 : /* Update dependency on schema if caller said so */
19376 179 : if (hasDependEntry &&
19377 76 : changeDependencyFor(RelationRelationId,
19378 : relOid,
19379 : NamespaceRelationId,
19380 : oldNspOid,
19381 : newNspOid) != 1)
19382 0 : elog(ERROR, "could not change schema dependency for relation \"%s\"",
19383 : NameStr(classForm->relname));
19384 : }
19385 : else
19386 28 : UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19387 131 : if (!already_done)
19388 : {
19389 131 : add_exact_object_address(&thisobj, objsMoved);
19390 :
19391 131 : InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19392 : }
19393 :
19394 131 : heap_freetuple(classTup);
19395 131 : }
19396 :
19397 : /*
19398 : * Move all indexes for the specified relation to another namespace.
19399 : *
19400 : * Note: we assume adequate permission checking was done by the caller,
19401 : * and that the caller has a suitable lock on the owning relation.
19402 : */
19403 : static void
19404 64 : AlterIndexNamespaces(Relation classRel, Relation rel,
19405 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
19406 : {
19407 : List *indexList;
19408 : ListCell *l;
19409 :
19410 64 : indexList = RelationGetIndexList(rel);
19411 :
19412 94 : foreach(l, indexList)
19413 : {
19414 30 : Oid indexOid = lfirst_oid(l);
19415 : ObjectAddress thisobj;
19416 :
19417 30 : thisobj.classId = RelationRelationId;
19418 30 : thisobj.objectId = indexOid;
19419 30 : thisobj.objectSubId = 0;
19420 :
19421 : /*
19422 : * Note: currently, the index will not have its own dependency on the
19423 : * namespace, so we don't need to do changeDependencyFor(). There's no
19424 : * row type in pg_type, either.
19425 : *
19426 : * XXX this objsMoved test may be pointless -- surely we have a single
19427 : * dependency link from a relation to each index?
19428 : */
19429 30 : if (!object_address_present(&thisobj, objsMoved))
19430 : {
19431 30 : AlterRelationNamespaceInternal(classRel, indexOid,
19432 : oldNspOid, newNspOid,
19433 : false, objsMoved);
19434 30 : add_exact_object_address(&thisobj, objsMoved);
19435 : }
19436 : }
19437 :
19438 64 : list_free(indexList);
19439 64 : }
19440 :
19441 : /*
19442 : * Move all identity and SERIAL-column sequences of the specified relation to another
19443 : * namespace.
19444 : *
19445 : * Note: we assume adequate permission checking was done by the caller,
19446 : * and that the caller has a suitable lock on the owning relation.
19447 : */
19448 : static void
19449 64 : AlterSeqNamespaces(Relation classRel, Relation rel,
19450 : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
19451 : LOCKMODE lockmode)
19452 : {
19453 : Relation depRel;
19454 : SysScanDesc scan;
19455 : ScanKeyData key[2];
19456 : HeapTuple tup;
19457 :
19458 : /*
19459 : * SERIAL sequences are those having an auto dependency on one of the
19460 : * table's columns (we don't care *which* column, exactly).
19461 : */
19462 64 : depRel = table_open(DependRelationId, AccessShareLock);
19463 :
19464 64 : ScanKeyInit(&key[0],
19465 : Anum_pg_depend_refclassid,
19466 : BTEqualStrategyNumber, F_OIDEQ,
19467 : ObjectIdGetDatum(RelationRelationId));
19468 64 : ScanKeyInit(&key[1],
19469 : Anum_pg_depend_refobjid,
19470 : BTEqualStrategyNumber, F_OIDEQ,
19471 : ObjectIdGetDatum(RelationGetRelid(rel)));
19472 : /* we leave refobjsubid unspecified */
19473 :
19474 64 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
19475 : NULL, 2, key);
19476 :
19477 417 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
19478 : {
19479 353 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
19480 : Relation seqRel;
19481 :
19482 : /* skip dependencies other than auto dependencies on columns */
19483 353 : if (depForm->refobjsubid == 0 ||
19484 252 : depForm->classid != RelationRelationId ||
19485 28 : depForm->objsubid != 0 ||
19486 28 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
19487 325 : continue;
19488 :
19489 : /* Use relation_open just in case it's an index */
19490 28 : seqRel = relation_open(depForm->objid, lockmode);
19491 :
19492 : /* skip non-sequence relations */
19493 28 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
19494 : {
19495 : /* No need to keep the lock */
19496 0 : relation_close(seqRel, lockmode);
19497 0 : continue;
19498 : }
19499 :
19500 : /* Fix the pg_class and pg_depend entries */
19501 28 : AlterRelationNamespaceInternal(classRel, depForm->objid,
19502 : oldNspOid, newNspOid,
19503 : true, objsMoved);
19504 :
19505 : /*
19506 : * Sequences used to have entries in pg_type, but no longer do. If we
19507 : * ever re-instate that, we'll need to move the pg_type entry to the
19508 : * new namespace, too (using AlterTypeNamespaceInternal).
19509 : */
19510 : Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
19511 :
19512 : /* Now we can close it. Keep the lock till end of transaction. */
19513 28 : relation_close(seqRel, NoLock);
19514 : }
19515 :
19516 64 : systable_endscan(scan);
19517 :
19518 64 : relation_close(depRel, AccessShareLock);
19519 64 : }
19520 :
19521 :
19522 : /*
19523 : * This code supports
19524 : * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
19525 : *
19526 : * Because we only support this for TEMP tables, it's sufficient to remember
19527 : * the state in a backend-local data structure.
19528 : */
19529 :
19530 : /*
19531 : * Register a newly-created relation's ON COMMIT action.
19532 : */
19533 : void
19534 120 : register_on_commit_action(Oid relid, OnCommitAction action)
19535 : {
19536 : OnCommitItem *oc;
19537 : MemoryContext oldcxt;
19538 :
19539 : /*
19540 : * We needn't bother registering the relation unless there is an ON COMMIT
19541 : * action we need to take.
19542 : */
19543 120 : if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19544 16 : return;
19545 :
19546 104 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
19547 :
19548 104 : oc = palloc_object(OnCommitItem);
19549 104 : oc->relid = relid;
19550 104 : oc->oncommit = action;
19551 104 : oc->creating_subid = GetCurrentSubTransactionId();
19552 104 : oc->deleting_subid = InvalidSubTransactionId;
19553 :
19554 : /*
19555 : * We use lcons() here so that ON COMMIT actions are processed in reverse
19556 : * order of registration. That might not be essential but it seems
19557 : * reasonable.
19558 : */
19559 104 : on_commits = lcons(oc, on_commits);
19560 :
19561 104 : MemoryContextSwitchTo(oldcxt);
19562 : }
19563 :
19564 : /*
19565 : * Unregister any ON COMMIT action when a relation is deleted.
19566 : *
19567 : * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
19568 : */
19569 : void
19570 33529 : remove_on_commit_action(Oid relid)
19571 : {
19572 : ListCell *l;
19573 :
19574 33642 : foreach(l, on_commits)
19575 : {
19576 205 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19577 :
19578 205 : if (oc->relid == relid)
19579 : {
19580 92 : oc->deleting_subid = GetCurrentSubTransactionId();
19581 92 : break;
19582 : }
19583 : }
19584 33529 : }
19585 :
19586 : /*
19587 : * Perform ON COMMIT actions.
19588 : *
19589 : * This is invoked just before actually committing, since it's possible
19590 : * to encounter errors.
19591 : */
19592 : void
19593 615389 : PreCommit_on_commit_actions(void)
19594 : {
19595 : ListCell *l;
19596 615389 : List *oids_to_truncate = NIL;
19597 615389 : List *oids_to_drop = NIL;
19598 :
19599 615935 : foreach(l, on_commits)
19600 : {
19601 546 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19602 :
19603 : /* Ignore entry if already dropped in this xact */
19604 546 : if (oc->deleting_subid != InvalidSubTransactionId)
19605 49 : continue;
19606 :
19607 497 : switch (oc->oncommit)
19608 : {
19609 0 : case ONCOMMIT_NOOP:
19610 : case ONCOMMIT_PRESERVE_ROWS:
19611 : /* Do nothing (there shouldn't be such entries, actually) */
19612 0 : break;
19613 462 : case ONCOMMIT_DELETE_ROWS:
19614 :
19615 : /*
19616 : * If this transaction hasn't accessed any temporary
19617 : * relations, we can skip truncating ON COMMIT DELETE ROWS
19618 : * tables, as they must still be empty.
19619 : */
19620 462 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
19621 298 : oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
19622 462 : break;
19623 35 : case ONCOMMIT_DROP:
19624 35 : oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
19625 35 : break;
19626 : }
19627 : }
19628 :
19629 : /*
19630 : * Truncate relations before dropping so that all dependencies between
19631 : * relations are removed after they are worked on. Doing it like this
19632 : * might be a waste as it is possible that a relation being truncated will
19633 : * be dropped anyway due to its parent being dropped, but this makes the
19634 : * code more robust because of not having to re-check that the relation
19635 : * exists at truncation time.
19636 : */
19637 615389 : if (oids_to_truncate != NIL)
19638 254 : heap_truncate(oids_to_truncate);
19639 :
19640 615385 : if (oids_to_drop != NIL)
19641 : {
19642 31 : ObjectAddresses *targetObjects = new_object_addresses();
19643 :
19644 66 : foreach(l, oids_to_drop)
19645 : {
19646 : ObjectAddress object;
19647 :
19648 35 : object.classId = RelationRelationId;
19649 35 : object.objectId = lfirst_oid(l);
19650 35 : object.objectSubId = 0;
19651 :
19652 : Assert(!object_address_present(&object, targetObjects));
19653 :
19654 35 : add_exact_object_address(&object, targetObjects);
19655 : }
19656 :
19657 : /*
19658 : * Object deletion might involve toast table access (to clean up
19659 : * toasted catalog entries), so ensure we have a valid snapshot.
19660 : */
19661 31 : PushActiveSnapshot(GetTransactionSnapshot());
19662 :
19663 : /*
19664 : * Since this is an automatic drop, rather than one directly initiated
19665 : * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19666 : */
19667 31 : performMultipleDeletions(targetObjects, DROP_CASCADE,
19668 : PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
19669 :
19670 31 : PopActiveSnapshot();
19671 :
19672 : #ifdef USE_ASSERT_CHECKING
19673 :
19674 : /*
19675 : * Note that table deletion will call remove_on_commit_action, so the
19676 : * entry should get marked as deleted.
19677 : */
19678 : foreach(l, on_commits)
19679 : {
19680 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19681 :
19682 : if (oc->oncommit != ONCOMMIT_DROP)
19683 : continue;
19684 :
19685 : Assert(oc->deleting_subid != InvalidSubTransactionId);
19686 : }
19687 : #endif
19688 : }
19689 615385 : }
19690 :
19691 : /*
19692 : * Post-commit or post-abort cleanup for ON COMMIT management.
19693 : *
19694 : * All we do here is remove no-longer-needed OnCommitItem entries.
19695 : *
19696 : * During commit, remove entries that were deleted during this transaction;
19697 : * during abort, remove those created during this transaction.
19698 : */
19699 : void
19700 650536 : AtEOXact_on_commit_actions(bool isCommit)
19701 : {
19702 : ListCell *cur_item;
19703 :
19704 651106 : foreach(cur_item, on_commits)
19705 : {
19706 570 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19707 :
19708 642 : if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19709 72 : oc->creating_subid != InvalidSubTransactionId)
19710 : {
19711 : /* cur_item must be removed */
19712 104 : on_commits = foreach_delete_current(on_commits, cur_item);
19713 104 : pfree(oc);
19714 : }
19715 : else
19716 : {
19717 : /* cur_item must be preserved */
19718 466 : oc->creating_subid = InvalidSubTransactionId;
19719 466 : oc->deleting_subid = InvalidSubTransactionId;
19720 : }
19721 : }
19722 650536 : }
19723 :
19724 : /*
19725 : * Post-subcommit or post-subabort cleanup for ON COMMIT management.
19726 : *
19727 : * During subabort, we can immediately remove entries created during this
19728 : * subtransaction. During subcommit, just relabel entries marked during
19729 : * this subtransaction as being the parent's responsibility.
19730 : */
19731 : void
19732 11064 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
19733 : SubTransactionId parentSubid)
19734 : {
19735 : ListCell *cur_item;
19736 :
19737 11064 : foreach(cur_item, on_commits)
19738 : {
19739 0 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
19740 :
19741 0 : if (!isCommit && oc->creating_subid == mySubid)
19742 : {
19743 : /* cur_item must be removed */
19744 0 : on_commits = foreach_delete_current(on_commits, cur_item);
19745 0 : pfree(oc);
19746 : }
19747 : else
19748 : {
19749 : /* cur_item must be preserved */
19750 0 : if (oc->creating_subid == mySubid)
19751 0 : oc->creating_subid = parentSubid;
19752 0 : if (oc->deleting_subid == mySubid)
19753 0 : oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19754 : }
19755 : }
19756 11064 : }
19757 :
19758 : /*
19759 : * This is intended as a callback for RangeVarGetRelidExtended(). It allows
19760 : * the relation to be locked only if (1) it's a plain or partitioned table,
19761 : * materialized view, or TOAST table and (2) the current user is the owner (or
19762 : * the superuser) or has been granted MAINTAIN. This meets the
19763 : * permission-checking needs of CLUSTER, REINDEX TABLE, and REFRESH
19764 : * MATERIALIZED VIEW; we expose it here so that it can be used by all.
19765 : */
19766 : void
19767 717 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
19768 : Oid relId, Oid oldRelId, void *arg)
19769 : {
19770 : char relkind;
19771 : AclResult aclresult;
19772 :
19773 : /* Nothing to do if the relation was not found. */
19774 717 : if (!OidIsValid(relId))
19775 3 : return;
19776 :
19777 : /*
19778 : * If the relation does exist, check whether it's an index. But note that
19779 : * the relation might have been dropped between the time we did the name
19780 : * lookup and now. In that case, there's nothing to do.
19781 : */
19782 714 : relkind = get_rel_relkind(relId);
19783 714 : if (!relkind)
19784 0 : return;
19785 714 : if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19786 102 : relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19787 18 : ereport(ERROR,
19788 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19789 : errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19790 :
19791 : /* Check permissions */
19792 696 : aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
19793 696 : if (aclresult != ACLCHECK_OK)
19794 20 : aclcheck_error(aclresult,
19795 20 : get_relkind_objtype(get_rel_relkind(relId)),
19796 20 : relation->relname);
19797 : }
19798 :
19799 : /*
19800 : * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
19801 : */
19802 : static void
19803 1416 : RangeVarCallbackForTruncate(const RangeVar *relation,
19804 : Oid relId, Oid oldRelId, void *arg)
19805 : {
19806 : HeapTuple tuple;
19807 :
19808 : /* Nothing to do if the relation was not found. */
19809 1416 : if (!OidIsValid(relId))
19810 0 : return;
19811 :
19812 1416 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19813 1416 : if (!HeapTupleIsValid(tuple)) /* should not happen */
19814 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
19815 :
19816 1416 : truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
19817 1413 : truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
19818 :
19819 1393 : ReleaseSysCache(tuple);
19820 : }
19821 :
19822 : /*
19823 : * Callback for RangeVarGetRelidExtended(). Checks that the current user is
19824 : * the owner of the relation, or superuser.
19825 : */
19826 : void
19827 11952 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
19828 : Oid relId, Oid oldRelId, void *arg)
19829 : {
19830 : HeapTuple tuple;
19831 :
19832 : /* Nothing to do if the relation was not found. */
19833 11952 : if (!OidIsValid(relId))
19834 18 : return;
19835 :
19836 11934 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19837 11934 : if (!HeapTupleIsValid(tuple)) /* should not happen */
19838 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
19839 :
19840 11934 : if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
19841 16 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
19842 16 : relation->relname);
19843 :
19844 23776 : if (!allowSystemTableMods &&
19845 11858 : IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19846 1 : ereport(ERROR,
19847 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19848 : errmsg("permission denied: \"%s\" is a system catalog",
19849 : relation->relname)));
19850 :
19851 11917 : ReleaseSysCache(tuple);
19852 : }
19853 :
19854 : /*
19855 : * Common RangeVarGetRelid callback for rename, set schema, and alter table
19856 : * processing.
19857 : */
19858 : static void
19859 22918 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
19860 : void *arg)
19861 : {
19862 22918 : Node *stmt = (Node *) arg;
19863 : ObjectType reltype;
19864 : HeapTuple tuple;
19865 : Form_pg_class classform;
19866 : AclResult aclresult;
19867 : char relkind;
19868 :
19869 22918 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
19870 22918 : if (!HeapTupleIsValid(tuple))
19871 165 : return; /* concurrently dropped */
19872 22753 : classform = (Form_pg_class) GETSTRUCT(tuple);
19873 22753 : relkind = classform->relkind;
19874 :
19875 : /* Must own relation. */
19876 22753 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
19877 56 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
19878 :
19879 : /* No system table modifications unless explicitly allowed. */
19880 22697 : if (!allowSystemTableMods && IsSystemClass(relid, classform))
19881 18 : ereport(ERROR,
19882 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
19883 : errmsg("permission denied: \"%s\" is a system catalog",
19884 : rv->relname)));
19885 :
19886 : /*
19887 : * Extract the specified relation type from the statement parse tree.
19888 : *
19889 : * Also, for ALTER .. RENAME, check permissions: the user must (still)
19890 : * have CREATE rights on the containing namespace.
19891 : */
19892 22679 : if (IsA(stmt, RenameStmt))
19893 : {
19894 308 : aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
19895 : GetUserId(), ACL_CREATE);
19896 308 : if (aclresult != ACLCHECK_OK)
19897 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
19898 0 : get_namespace_name(classform->relnamespace));
19899 308 : reltype = ((RenameStmt *) stmt)->renameType;
19900 : }
19901 22371 : else if (IsA(stmt, AlterObjectSchemaStmt))
19902 74 : reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
19903 :
19904 22297 : else if (IsA(stmt, AlterTableStmt))
19905 22297 : reltype = ((AlterTableStmt *) stmt)->objtype;
19906 : else
19907 : {
19908 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
19909 : reltype = OBJECT_TABLE; /* placate compiler */
19910 : }
19911 :
19912 : /*
19913 : * For compatibility with prior releases, we allow ALTER TABLE to be used
19914 : * with most other types of relations (but not composite types). We allow
19915 : * similar flexibility for ALTER INDEX in the case of RENAME, but not
19916 : * otherwise. Otherwise, the user must select the correct form of the
19917 : * command for the relation at issue.
19918 : */
19919 22679 : if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
19920 0 : ereport(ERROR,
19921 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19922 : errmsg("\"%s\" is not a sequence", rv->relname)));
19923 :
19924 22679 : if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
19925 0 : ereport(ERROR,
19926 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19927 : errmsg("\"%s\" is not a view", rv->relname)));
19928 :
19929 22679 : if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
19930 0 : ereport(ERROR,
19931 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19932 : errmsg("\"%s\" is not a materialized view", rv->relname)));
19933 :
19934 22679 : if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
19935 0 : ereport(ERROR,
19936 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19937 : errmsg("\"%s\" is not a foreign table", rv->relname)));
19938 :
19939 22679 : if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
19940 0 : ereport(ERROR,
19941 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19942 : errmsg("\"%s\" is not a composite type", rv->relname)));
19943 :
19944 22679 : if (reltype == OBJECT_PROPGRAPH && relkind != RELKIND_PROPGRAPH)
19945 0 : ereport(ERROR,
19946 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19947 : errmsg("\"%s\" is not a property graph", rv->relname)));
19948 :
19949 22679 : if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
19950 : relkind != RELKIND_PARTITIONED_INDEX
19951 21 : && !IsA(stmt, RenameStmt))
19952 4 : ereport(ERROR,
19953 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19954 : errmsg("\"%s\" is not an index", rv->relname)));
19955 :
19956 : /*
19957 : * Don't allow ALTER TABLE on composite types. We want people to use ALTER
19958 : * TYPE for that.
19959 : */
19960 22675 : if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
19961 0 : ereport(ERROR,
19962 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19963 : errmsg("\"%s\" is a composite type", rv->relname),
19964 : /* translator: %s is an SQL ALTER command */
19965 : errhint("Use %s instead.",
19966 : "ALTER TYPE")));
19967 :
19968 : /*
19969 : * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
19970 : * to a different schema, such as indexes and TOAST tables.
19971 : */
19972 22675 : if (IsA(stmt, AlterObjectSchemaStmt))
19973 : {
19974 74 : if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
19975 0 : ereport(ERROR,
19976 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19977 : errmsg("cannot change schema of index \"%s\"",
19978 : rv->relname),
19979 : errhint("Change the schema of the table instead.")));
19980 74 : else if (relkind == RELKIND_COMPOSITE_TYPE)
19981 0 : ereport(ERROR,
19982 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19983 : errmsg("cannot change schema of composite type \"%s\"",
19984 : rv->relname),
19985 : /* translator: %s is an SQL ALTER command */
19986 : errhint("Use %s instead.",
19987 : "ALTER TYPE")));
19988 74 : else if (relkind == RELKIND_TOASTVALUE)
19989 0 : ereport(ERROR,
19990 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19991 : errmsg("cannot change schema of TOAST table \"%s\"",
19992 : rv->relname),
19993 : errhint("Change the schema of the table instead.")));
19994 : }
19995 :
19996 22675 : ReleaseSysCache(tuple);
19997 : }
19998 :
19999 : /*
20000 : * Transform any expressions present in the partition key
20001 : *
20002 : * Returns a transformed PartitionSpec.
20003 : */
20004 : static PartitionSpec *
20005 3606 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
20006 : {
20007 : PartitionSpec *newspec;
20008 : ParseState *pstate;
20009 : ParseNamespaceItem *nsitem;
20010 : ListCell *l;
20011 :
20012 3606 : newspec = makeNode(PartitionSpec);
20013 :
20014 3606 : newspec->strategy = partspec->strategy;
20015 3606 : newspec->partParams = NIL;
20016 3606 : newspec->location = partspec->location;
20017 :
20018 : /* Check valid number of columns for strategy */
20019 5229 : if (partspec->strategy == PARTITION_STRATEGY_LIST &&
20020 1623 : list_length(partspec->partParams) != 1)
20021 4 : ereport(ERROR,
20022 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20023 : errmsg("cannot use \"list\" partition strategy with more than one column")));
20024 :
20025 : /*
20026 : * Create a dummy ParseState and insert the target relation as its sole
20027 : * rangetable entry. We need a ParseState for transformExpr.
20028 : */
20029 3602 : pstate = make_parsestate(NULL);
20030 3602 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
20031 : NULL, false, true);
20032 3602 : addNSItemToQuery(pstate, nsitem, true, true, true);
20033 :
20034 : /* take care of any partition expressions */
20035 7506 : foreach(l, partspec->partParams)
20036 : {
20037 3920 : PartitionElem *pelem = lfirst_node(PartitionElem, l);
20038 :
20039 3920 : if (pelem->expr)
20040 : {
20041 : /* Copy, to avoid scribbling on the input */
20042 232 : pelem = copyObject(pelem);
20043 :
20044 : /* Now do parse transformation of the expression */
20045 232 : pelem->expr = transformExpr(pstate, pelem->expr,
20046 : EXPR_KIND_PARTITION_EXPRESSION);
20047 :
20048 : /* we have to fix its collations too */
20049 216 : assign_expr_collations(pstate, pelem->expr);
20050 : }
20051 :
20052 3904 : newspec->partParams = lappend(newspec->partParams, pelem);
20053 : }
20054 :
20055 3586 : return newspec;
20056 : }
20057 :
20058 : /*
20059 : * Compute per-partition-column information from a list of PartitionElems.
20060 : * Expressions in the PartitionElems must be parse-analyzed already.
20061 : */
20062 : static void
20063 3586 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
20064 : List **partexprs, Oid *partopclass, Oid *partcollation,
20065 : PartitionStrategy strategy)
20066 : {
20067 : int attn;
20068 : ListCell *lc;
20069 : Oid am_oid;
20070 :
20071 3586 : attn = 0;
20072 7402 : foreach(lc, partParams)
20073 : {
20074 3904 : PartitionElem *pelem = lfirst_node(PartitionElem, lc);
20075 : Oid atttype;
20076 : Oid attcollation;
20077 :
20078 3904 : if (pelem->name != NULL)
20079 : {
20080 : /* Simple attribute reference */
20081 : HeapTuple atttuple;
20082 : Form_pg_attribute attform;
20083 :
20084 3688 : atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
20085 3688 : pelem->name);
20086 3688 : if (!HeapTupleIsValid(atttuple))
20087 8 : ereport(ERROR,
20088 : (errcode(ERRCODE_UNDEFINED_COLUMN),
20089 : errmsg("column \"%s\" named in partition key does not exist",
20090 : pelem->name),
20091 : parser_errposition(pstate, pelem->location)));
20092 3680 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
20093 :
20094 3680 : if (attform->attnum <= 0)
20095 4 : ereport(ERROR,
20096 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20097 : errmsg("cannot use system column \"%s\" in partition key",
20098 : pelem->name),
20099 : parser_errposition(pstate, pelem->location)));
20100 :
20101 : /*
20102 : * Stored generated columns cannot work: They are computed after
20103 : * BEFORE triggers, but partition routing is done before all
20104 : * triggers. Maybe virtual generated columns could be made to
20105 : * work, but then they would need to be handled as an expression
20106 : * below.
20107 : */
20108 3676 : if (attform->attgenerated)
20109 8 : ereport(ERROR,
20110 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20111 : errmsg("cannot use generated column in partition key"),
20112 : errdetail("Column \"%s\" is a generated column.",
20113 : pelem->name),
20114 : parser_errposition(pstate, pelem->location)));
20115 :
20116 3668 : partattrs[attn] = attform->attnum;
20117 3668 : atttype = attform->atttypid;
20118 3668 : attcollation = attform->attcollation;
20119 3668 : ReleaseSysCache(atttuple);
20120 : }
20121 : else
20122 : {
20123 : /* Expression */
20124 216 : Node *expr = pelem->expr;
20125 : char partattname[16];
20126 216 : Bitmapset *expr_attrs = NULL;
20127 : int i;
20128 :
20129 : Assert(expr != NULL);
20130 216 : atttype = exprType(expr);
20131 216 : attcollation = exprCollation(expr);
20132 :
20133 : /*
20134 : * The expression must be of a storable type (e.g., not RECORD).
20135 : * The test is the same as for whether a table column is of a safe
20136 : * type (which is why we needn't check for the non-expression
20137 : * case).
20138 : */
20139 216 : snprintf(partattname, sizeof(partattname), "%d", attn + 1);
20140 216 : CheckAttributeType(partattname,
20141 : atttype, attcollation,
20142 : NIL, CHKATYPE_IS_PARTKEY);
20143 :
20144 : /*
20145 : * Strip any top-level COLLATE clause. This ensures that we treat
20146 : * "x COLLATE y" and "(x COLLATE y)" alike.
20147 : */
20148 208 : while (IsA(expr, CollateExpr))
20149 0 : expr = (Node *) ((CollateExpr *) expr)->arg;
20150 :
20151 : /*
20152 : * Examine all the columns in the partition key expression. When
20153 : * the whole-row reference is present, examine all the columns of
20154 : * the partitioned table.
20155 : */
20156 208 : pull_varattnos(expr, 1, &expr_attrs);
20157 208 : if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, expr_attrs))
20158 : {
20159 40 : expr_attrs = bms_add_range(expr_attrs,
20160 : 1 - FirstLowInvalidHeapAttributeNumber,
20161 20 : RelationGetNumberOfAttributes(rel) - FirstLowInvalidHeapAttributeNumber);
20162 20 : expr_attrs = bms_del_member(expr_attrs, 0 - FirstLowInvalidHeapAttributeNumber);
20163 : }
20164 :
20165 208 : i = -1;
20166 457 : while ((i = bms_next_member(expr_attrs, i)) >= 0)
20167 : {
20168 281 : AttrNumber attno = i + FirstLowInvalidHeapAttributeNumber;
20169 :
20170 : Assert(attno != 0);
20171 :
20172 : /*
20173 : * Cannot allow system column references, since that would
20174 : * make partition routing impossible: their values won't be
20175 : * known yet when we need to do that.
20176 : */
20177 281 : if (attno < 0)
20178 0 : ereport(ERROR,
20179 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20180 : errmsg("partition key expressions cannot contain system column references")));
20181 :
20182 : /*
20183 : * Stored generated columns cannot work: They are computed
20184 : * after BEFORE triggers, but partition routing is done before
20185 : * all triggers. Virtual generated columns could probably
20186 : * work, but it would require more work elsewhere (for example
20187 : * SET EXPRESSION would need to check whether the column is
20188 : * used in partition keys). Seems safer to prohibit for now.
20189 : */
20190 281 : if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
20191 32 : ereport(ERROR,
20192 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20193 : errmsg("cannot use generated column in partition key"),
20194 : errdetail("Column \"%s\" is a generated column.",
20195 : get_attname(RelationGetRelid(rel), attno, false)),
20196 : parser_errposition(pstate, pelem->location)));
20197 : }
20198 :
20199 176 : if (IsA(expr, Var) &&
20200 8 : ((Var *) expr)->varattno > 0)
20201 : {
20202 :
20203 : /*
20204 : * User wrote "(column)" or "(column COLLATE something)".
20205 : * Treat it like simple attribute anyway.
20206 : */
20207 4 : partattrs[attn] = ((Var *) expr)->varattno;
20208 : }
20209 : else
20210 : {
20211 172 : partattrs[attn] = 0; /* marks the column as expression */
20212 172 : *partexprs = lappend(*partexprs, expr);
20213 :
20214 : /*
20215 : * transformPartitionSpec() should have already rejected
20216 : * subqueries, aggregates, window functions, and SRFs, based
20217 : * on the EXPR_KIND_ for partition expressions.
20218 : */
20219 :
20220 : /*
20221 : * Preprocess the expression before checking for mutability.
20222 : * This is essential for the reasons described in
20223 : * contain_mutable_functions_after_planning. However, we call
20224 : * expression_planner for ourselves rather than using that
20225 : * function, because if constant-folding reduces the
20226 : * expression to a constant, we'd like to know that so we can
20227 : * complain below.
20228 : *
20229 : * Like contain_mutable_functions_after_planning, assume that
20230 : * expression_planner won't scribble on its input, so this
20231 : * won't affect the partexprs entry we saved above.
20232 : */
20233 172 : expr = (Node *) expression_planner((Expr *) expr);
20234 :
20235 : /*
20236 : * Partition expressions cannot contain mutable functions,
20237 : * because a given row must always map to the same partition
20238 : * as long as there is no change in the partition boundary
20239 : * structure.
20240 : */
20241 172 : if (contain_mutable_functions(expr))
20242 4 : ereport(ERROR,
20243 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20244 : errmsg("functions in partition key expression must be marked IMMUTABLE")));
20245 :
20246 : /*
20247 : * While it is not exactly *wrong* for a partition expression
20248 : * to be a constant, it seems better to reject such keys.
20249 : */
20250 168 : if (IsA(expr, Const))
20251 8 : ereport(ERROR,
20252 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20253 : errmsg("cannot use constant expression as partition key")));
20254 : }
20255 : }
20256 :
20257 : /*
20258 : * Apply collation override if any
20259 : */
20260 3832 : if (pelem->collation)
20261 36 : attcollation = get_collation_oid(pelem->collation, false);
20262 :
20263 : /*
20264 : * Check we have a collation iff it's a collatable type. The only
20265 : * expected failures here are (1) COLLATE applied to a noncollatable
20266 : * type, or (2) partition expression had an unresolved collation. But
20267 : * we might as well code this to be a complete consistency check.
20268 : */
20269 3832 : if (type_is_collatable(atttype))
20270 : {
20271 436 : if (!OidIsValid(attcollation))
20272 0 : ereport(ERROR,
20273 : (errcode(ERRCODE_INDETERMINATE_COLLATION),
20274 : errmsg("could not determine which collation to use for partition expression"),
20275 : errhint("Use the COLLATE clause to set the collation explicitly.")));
20276 : }
20277 : else
20278 : {
20279 3396 : if (OidIsValid(attcollation))
20280 0 : ereport(ERROR,
20281 : (errcode(ERRCODE_DATATYPE_MISMATCH),
20282 : errmsg("collations are not supported by type %s",
20283 : format_type_be(atttype))));
20284 : }
20285 :
20286 3832 : partcollation[attn] = attcollation;
20287 :
20288 : /*
20289 : * Identify the appropriate operator class. For list and range
20290 : * partitioning, we use a btree operator class; hash partitioning uses
20291 : * a hash operator class.
20292 : */
20293 3832 : if (strategy == PARTITION_STRATEGY_HASH)
20294 215 : am_oid = HASH_AM_OID;
20295 : else
20296 3617 : am_oid = BTREE_AM_OID;
20297 :
20298 3832 : if (!pelem->opclass)
20299 : {
20300 3740 : partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
20301 :
20302 3740 : if (!OidIsValid(partopclass[attn]))
20303 : {
20304 8 : if (strategy == PARTITION_STRATEGY_HASH)
20305 0 : ereport(ERROR,
20306 : (errcode(ERRCODE_UNDEFINED_OBJECT),
20307 : errmsg("data type %s has no default operator class for access method \"%s\"",
20308 : format_type_be(atttype), "hash"),
20309 : errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
20310 : else
20311 8 : ereport(ERROR,
20312 : (errcode(ERRCODE_UNDEFINED_OBJECT),
20313 : errmsg("data type %s has no default operator class for access method \"%s\"",
20314 : format_type_be(atttype), "btree"),
20315 : errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
20316 : }
20317 : }
20318 : else
20319 92 : partopclass[attn] = ResolveOpClass(pelem->opclass,
20320 : atttype,
20321 : am_oid == HASH_AM_OID ? "hash" : "btree",
20322 : am_oid);
20323 :
20324 3816 : attn++;
20325 : }
20326 3498 : }
20327 :
20328 : /*
20329 : * PartConstraintImpliedByRelConstraint
20330 : * Do scanrel's existing constraints imply the partition constraint?
20331 : *
20332 : * "Existing constraints" include its check constraints and column-level
20333 : * not-null constraints. partConstraint describes the partition constraint,
20334 : * in implicit-AND form.
20335 : */
20336 : bool
20337 2062 : PartConstraintImpliedByRelConstraint(Relation scanrel,
20338 : List *partConstraint)
20339 : {
20340 2062 : List *existConstraint = NIL;
20341 2062 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20342 : int i;
20343 :
20344 2062 : if (constr && constr->has_not_null)
20345 : {
20346 544 : int natts = scanrel->rd_att->natts;
20347 :
20348 1870 : for (i = 1; i <= natts; i++)
20349 : {
20350 1326 : CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20351 :
20352 : /* invalid not-null constraint must be ignored here */
20353 1326 : if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20354 : {
20355 747 : Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
20356 747 : NullTest *ntest = makeNode(NullTest);
20357 :
20358 747 : ntest->arg = (Expr *) makeVar(1,
20359 : i,
20360 : wholeatt->atttypid,
20361 : wholeatt->atttypmod,
20362 : wholeatt->attcollation,
20363 : 0);
20364 747 : ntest->nulltesttype = IS_NOT_NULL;
20365 :
20366 : /*
20367 : * argisrow=false is correct even for a composite column,
20368 : * because attnotnull does not represent a SQL-spec IS NOT
20369 : * NULL test in such a case, just IS DISTINCT FROM NULL.
20370 : */
20371 747 : ntest->argisrow = false;
20372 747 : ntest->location = -1;
20373 747 : existConstraint = lappend(existConstraint, ntest);
20374 : }
20375 : }
20376 : }
20377 :
20378 2062 : return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20379 : }
20380 :
20381 : /*
20382 : * ConstraintImpliedByRelConstraint
20383 : * Do scanrel's existing constraints imply the given constraint?
20384 : *
20385 : * testConstraint is the constraint to validate. provenConstraint is a
20386 : * caller-provided list of conditions which this function may assume
20387 : * to be true. Both provenConstraint and testConstraint must be in
20388 : * implicit-AND form, must only contain immutable clauses, and must
20389 : * contain only Vars with varno = 1.
20390 : */
20391 : bool
20392 2878 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
20393 : {
20394 2878 : List *existConstraint = list_copy(provenConstraint);
20395 2878 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20396 : int num_check,
20397 : i;
20398 :
20399 2878 : num_check = (constr != NULL) ? constr->num_check : 0;
20400 3214 : for (i = 0; i < num_check; i++)
20401 : {
20402 : Node *cexpr;
20403 :
20404 : /*
20405 : * If this constraint hasn't been fully validated yet, we must ignore
20406 : * it here.
20407 : */
20408 336 : if (!constr->check[i].ccvalid)
20409 12 : continue;
20410 :
20411 : /*
20412 : * NOT ENFORCED constraints are always marked as invalid, which should
20413 : * have been ignored.
20414 : */
20415 : Assert(constr->check[i].ccenforced);
20416 :
20417 324 : cexpr = stringToNode(constr->check[i].ccbin);
20418 :
20419 : /*
20420 : * Run each expression through const-simplification and
20421 : * canonicalization. It is necessary, because we will be comparing it
20422 : * to similarly-processed partition constraint expressions, and may
20423 : * fail to detect valid matches without this.
20424 : */
20425 324 : cexpr = eval_const_expressions(NULL, cexpr);
20426 324 : cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
20427 :
20428 324 : existConstraint = list_concat(existConstraint,
20429 324 : make_ands_implicit((Expr *) cexpr));
20430 : }
20431 :
20432 : /*
20433 : * Try to make the proof. Since we are comparing CHECK constraints, we
20434 : * need to use weak implication, i.e., we assume existConstraint is
20435 : * not-false and try to prove the same for testConstraint.
20436 : *
20437 : * Note that predicate_implied_by assumes its first argument is known
20438 : * immutable. That should always be true for both NOT NULL and partition
20439 : * constraints, so we don't test it here.
20440 : */
20441 2878 : return predicate_implied_by(testConstraint, existConstraint, true);
20442 : }
20443 :
20444 : /*
20445 : * QueuePartitionConstraintValidation
20446 : *
20447 : * Add an entry to wqueue to have the given partition constraint validated by
20448 : * Phase 3, for the given relation, and all its children.
20449 : *
20450 : * We first verify whether the given constraint is implied by pre-existing
20451 : * relation constraints; if it is, there's no need to scan the table to
20452 : * validate, so don't queue in that case.
20453 : */
20454 : static void
20455 1737 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
20456 : List *partConstraint,
20457 : bool validate_default)
20458 : {
20459 : /*
20460 : * Based on the table's existing constraints, determine whether or not we
20461 : * may skip scanning the table.
20462 : */
20463 1737 : if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
20464 : {
20465 55 : if (!validate_default)
20466 41 : ereport(DEBUG1,
20467 : (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
20468 : RelationGetRelationName(scanrel))));
20469 : else
20470 14 : ereport(DEBUG1,
20471 : (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
20472 : RelationGetRelationName(scanrel))));
20473 55 : return;
20474 : }
20475 :
20476 : /*
20477 : * Constraints proved insufficient. For plain relations, queue a
20478 : * validation item now; for partitioned tables, recurse to process each
20479 : * partition.
20480 : */
20481 1682 : if (scanrel->rd_rel->relkind == RELKIND_RELATION)
20482 : {
20483 : AlteredTableInfo *tab;
20484 :
20485 : /* Grab a work queue entry. */
20486 1407 : tab = ATGetQueueEntry(wqueue, scanrel);
20487 : Assert(tab->partition_constraint == NULL);
20488 1407 : tab->partition_constraint = (Expr *) linitial(partConstraint);
20489 1407 : tab->validate_default = validate_default;
20490 : }
20491 275 : else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20492 : {
20493 244 : PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
20494 : int i;
20495 :
20496 524 : for (i = 0; i < partdesc->nparts; i++)
20497 : {
20498 : Relation part_rel;
20499 : List *thisPartConstraint;
20500 :
20501 : /*
20502 : * This is the minimum lock we need to prevent deadlocks.
20503 : */
20504 280 : part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
20505 :
20506 : /*
20507 : * Adjust the constraint for scanrel so that it matches this
20508 : * partition's attribute numbers.
20509 : */
20510 : thisPartConstraint =
20511 280 : map_partition_varattnos(partConstraint, 1,
20512 : part_rel, scanrel);
20513 :
20514 280 : QueuePartitionConstraintValidation(wqueue, part_rel,
20515 : thisPartConstraint,
20516 : validate_default);
20517 280 : table_close(part_rel, NoLock); /* keep lock till commit */
20518 : }
20519 : }
20520 : }
20521 :
20522 : /*
20523 : * attachPartitionTable: attach a new partition to the partitioned table
20524 : *
20525 : * wqueue: the ALTER TABLE work queue; can be NULL when not running as part
20526 : * of an ALTER TABLE sequence.
20527 : * rel: partitioned relation;
20528 : * attachrel: relation of attached partition;
20529 : * bound: bounds of attached relation.
20530 : */
20531 : static void
20532 1932 : attachPartitionTable(List **wqueue, Relation rel, Relation attachrel, PartitionBoundSpec *bound)
20533 : {
20534 : /*
20535 : * Create an inheritance; the relevant checks are performed inside the
20536 : * function.
20537 : */
20538 1932 : CreateInheritance(attachrel, rel, true);
20539 :
20540 : /* Update the pg_class entry. */
20541 1860 : StorePartitionBound(attachrel, rel, bound);
20542 :
20543 : /* Ensure there exists a correct set of indexes in the partition. */
20544 1860 : AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
20545 :
20546 : /* and triggers */
20547 1840 : CloneRowTriggersToPartition(rel, attachrel);
20548 :
20549 : /*
20550 : * Clone foreign key constraints. Callee is responsible for setting up
20551 : * for phase 3 constraint verification.
20552 : */
20553 1836 : CloneForeignKeyConstraints(wqueue, rel, attachrel);
20554 1824 : }
20555 :
20556 : /*
20557 : * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
20558 : *
20559 : * Return the address of the newly attached partition.
20560 : */
20561 : static ObjectAddress
20562 1608 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
20563 : AlterTableUtilityContext *context)
20564 : {
20565 : Relation attachrel,
20566 : catalog;
20567 : List *attachrel_children;
20568 : List *partConstraint;
20569 : SysScanDesc scan;
20570 : ScanKeyData skey;
20571 : AttrNumber attno;
20572 : int natts;
20573 : TupleDesc tupleDesc;
20574 : ObjectAddress address;
20575 : const char *trigger_name;
20576 : Oid defaultPartOid;
20577 : List *partBoundConstraint;
20578 1608 : List *exceptpuboids = NIL;
20579 1608 : ParseState *pstate = make_parsestate(NULL);
20580 :
20581 1608 : pstate->p_sourcetext = context->queryString;
20582 :
20583 : /*
20584 : * We must lock the default partition if one exists, because attaching a
20585 : * new partition will change its partition constraint.
20586 : */
20587 : defaultPartOid =
20588 1608 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
20589 1608 : if (OidIsValid(defaultPartOid))
20590 117 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
20591 :
20592 1608 : attachrel = table_openrv(cmd->name, AccessExclusiveLock);
20593 :
20594 : /*
20595 : * XXX I think it'd be a good idea to grab locks on all tables referenced
20596 : * by FKs at this point also.
20597 : */
20598 :
20599 : /*
20600 : * Must be owner of both parent and source table -- parent was checked by
20601 : * ATSimplePermissions call in ATPrepCmd
20602 : */
20603 1604 : ATSimplePermissions(AT_AttachPartition, attachrel,
20604 : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
20605 :
20606 : /* A partition can only have one parent */
20607 1600 : if (attachrel->rd_rel->relispartition)
20608 4 : ereport(ERROR,
20609 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20610 : errmsg("\"%s\" is already a partition",
20611 : RelationGetRelationName(attachrel))));
20612 :
20613 1596 : if (OidIsValid(attachrel->rd_rel->reloftype))
20614 4 : ereport(ERROR,
20615 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20616 : errmsg("cannot attach a typed table as partition")));
20617 :
20618 : /*
20619 : * Disallow attaching a partition if the table is referenced in a
20620 : * publication EXCEPT clause. Changing the partition hierarchy could alter
20621 : * the effective publication membership.
20622 : */
20623 1592 : exceptpuboids = GetRelationExcludedPublications(RelationGetRelid(attachrel));
20624 1592 : if (exceptpuboids != NIL)
20625 : {
20626 4 : bool first = true;
20627 : StringInfoData pubnames;
20628 :
20629 4 : initStringInfo(&pubnames);
20630 :
20631 12 : foreach_oid(pubid, exceptpuboids)
20632 : {
20633 4 : char *pubname = get_publication_name(pubid, false);
20634 :
20635 4 : if (!first)
20636 : {
20637 : /*
20638 : * translator: This is a separator in a list of publication
20639 : * names.
20640 : */
20641 0 : appendStringInfoString(&pubnames, _(", "));
20642 : }
20643 :
20644 4 : first = false;
20645 :
20646 4 : appendStringInfo(&pubnames, _("\"%s\""), pubname);
20647 : }
20648 :
20649 4 : ereport(ERROR,
20650 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20651 : errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause",
20652 : "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause",
20653 : list_length(exceptpuboids),
20654 : RelationGetRelationName(attachrel),
20655 : pubnames.data),
20656 : errdetail("The publication EXCEPT clause cannot contain tables that are partitions."),
20657 : errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES."));
20658 : }
20659 :
20660 1588 : list_free(exceptpuboids);
20661 :
20662 : /*
20663 : * Table being attached should not already be part of inheritance; either
20664 : * as a child table...
20665 : */
20666 1588 : catalog = table_open(InheritsRelationId, AccessShareLock);
20667 1588 : ScanKeyInit(&skey,
20668 : Anum_pg_inherits_inhrelid,
20669 : BTEqualStrategyNumber, F_OIDEQ,
20670 : ObjectIdGetDatum(RelationGetRelid(attachrel)));
20671 1588 : scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
20672 : NULL, 1, &skey);
20673 1588 : if (HeapTupleIsValid(systable_getnext(scan)))
20674 4 : ereport(ERROR,
20675 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20676 : errmsg("cannot attach inheritance child as partition")));
20677 1584 : systable_endscan(scan);
20678 :
20679 : /* ...or as a parent table (except the case when it is partitioned) */
20680 1584 : ScanKeyInit(&skey,
20681 : Anum_pg_inherits_inhparent,
20682 : BTEqualStrategyNumber, F_OIDEQ,
20683 : ObjectIdGetDatum(RelationGetRelid(attachrel)));
20684 1584 : scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
20685 : 1, &skey);
20686 1584 : if (HeapTupleIsValid(systable_getnext(scan)) &&
20687 184 : attachrel->rd_rel->relkind == RELKIND_RELATION)
20688 4 : ereport(ERROR,
20689 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20690 : errmsg("cannot attach inheritance parent as partition")));
20691 1580 : systable_endscan(scan);
20692 1580 : table_close(catalog, AccessShareLock);
20693 :
20694 : /*
20695 : * Prevent circularity by seeing if rel is a partition of attachrel. (In
20696 : * particular, this disallows making a rel a partition of itself.)
20697 : *
20698 : * We do that by checking if rel is a member of the list of attachrel's
20699 : * partitions provided the latter is partitioned at all. We want to avoid
20700 : * having to construct this list again, so we request the strongest lock
20701 : * on all partitions. We need the strongest lock, because we may decide
20702 : * to scan them if we find out that the table being attached (or its leaf
20703 : * partitions) may contain rows that violate the partition constraint. If
20704 : * the table has a constraint that would prevent such rows, which by
20705 : * definition is present in all the partitions, we need not scan the
20706 : * table, nor its partitions. But we cannot risk a deadlock by taking a
20707 : * weaker lock now and the stronger one only when needed.
20708 : */
20709 1580 : attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
20710 : AccessExclusiveLock, NULL);
20711 1580 : if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
20712 8 : ereport(ERROR,
20713 : (errcode(ERRCODE_DUPLICATE_TABLE),
20714 : errmsg("circular inheritance not allowed"),
20715 : errdetail("\"%s\" is already a child of \"%s\".",
20716 : RelationGetRelationName(rel),
20717 : RelationGetRelationName(attachrel))));
20718 :
20719 : /* If the parent is permanent, so must be all of its partitions. */
20720 1572 : if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
20721 1544 : attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
20722 4 : ereport(ERROR,
20723 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20724 : errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
20725 : RelationGetRelationName(rel))));
20726 :
20727 : /* Temp parent cannot have a partition that is itself not a temp */
20728 1568 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
20729 28 : attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
20730 12 : ereport(ERROR,
20731 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20732 : errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
20733 : RelationGetRelationName(rel))));
20734 :
20735 : /* If the parent is temp, it must belong to this session */
20736 1556 : if (RELATION_IS_OTHER_TEMP(rel))
20737 0 : ereport(ERROR,
20738 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20739 : errmsg("cannot attach as partition of temporary relation of another session")));
20740 :
20741 : /* Ditto for the partition */
20742 1556 : if (RELATION_IS_OTHER_TEMP(attachrel))
20743 0 : ereport(ERROR,
20744 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20745 : errmsg("cannot attach temporary relation of another session as partition")));
20746 :
20747 : /*
20748 : * Check if attachrel has any identity columns or any columns that aren't
20749 : * in the parent.
20750 : */
20751 1556 : tupleDesc = RelationGetDescr(attachrel);
20752 1556 : natts = tupleDesc->natts;
20753 5378 : for (attno = 1; attno <= natts; attno++)
20754 : {
20755 3850 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
20756 3850 : char *attributeName = NameStr(attribute->attname);
20757 :
20758 : /* Ignore dropped */
20759 3850 : if (attribute->attisdropped)
20760 408 : continue;
20761 :
20762 3442 : if (attribute->attidentity)
20763 16 : ereport(ERROR,
20764 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
20765 : errmsg("table \"%s\" being attached contains an identity column \"%s\"",
20766 : RelationGetRelationName(attachrel), attributeName),
20767 : errdetail("The new partition may not contain an identity column."));
20768 :
20769 : /* Try to find the column in parent (matching on column name) */
20770 3426 : if (!SearchSysCacheExists2(ATTNAME,
20771 : ObjectIdGetDatum(RelationGetRelid(rel)),
20772 : CStringGetDatum(attributeName)))
20773 12 : ereport(ERROR,
20774 : (errcode(ERRCODE_DATATYPE_MISMATCH),
20775 : errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
20776 : RelationGetRelationName(attachrel), attributeName,
20777 : RelationGetRelationName(rel)),
20778 : errdetail("The new partition may contain only the columns present in parent.")));
20779 : }
20780 :
20781 : /*
20782 : * If child_rel has row-level triggers with transition tables, we
20783 : * currently don't allow it to become a partition. See also prohibitions
20784 : * in ATExecAddInherit() and CreateTrigger().
20785 : */
20786 1528 : trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
20787 1528 : if (trigger_name != NULL)
20788 4 : ereport(ERROR,
20789 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
20790 : errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
20791 : trigger_name, RelationGetRelationName(attachrel)),
20792 : errdetail("ROW triggers with transition tables are not supported on partitions.")));
20793 :
20794 : /*
20795 : * Check that the new partition's bound is valid and does not overlap any
20796 : * of existing partitions of the parent - note that it does not return on
20797 : * error.
20798 : */
20799 1524 : check_new_partition_bound(RelationGetRelationName(attachrel), rel,
20800 : cmd->bound, pstate);
20801 :
20802 1500 : attachPartitionTable(wqueue, rel, attachrel, cmd->bound);
20803 :
20804 : /*
20805 : * Generate a partition constraint from the partition bound specification.
20806 : * If the parent itself is a partition, make sure to include its
20807 : * constraint as well.
20808 : */
20809 1392 : partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
20810 :
20811 : /*
20812 : * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
20813 : * since it's needed later to construct the constraint expression for
20814 : * validating against the default partition, if any.
20815 : */
20816 1392 : partConstraint = list_concat_copy(partBoundConstraint,
20817 1392 : RelationGetPartitionQual(rel));
20818 :
20819 : /* Skip validation if there are no constraints to validate. */
20820 1392 : if (partConstraint)
20821 : {
20822 : /*
20823 : * Run the partition quals through const-simplification similar to
20824 : * check constraints. We skip canonicalize_qual, though, because
20825 : * partition quals should be in canonical form already.
20826 : */
20827 : partConstraint =
20828 1364 : (List *) eval_const_expressions(NULL,
20829 : (Node *) partConstraint);
20830 :
20831 : /* XXX this sure looks wrong */
20832 1364 : partConstraint = list_make1(make_ands_explicit(partConstraint));
20833 :
20834 : /*
20835 : * Adjust the generated constraint to match this partition's attribute
20836 : * numbers.
20837 : */
20838 1364 : partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
20839 : rel);
20840 :
20841 : /* Validate partition constraints against the table being attached. */
20842 1364 : QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
20843 : false);
20844 : }
20845 :
20846 : /*
20847 : * If we're attaching a partition other than the default partition and a
20848 : * default one exists, then that partition's partition constraint changes,
20849 : * so add an entry to the work queue to validate it, too. (We must not do
20850 : * this when the partition being attached is the default one; we already
20851 : * did it above!)
20852 : */
20853 1392 : if (OidIsValid(defaultPartOid))
20854 : {
20855 : Relation defaultrel;
20856 : List *defPartConstraint;
20857 :
20858 : Assert(!cmd->bound->is_default);
20859 :
20860 : /* we already hold a lock on the default partition */
20861 93 : defaultrel = table_open(defaultPartOid, NoLock);
20862 : defPartConstraint =
20863 93 : get_proposed_default_constraint(partBoundConstraint);
20864 :
20865 : /*
20866 : * Map the Vars in the constraint expression from rel's attnos to
20867 : * defaultrel's.
20868 : */
20869 : defPartConstraint =
20870 93 : map_partition_varattnos(defPartConstraint,
20871 : 1, defaultrel, rel);
20872 93 : QueuePartitionConstraintValidation(wqueue, defaultrel,
20873 : defPartConstraint, true);
20874 :
20875 : /* keep our lock until commit. */
20876 93 : table_close(defaultrel, NoLock);
20877 : }
20878 :
20879 1392 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
20880 :
20881 : /*
20882 : * If the partition we just attached is partitioned itself, invalidate
20883 : * relcache for all descendent partitions too to ensure that their
20884 : * rd_partcheck expression trees are rebuilt; partitions already locked at
20885 : * the beginning of this function.
20886 : */
20887 1392 : if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20888 : {
20889 : ListCell *l;
20890 :
20891 711 : foreach(l, attachrel_children)
20892 : {
20893 482 : CacheInvalidateRelcacheByRelid(lfirst_oid(l));
20894 : }
20895 : }
20896 :
20897 : /* keep our lock until commit */
20898 1392 : table_close(attachrel, NoLock);
20899 :
20900 1392 : return address;
20901 : }
20902 :
20903 : /*
20904 : * AttachPartitionEnsureIndexes
20905 : * subroutine for ATExecAttachPartition to create/match indexes
20906 : *
20907 : * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
20908 : * PARTITION: every partition must have an index attached to each index on the
20909 : * partitioned table.
20910 : */
20911 : static void
20912 1860 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
20913 : {
20914 : List *idxes;
20915 : List *attachRelIdxs;
20916 : Relation *attachrelIdxRels;
20917 : IndexInfo **attachInfos;
20918 : ListCell *cell;
20919 : MemoryContext cxt;
20920 : MemoryContext oldcxt;
20921 :
20922 1860 : cxt = AllocSetContextCreate(CurrentMemoryContext,
20923 : "AttachPartitionEnsureIndexes",
20924 : ALLOCSET_DEFAULT_SIZES);
20925 1860 : oldcxt = MemoryContextSwitchTo(cxt);
20926 :
20927 1860 : idxes = RelationGetIndexList(rel);
20928 1860 : attachRelIdxs = RelationGetIndexList(attachrel);
20929 1860 : attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
20930 1860 : attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
20931 :
20932 : /* Build arrays of all existing indexes and their IndexInfos */
20933 3989 : foreach_oid(cldIdxId, attachRelIdxs)
20934 : {
20935 269 : int i = foreach_current_index(cldIdxId);
20936 :
20937 269 : attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
20938 269 : attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
20939 : }
20940 :
20941 : /*
20942 : * If we're attaching a foreign table, we must fail if any of the indexes
20943 : * is a constraint index; otherwise, there's nothing to do here. Do this
20944 : * before starting work, to avoid wasting the effort of building a few
20945 : * non-unique indexes before coming across a unique one.
20946 : */
20947 1860 : if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
20948 : {
20949 55 : foreach(cell, idxes)
20950 : {
20951 24 : Oid idx = lfirst_oid(cell);
20952 24 : Relation idxRel = index_open(idx, AccessShareLock);
20953 :
20954 24 : if (idxRel->rd_index->indisunique ||
20955 16 : idxRel->rd_index->indisprimary)
20956 8 : ereport(ERROR,
20957 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20958 : errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
20959 : RelationGetRelationName(attachrel),
20960 : RelationGetRelationName(rel)),
20961 : errdetail("Partitioned table \"%s\" contains unique indexes.",
20962 : RelationGetRelationName(rel))));
20963 16 : index_close(idxRel, AccessShareLock);
20964 : }
20965 :
20966 31 : goto out;
20967 : }
20968 :
20969 : /*
20970 : * For each index on the partitioned table, find a matching one in the
20971 : * partition-to-be; if one is not found, create one.
20972 : */
20973 2302 : foreach(cell, idxes)
20974 : {
20975 493 : Oid idx = lfirst_oid(cell);
20976 493 : Relation idxRel = index_open(idx, AccessShareLock);
20977 : IndexInfo *info;
20978 : AttrMap *attmap;
20979 493 : bool found = false;
20980 : Oid constraintOid;
20981 :
20982 : /*
20983 : * Ignore indexes in the partitioned table other than partitioned
20984 : * indexes.
20985 : */
20986 493 : if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
20987 : {
20988 0 : index_close(idxRel, AccessShareLock);
20989 0 : continue;
20990 : }
20991 :
20992 : /* construct an indexinfo to compare existing indexes against */
20993 493 : info = BuildIndexInfo(idxRel);
20994 493 : attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
20995 : RelationGetDescr(rel),
20996 : false);
20997 493 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
20998 :
20999 : /*
21000 : * Scan the list of existing indexes in the partition-to-be, and mark
21001 : * the first matching, valid, unattached one we find, if any, as
21002 : * partition of the parent index. If we find one, we're done.
21003 : */
21004 533 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21005 : {
21006 197 : Oid cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
21007 197 : Oid cldConstrOid = InvalidOid;
21008 :
21009 : /* does this index have a parent? if so, can't use it */
21010 197 : if (attachrelIdxRels[i]->rd_rel->relispartition)
21011 8 : continue;
21012 :
21013 : /* If this index is invalid, can't use it */
21014 189 : if (!attachrelIdxRels[i]->rd_index->indisvalid)
21015 4 : continue;
21016 :
21017 185 : if (CompareIndexInfo(attachInfos[i], info,
21018 185 : attachrelIdxRels[i]->rd_indcollation,
21019 185 : idxRel->rd_indcollation,
21020 185 : attachrelIdxRels[i]->rd_opfamily,
21021 185 : idxRel->rd_opfamily,
21022 : attmap))
21023 : {
21024 : /*
21025 : * If this index is being created in the parent because of a
21026 : * constraint, then the child needs to have a constraint also,
21027 : * so look for one. If there is no such constraint, this
21028 : * index is no good, so keep looking.
21029 : */
21030 161 : if (OidIsValid(constraintOid))
21031 : {
21032 : cldConstrOid =
21033 96 : get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
21034 : cldIdxId);
21035 : /* no dice */
21036 96 : if (!OidIsValid(cldConstrOid))
21037 4 : continue;
21038 :
21039 : /* Ensure they're both the same type of constraint */
21040 184 : if (get_constraint_type(constraintOid) !=
21041 92 : get_constraint_type(cldConstrOid))
21042 0 : continue;
21043 : }
21044 :
21045 : /* bingo. */
21046 157 : IndexSetParentIndex(attachrelIdxRels[i], idx);
21047 157 : if (OidIsValid(constraintOid))
21048 92 : ConstraintSetParentConstraint(cldConstrOid, constraintOid,
21049 : RelationGetRelid(attachrel));
21050 157 : found = true;
21051 :
21052 157 : CommandCounterIncrement();
21053 157 : break;
21054 : }
21055 : }
21056 :
21057 : /*
21058 : * If no suitable index was found in the partition-to-be, create one
21059 : * now. Note that if this is a PK, not-null constraints must already
21060 : * exist.
21061 : */
21062 493 : if (!found)
21063 : {
21064 : IndexStmt *stmt;
21065 : Oid conOid;
21066 :
21067 336 : stmt = generateClonedIndexStmt(NULL,
21068 : idxRel, attmap,
21069 : &conOid);
21070 336 : DefineIndex(NULL,
21071 : RelationGetRelid(attachrel), stmt, InvalidOid,
21072 : RelationGetRelid(idxRel),
21073 : conOid,
21074 : -1,
21075 : true, false, false, false, false);
21076 : }
21077 :
21078 481 : index_close(idxRel, AccessShareLock);
21079 : }
21080 :
21081 1840 : out:
21082 : /* Clean up. */
21083 2101 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21084 261 : index_close(attachrelIdxRels[i], AccessShareLock);
21085 1840 : MemoryContextSwitchTo(oldcxt);
21086 1840 : MemoryContextDelete(cxt);
21087 1840 : }
21088 :
21089 : /*
21090 : * CloneRowTriggersToPartition
21091 : * subroutine for ATExecAttachPartition/DefineRelation to create row
21092 : * triggers on partitions
21093 : */
21094 : static void
21095 2100 : CloneRowTriggersToPartition(Relation parent, Relation partition)
21096 : {
21097 : Relation pg_trigger;
21098 : ScanKeyData key;
21099 : SysScanDesc scan;
21100 : HeapTuple tuple;
21101 : MemoryContext perTupCxt;
21102 :
21103 2100 : ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
21104 : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
21105 2100 : pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
21106 2100 : scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
21107 : true, NULL, 1, &key);
21108 :
21109 2100 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
21110 : "clone trig", ALLOCSET_SMALL_SIZES);
21111 :
21112 3329 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
21113 : {
21114 1233 : Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
21115 : CreateTrigStmt *trigStmt;
21116 1233 : Node *qual = NULL;
21117 : Datum value;
21118 : bool isnull;
21119 1233 : List *cols = NIL;
21120 1233 : List *trigargs = NIL;
21121 : MemoryContext oldcxt;
21122 :
21123 : /*
21124 : * Ignore statement-level triggers; those are not cloned.
21125 : */
21126 1233 : if (!TRIGGER_FOR_ROW(trigForm->tgtype))
21127 1102 : continue;
21128 :
21129 : /*
21130 : * Don't clone internal triggers, because the constraint cloning code
21131 : * will.
21132 : */
21133 1205 : if (trigForm->tgisinternal)
21134 1074 : continue;
21135 :
21136 : /*
21137 : * Complain if we find an unexpected trigger type.
21138 : */
21139 131 : if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
21140 107 : !TRIGGER_FOR_AFTER(trigForm->tgtype))
21141 0 : elog(ERROR, "unexpected trigger \"%s\" found",
21142 : NameStr(trigForm->tgname));
21143 :
21144 : /* Use short-lived context for CREATE TRIGGER */
21145 131 : oldcxt = MemoryContextSwitchTo(perTupCxt);
21146 :
21147 : /*
21148 : * If there is a WHEN clause, generate a 'cooked' version of it that's
21149 : * appropriate for the partition.
21150 : */
21151 131 : value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
21152 : RelationGetDescr(pg_trigger), &isnull);
21153 131 : if (!isnull)
21154 : {
21155 4 : qual = stringToNode(TextDatumGetCString(value));
21156 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
21157 : partition, parent);
21158 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
21159 : partition, parent);
21160 : }
21161 :
21162 : /*
21163 : * If there is a column list, transform it to a list of column names.
21164 : * Note we don't need to map this list in any way ...
21165 : */
21166 131 : if (trigForm->tgattr.dim1 > 0)
21167 : {
21168 : int i;
21169 :
21170 8 : for (i = 0; i < trigForm->tgattr.dim1; i++)
21171 : {
21172 : Form_pg_attribute col;
21173 :
21174 4 : col = TupleDescAttr(parent->rd_att,
21175 4 : trigForm->tgattr.values[i] - 1);
21176 4 : cols = lappend(cols,
21177 4 : makeString(pstrdup(NameStr(col->attname))));
21178 : }
21179 : }
21180 :
21181 : /* Reconstruct trigger arguments list. */
21182 131 : if (trigForm->tgnargs > 0)
21183 : {
21184 : char *p;
21185 :
21186 36 : value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
21187 : RelationGetDescr(pg_trigger), &isnull);
21188 36 : if (isnull)
21189 0 : elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
21190 : NameStr(trigForm->tgname), RelationGetRelationName(partition));
21191 :
21192 36 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
21193 :
21194 80 : for (int i = 0; i < trigForm->tgnargs; i++)
21195 : {
21196 44 : trigargs = lappend(trigargs, makeString(pstrdup(p)));
21197 44 : p += strlen(p) + 1;
21198 : }
21199 : }
21200 :
21201 131 : trigStmt = makeNode(CreateTrigStmt);
21202 131 : trigStmt->replace = false;
21203 131 : trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
21204 131 : trigStmt->trigname = NameStr(trigForm->tgname);
21205 131 : trigStmt->relation = NULL;
21206 131 : trigStmt->funcname = NULL; /* passed separately */
21207 131 : trigStmt->args = trigargs;
21208 131 : trigStmt->row = true;
21209 131 : trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
21210 131 : trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
21211 131 : trigStmt->columns = cols;
21212 131 : trigStmt->whenClause = NULL; /* passed separately */
21213 131 : trigStmt->transitionRels = NIL; /* not supported at present */
21214 131 : trigStmt->deferrable = trigForm->tgdeferrable;
21215 131 : trigStmt->initdeferred = trigForm->tginitdeferred;
21216 131 : trigStmt->constrrel = NULL; /* passed separately */
21217 :
21218 131 : CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
21219 : trigForm->tgconstrrelid, InvalidOid, InvalidOid,
21220 : trigForm->tgfoid, trigForm->oid, qual,
21221 131 : false, true, trigForm->tgenabled);
21222 :
21223 127 : MemoryContextSwitchTo(oldcxt);
21224 127 : MemoryContextReset(perTupCxt);
21225 : }
21226 :
21227 2096 : MemoryContextDelete(perTupCxt);
21228 :
21229 2096 : systable_endscan(scan);
21230 2096 : table_close(pg_trigger, RowExclusiveLock);
21231 2096 : }
21232 :
21233 : /*
21234 : * ALTER TABLE DETACH PARTITION
21235 : *
21236 : * Return the address of the relation that is no longer a partition of rel.
21237 : *
21238 : * If concurrent mode is requested, we run in two transactions. A side-
21239 : * effect is that this command cannot run in a multi-part ALTER TABLE.
21240 : * Currently, that's enforced by the grammar.
21241 : *
21242 : * The strategy for concurrency is to first modify the partition's
21243 : * pg_inherit catalog row to make it visible to everyone that the
21244 : * partition is detached, lock the partition against writes, and commit
21245 : * the transaction; anyone who requests the partition descriptor from
21246 : * that point onwards has to ignore such a partition. In a second
21247 : * transaction, we wait until all transactions that could have seen the
21248 : * partition as attached are gone, then we remove the rest of partition
21249 : * metadata (pg_inherits and pg_class.relpartbounds).
21250 : */
21251 : static ObjectAddress
21252 373 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
21253 : RangeVar *name, bool concurrent)
21254 : {
21255 : Relation partRel;
21256 : ObjectAddress address;
21257 : Oid defaultPartOid;
21258 :
21259 : /*
21260 : * We must lock the default partition, because detaching this partition
21261 : * will change its partition constraint.
21262 : */
21263 : defaultPartOid =
21264 373 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
21265 373 : if (OidIsValid(defaultPartOid))
21266 : {
21267 : /*
21268 : * Concurrent detaching when a default partition exists is not
21269 : * supported. The main problem is that the default partition
21270 : * constraint would change. And there's a definitional problem: what
21271 : * should happen to the tuples that are being inserted that belong to
21272 : * the partition being detached? Putting them on the partition being
21273 : * detached would be wrong, since they'd become "lost" after the
21274 : * detaching completes but we cannot put them in the default partition
21275 : * either until we alter its partition constraint.
21276 : *
21277 : * I think we could solve this problem if we effected the constraint
21278 : * change before committing the first transaction. But the lock would
21279 : * have to remain AEL and it would cause concurrent query planning to
21280 : * be blocked, so changing it that way would be even worse.
21281 : */
21282 74 : if (concurrent)
21283 8 : ereport(ERROR,
21284 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21285 : errmsg("cannot detach partitions concurrently when a default partition exists")));
21286 66 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
21287 : }
21288 :
21289 : /*
21290 : * In concurrent mode, the partition is locked with share-update-exclusive
21291 : * in the first transaction. This allows concurrent transactions to be
21292 : * doing DML to the partition.
21293 : */
21294 365 : partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
21295 : AccessExclusiveLock);
21296 :
21297 : /*
21298 : * Check inheritance conditions and either delete the pg_inherits row (in
21299 : * non-concurrent mode) or just set the inhdetachpending flag.
21300 : */
21301 357 : if (!concurrent)
21302 282 : RemoveInheritance(partRel, rel, false);
21303 : else
21304 75 : MarkInheritDetached(partRel, rel);
21305 :
21306 : /*
21307 : * Ensure that foreign keys still hold after this detach. This keeps
21308 : * locks on the referencing tables, which prevents concurrent transactions
21309 : * from adding rows that we wouldn't see. For this to work in concurrent
21310 : * mode, it is critical that the partition appears as no longer attached
21311 : * for the RI queries as soon as the first transaction commits.
21312 : */
21313 344 : ATDetachCheckNoForeignKeyRefs(partRel);
21314 :
21315 : /*
21316 : * Concurrent mode has to work harder; first we add a new constraint to
21317 : * the partition that matches the partition constraint. Then we close our
21318 : * existing transaction, and in a new one wait for all processes to catch
21319 : * up on the catalog updates we've done so far; at that point we can
21320 : * complete the operation.
21321 : */
21322 322 : if (concurrent)
21323 : {
21324 : Oid partrelid,
21325 : parentrelid;
21326 : LOCKTAG tag;
21327 : char *parentrelname;
21328 : char *partrelname;
21329 :
21330 : /*
21331 : * We're almost done now; the only traces that remain are the
21332 : * pg_inherits tuple and the partition's relpartbounds. Before we can
21333 : * remove those, we need to wait until all transactions that know that
21334 : * this is a partition are gone.
21335 : */
21336 :
21337 : /*
21338 : * Remember relation OIDs to re-acquire them later; and relation names
21339 : * too, for error messages if something is dropped in between.
21340 : */
21341 72 : partrelid = RelationGetRelid(partRel);
21342 72 : parentrelid = RelationGetRelid(rel);
21343 72 : parentrelname = MemoryContextStrdup(PortalContext,
21344 72 : RelationGetRelationName(rel));
21345 72 : partrelname = MemoryContextStrdup(PortalContext,
21346 72 : RelationGetRelationName(partRel));
21347 :
21348 : /* Invalidate relcache entries for the parent -- must be before close */
21349 72 : CacheInvalidateRelcache(rel);
21350 :
21351 72 : table_close(partRel, NoLock);
21352 72 : table_close(rel, NoLock);
21353 72 : tab->rel = NULL;
21354 :
21355 : /* Make updated catalog entry visible */
21356 72 : PopActiveSnapshot();
21357 72 : CommitTransactionCommand();
21358 :
21359 72 : StartTransactionCommand();
21360 :
21361 : /*
21362 : * Now wait. This ensures that all queries that were planned
21363 : * including the partition are finished before we remove the rest of
21364 : * catalog entries. We don't need or indeed want to acquire this
21365 : * lock, though -- that would block later queries.
21366 : *
21367 : * We don't need to concern ourselves with waiting for a lock on the
21368 : * partition itself, since we will acquire AccessExclusiveLock below.
21369 : */
21370 72 : SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
21371 72 : WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
21372 :
21373 : /*
21374 : * Now acquire locks in both relations again. Note they may have been
21375 : * removed in the meantime, so care is required.
21376 : */
21377 47 : rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
21378 47 : partRel = try_relation_open(partrelid, AccessExclusiveLock);
21379 :
21380 : /* If the relations aren't there, something bad happened; bail out */
21381 47 : if (rel == NULL)
21382 : {
21383 0 : if (partRel != NULL) /* shouldn't happen */
21384 0 : elog(WARNING, "dangling partition \"%s\" remains, can't fix",
21385 : partrelname);
21386 0 : ereport(ERROR,
21387 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21388 : errmsg("partitioned table \"%s\" was removed concurrently",
21389 : parentrelname)));
21390 : }
21391 47 : if (partRel == NULL)
21392 0 : ereport(ERROR,
21393 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21394 : errmsg("partition \"%s\" was removed concurrently", partrelname)));
21395 :
21396 47 : tab->rel = rel;
21397 : }
21398 :
21399 : /*
21400 : * Detaching the partition might involve TOAST table access, so ensure we
21401 : * have a valid snapshot.
21402 : */
21403 297 : PushActiveSnapshot(GetTransactionSnapshot());
21404 :
21405 : /* Do the final part of detaching */
21406 297 : DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
21407 :
21408 296 : PopActiveSnapshot();
21409 :
21410 296 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21411 :
21412 : /* keep our lock until commit */
21413 296 : table_close(partRel, NoLock);
21414 :
21415 296 : return address;
21416 : }
21417 :
21418 : /*
21419 : * Second part of ALTER TABLE .. DETACH.
21420 : *
21421 : * This is separate so that it can be run independently when the second
21422 : * transaction of the concurrent algorithm fails (crash or abort).
21423 : */
21424 : static void
21425 681 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
21426 : Oid defaultPartOid)
21427 : {
21428 : Relation classRel;
21429 : List *fks;
21430 : ListCell *cell;
21431 : List *indexes;
21432 : Datum new_val[Natts_pg_class];
21433 : bool new_null[Natts_pg_class],
21434 : new_repl[Natts_pg_class];
21435 : HeapTuple tuple,
21436 : newtuple;
21437 681 : Relation trigrel = NULL;
21438 681 : List *fkoids = NIL;
21439 :
21440 681 : if (concurrent)
21441 : {
21442 : /*
21443 : * We can remove the pg_inherits row now. (In the non-concurrent case,
21444 : * this was already done).
21445 : */
21446 54 : RemoveInheritance(partRel, rel, true);
21447 : }
21448 :
21449 : /* Drop any triggers that were cloned on creation/attach. */
21450 681 : DropClonedTriggersFromPartition(RelationGetRelid(partRel));
21451 :
21452 : /*
21453 : * Detach any foreign keys that are inherited. This includes creating
21454 : * additional action triggers.
21455 : */
21456 681 : fks = copyObject(RelationGetFKeyList(partRel));
21457 681 : if (fks != NIL)
21458 60 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
21459 :
21460 : /*
21461 : * It's possible that the partition being detached has a foreign key that
21462 : * references a partitioned table. When that happens, there are multiple
21463 : * pg_constraint rows for the partition: one points to the partitioned
21464 : * table itself, while the others point to each of its partitions. Only
21465 : * the topmost one is to be considered here; the child constraints must be
21466 : * left alone, because conceptually those aren't coming from our parent
21467 : * partitioned table, but from this partition itself.
21468 : *
21469 : * We implement this by collecting all the constraint OIDs in a first scan
21470 : * of the FK array, and skipping in the loop below those constraints whose
21471 : * parents are listed here.
21472 : */
21473 1478 : foreach_node(ForeignKeyCacheInfo, fk, fks)
21474 116 : fkoids = lappend_oid(fkoids, fk->conoid);
21475 :
21476 797 : foreach(cell, fks)
21477 : {
21478 116 : ForeignKeyCacheInfo *fk = lfirst(cell);
21479 : HeapTuple contup;
21480 : Form_pg_constraint conform;
21481 :
21482 116 : contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
21483 116 : if (!HeapTupleIsValid(contup))
21484 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
21485 116 : conform = (Form_pg_constraint) GETSTRUCT(contup);
21486 :
21487 : /*
21488 : * Consider only inherited foreign keys, and only if their parents
21489 : * aren't in the list.
21490 : */
21491 116 : if (conform->contype != CONSTRAINT_FOREIGN ||
21492 216 : !OidIsValid(conform->conparentid) ||
21493 100 : list_member_oid(fkoids, conform->conparentid))
21494 : {
21495 44 : ReleaseSysCache(contup);
21496 44 : continue;
21497 : }
21498 :
21499 : /*
21500 : * The constraint on this table must be marked no longer a child of
21501 : * the parent's constraint, as do its check triggers.
21502 : */
21503 72 : ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
21504 :
21505 : /*
21506 : * Also, look up the partition's "check" triggers corresponding to the
21507 : * ENFORCED constraint being detached and detach them from the parent
21508 : * triggers. NOT ENFORCED constraints do not have these triggers;
21509 : * therefore, this step is not needed.
21510 : */
21511 72 : if (fk->conenforced)
21512 : {
21513 : Oid insertTriggerOid,
21514 : updateTriggerOid;
21515 :
21516 72 : GetForeignKeyCheckTriggers(trigrel,
21517 : fk->conoid, fk->confrelid, fk->conrelid,
21518 : &insertTriggerOid, &updateTriggerOid);
21519 : Assert(OidIsValid(insertTriggerOid));
21520 72 : TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
21521 : RelationGetRelid(partRel));
21522 : Assert(OidIsValid(updateTriggerOid));
21523 72 : TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
21524 : RelationGetRelid(partRel));
21525 : }
21526 :
21527 : /*
21528 : * Lastly, create the action triggers on the referenced table, using
21529 : * addFkRecurseReferenced, which requires some elaborate setup (so put
21530 : * it in a separate block). While at it, if the table is partitioned,
21531 : * that function will recurse to create the pg_constraint rows and
21532 : * action triggers for each partition.
21533 : *
21534 : * Note there's no need to do addFkConstraint() here, because the
21535 : * pg_constraint row already exists.
21536 : */
21537 : {
21538 : Constraint *fkconstraint;
21539 : int numfks;
21540 : AttrNumber conkey[INDEX_MAX_KEYS];
21541 : AttrNumber confkey[INDEX_MAX_KEYS];
21542 : Oid conpfeqop[INDEX_MAX_KEYS];
21543 : Oid conppeqop[INDEX_MAX_KEYS];
21544 : Oid conffeqop[INDEX_MAX_KEYS];
21545 : int numfkdelsetcols;
21546 : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
21547 : Relation refdRel;
21548 :
21549 72 : DeconstructFkConstraintRow(contup,
21550 : &numfks,
21551 : conkey,
21552 : confkey,
21553 : conpfeqop,
21554 : conppeqop,
21555 : conffeqop,
21556 : &numfkdelsetcols,
21557 : confdelsetcols);
21558 :
21559 : /* Create a synthetic node we'll use throughout */
21560 72 : fkconstraint = makeNode(Constraint);
21561 72 : fkconstraint->contype = CONSTRAINT_FOREIGN;
21562 72 : fkconstraint->conname = pstrdup(NameStr(conform->conname));
21563 72 : fkconstraint->deferrable = conform->condeferrable;
21564 72 : fkconstraint->initdeferred = conform->condeferred;
21565 72 : fkconstraint->is_enforced = conform->conenforced;
21566 72 : fkconstraint->skip_validation = true;
21567 72 : fkconstraint->initially_valid = conform->convalidated;
21568 : /* a few irrelevant fields omitted here */
21569 72 : fkconstraint->pktable = NULL;
21570 72 : fkconstraint->fk_attrs = NIL;
21571 72 : fkconstraint->pk_attrs = NIL;
21572 72 : fkconstraint->fk_matchtype = conform->confmatchtype;
21573 72 : fkconstraint->fk_upd_action = conform->confupdtype;
21574 72 : fkconstraint->fk_del_action = conform->confdeltype;
21575 72 : fkconstraint->fk_del_set_cols = NIL;
21576 72 : fkconstraint->old_conpfeqop = NIL;
21577 72 : fkconstraint->old_pktable_oid = InvalidOid;
21578 72 : fkconstraint->location = -1;
21579 :
21580 : /* set up colnames, used to generate the constraint name */
21581 176 : for (int i = 0; i < numfks; i++)
21582 : {
21583 : Form_pg_attribute att;
21584 :
21585 104 : att = TupleDescAttr(RelationGetDescr(partRel),
21586 104 : conkey[i] - 1);
21587 :
21588 104 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
21589 104 : makeString(NameStr(att->attname)));
21590 : }
21591 :
21592 72 : refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
21593 :
21594 72 : addFkRecurseReferenced(fkconstraint, partRel,
21595 : refdRel,
21596 : conform->conindid,
21597 : fk->conoid,
21598 : numfks,
21599 : confkey,
21600 : conkey,
21601 : conpfeqop,
21602 : conppeqop,
21603 : conffeqop,
21604 : numfkdelsetcols,
21605 : confdelsetcols,
21606 : true,
21607 : InvalidOid, InvalidOid,
21608 72 : conform->conperiod);
21609 72 : table_close(refdRel, NoLock); /* keep lock till end of xact */
21610 : }
21611 :
21612 72 : ReleaseSysCache(contup);
21613 : }
21614 681 : list_free_deep(fks);
21615 681 : if (trigrel)
21616 60 : table_close(trigrel, RowExclusiveLock);
21617 :
21618 : /*
21619 : * Any sub-constraints that are in the referenced-side of a larger
21620 : * constraint have to be removed. This partition is no longer part of the
21621 : * key space of the constraint.
21622 : */
21623 736 : foreach(cell, GetParentedForeignKeyRefs(partRel))
21624 : {
21625 56 : Oid constrOid = lfirst_oid(cell);
21626 : ObjectAddress constraint;
21627 :
21628 56 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
21629 56 : deleteDependencyRecordsForClass(ConstraintRelationId,
21630 : constrOid,
21631 : ConstraintRelationId,
21632 : DEPENDENCY_INTERNAL);
21633 56 : CommandCounterIncrement();
21634 :
21635 56 : ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
21636 56 : performDeletion(&constraint, DROP_RESTRICT, 0);
21637 : }
21638 :
21639 : /* Now we can detach indexes */
21640 680 : indexes = RelationGetIndexList(partRel);
21641 987 : foreach(cell, indexes)
21642 : {
21643 307 : Oid idxid = lfirst_oid(cell);
21644 : Oid parentidx;
21645 : Relation idx;
21646 : Oid constrOid;
21647 : Oid parentConstrOid;
21648 :
21649 307 : if (!has_superclass(idxid))
21650 9 : continue;
21651 :
21652 298 : parentidx = get_partition_parent(idxid, false);
21653 : Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
21654 :
21655 298 : idx = index_open(idxid, AccessExclusiveLock);
21656 298 : IndexSetParentIndex(idx, InvalidOid);
21657 :
21658 : /*
21659 : * If there's a constraint associated with the index, detach it too.
21660 : * Careful: it is possible for a constraint index in a partition to be
21661 : * the child of a non-constraint index, so verify whether the parent
21662 : * index does actually have a constraint.
21663 : */
21664 298 : constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
21665 : idxid);
21666 298 : parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
21667 : parentidx);
21668 298 : if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
21669 135 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
21670 :
21671 298 : index_close(idx, NoLock);
21672 : }
21673 :
21674 : /* Update pg_class tuple */
21675 680 : classRel = table_open(RelationRelationId, RowExclusiveLock);
21676 680 : tuple = SearchSysCacheCopy1(RELOID,
21677 : ObjectIdGetDatum(RelationGetRelid(partRel)));
21678 680 : if (!HeapTupleIsValid(tuple))
21679 0 : elog(ERROR, "cache lookup failed for relation %u",
21680 : RelationGetRelid(partRel));
21681 : Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
21682 :
21683 : /* Clear relpartbound and reset relispartition */
21684 680 : memset(new_val, 0, sizeof(new_val));
21685 680 : memset(new_null, false, sizeof(new_null));
21686 680 : memset(new_repl, false, sizeof(new_repl));
21687 680 : new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
21688 680 : new_null[Anum_pg_class_relpartbound - 1] = true;
21689 680 : new_repl[Anum_pg_class_relpartbound - 1] = true;
21690 680 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
21691 : new_val, new_null, new_repl);
21692 :
21693 680 : ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
21694 680 : CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
21695 680 : heap_freetuple(newtuple);
21696 680 : table_close(classRel, RowExclusiveLock);
21697 :
21698 : /*
21699 : * Drop identity property from all identity columns of partition.
21700 : */
21701 2200 : for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
21702 : {
21703 1520 : Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
21704 :
21705 1520 : if (!attr->attisdropped && attr->attidentity)
21706 20 : ATExecDropIdentity(partRel, NameStr(attr->attname), false,
21707 : AccessExclusiveLock, true, true);
21708 : }
21709 :
21710 680 : if (OidIsValid(defaultPartOid))
21711 : {
21712 : /*
21713 : * If the relation being detached is the default partition itself,
21714 : * remove it from the parent's pg_partitioned_table entry.
21715 : *
21716 : * If not, we must invalidate default partition's relcache entry, as
21717 : * in StorePartitionBound: its partition constraint depends on every
21718 : * other partition's partition constraint.
21719 : */
21720 159 : if (RelationGetRelid(partRel) == defaultPartOid)
21721 29 : update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
21722 : else
21723 130 : CacheInvalidateRelcacheByRelid(defaultPartOid);
21724 : }
21725 :
21726 : /*
21727 : * Invalidate the parent's relcache so that the partition is no longer
21728 : * included in its partition descriptor.
21729 : */
21730 680 : CacheInvalidateRelcache(rel);
21731 :
21732 : /*
21733 : * If the partition we just detached is partitioned itself, invalidate
21734 : * relcache for all descendent partitions too to ensure that their
21735 : * rd_partcheck expression trees are rebuilt; must lock partitions before
21736 : * doing so, using the same lockmode as what partRel has been locked with
21737 : * by the caller.
21738 : */
21739 680 : if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21740 : {
21741 : List *children;
21742 :
21743 41 : children = find_all_inheritors(RelationGetRelid(partRel),
21744 : AccessExclusiveLock, NULL);
21745 135 : foreach(cell, children)
21746 : {
21747 94 : CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
21748 : }
21749 : }
21750 680 : }
21751 :
21752 : /*
21753 : * ALTER TABLE ... DETACH PARTITION ... FINALIZE
21754 : *
21755 : * To use when a DETACH PARTITION command previously did not run to
21756 : * completion; this completes the detaching process.
21757 : */
21758 : static ObjectAddress
21759 7 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
21760 : {
21761 : Relation partRel;
21762 : ObjectAddress address;
21763 7 : Snapshot snap = GetActiveSnapshot();
21764 :
21765 7 : partRel = table_openrv(name, AccessExclusiveLock);
21766 :
21767 : /*
21768 : * Wait until existing snapshots are gone. This is important if the
21769 : * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
21770 : * user could immediately run DETACH FINALIZE without actually waiting for
21771 : * existing transactions. We must not complete the detach action until
21772 : * all such queries are complete (otherwise we would present them with an
21773 : * inconsistent view of catalogs).
21774 : */
21775 7 : WaitForOlderSnapshots(snap->xmin, false);
21776 :
21777 7 : DetachPartitionFinalize(rel, partRel, true, InvalidOid);
21778 :
21779 7 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21780 :
21781 7 : table_close(partRel, NoLock);
21782 :
21783 7 : return address;
21784 : }
21785 :
21786 : /*
21787 : * DropClonedTriggersFromPartition
21788 : * subroutine for ATExecDetachPartition to remove any triggers that were
21789 : * cloned to the partition when it was created-as-partition or attached.
21790 : * This undoes what CloneRowTriggersToPartition did.
21791 : */
21792 : static void
21793 681 : DropClonedTriggersFromPartition(Oid partitionId)
21794 : {
21795 : ScanKeyData skey;
21796 : SysScanDesc scan;
21797 : HeapTuple trigtup;
21798 : Relation tgrel;
21799 : ObjectAddresses *objects;
21800 :
21801 681 : objects = new_object_addresses();
21802 :
21803 : /*
21804 : * Scan pg_trigger to search for all triggers on this rel.
21805 : */
21806 681 : ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
21807 : F_OIDEQ, ObjectIdGetDatum(partitionId));
21808 681 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
21809 681 : scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
21810 : true, NULL, 1, &skey);
21811 1017 : while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
21812 : {
21813 336 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
21814 : ObjectAddress trig;
21815 :
21816 : /* Ignore triggers that weren't cloned */
21817 336 : if (!OidIsValid(pg_trigger->tgparentid))
21818 296 : continue;
21819 :
21820 : /*
21821 : * Ignore internal triggers that are implementation objects of foreign
21822 : * keys, because these will be detached when the foreign keys
21823 : * themselves are.
21824 : */
21825 280 : if (OidIsValid(pg_trigger->tgconstrrelid))
21826 240 : continue;
21827 :
21828 : /*
21829 : * This is ugly, but necessary: remove the dependency markings on the
21830 : * trigger so that it can be removed.
21831 : */
21832 40 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
21833 : TriggerRelationId,
21834 : DEPENDENCY_PARTITION_PRI);
21835 40 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
21836 : RelationRelationId,
21837 : DEPENDENCY_PARTITION_SEC);
21838 :
21839 : /* remember this trigger to remove it below */
21840 40 : ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
21841 40 : add_exact_object_address(&trig, objects);
21842 : }
21843 :
21844 : /* make the dependency removal visible to the deletion below */
21845 681 : CommandCounterIncrement();
21846 681 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
21847 :
21848 : /* done */
21849 681 : free_object_addresses(objects);
21850 681 : systable_endscan(scan);
21851 681 : table_close(tgrel, RowExclusiveLock);
21852 681 : }
21853 :
21854 : /*
21855 : * Before acquiring lock on an index, acquire the same lock on the owning
21856 : * table.
21857 : */
21858 : struct AttachIndexCallbackState
21859 : {
21860 : Oid partitionOid;
21861 : Oid parentTblOid;
21862 : bool lockedParentTbl;
21863 : };
21864 :
21865 : static void
21866 283 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
21867 : void *arg)
21868 : {
21869 : struct AttachIndexCallbackState *state;
21870 : Form_pg_class classform;
21871 : HeapTuple tuple;
21872 :
21873 283 : state = (struct AttachIndexCallbackState *) arg;
21874 :
21875 283 : if (!state->lockedParentTbl)
21876 : {
21877 275 : LockRelationOid(state->parentTblOid, AccessShareLock);
21878 275 : state->lockedParentTbl = true;
21879 : }
21880 :
21881 : /*
21882 : * If we previously locked some other heap, and the name we're looking up
21883 : * no longer refers to an index on that relation, release the now-useless
21884 : * lock. XXX maybe we should do *after* we verify whether the index does
21885 : * not actually belong to the same relation ...
21886 : */
21887 283 : if (relOid != oldRelOid && OidIsValid(state->partitionOid))
21888 : {
21889 0 : UnlockRelationOid(state->partitionOid, AccessShareLock);
21890 0 : state->partitionOid = InvalidOid;
21891 : }
21892 :
21893 : /* Didn't find a relation, so no need for locking or permission checks. */
21894 283 : if (!OidIsValid(relOid))
21895 4 : return;
21896 :
21897 279 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
21898 279 : if (!HeapTupleIsValid(tuple))
21899 0 : return; /* concurrently dropped, so nothing to do */
21900 279 : classform = (Form_pg_class) GETSTRUCT(tuple);
21901 279 : if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
21902 214 : classform->relkind != RELKIND_INDEX)
21903 4 : ereport(ERROR,
21904 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
21905 : errmsg("\"%s\" is not an index", rv->relname)));
21906 275 : ReleaseSysCache(tuple);
21907 :
21908 : /*
21909 : * Since we need only examine the heap's tupledesc, an access share lock
21910 : * on it (preventing any DDL) is sufficient.
21911 : */
21912 275 : state->partitionOid = IndexGetRelation(relOid, false);
21913 275 : LockRelationOid(state->partitionOid, AccessShareLock);
21914 : }
21915 :
21916 : /*
21917 : * ALTER INDEX i1 ATTACH PARTITION i2
21918 : */
21919 : static ObjectAddress
21920 275 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
21921 : {
21922 : Relation partIdx;
21923 : Relation partTbl;
21924 : Relation parentTbl;
21925 : ObjectAddress address;
21926 : Oid partIdxId;
21927 : Oid currParent;
21928 : struct AttachIndexCallbackState state;
21929 :
21930 : /*
21931 : * We need to obtain lock on the index 'name' to modify it, but we also
21932 : * need to read its owning table's tuple descriptor -- so we need to lock
21933 : * both. To avoid deadlocks, obtain lock on the table before doing so on
21934 : * the index. Furthermore, we need to examine the parent table of the
21935 : * partition, so lock that one too.
21936 : */
21937 275 : state.partitionOid = InvalidOid;
21938 275 : state.parentTblOid = parentIdx->rd_index->indrelid;
21939 275 : state.lockedParentTbl = false;
21940 : partIdxId =
21941 275 : RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
21942 : RangeVarCallbackForAttachIndex,
21943 : &state);
21944 : /* Not there? */
21945 267 : if (!OidIsValid(partIdxId))
21946 0 : ereport(ERROR,
21947 : (errcode(ERRCODE_UNDEFINED_OBJECT),
21948 : errmsg("index \"%s\" does not exist", name->relname)));
21949 :
21950 : /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
21951 267 : partIdx = relation_open(partIdxId, AccessExclusiveLock);
21952 :
21953 : /* we already hold locks on both tables, so this is safe: */
21954 267 : parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
21955 267 : partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
21956 :
21957 267 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
21958 :
21959 : /*
21960 : * Check if the index is already attached to the correct parent,
21961 : * ultimately attempting one round of validation if already the case.
21962 : */
21963 534 : currParent = partIdx->rd_rel->relispartition ?
21964 267 : get_partition_parent(partIdxId, false) : InvalidOid;
21965 267 : if (currParent != RelationGetRelid(parentIdx))
21966 : {
21967 : IndexInfo *childInfo;
21968 : IndexInfo *parentInfo;
21969 : AttrMap *attmap;
21970 : bool found;
21971 : int i;
21972 : PartitionDesc partDesc;
21973 : Oid constraintOid,
21974 243 : cldConstrId = InvalidOid;
21975 :
21976 : /*
21977 : * If this partition already has an index attached, refuse the
21978 : * operation.
21979 : */
21980 243 : refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
21981 :
21982 239 : if (OidIsValid(currParent))
21983 0 : ereport(ERROR,
21984 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21985 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
21986 : RelationGetRelationName(partIdx),
21987 : RelationGetRelationName(parentIdx)),
21988 : errdetail("Index \"%s\" is already attached to another index.",
21989 : RelationGetRelationName(partIdx))));
21990 :
21991 : /* Make sure it indexes a partition of the other index's table */
21992 239 : partDesc = RelationGetPartitionDesc(parentTbl, true);
21993 239 : found = false;
21994 364 : for (i = 0; i < partDesc->nparts; i++)
21995 : {
21996 360 : if (partDesc->oids[i] == state.partitionOid)
21997 : {
21998 235 : found = true;
21999 235 : break;
22000 : }
22001 : }
22002 239 : if (!found)
22003 4 : ereport(ERROR,
22004 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22005 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22006 : RelationGetRelationName(partIdx),
22007 : RelationGetRelationName(parentIdx)),
22008 : errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
22009 : RelationGetRelationName(partIdx),
22010 : RelationGetRelationName(parentTbl))));
22011 :
22012 : /* Ensure the indexes are compatible */
22013 235 : childInfo = BuildIndexInfo(partIdx);
22014 235 : parentInfo = BuildIndexInfo(parentIdx);
22015 235 : attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
22016 : RelationGetDescr(parentTbl),
22017 : false);
22018 235 : if (!CompareIndexInfo(childInfo, parentInfo,
22019 235 : partIdx->rd_indcollation,
22020 235 : parentIdx->rd_indcollation,
22021 235 : partIdx->rd_opfamily,
22022 235 : parentIdx->rd_opfamily,
22023 : attmap))
22024 28 : ereport(ERROR,
22025 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22026 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22027 : RelationGetRelationName(partIdx),
22028 : RelationGetRelationName(parentIdx)),
22029 : errdetail("The index definitions do not match.")));
22030 :
22031 : /*
22032 : * If there is a constraint in the parent, make sure there is one in
22033 : * the child too.
22034 : */
22035 207 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
22036 : RelationGetRelid(parentIdx));
22037 :
22038 207 : if (OidIsValid(constraintOid))
22039 : {
22040 71 : cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
22041 : partIdxId);
22042 71 : if (!OidIsValid(cldConstrId))
22043 4 : ereport(ERROR,
22044 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22045 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22046 : RelationGetRelationName(partIdx),
22047 : RelationGetRelationName(parentIdx)),
22048 : errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
22049 : RelationGetRelationName(parentIdx),
22050 : RelationGetRelationName(parentTbl),
22051 : RelationGetRelationName(partIdx))));
22052 : }
22053 :
22054 : /*
22055 : * If it's a primary key, make sure the columns in the partition are
22056 : * NOT NULL.
22057 : */
22058 203 : if (parentIdx->rd_index->indisprimary)
22059 55 : verifyPartitionIndexNotNull(childInfo, partTbl);
22060 :
22061 : /* All good -- do it */
22062 203 : IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
22063 203 : if (OidIsValid(constraintOid))
22064 67 : ConstraintSetParentConstraint(cldConstrId, constraintOid,
22065 : RelationGetRelid(partTbl));
22066 :
22067 203 : free_attrmap(attmap);
22068 :
22069 203 : validatePartitionedIndex(parentIdx, parentTbl);
22070 : }
22071 24 : else if (!parentIdx->rd_index->indisvalid)
22072 : {
22073 : /*
22074 : * The index is attached, but the parent is still invalid; see if it
22075 : * can be validated now.
22076 : */
22077 12 : validatePartitionedIndex(parentIdx, parentTbl);
22078 : }
22079 :
22080 227 : relation_close(parentTbl, AccessShareLock);
22081 : /* keep these locks till commit */
22082 227 : relation_close(partTbl, NoLock);
22083 227 : relation_close(partIdx, NoLock);
22084 :
22085 227 : return address;
22086 : }
22087 :
22088 : /*
22089 : * Verify whether the given partition already contains an index attached
22090 : * to the given partitioned index. If so, raise an error.
22091 : */
22092 : static void
22093 243 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
22094 : {
22095 : Oid existingIdx;
22096 :
22097 243 : existingIdx = index_get_partition(partitionTbl,
22098 : RelationGetRelid(parentIdx));
22099 243 : if (OidIsValid(existingIdx))
22100 4 : ereport(ERROR,
22101 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22102 : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22103 : RelationGetRelationName(partIdx),
22104 : RelationGetRelationName(parentIdx)),
22105 : errdetail("Another index \"%s\" is already attached for partition \"%s\".",
22106 : get_rel_name(existingIdx),
22107 : RelationGetRelationName(partitionTbl))));
22108 239 : }
22109 :
22110 : /*
22111 : * Verify whether the set of attached partition indexes to a parent index on
22112 : * a partitioned table is complete. If it is, mark the parent index valid.
22113 : *
22114 : * This should be called each time a partition index is attached.
22115 : */
22116 : static void
22117 247 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
22118 : {
22119 : Relation inheritsRel;
22120 : SysScanDesc scan;
22121 : ScanKeyData key;
22122 247 : int tuples = 0;
22123 : HeapTuple inhTup;
22124 247 : bool updated = false;
22125 :
22126 : Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
22127 :
22128 : /*
22129 : * Scan pg_inherits for this parent index. Count each valid index we find
22130 : * (verifying the pg_index entry for each), and if we reach the total
22131 : * amount we expect, we can mark this parent index as valid.
22132 : */
22133 247 : inheritsRel = table_open(InheritsRelationId, AccessShareLock);
22134 247 : ScanKeyInit(&key, Anum_pg_inherits_inhparent,
22135 : BTEqualStrategyNumber, F_OIDEQ,
22136 : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22137 247 : scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
22138 : NULL, 1, &key);
22139 629 : while ((inhTup = systable_getnext(scan)) != NULL)
22140 : {
22141 382 : Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
22142 : HeapTuple indTup;
22143 : Form_pg_index indexForm;
22144 :
22145 382 : indTup = SearchSysCache1(INDEXRELID,
22146 : ObjectIdGetDatum(inhForm->inhrelid));
22147 382 : if (!HeapTupleIsValid(indTup))
22148 0 : elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
22149 382 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22150 382 : if (indexForm->indisvalid)
22151 316 : tuples += 1;
22152 382 : ReleaseSysCache(indTup);
22153 : }
22154 :
22155 : /* Done with pg_inherits */
22156 247 : systable_endscan(scan);
22157 247 : table_close(inheritsRel, AccessShareLock);
22158 :
22159 : /*
22160 : * If we found as many inherited indexes as the partitioned table has
22161 : * partitions, we're good; update pg_index to set indisvalid.
22162 : */
22163 247 : if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
22164 : {
22165 : Relation idxRel;
22166 : HeapTuple indTup;
22167 : Form_pg_index indexForm;
22168 :
22169 116 : idxRel = table_open(IndexRelationId, RowExclusiveLock);
22170 116 : indTup = SearchSysCacheCopy1(INDEXRELID,
22171 : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22172 116 : if (!HeapTupleIsValid(indTup))
22173 0 : elog(ERROR, "cache lookup failed for index %u",
22174 : RelationGetRelid(partedIdx));
22175 116 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22176 :
22177 116 : indexForm->indisvalid = true;
22178 116 : updated = true;
22179 :
22180 116 : CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
22181 :
22182 116 : table_close(idxRel, RowExclusiveLock);
22183 116 : heap_freetuple(indTup);
22184 : }
22185 :
22186 : /*
22187 : * If this index is in turn a partition of a larger index, validating it
22188 : * might cause the parent to become valid also. Try that.
22189 : */
22190 247 : if (updated && partedIdx->rd_rel->relispartition)
22191 : {
22192 : Oid parentIdxId,
22193 : parentTblId;
22194 : Relation parentIdx,
22195 : parentTbl;
22196 :
22197 : /* make sure we see the validation we just did */
22198 32 : CommandCounterIncrement();
22199 :
22200 32 : parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
22201 32 : parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
22202 32 : parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
22203 32 : parentTbl = relation_open(parentTblId, AccessExclusiveLock);
22204 : Assert(!parentIdx->rd_index->indisvalid);
22205 :
22206 32 : validatePartitionedIndex(parentIdx, parentTbl);
22207 :
22208 32 : relation_close(parentIdx, AccessExclusiveLock);
22209 32 : relation_close(parentTbl, AccessExclusiveLock);
22210 : }
22211 247 : }
22212 :
22213 : /*
22214 : * When attaching an index as a partition of a partitioned index which is a
22215 : * primary key, verify that all the columns in the partition are marked NOT
22216 : * NULL.
22217 : */
22218 : static void
22219 55 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
22220 : {
22221 111 : for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
22222 : {
22223 56 : Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
22224 56 : iinfo->ii_IndexAttrNumbers[i] - 1);
22225 :
22226 56 : if (!att->attnotnull)
22227 0 : ereport(ERROR,
22228 : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
22229 : errmsg("invalid primary key definition"),
22230 : errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
22231 : NameStr(att->attname),
22232 : RelationGetRelationName(partition)));
22233 : }
22234 55 : }
22235 :
22236 : /*
22237 : * Return an OID list of constraints that reference the given relation
22238 : * that are marked as having a parent constraints.
22239 : */
22240 : static List *
22241 1025 : GetParentedForeignKeyRefs(Relation partition)
22242 : {
22243 : Relation pg_constraint;
22244 : HeapTuple tuple;
22245 : SysScanDesc scan;
22246 : ScanKeyData key[2];
22247 1025 : List *constraints = NIL;
22248 :
22249 : /*
22250 : * If no indexes, or no columns are referenceable by FKs, we can avoid the
22251 : * scan.
22252 : */
22253 1457 : if (RelationGetIndexList(partition) == NIL ||
22254 432 : bms_is_empty(RelationGetIndexAttrBitmap(partition,
22255 : INDEX_ATTR_BITMAP_KEY)))
22256 766 : return NIL;
22257 :
22258 : /* Search for constraints referencing this table */
22259 259 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
22260 259 : ScanKeyInit(&key[0],
22261 : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
22262 : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
22263 259 : ScanKeyInit(&key[1],
22264 : Anum_pg_constraint_contype, BTEqualStrategyNumber,
22265 : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
22266 :
22267 : /* XXX This is a seqscan, as we don't have a usable index */
22268 259 : scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
22269 380 : while ((tuple = systable_getnext(scan)) != NULL)
22270 : {
22271 121 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22272 :
22273 : /*
22274 : * We only need to process constraints that are part of larger ones.
22275 : */
22276 121 : if (!OidIsValid(constrForm->conparentid))
22277 0 : continue;
22278 :
22279 121 : constraints = lappend_oid(constraints, constrForm->oid);
22280 : }
22281 :
22282 259 : systable_endscan(scan);
22283 259 : table_close(pg_constraint, AccessShareLock);
22284 :
22285 259 : return constraints;
22286 : }
22287 :
22288 : /*
22289 : * During DETACH PARTITION, verify that any foreign keys pointing to the
22290 : * partitioned table would not become invalid. An error is raised if any
22291 : * referenced values exist.
22292 : */
22293 : static void
22294 344 : ATDetachCheckNoForeignKeyRefs(Relation partition)
22295 : {
22296 : List *constraints;
22297 : ListCell *cell;
22298 :
22299 344 : constraints = GetParentedForeignKeyRefs(partition);
22300 :
22301 387 : foreach(cell, constraints)
22302 : {
22303 65 : Oid constrOid = lfirst_oid(cell);
22304 : HeapTuple tuple;
22305 : Form_pg_constraint constrForm;
22306 : Relation rel;
22307 65 : Trigger trig = {0};
22308 :
22309 65 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
22310 65 : if (!HeapTupleIsValid(tuple))
22311 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
22312 65 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22313 :
22314 : Assert(OidIsValid(constrForm->conparentid));
22315 : Assert(constrForm->confrelid == RelationGetRelid(partition));
22316 :
22317 : /* prevent data changes into the referencing table until commit */
22318 65 : rel = table_open(constrForm->conrelid, ShareLock);
22319 :
22320 65 : trig.tgoid = InvalidOid;
22321 65 : trig.tgname = NameStr(constrForm->conname);
22322 65 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
22323 65 : trig.tgisinternal = true;
22324 65 : trig.tgconstrrelid = RelationGetRelid(partition);
22325 65 : trig.tgconstrindid = constrForm->conindid;
22326 65 : trig.tgconstraint = constrForm->oid;
22327 65 : trig.tgdeferrable = false;
22328 65 : trig.tginitdeferred = false;
22329 : /* we needn't fill in remaining fields */
22330 :
22331 65 : RI_PartitionRemove_Check(&trig, rel, partition);
22332 :
22333 43 : ReleaseSysCache(tuple);
22334 :
22335 43 : table_close(rel, NoLock);
22336 : }
22337 322 : }
22338 :
22339 : /*
22340 : * resolve column compression specification to compression method.
22341 : */
22342 : static char
22343 170083 : GetAttributeCompression(Oid atttypid, const char *compression)
22344 : {
22345 : char cmethod;
22346 :
22347 170083 : if (compression == NULL || strcmp(compression, "default") == 0)
22348 169944 : return InvalidCompressionMethod;
22349 :
22350 : /*
22351 : * To specify a nondefault method, the column data type must be toastable.
22352 : * Note this says nothing about whether the column's attstorage setting
22353 : * permits compression; we intentionally allow attstorage and
22354 : * attcompression to be independent. But with a non-toastable type,
22355 : * attstorage could not be set to a value that would permit compression.
22356 : *
22357 : * We don't actually need to enforce this, since nothing bad would happen
22358 : * if attcompression were non-default; it would never be consulted. But
22359 : * it seems more user-friendly to complain about a certainly-useless
22360 : * attempt to set the property.
22361 : */
22362 139 : if (!TypeIsToastable(atttypid))
22363 4 : ereport(ERROR,
22364 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22365 : errmsg("column data type %s does not support compression",
22366 : format_type_be(atttypid))));
22367 :
22368 135 : cmethod = CompressionNameToMethod(compression);
22369 135 : if (!CompressionMethodIsValid(cmethod))
22370 8 : ereport(ERROR,
22371 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22372 : errmsg("invalid compression method \"%s\"", compression)));
22373 :
22374 127 : return cmethod;
22375 : }
22376 :
22377 : /*
22378 : * resolve column storage specification
22379 : */
22380 : static char
22381 204 : GetAttributeStorage(Oid atttypid, const char *storagemode)
22382 : {
22383 204 : char cstorage = 0;
22384 :
22385 204 : if (pg_strcasecmp(storagemode, "plain") == 0)
22386 37 : cstorage = TYPSTORAGE_PLAIN;
22387 167 : else if (pg_strcasecmp(storagemode, "external") == 0)
22388 104 : cstorage = TYPSTORAGE_EXTERNAL;
22389 63 : else if (pg_strcasecmp(storagemode, "extended") == 0)
22390 26 : cstorage = TYPSTORAGE_EXTENDED;
22391 37 : else if (pg_strcasecmp(storagemode, "main") == 0)
22392 33 : cstorage = TYPSTORAGE_MAIN;
22393 4 : else if (pg_strcasecmp(storagemode, "default") == 0)
22394 4 : cstorage = get_typstorage(atttypid);
22395 : else
22396 0 : ereport(ERROR,
22397 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22398 : errmsg("invalid storage type \"%s\"",
22399 : storagemode)));
22400 :
22401 : /*
22402 : * safety check: do not allow toasted storage modes unless column datatype
22403 : * is TOAST-aware.
22404 : */
22405 204 : if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
22406 4 : ereport(ERROR,
22407 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22408 : errmsg("column data type %s can only have storage PLAIN",
22409 : format_type_be(atttypid))));
22410 :
22411 200 : return cstorage;
22412 : }
22413 :
22414 : /*
22415 : * buildExpressionExecutionStates: build the needed expression execution states
22416 : * for new partition (newPartRel) checks and initialize expressions for
22417 : * generated columns. All expressions should be created in "tab"
22418 : * (AlteredTableInfo structure).
22419 : */
22420 : static void
22421 432 : buildExpressionExecutionStates(AlteredTableInfo *tab, Relation newPartRel, EState *estate)
22422 : {
22423 : /*
22424 : * Build the needed expression execution states. Here, we expect only NOT
22425 : * NULL and CHECK constraint.
22426 : */
22427 880 : foreach_ptr(NewConstraint, con, tab->constraints)
22428 : {
22429 16 : switch (con->contype)
22430 : {
22431 16 : case CONSTR_CHECK:
22432 :
22433 : /*
22434 : * We already expanded virtual expression in
22435 : * createTableConstraints.
22436 : */
22437 16 : con->qualstate = ExecPrepareExpr((Expr *) con->qual, estate);
22438 16 : break;
22439 0 : case CONSTR_NOTNULL:
22440 : /* Nothing to do here. */
22441 0 : break;
22442 0 : default:
22443 0 : elog(ERROR, "unrecognized constraint type: %d",
22444 : (int) con->contype);
22445 : }
22446 : }
22447 :
22448 : /* Expression already planned in createTableConstraints */
22449 908 : foreach_ptr(NewColumnValue, ex, tab->newvals)
22450 44 : ex->exprstate = ExecInitExpr((Expr *) ex->expr, NULL);
22451 432 : }
22452 :
22453 : /*
22454 : * evaluateGeneratedExpressionsAndCheckConstraints: evaluate any generated
22455 : * expressions for "tab" (AlteredTableInfo structure) whose inputs come from
22456 : * the new tuple (insertslot) of the new partition (newPartRel).
22457 : */
22458 : static void
22459 664 : evaluateGeneratedExpressionsAndCheckConstraints(AlteredTableInfo *tab,
22460 : Relation newPartRel,
22461 : TupleTableSlot *insertslot,
22462 : ExprContext *econtext)
22463 : {
22464 664 : econtext->ecxt_scantuple = insertslot;
22465 :
22466 1392 : foreach_ptr(NewColumnValue, ex, tab->newvals)
22467 : {
22468 64 : if (!ex->is_generated)
22469 0 : continue;
22470 :
22471 64 : insertslot->tts_values[ex->attnum - 1]
22472 64 : = ExecEvalExpr(ex->exprstate,
22473 : econtext,
22474 64 : &insertslot->tts_isnull[ex->attnum - 1]);
22475 : }
22476 :
22477 1352 : foreach_ptr(NewConstraint, con, tab->constraints)
22478 : {
22479 24 : switch (con->contype)
22480 : {
22481 24 : case CONSTR_CHECK:
22482 24 : if (!ExecCheck(con->qualstate, econtext))
22483 0 : ereport(ERROR,
22484 : errcode(ERRCODE_CHECK_VIOLATION),
22485 : errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
22486 : con->name, RelationGetRelationName(newPartRel)),
22487 : errtableconstraint(newPartRel, con->name));
22488 24 : break;
22489 0 : case CONSTR_NOTNULL:
22490 : case CONSTR_FOREIGN:
22491 : /* Nothing to do here */
22492 0 : break;
22493 0 : default:
22494 0 : elog(ERROR, "unrecognized constraint type: %d",
22495 : (int) con->contype);
22496 : }
22497 : }
22498 664 : }
22499 :
22500 : /*
22501 : * getAttributesList: build a list of columns (ColumnDef) based on parent_rel
22502 : */
22503 : static List *
22504 452 : getAttributesList(Relation parent_rel)
22505 : {
22506 : AttrNumber parent_attno;
22507 : TupleDesc modelDesc;
22508 452 : List *colList = NIL;
22509 :
22510 452 : modelDesc = RelationGetDescr(parent_rel);
22511 :
22512 1609 : for (parent_attno = 1; parent_attno <= modelDesc->natts;
22513 1157 : parent_attno++)
22514 : {
22515 1157 : Form_pg_attribute attribute = TupleDescAttr(modelDesc,
22516 : parent_attno - 1);
22517 : ColumnDef *def;
22518 :
22519 : /* Ignore dropped columns in the parent. */
22520 1157 : if (attribute->attisdropped)
22521 0 : continue;
22522 :
22523 1157 : def = makeColumnDef(NameStr(attribute->attname), attribute->atttypid,
22524 : attribute->atttypmod, attribute->attcollation);
22525 :
22526 1157 : def->is_not_null = attribute->attnotnull;
22527 :
22528 : /* Copy identity. */
22529 1157 : def->identity = attribute->attidentity;
22530 :
22531 : /* Copy attgenerated. */
22532 1157 : def->generated = attribute->attgenerated;
22533 :
22534 1157 : def->storage = attribute->attstorage;
22535 :
22536 : /* Likewise, copy compression. */
22537 1157 : if (CompressionMethodIsValid(attribute->attcompression))
22538 12 : def->compression =
22539 12 : pstrdup(GetCompressionMethodName(attribute->attcompression));
22540 : else
22541 1145 : def->compression = NULL;
22542 :
22543 : /* Add to column list. */
22544 1157 : colList = lappend(colList, def);
22545 : }
22546 :
22547 452 : return colList;
22548 : }
22549 :
22550 : /*
22551 : * createTableConstraints:
22552 : * create check constraints, default values, and generated values for newRel
22553 : * based on parent_rel. tab is pending-work queue for newRel, we may need it in
22554 : * MergePartitionsMoveRows.
22555 : */
22556 : static void
22557 432 : createTableConstraints(List **wqueue, AlteredTableInfo *tab,
22558 : Relation parent_rel, Relation newRel)
22559 : {
22560 : TupleDesc tupleDesc;
22561 : TupleConstr *constr;
22562 : AttrMap *attmap;
22563 : AttrNumber parent_attno;
22564 : int ccnum;
22565 432 : List *constraints = NIL;
22566 432 : List *cookedConstraints = NIL;
22567 :
22568 432 : tupleDesc = RelationGetDescr(parent_rel);
22569 432 : constr = tupleDesc->constr;
22570 :
22571 432 : if (!constr)
22572 276 : return;
22573 :
22574 : /*
22575 : * Construct a map from the parent relation's attnos to the child rel's.
22576 : * This re-checks type match, etc, although it shouldn't be possible to
22577 : * have a failure since both tables are locked.
22578 : */
22579 156 : attmap = build_attrmap_by_name(RelationGetDescr(newRel),
22580 : tupleDesc,
22581 : false);
22582 :
22583 : /* Cycle for default values. */
22584 592 : for (parent_attno = 1; parent_attno <= tupleDesc->natts; parent_attno++)
22585 : {
22586 436 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
22587 : parent_attno - 1);
22588 :
22589 : /* Ignore dropped columns in the parent. */
22590 436 : if (attribute->attisdropped)
22591 0 : continue;
22592 :
22593 : /* Copy the default, if present, and it should be copied. */
22594 436 : if (attribute->atthasdef)
22595 : {
22596 100 : Node *this_default = NULL;
22597 : bool found_whole_row;
22598 : AttrNumber num;
22599 : Node *def;
22600 : NewColumnValue *newval;
22601 :
22602 100 : if (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
22603 4 : this_default = build_generation_expression(parent_rel, attribute->attnum);
22604 : else
22605 : {
22606 96 : this_default = TupleDescGetDefault(tupleDesc, attribute->attnum);
22607 96 : if (this_default == NULL)
22608 0 : elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
22609 : attribute->attnum, RelationGetRelationName(parent_rel));
22610 : }
22611 :
22612 100 : num = attmap->attnums[parent_attno - 1];
22613 100 : def = map_variable_attnos(this_default, 1, 0, attmap, InvalidOid, &found_whole_row);
22614 :
22615 100 : if (found_whole_row && attribute->attgenerated != '\0')
22616 0 : elog(ERROR, "cannot convert whole-row table reference");
22617 :
22618 : /* Add a pre-cooked default expression. */
22619 100 : StoreAttrDefault(newRel, num, def, true);
22620 :
22621 : /*
22622 : * Stored generated column expressions in parent_rel might
22623 : * reference the tableoid. newRel, parent_rel tableoid clear is
22624 : * not the same. If so, these stored generated columns require
22625 : * recomputation for newRel within MergePartitionsMoveRows.
22626 : */
22627 100 : if (attribute->attgenerated == ATTRIBUTE_GENERATED_STORED)
22628 : {
22629 44 : newval = palloc0_object(NewColumnValue);
22630 44 : newval->attnum = num;
22631 44 : newval->expr = expression_planner((Expr *) def);
22632 44 : newval->is_generated = (attribute->attgenerated != '\0');
22633 44 : tab->newvals = lappend(tab->newvals, newval);
22634 : }
22635 : }
22636 : }
22637 :
22638 : /* Cycle for CHECK constraints. */
22639 224 : for (ccnum = 0; ccnum < constr->num_check; ccnum++)
22640 : {
22641 68 : char *ccname = constr->check[ccnum].ccname;
22642 68 : char *ccbin = constr->check[ccnum].ccbin;
22643 68 : bool ccenforced = constr->check[ccnum].ccenforced;
22644 68 : bool ccnoinherit = constr->check[ccnum].ccnoinherit;
22645 68 : bool ccvalid = constr->check[ccnum].ccvalid;
22646 : Node *ccbin_node;
22647 : bool found_whole_row;
22648 : Constraint *con;
22649 :
22650 : /*
22651 : * The partitioned table can not have a NO INHERIT check constraint
22652 : * (see StoreRelCheck function for details).
22653 : */
22654 : Assert(!ccnoinherit);
22655 :
22656 68 : ccbin_node = map_variable_attnos(stringToNode(ccbin),
22657 : 1, 0,
22658 : attmap,
22659 : InvalidOid, &found_whole_row);
22660 :
22661 : /*
22662 : * For the moment we have to reject whole-row variables (as for CREATE
22663 : * TABLE LIKE and inheritances).
22664 : */
22665 68 : if (found_whole_row)
22666 0 : elog(ERROR, "Constraint \"%s\" contains a whole-row reference to table \"%s\".",
22667 : ccname,
22668 : RelationGetRelationName(parent_rel));
22669 :
22670 68 : con = makeNode(Constraint);
22671 68 : con->contype = CONSTR_CHECK;
22672 68 : con->conname = pstrdup(ccname);
22673 68 : con->deferrable = false;
22674 68 : con->initdeferred = false;
22675 68 : con->is_enforced = ccenforced;
22676 68 : con->skip_validation = !ccvalid;
22677 68 : con->initially_valid = ccvalid;
22678 68 : con->is_no_inherit = ccnoinherit;
22679 68 : con->raw_expr = NULL;
22680 68 : con->cooked_expr = nodeToString(ccbin_node);
22681 68 : con->location = -1;
22682 68 : constraints = lappend(constraints, con);
22683 : }
22684 :
22685 : /* Install all CHECK constraints. */
22686 156 : cookedConstraints = AddRelationNewConstraints(newRel, NIL, constraints,
22687 : false, true, true, NULL);
22688 :
22689 : /* Make the additional catalog changes visible. */
22690 156 : CommandCounterIncrement();
22691 :
22692 : /*
22693 : * parent_rel check constraint expression may reference tableoid, so later
22694 : * in MergePartitionsMoveRows, we need to evaluate the check constraint
22695 : * again for the newRel. We can check whether the check constraint
22696 : * contains a tableoid reference via pull_varattnos.
22697 : */
22698 380 : foreach_ptr(CookedConstraint, ccon, cookedConstraints)
22699 : {
22700 68 : if (!ccon->skip_validation)
22701 : {
22702 : Node *qual;
22703 44 : Bitmapset *attnums = NULL;
22704 :
22705 : Assert(ccon->contype == CONSTR_CHECK);
22706 44 : qual = expand_generated_columns_in_expr(ccon->expr, newRel, 1);
22707 44 : pull_varattnos(qual, 1, &attnums);
22708 :
22709 : /*
22710 : * Add a check only if it contains a tableoid
22711 : * (TableOidAttributeNumber).
22712 : */
22713 44 : if (bms_is_member(TableOidAttributeNumber - FirstLowInvalidHeapAttributeNumber,
22714 : attnums))
22715 : {
22716 : NewConstraint *newcon;
22717 :
22718 16 : newcon = palloc0_object(NewConstraint);
22719 16 : newcon->name = ccon->name;
22720 16 : newcon->contype = CONSTR_CHECK;
22721 16 : newcon->qual = qual;
22722 :
22723 16 : tab->constraints = lappend(tab->constraints, newcon);
22724 : }
22725 : }
22726 : }
22727 :
22728 : /* Don't need the cookedConstraints anymore. */
22729 156 : list_free_deep(cookedConstraints);
22730 :
22731 : /* Reproduce not-null constraints. */
22732 156 : if (constr->has_not_null)
22733 : {
22734 : List *nnconstraints;
22735 :
22736 : /*
22737 : * The "include_noinh" argument is false because a partitioned table
22738 : * can't have NO INHERIT constraint.
22739 : */
22740 108 : nnconstraints = RelationGetNotNullConstraints(RelationGetRelid(parent_rel),
22741 : false, false);
22742 :
22743 : Assert(list_length(nnconstraints) > 0);
22744 :
22745 : /*
22746 : * We already set pg_attribute.attnotnull in createPartitionTable. No
22747 : * need call set_attnotnull again.
22748 : */
22749 108 : AddRelationNewConstraints(newRel, NIL, nnconstraints, false, true, true, NULL);
22750 : }
22751 : }
22752 :
22753 : /*
22754 : * createPartitionTable:
22755 : *
22756 : * Create a new partition (newPartName) for the partitioned table (parent_rel).
22757 : * ownerId is determined by the partition on which the operation is performed,
22758 : * so it is passed separately. The new partition will inherit the access method
22759 : * and persistence type from the parent table.
22760 : *
22761 : * Returns the created relation (locked in AccessExclusiveLock mode).
22762 : */
22763 : static Relation
22764 452 : createPartitionTable(List **wqueue, RangeVar *newPartName,
22765 : Relation parent_rel, Oid ownerId)
22766 : {
22767 : Relation newRel;
22768 : Oid newRelId;
22769 : Oid existingRelid;
22770 : TupleDesc descriptor;
22771 452 : List *colList = NIL;
22772 : Oid relamId;
22773 : Oid namespaceId;
22774 : AlteredTableInfo *new_partrel_tab;
22775 452 : Form_pg_class parent_relform = parent_rel->rd_rel;
22776 :
22777 : /* If the existing rel is temp, it must belong to this session. */
22778 452 : if (RELATION_IS_OTHER_TEMP(parent_rel))
22779 0 : ereport(ERROR,
22780 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
22781 : errmsg("cannot create as partition of temporary relation of another session"));
22782 :
22783 : /* Look up inheritance ancestors and generate the relation schema. */
22784 452 : colList = getAttributesList(parent_rel);
22785 :
22786 : /* Create a tuple descriptor from the relation schema. */
22787 452 : descriptor = BuildDescForRelation(colList);
22788 :
22789 : /* Look up the access method for the new relation. */
22790 452 : relamId = (parent_relform->relam != InvalidOid) ? parent_relform->relam : HEAP_TABLE_AM_OID;
22791 :
22792 : /* Look up the namespace in which we are supposed to create the relation. */
22793 : namespaceId =
22794 452 : RangeVarGetAndCheckCreationNamespace(newPartName, NoLock, &existingRelid);
22795 452 : if (OidIsValid(existingRelid))
22796 0 : ereport(ERROR,
22797 : errcode(ERRCODE_DUPLICATE_TABLE),
22798 : errmsg("relation \"%s\" already exists", newPartName->relname));
22799 :
22800 : /*
22801 : * We intended to create the partition with the same persistence as the
22802 : * parent table, but we still need to recheck because that might be
22803 : * affected by the search_path. If the parent is permanent, so must be
22804 : * all of its partitions.
22805 : */
22806 452 : if (parent_relform->relpersistence != RELPERSISTENCE_TEMP &&
22807 416 : newPartName->relpersistence == RELPERSISTENCE_TEMP)
22808 8 : ereport(ERROR,
22809 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
22810 : errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
22811 : RelationGetRelationName(parent_rel)));
22812 :
22813 : /* Permanent rels cannot be partitions belonging to a temporary parent. */
22814 444 : if (newPartName->relpersistence != RELPERSISTENCE_TEMP &&
22815 420 : parent_relform->relpersistence == RELPERSISTENCE_TEMP)
22816 12 : ereport(ERROR,
22817 : errcode(ERRCODE_WRONG_OBJECT_TYPE),
22818 : errmsg("cannot create a permanent relation as partition of temporary relation \"%s\"",
22819 : RelationGetRelationName(parent_rel)));
22820 :
22821 : /* Create the relation. */
22822 432 : newRelId = heap_create_with_catalog(newPartName->relname,
22823 : namespaceId,
22824 : parent_relform->reltablespace,
22825 : InvalidOid,
22826 : InvalidOid,
22827 : InvalidOid,
22828 : ownerId,
22829 : relamId,
22830 : descriptor,
22831 : NIL,
22832 : RELKIND_RELATION,
22833 432 : newPartName->relpersistence,
22834 : false,
22835 : false,
22836 : ONCOMMIT_NOOP,
22837 : (Datum) 0,
22838 : true,
22839 : allowSystemTableMods,
22840 : true,
22841 : InvalidOid,
22842 : NULL);
22843 :
22844 : /*
22845 : * We must bump the command counter to make the newly-created relation
22846 : * tuple visible for opening.
22847 : */
22848 432 : CommandCounterIncrement();
22849 :
22850 : /*
22851 : * Open the new partition with no lock, because we already have an
22852 : * AccessExclusiveLock placed there after creation.
22853 : */
22854 432 : newRel = table_open(newRelId, NoLock);
22855 :
22856 : /* Find or create a work queue entry for the newly created table. */
22857 432 : new_partrel_tab = ATGetQueueEntry(wqueue, newRel);
22858 :
22859 : /* Create constraints, default values, and generated values. */
22860 432 : createTableConstraints(wqueue, new_partrel_tab, parent_rel, newRel);
22861 :
22862 : /*
22863 : * Need to call CommandCounterIncrement, so a fresh relcache entry has
22864 : * newly installed constraint info.
22865 : */
22866 432 : CommandCounterIncrement();
22867 :
22868 432 : return newRel;
22869 : }
22870 :
22871 : /*
22872 : * MergePartitionsMoveRows: scan partitions to be merged (mergingPartitions)
22873 : * of the partitioned table and move rows into the new partition
22874 : * (newPartRel). We also verify check constraints against these rows.
22875 : */
22876 : static void
22877 90 : MergePartitionsMoveRows(List **wqueue, List *mergingPartitions, Relation newPartRel)
22878 : {
22879 : CommandId mycid;
22880 : EState *estate;
22881 : AlteredTableInfo *tab;
22882 : ListCell *ltab;
22883 :
22884 : /* The FSM is empty, so don't bother using it. */
22885 90 : uint32 ti_options = TABLE_INSERT_SKIP_FSM;
22886 : BulkInsertState bistate; /* state of bulk inserts for partition */
22887 : TupleTableSlot *dstslot;
22888 :
22889 : /* Find the work queue entry for the new partition table: newPartRel. */
22890 90 : tab = ATGetQueueEntry(wqueue, newPartRel);
22891 :
22892 : /* Generate the constraint and default execution states. */
22893 90 : estate = CreateExecutorState();
22894 :
22895 90 : buildExpressionExecutionStates(tab, newPartRel, estate);
22896 :
22897 90 : mycid = GetCurrentCommandId(true);
22898 :
22899 : /* Prepare a BulkInsertState for table_tuple_insert. */
22900 90 : bistate = GetBulkInsertState();
22901 :
22902 : /* Create the necessary tuple slot. */
22903 90 : dstslot = table_slot_create(newPartRel, NULL);
22904 :
22905 388 : foreach_oid(merging_oid, mergingPartitions)
22906 : {
22907 : ExprContext *econtext;
22908 : TupleTableSlot *srcslot;
22909 : TupleConversionMap *tuple_map;
22910 : TableScanDesc scan;
22911 : MemoryContext oldCxt;
22912 : Snapshot snapshot;
22913 : Relation mergingPartition;
22914 :
22915 208 : econtext = GetPerTupleExprContext(estate);
22916 :
22917 : /*
22918 : * Partition is already locked in the transformPartitionCmdForMerge
22919 : * function.
22920 : */
22921 208 : mergingPartition = table_open(merging_oid, NoLock);
22922 :
22923 : /* Create a source tuple slot for the partition being merged. */
22924 208 : srcslot = table_slot_create(mergingPartition, NULL);
22925 :
22926 : /*
22927 : * Map computing for moving attributes of the merged partition to the
22928 : * new partition.
22929 : */
22930 208 : tuple_map = convert_tuples_by_name(RelationGetDescr(mergingPartition),
22931 : RelationGetDescr(newPartRel));
22932 :
22933 : /* Scan through the rows. */
22934 208 : snapshot = RegisterSnapshot(GetLatestSnapshot());
22935 208 : scan = table_beginscan(mergingPartition, snapshot, 0, NULL,
22936 : SO_NONE);
22937 :
22938 : /*
22939 : * Switch to per-tuple memory context and reset it for each tuple
22940 : * produced, so we don't leak memory.
22941 : */
22942 208 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
22943 :
22944 449 : while (table_scan_getnextslot(scan, ForwardScanDirection, srcslot))
22945 : {
22946 : TupleTableSlot *insertslot;
22947 :
22948 241 : CHECK_FOR_INTERRUPTS();
22949 :
22950 241 : if (tuple_map)
22951 : {
22952 : /* Need to use a map to copy attributes. */
22953 28 : insertslot = execute_attr_map_slot(tuple_map->attrMap, srcslot, dstslot);
22954 : }
22955 : else
22956 : {
22957 213 : slot_getallattrs(srcslot);
22958 :
22959 : /* Copy attributes directly. */
22960 213 : insertslot = dstslot;
22961 :
22962 213 : ExecClearTuple(insertslot);
22963 :
22964 213 : memcpy(insertslot->tts_values, srcslot->tts_values,
22965 213 : sizeof(Datum) * srcslot->tts_nvalid);
22966 213 : memcpy(insertslot->tts_isnull, srcslot->tts_isnull,
22967 213 : sizeof(bool) * srcslot->tts_nvalid);
22968 :
22969 213 : ExecStoreVirtualTuple(insertslot);
22970 : }
22971 :
22972 : /*
22973 : * Constraints and GENERATED expressions might reference the
22974 : * tableoid column, so fill tts_tableOid with the desired value.
22975 : * (We must do this each time, because it gets overwritten with
22976 : * newrel's OID during storing.)
22977 : */
22978 241 : insertslot->tts_tableOid = RelationGetRelid(newPartRel);
22979 :
22980 : /*
22981 : * Now, evaluate any generated expressions whose inputs come from
22982 : * the new tuple. We assume these columns won't reference each
22983 : * other, so that there's no ordering dependency.
22984 : */
22985 241 : evaluateGeneratedExpressionsAndCheckConstraints(tab, newPartRel,
22986 : insertslot, econtext);
22987 :
22988 : /* Write the tuple out to the new relation. */
22989 241 : table_tuple_insert(newPartRel, insertslot, mycid,
22990 : ti_options, bistate);
22991 :
22992 241 : ResetExprContext(econtext);
22993 : }
22994 :
22995 208 : MemoryContextSwitchTo(oldCxt);
22996 208 : table_endscan(scan);
22997 208 : UnregisterSnapshot(snapshot);
22998 :
22999 208 : if (tuple_map)
23000 20 : free_conversion_map(tuple_map);
23001 :
23002 208 : ExecDropSingleTupleTableSlot(srcslot);
23003 208 : table_close(mergingPartition, NoLock);
23004 : }
23005 :
23006 90 : FreeExecutorState(estate);
23007 90 : ExecDropSingleTupleTableSlot(dstslot);
23008 90 : FreeBulkInsertState(bistate);
23009 :
23010 90 : table_finish_bulk_insert(newPartRel, ti_options);
23011 :
23012 : /*
23013 : * We don't need to process this newPartRel since we already processed it
23014 : * here, so delete the ALTER TABLE queue for it.
23015 : */
23016 180 : foreach(ltab, *wqueue)
23017 : {
23018 180 : tab = (AlteredTableInfo *) lfirst(ltab);
23019 180 : if (tab->relid == RelationGetRelid(newPartRel))
23020 : {
23021 90 : *wqueue = list_delete_cell(*wqueue, ltab);
23022 90 : break;
23023 : }
23024 : }
23025 90 : }
23026 :
23027 : /*
23028 : * detachPartitionTable: detach partition "child_rel" from partitioned table
23029 : * "parent_rel" with default partition identifier "defaultPartOid"
23030 : */
23031 : static void
23032 377 : detachPartitionTable(Relation parent_rel, Relation child_rel, Oid defaultPartOid)
23033 : {
23034 : /* Remove the pg_inherits row first. */
23035 377 : RemoveInheritance(child_rel, parent_rel, false);
23036 :
23037 : /*
23038 : * Detaching the partition might involve TOAST table access, so ensure we
23039 : * have a valid snapshot.
23040 : */
23041 377 : PushActiveSnapshot(GetTransactionSnapshot());
23042 :
23043 : /* Do the final part of detaching. */
23044 377 : DetachPartitionFinalize(parent_rel, child_rel, false, defaultPartOid);
23045 :
23046 377 : PopActiveSnapshot();
23047 377 : }
23048 :
23049 : /*
23050 : * equal_oid_lists: return true if two OID lists, each sorted in ascending
23051 : * order, contain the same OIDs in the same order.
23052 : */
23053 : static bool
23054 86 : equal_oid_lists(const List *a, const List *b)
23055 : {
23056 : ListCell *la,
23057 : *lb;
23058 :
23059 86 : if (list_length(a) != list_length(b))
23060 4 : return false;
23061 :
23062 86 : forboth(la, a, lb, b)
23063 : {
23064 6 : if (lfirst_oid(la) != lfirst_oid(lb))
23065 2 : return false;
23066 : }
23067 80 : return true;
23068 : }
23069 :
23070 : /*
23071 : * Comparator for list_sort() on a list of PartitionIndexExtDepEntry *.
23072 : * Orders by parentIndexOid, then by indexOid as a tiebreaker so conflict
23073 : * reports for different parent indexes are deterministic.
23074 : */
23075 : static int
23076 145 : cmp_partition_index_ext_dep(const ListCell *a, const ListCell *b)
23077 : {
23078 145 : const PartitionIndexExtDepEntry *ea = lfirst(a);
23079 145 : const PartitionIndexExtDepEntry *eb = lfirst(b);
23080 :
23081 145 : if (ea->parentIndexOid != eb->parentIndexOid)
23082 53 : return pg_cmp_u32(ea->parentIndexOid, eb->parentIndexOid);
23083 92 : return pg_cmp_u32(ea->indexOid, eb->indexOid);
23084 : }
23085 :
23086 : /*
23087 : * collectPartitionIndexExtDeps: collect extension dependencies from indexes
23088 : * on the given partitions.
23089 : *
23090 : * For each partition index that has a parent partitioned index, we collect
23091 : * extension dependencies. All source partition indexes sharing the same
23092 : * parent partitioned index must depend on exactly the same set of
23093 : * extensions; otherwise an error is raised so that we neither silently drop
23094 : * nor silently add dependencies on the merged partition's index.
23095 : *
23096 : * Indexes that don't have a parent partitioned index (i.e., indexes created
23097 : * directly on a partition without a corresponding parent index) are skipped.
23098 : *
23099 : * The returned list is sorted by parentIndexOid with exactly one entry per
23100 : * parent partitioned index, so applyPartitionIndexExtDeps() can scan it
23101 : * linearly.
23102 : */
23103 : static List *
23104 245 : collectPartitionIndexExtDeps(List *partitionOids)
23105 : {
23106 245 : List *collected = NIL;
23107 245 : List *result = NIL;
23108 245 : PartitionIndexExtDepEntry *prev = NULL;
23109 :
23110 : /*
23111 : * Phase 1: collect one entry per (partition index -> parent index) pair,
23112 : * with its extension dependency OIDs sorted ascending.
23113 : */
23114 879 : foreach_oid(partOid, partitionOids)
23115 : {
23116 : Relation partRel;
23117 : List *indexList;
23118 :
23119 : /*
23120 : * Use NoLock since the caller already holds AccessExclusiveLock on
23121 : * these partitions.
23122 : */
23123 389 : partRel = table_open(partOid, NoLock);
23124 389 : indexList = RelationGetIndexList(partRel);
23125 :
23126 977 : foreach_oid(indexOid, indexList)
23127 : {
23128 : Oid parentIndexOid;
23129 : PartitionIndexExtDepEntry *entry;
23130 :
23131 199 : if (!get_rel_relispartition(indexOid))
23132 1 : continue;
23133 :
23134 198 : parentIndexOid = get_partition_parent(indexOid, true);
23135 198 : if (!OidIsValid(parentIndexOid))
23136 0 : continue;
23137 :
23138 198 : entry = palloc(sizeof(PartitionIndexExtDepEntry));
23139 198 : entry->parentIndexOid = parentIndexOid;
23140 198 : entry->indexOid = indexOid;
23141 198 : entry->extensionOids = getAutoExtensionsOfObject(RelationRelationId,
23142 : indexOid);
23143 198 : list_sort(entry->extensionOids, list_oid_cmp);
23144 :
23145 198 : collected = lappend(collected, entry);
23146 : }
23147 :
23148 389 : list_free(indexList);
23149 389 : table_close(partRel, NoLock);
23150 : }
23151 :
23152 : /*
23153 : * Phase 2: sort by parentIndexOid so entries sharing a parent index sit
23154 : * adjacent.
23155 : */
23156 245 : list_sort(collected, cmp_partition_index_ext_dep);
23157 :
23158 : /*
23159 : * Phase 3: single linear pass verifying that adjacent entries sharing a
23160 : * parent index have identical extension dependencies, and keeping one
23161 : * representative entry per parent index.
23162 : */
23163 664 : foreach_ptr(PartitionIndexExtDepEntry, entry, collected)
23164 : {
23165 186 : if (prev != NULL && prev->parentIndexOid == entry->parentIndexOid)
23166 : {
23167 86 : if (!equal_oid_lists(prev->extensionOids, entry->extensionOids))
23168 6 : ereport(ERROR,
23169 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
23170 : errmsg("cannot merge partitions with conflicting extension dependencies"),
23171 : errdetail("Partition indexes \"%s\" and \"%s\" depend on different extensions.",
23172 : get_rel_name(prev->indexOid),
23173 : get_rel_name(entry->indexOid))));
23174 :
23175 : /* Duplicate entry for the same parent index; discard. */
23176 80 : list_free(entry->extensionOids);
23177 80 : pfree(entry);
23178 80 : continue;
23179 : }
23180 :
23181 100 : result = lappend(result, entry);
23182 100 : prev = entry;
23183 : }
23184 :
23185 239 : list_free(collected);
23186 :
23187 239 : return result;
23188 : }
23189 :
23190 : /*
23191 : * applyPartitionIndexExtDeps: apply collected extension dependencies to
23192 : * indexes on a new partition.
23193 : *
23194 : * For each index on the new partition, look up its parent index in the
23195 : * extDepState list. If found, record extension dependencies on the new index.
23196 : * extDepState is sorted by parentIndexOid, so the inner scan can bail out
23197 : * as soon as it passes the target OID.
23198 : */
23199 : static void
23200 432 : applyPartitionIndexExtDeps(Oid newPartOid, List *extDepState)
23201 : {
23202 : Relation partRel;
23203 : List *indexList;
23204 :
23205 432 : if (extDepState == NIL)
23206 284 : return;
23207 :
23208 : /*
23209 : * Use NoLock since the caller already holds AccessExclusiveLock on the
23210 : * new partition.
23211 : */
23212 148 : partRel = table_open(newPartOid, NoLock);
23213 148 : indexList = RelationGetIndexList(partRel);
23214 :
23215 468 : foreach_oid(indexOid, indexList)
23216 : {
23217 : Oid parentIdxOid;
23218 :
23219 172 : if (!get_rel_relispartition(indexOid))
23220 0 : continue;
23221 :
23222 172 : parentIdxOid = get_partition_parent(indexOid, true);
23223 172 : if (!OidIsValid(parentIdxOid))
23224 0 : continue;
23225 :
23226 368 : foreach_ptr(PartitionIndexExtDepEntry, entry, extDepState)
23227 : {
23228 : ObjectAddress indexAddr;
23229 :
23230 196 : if (entry->parentIndexOid > parentIdxOid)
23231 172 : break;
23232 196 : if (entry->parentIndexOid < parentIdxOid)
23233 24 : continue;
23234 :
23235 172 : ObjectAddressSet(indexAddr, RelationRelationId, indexOid);
23236 :
23237 352 : foreach_oid(extOid, entry->extensionOids)
23238 : {
23239 : ObjectAddress extAddr;
23240 :
23241 8 : ObjectAddressSet(extAddr, ExtensionRelationId, extOid);
23242 8 : recordDependencyOn(&indexAddr, &extAddr,
23243 : DEPENDENCY_AUTO_EXTENSION);
23244 : }
23245 172 : break;
23246 : }
23247 : }
23248 :
23249 148 : list_free(indexList);
23250 148 : table_close(partRel, NoLock);
23251 : }
23252 :
23253 : /*
23254 : * freePartitionIndexExtDeps: free memory allocated by collectPartitionIndexExtDeps.
23255 : */
23256 : static void
23257 215 : freePartitionIndexExtDeps(List *extDepState)
23258 : {
23259 524 : foreach_ptr(PartitionIndexExtDepEntry, entry, extDepState)
23260 : {
23261 94 : list_free(entry->extensionOids);
23262 94 : pfree(entry);
23263 : }
23264 215 : list_free(extDepState);
23265 215 : }
23266 :
23267 : /*
23268 : * ALTER TABLE <name> MERGE PARTITIONS <partition-list> INTO <partition-name>
23269 : */
23270 : static void
23271 124 : ATExecMergePartitions(List **wqueue, AlteredTableInfo *tab, Relation rel,
23272 : PartitionCmd *cmd, AlterTableUtilityContext *context)
23273 : {
23274 : Relation newPartRel;
23275 124 : List *mergingPartitions = NIL;
23276 124 : List *extDepState = NIL;
23277 : Oid defaultPartOid;
23278 : Oid existingRelid;
23279 124 : Oid ownerId = InvalidOid;
23280 : Oid save_userid;
23281 : int save_sec_context;
23282 : int save_nestlevel;
23283 :
23284 : /*
23285 : * Check ownership of merged partitions - partitions with different owners
23286 : * cannot be merged. Also, collect the OIDs of these partitions during the
23287 : * check.
23288 : */
23289 520 : foreach_node(RangeVar, name, cmd->partlist)
23290 : {
23291 : Relation mergingPartition;
23292 :
23293 : /*
23294 : * We are going to detach and remove this partition. We already took
23295 : * AccessExclusiveLock lock on transformPartitionCmdForMerge, so here,
23296 : * NoLock is fine.
23297 : */
23298 280 : mergingPartition = table_openrv_extended(name, NoLock, false);
23299 : Assert(CheckRelationLockedByMe(mergingPartition, AccessExclusiveLock, false));
23300 :
23301 280 : if (OidIsValid(ownerId))
23302 : {
23303 : /* Do the partitions being merged have different owners? */
23304 156 : if (ownerId != mergingPartition->rd_rel->relowner)
23305 4 : ereport(ERROR,
23306 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
23307 : errmsg("partitions being merged have different owners"));
23308 : }
23309 : else
23310 124 : ownerId = mergingPartition->rd_rel->relowner;
23311 :
23312 : /* Store the next merging partition into the list. */
23313 276 : mergingPartitions = lappend_oid(mergingPartitions,
23314 : RelationGetRelid(mergingPartition));
23315 :
23316 276 : table_close(mergingPartition, NoLock);
23317 : }
23318 :
23319 : /* Look up the existing relation by the new partition name. */
23320 120 : RangeVarGetAndCheckCreationNamespace(cmd->name, NoLock, &existingRelid);
23321 :
23322 : /*
23323 : * Check if this name is already taken. This helps us to detect the
23324 : * situation when one of the merging partitions has the same name as the
23325 : * new partition. Otherwise, this would fail later on anyway, but
23326 : * catching this here allows us to emit a nicer error message.
23327 : */
23328 120 : if (OidIsValid(existingRelid))
23329 : {
23330 17 : if (list_member_oid(mergingPartitions, existingRelid))
23331 : {
23332 : /*
23333 : * The new partition has the same name as one of the merging
23334 : * partitions.
23335 : */
23336 : char tmpRelName[NAMEDATALEN];
23337 :
23338 : /* Generate a temporary name. */
23339 13 : sprintf(tmpRelName, "merge-%u-%X-tmp", RelationGetRelid(rel), MyProcPid);
23340 :
23341 : /*
23342 : * Rename the existing partition with a temporary name, leaving it
23343 : * free for the new partition. We don't need to care about this
23344 : * in the future because we're going to eventually drop the
23345 : * existing partition anyway.
23346 : */
23347 13 : RenameRelationInternal(existingRelid, tmpRelName, true, false);
23348 :
23349 : /*
23350 : * We must bump the command counter to make the new partition
23351 : * tuple visible for rename.
23352 : */
23353 13 : CommandCounterIncrement();
23354 : }
23355 : else
23356 : {
23357 4 : ereport(ERROR,
23358 : errcode(ERRCODE_DUPLICATE_TABLE),
23359 : errmsg("relation \"%s\" already exists", cmd->name->relname));
23360 : }
23361 : }
23362 :
23363 : defaultPartOid =
23364 116 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
23365 :
23366 : /*
23367 : * Collect extension dependencies from indexes on the merging partitions.
23368 : * We must do this before detaching them, so we can restore the
23369 : * dependencies on the new partition's indexes later.
23370 : */
23371 116 : extDepState = collectPartitionIndexExtDeps(mergingPartitions);
23372 :
23373 : /* Detach all merging partitions. */
23374 468 : foreach_oid(mergingPartitionOid, mergingPartitions)
23375 : {
23376 : Relation child_rel;
23377 :
23378 248 : child_rel = table_open(mergingPartitionOid, NoLock);
23379 :
23380 248 : detachPartitionTable(rel, child_rel, defaultPartOid);
23381 :
23382 248 : table_close(child_rel, NoLock);
23383 : }
23384 :
23385 : /*
23386 : * Perform a preliminary check to determine whether it's safe to drop all
23387 : * merging partitions before we actually do so later. After merging rows
23388 : * into the new partitions via MergePartitionsMoveRows, all old partitions
23389 : * need to be dropped. However, since the drop behavior is DROP_RESTRICT
23390 : * and the merge process (MergePartitionsMoveRows) can be time-consuming,
23391 : * performing an early check on the drop eligibility of old partitions is
23392 : * preferable.
23393 : */
23394 456 : foreach_oid(mergingPartitionOid, mergingPartitions)
23395 : {
23396 : ObjectAddress object;
23397 :
23398 : /* Get oid of the later to be dropped relation. */
23399 244 : object.objectId = mergingPartitionOid;
23400 244 : object.classId = RelationRelationId;
23401 244 : object.objectSubId = 0;
23402 :
23403 244 : performDeletionCheck(&object, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
23404 : }
23405 :
23406 : /*
23407 : * Create a table for the new partition, using the partitioned table as a
23408 : * model.
23409 : */
23410 : Assert(OidIsValid(ownerId));
23411 106 : newPartRel = createPartitionTable(wqueue, cmd->name, rel, ownerId);
23412 :
23413 : /*
23414 : * Switch to the table owner's userid, so that any index functions are run
23415 : * as that user. Also, lockdown security-restricted operations and
23416 : * arrange to make GUC variable changes local to this command.
23417 : *
23418 : * Need to do it after determining the namespace in the
23419 : * createPartitionTable() call.
23420 : */
23421 90 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
23422 90 : SetUserIdAndSecContext(ownerId,
23423 : save_sec_context | SECURITY_RESTRICTED_OPERATION);
23424 90 : save_nestlevel = NewGUCNestLevel();
23425 90 : RestrictSearchPath();
23426 :
23427 : /* Copy data from merged partitions to the new partition. */
23428 90 : MergePartitionsMoveRows(wqueue, mergingPartitions, newPartRel);
23429 :
23430 : /* Drop the current partitions before attaching the new one. */
23431 388 : foreach_oid(mergingPartitionOid, mergingPartitions)
23432 : {
23433 : ObjectAddress object;
23434 :
23435 208 : object.objectId = mergingPartitionOid;
23436 208 : object.classId = RelationRelationId;
23437 208 : object.objectSubId = 0;
23438 :
23439 208 : performDeletion(&object, DROP_RESTRICT, 0);
23440 : }
23441 :
23442 90 : list_free(mergingPartitions);
23443 :
23444 : /*
23445 : * Attach a new partition to the partitioned table. wqueue = NULL:
23446 : * verification for each cloned constraint is not needed.
23447 : */
23448 90 : attachPartitionTable(NULL, rel, newPartRel, cmd->bound);
23449 :
23450 : /*
23451 : * Apply extension dependencies to the new partition's indexes. This
23452 : * preserves any "DEPENDS ON EXTENSION" settings from the merged
23453 : * partitions.
23454 : */
23455 90 : applyPartitionIndexExtDeps(RelationGetRelid(newPartRel), extDepState);
23456 :
23457 90 : freePartitionIndexExtDeps(extDepState);
23458 :
23459 : /* Keep the lock until commit. */
23460 90 : table_close(newPartRel, NoLock);
23461 :
23462 : /* Roll back any GUC changes executed by index functions. */
23463 90 : AtEOXact_GUC(false, save_nestlevel);
23464 :
23465 : /* Restore the userid and security context. */
23466 90 : SetUserIdAndSecContext(save_userid, save_sec_context);
23467 90 : }
23468 :
23469 : /*
23470 : * Struct with the context of the new partition for inserting rows from the
23471 : * split partition.
23472 : */
23473 : typedef struct SplitPartitionContext
23474 : {
23475 : ExprState *partqualstate; /* expression for checking a slot for a
23476 : * partition (NULL for DEFAULT partition) */
23477 : BulkInsertState bistate; /* state of bulk inserts for partition */
23478 : TupleTableSlot *dstslot; /* slot for inserting row into partition */
23479 : AlteredTableInfo *tab; /* structure with generated column expressions
23480 : * and check constraint expressions. */
23481 : Relation partRel; /* relation for partition */
23482 : } SplitPartitionContext;
23483 :
23484 : /*
23485 : * createSplitPartitionContext: create context for partition and fill it
23486 : */
23487 : static SplitPartitionContext *
23488 342 : createSplitPartitionContext(Relation partRel)
23489 : {
23490 : SplitPartitionContext *pc;
23491 :
23492 342 : pc = palloc0_object(SplitPartitionContext);
23493 342 : pc->partRel = partRel;
23494 :
23495 : /*
23496 : * Prepare a BulkInsertState for table_tuple_insert. The FSM is empty, so
23497 : * don't bother using it.
23498 : */
23499 342 : pc->bistate = GetBulkInsertState();
23500 :
23501 : /* Create a destination tuple slot for the new partition. */
23502 342 : pc->dstslot = table_slot_create(pc->partRel, NULL);
23503 :
23504 342 : return pc;
23505 : }
23506 :
23507 : /*
23508 : * deleteSplitPartitionContext: delete context for partition
23509 : */
23510 : static void
23511 342 : deleteSplitPartitionContext(SplitPartitionContext *pc, List **wqueue, uint32 ti_options)
23512 : {
23513 : ListCell *ltab;
23514 :
23515 342 : ExecDropSingleTupleTableSlot(pc->dstslot);
23516 342 : FreeBulkInsertState(pc->bistate);
23517 :
23518 342 : table_finish_bulk_insert(pc->partRel, ti_options);
23519 :
23520 : /*
23521 : * We don't need to process this pc->partRel so delete the ALTER TABLE
23522 : * queue of it.
23523 : */
23524 684 : foreach(ltab, *wqueue)
23525 : {
23526 684 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
23527 :
23528 684 : if (tab->relid == RelationGetRelid(pc->partRel))
23529 : {
23530 342 : *wqueue = list_delete_cell(*wqueue, ltab);
23531 342 : break;
23532 : }
23533 : }
23534 :
23535 342 : pfree(pc);
23536 342 : }
23537 :
23538 : /*
23539 : * SplitPartitionMoveRows: scan split partition (splitRel) of partitioned table
23540 : * (rel) and move rows into new partitions.
23541 : *
23542 : * New partitions description:
23543 : * partlist: list of pointers to SinglePartitionSpec structures. It contains
23544 : * the partition specification details for all new partitions.
23545 : * newPartRels: list of Relations, new partitions created in
23546 : * ATExecSplitPartition.
23547 : */
23548 : static void
23549 125 : SplitPartitionMoveRows(List **wqueue, Relation rel, Relation splitRel,
23550 : List *partlist, List *newPartRels)
23551 : {
23552 : /* The FSM is empty, so don't bother using it. */
23553 125 : uint32 ti_options = TABLE_INSERT_SKIP_FSM;
23554 : CommandId mycid;
23555 : EState *estate;
23556 : ListCell *listptr,
23557 : *listptr2;
23558 : TupleTableSlot *srcslot;
23559 : ExprContext *econtext;
23560 : TableScanDesc scan;
23561 : Snapshot snapshot;
23562 : MemoryContext oldCxt;
23563 125 : List *partContexts = NIL;
23564 : TupleConversionMap *tuple_map;
23565 125 : SplitPartitionContext *defaultPartCtx = NULL,
23566 : *pc;
23567 :
23568 125 : mycid = GetCurrentCommandId(true);
23569 :
23570 125 : estate = CreateExecutorState();
23571 :
23572 467 : forboth(listptr, partlist, listptr2, newPartRels)
23573 : {
23574 342 : SinglePartitionSpec *sps = (SinglePartitionSpec *) lfirst(listptr);
23575 :
23576 342 : pc = createSplitPartitionContext((Relation) lfirst(listptr2));
23577 :
23578 : /* Find the work queue entry for the new partition table: newPartRel. */
23579 342 : pc->tab = ATGetQueueEntry(wqueue, pc->partRel);
23580 :
23581 342 : buildExpressionExecutionStates(pc->tab, pc->partRel, estate);
23582 :
23583 342 : if (sps->bound->is_default)
23584 : {
23585 : /*
23586 : * We should not create a structure to check the partition
23587 : * constraint for the new DEFAULT partition.
23588 : */
23589 32 : defaultPartCtx = pc;
23590 : }
23591 : else
23592 : {
23593 : List *partConstraint;
23594 :
23595 : /* Build expression execution states for partition check quals. */
23596 310 : partConstraint = get_qual_from_partbound(rel, sps->bound);
23597 : partConstraint =
23598 310 : (List *) eval_const_expressions(NULL,
23599 : (Node *) partConstraint);
23600 : /* Make a boolean expression for ExecCheck(). */
23601 310 : partConstraint = list_make1(make_ands_explicit(partConstraint));
23602 :
23603 : /*
23604 : * Map the vars in the constraint expression from rel's attnos to
23605 : * splitRel's.
23606 : */
23607 310 : partConstraint = map_partition_varattnos(partConstraint,
23608 : 1, splitRel, rel);
23609 :
23610 310 : pc->partqualstate =
23611 310 : ExecPrepareExpr((Expr *) linitial(partConstraint), estate);
23612 : Assert(pc->partqualstate != NULL);
23613 : }
23614 :
23615 : /* Store partition context into a list. */
23616 342 : partContexts = lappend(partContexts, pc);
23617 : }
23618 :
23619 125 : econtext = GetPerTupleExprContext(estate);
23620 :
23621 : /* Create the necessary tuple slot. */
23622 125 : srcslot = table_slot_create(splitRel, NULL);
23623 :
23624 : /*
23625 : * Map computing for moving attributes of the split partition to the new
23626 : * partition (for the first new partition, but other new partitions can
23627 : * use the same map).
23628 : */
23629 125 : pc = (SplitPartitionContext *) lfirst(list_head(partContexts));
23630 125 : tuple_map = convert_tuples_by_name(RelationGetDescr(splitRel),
23631 125 : RelationGetDescr(pc->partRel));
23632 :
23633 : /* Scan through the rows. */
23634 125 : snapshot = RegisterSnapshot(GetLatestSnapshot());
23635 125 : scan = table_beginscan(splitRel, snapshot, 0, NULL,
23636 : SO_NONE);
23637 :
23638 : /*
23639 : * Switch to per-tuple memory context and reset it for each tuple
23640 : * produced, so we don't leak memory.
23641 : */
23642 125 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
23643 :
23644 548 : while (table_scan_getnextslot(scan, ForwardScanDirection, srcslot))
23645 : {
23646 423 : bool found = false;
23647 : TupleTableSlot *insertslot;
23648 :
23649 423 : CHECK_FOR_INTERRUPTS();
23650 :
23651 423 : econtext->ecxt_scantuple = srcslot;
23652 :
23653 : /* Search partition for the current slot, srcslot. */
23654 1138 : foreach(listptr, partContexts)
23655 : {
23656 1062 : pc = (SplitPartitionContext *) lfirst(listptr);
23657 :
23658 : /* skip DEFAULT partition */
23659 1062 : if (pc->partqualstate && ExecCheck(pc->partqualstate, econtext))
23660 : {
23661 347 : found = true;
23662 347 : break;
23663 : }
23664 : }
23665 423 : if (!found)
23666 : {
23667 : /* Use the DEFAULT partition if it exists. */
23668 76 : if (defaultPartCtx)
23669 76 : pc = defaultPartCtx;
23670 : else
23671 0 : ereport(ERROR,
23672 : errcode(ERRCODE_CHECK_VIOLATION),
23673 : errmsg("cannot find partition for split partition row"),
23674 : errtable(splitRel));
23675 : }
23676 :
23677 423 : if (tuple_map)
23678 : {
23679 : /* Need to use a map to copy attributes. */
23680 16 : insertslot = execute_attr_map_slot(tuple_map->attrMap, srcslot, pc->dstslot);
23681 : }
23682 : else
23683 : {
23684 : /* Extract data from the old tuple. */
23685 407 : slot_getallattrs(srcslot);
23686 :
23687 : /* Copy attributes directly. */
23688 407 : insertslot = pc->dstslot;
23689 :
23690 407 : ExecClearTuple(insertslot);
23691 :
23692 407 : memcpy(insertslot->tts_values, srcslot->tts_values,
23693 407 : sizeof(Datum) * srcslot->tts_nvalid);
23694 407 : memcpy(insertslot->tts_isnull, srcslot->tts_isnull,
23695 407 : sizeof(bool) * srcslot->tts_nvalid);
23696 :
23697 407 : ExecStoreVirtualTuple(insertslot);
23698 : }
23699 :
23700 : /*
23701 : * Constraints and GENERATED expressions might reference the tableoid
23702 : * column, so fill tts_tableOid with the desired value. (We must do
23703 : * this each time, because it gets overwritten with newrel's OID
23704 : * during storing.)
23705 : */
23706 423 : insertslot->tts_tableOid = RelationGetRelid(pc->partRel);
23707 :
23708 : /*
23709 : * Now, evaluate any generated expressions whose inputs come from the
23710 : * new tuple. We assume these columns won't reference each other, so
23711 : * that there's no ordering dependency.
23712 : */
23713 423 : evaluateGeneratedExpressionsAndCheckConstraints(pc->tab, pc->partRel,
23714 : insertslot, econtext);
23715 :
23716 : /* Write the tuple out to the new relation. */
23717 423 : table_tuple_insert(pc->partRel, insertslot, mycid,
23718 423 : ti_options, pc->bistate);
23719 :
23720 423 : ResetExprContext(econtext);
23721 : }
23722 :
23723 125 : MemoryContextSwitchTo(oldCxt);
23724 :
23725 125 : table_endscan(scan);
23726 125 : UnregisterSnapshot(snapshot);
23727 :
23728 125 : if (tuple_map)
23729 4 : free_conversion_map(tuple_map);
23730 :
23731 125 : ExecDropSingleTupleTableSlot(srcslot);
23732 :
23733 125 : FreeExecutorState(estate);
23734 :
23735 592 : foreach_ptr(SplitPartitionContext, spc, partContexts)
23736 342 : deleteSplitPartitionContext(spc, wqueue, ti_options);
23737 125 : }
23738 :
23739 : /*
23740 : * ALTER TABLE <name> SPLIT PARTITION <partition-name> INTO <partition-list>
23741 : */
23742 : static void
23743 133 : ATExecSplitPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
23744 : PartitionCmd *cmd, AlterTableUtilityContext *context)
23745 : {
23746 : Relation splitRel;
23747 : Oid splitRelOid;
23748 : ListCell *listptr,
23749 : *listptr2;
23750 133 : bool isSameName = false;
23751 : char tmpRelName[NAMEDATALEN];
23752 133 : List *newPartRels = NIL;
23753 133 : List *extDepState = NIL;
23754 : ObjectAddress object;
23755 : Oid defaultPartOid;
23756 : Oid save_userid;
23757 : int save_sec_context;
23758 : int save_nestlevel;
23759 : List *splitPartList;
23760 :
23761 133 : defaultPartOid = get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
23762 :
23763 : /*
23764 : * Partition is already locked in the transformPartitionCmdForSplit
23765 : * function.
23766 : */
23767 133 : splitRel = table_openrv(cmd->name, NoLock);
23768 :
23769 133 : splitRelOid = RelationGetRelid(splitRel);
23770 :
23771 : /* Check descriptions of new partitions. */
23772 612 : foreach_node(SinglePartitionSpec, sps, cmd->partlist)
23773 : {
23774 : Oid existingRelid;
23775 :
23776 : /* Look up the existing relation by the new partition name. */
23777 354 : RangeVarGetAndCheckCreationNamespace(sps->name, NoLock, &existingRelid);
23778 :
23779 : /*
23780 : * This would fail later on anyway if the relation already exists. But
23781 : * by catching it here, we can emit a nicer error message.
23782 : */
23783 354 : if (existingRelid == splitRelOid && !isSameName)
23784 : /* One new partition can have the same name as a split partition. */
23785 29 : isSameName = true;
23786 325 : else if (OidIsValid(existingRelid))
23787 4 : ereport(ERROR,
23788 : errcode(ERRCODE_DUPLICATE_TABLE),
23789 : errmsg("relation \"%s\" already exists", sps->name->relname));
23790 : }
23791 :
23792 : /*
23793 : * Collect extension dependencies from indexes on the split partition. We
23794 : * must do this before detaching it, so we can restore the dependencies on
23795 : * the new partitions' indexes later.
23796 : */
23797 129 : splitPartList = list_make1_oid(splitRelOid);
23798 :
23799 129 : extDepState = collectPartitionIndexExtDeps(splitPartList);
23800 129 : list_free(splitPartList);
23801 :
23802 : /* Detach the split partition. */
23803 129 : detachPartitionTable(rel, splitRel, defaultPartOid);
23804 :
23805 : /*
23806 : * Perform a preliminary check to determine whether it's safe to drop the
23807 : * split partition before we actually do so later. After merging rows into
23808 : * the new partitions via SplitPartitionMoveRows, all old partitions need
23809 : * to be dropped. However, since the drop behavior is DROP_RESTRICT and
23810 : * the merge process (SplitPartitionMoveRows) can be time-consuming,
23811 : * performing an early check on the drop eligibility of old partitions is
23812 : * preferable.
23813 : */
23814 129 : object.objectId = splitRelOid;
23815 129 : object.classId = RelationRelationId;
23816 129 : object.objectSubId = 0;
23817 129 : performDeletionCheck(&object, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
23818 :
23819 : /*
23820 : * If a new partition has the same name as the split partition, then we
23821 : * should rename the split partition to reuse its name.
23822 : */
23823 129 : if (isSameName)
23824 : {
23825 : /*
23826 : * We must bump the command counter to make the split partition tuple
23827 : * visible for renaming.
23828 : */
23829 29 : CommandCounterIncrement();
23830 : /* Rename partition. */
23831 29 : sprintf(tmpRelName, "split-%u-%X-tmp", RelationGetRelid(rel), MyProcPid);
23832 29 : RenameRelationInternal(splitRelOid, tmpRelName, true, false);
23833 :
23834 : /*
23835 : * We must bump the command counter to make the split partition tuple
23836 : * visible after renaming.
23837 : */
23838 29 : CommandCounterIncrement();
23839 : }
23840 :
23841 : /* Create new partitions (like a split partition), without indexes. */
23842 596 : foreach_node(SinglePartitionSpec, sps, cmd->partlist)
23843 : {
23844 : Relation newPartRel;
23845 :
23846 346 : newPartRel = createPartitionTable(wqueue, sps->name, rel,
23847 346 : splitRel->rd_rel->relowner);
23848 342 : newPartRels = lappend(newPartRels, newPartRel);
23849 : }
23850 :
23851 : /*
23852 : * Switch to the table owner's userid, so that any index functions are run
23853 : * as that user. Also, lockdown security-restricted operations and
23854 : * arrange to make GUC variable changes local to this command.
23855 : *
23856 : * Need to do it after determining the namespace in the
23857 : * createPartitionTable() call.
23858 : */
23859 125 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
23860 125 : SetUserIdAndSecContext(splitRel->rd_rel->relowner,
23861 : save_sec_context | SECURITY_RESTRICTED_OPERATION);
23862 125 : save_nestlevel = NewGUCNestLevel();
23863 125 : RestrictSearchPath();
23864 :
23865 : /* Copy data from the split partition to the new partitions. */
23866 125 : SplitPartitionMoveRows(wqueue, rel, splitRel, cmd->partlist, newPartRels);
23867 : /* Keep the lock until commit. */
23868 125 : table_close(splitRel, NoLock);
23869 :
23870 : /* Attach new partitions to the partitioned table. */
23871 467 : forboth(listptr, cmd->partlist, listptr2, newPartRels)
23872 : {
23873 342 : SinglePartitionSpec *sps = (SinglePartitionSpec *) lfirst(listptr);
23874 342 : Relation newPartRel = (Relation) lfirst(listptr2);
23875 :
23876 : /*
23877 : * wqueue = NULL: verification for each cloned constraint is not
23878 : * needed.
23879 : */
23880 342 : attachPartitionTable(NULL, rel, newPartRel, sps->bound);
23881 :
23882 : /*
23883 : * Apply extension dependencies to the new partition's indexes. This
23884 : * preserves any "DEPENDS ON EXTENSION" settings from the split
23885 : * partition.
23886 : */
23887 342 : applyPartitionIndexExtDeps(RelationGetRelid(newPartRel), extDepState);
23888 :
23889 : /* Keep the lock until commit. */
23890 342 : table_close(newPartRel, NoLock);
23891 : }
23892 :
23893 125 : freePartitionIndexExtDeps(extDepState);
23894 :
23895 : /* Drop the split partition. */
23896 125 : object.classId = RelationRelationId;
23897 125 : object.objectId = splitRelOid;
23898 125 : object.objectSubId = 0;
23899 : /* Probably DROP_CASCADE is not needed. */
23900 125 : performDeletion(&object, DROP_RESTRICT, 0);
23901 :
23902 : /* Roll back any GUC changes executed by index functions. */
23903 125 : AtEOXact_GUC(false, save_nestlevel);
23904 :
23905 : /* Restore the userid and security context. */
23906 125 : SetUserIdAndSecContext(save_userid, save_sec_context);
23907 125 : }
|