Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * tablecmds.c
4 : : * Commands for creating and altering table structures and settings
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/commands/tablecmds.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/attmap.h"
18 : : #include "access/genam.h"
19 : : #include "access/gist.h"
20 : : #include "access/heapam.h"
21 : : #include "access/heapam_xlog.h"
22 : : #include "access/multixact.h"
23 : : #include "access/reloptions.h"
24 : : #include "access/relscan.h"
25 : : #include "access/sysattr.h"
26 : : #include "access/tableam.h"
27 : : #include "access/toast_compression.h"
28 : : #include "access/tupconvert.h"
29 : : #include "access/xact.h"
30 : : #include "access/xlog.h"
31 : : #include "access/xloginsert.h"
32 : : #include "catalog/catalog.h"
33 : : #include "catalog/heap.h"
34 : : #include "catalog/index.h"
35 : : #include "catalog/namespace.h"
36 : : #include "catalog/objectaccess.h"
37 : : #include "catalog/partition.h"
38 : : #include "catalog/pg_am.h"
39 : : #include "catalog/pg_attrdef.h"
40 : : #include "catalog/pg_collation.h"
41 : : #include "catalog/pg_constraint.h"
42 : : #include "catalog/pg_depend.h"
43 : : #include "catalog/pg_foreign_table.h"
44 : : #include "catalog/pg_inherits.h"
45 : : #include "catalog/pg_largeobject.h"
46 : : #include "catalog/pg_largeobject_metadata.h"
47 : : #include "catalog/pg_namespace.h"
48 : : #include "catalog/pg_opclass.h"
49 : : #include "catalog/pg_policy.h"
50 : : #include "catalog/pg_proc.h"
51 : : #include "catalog/pg_publication_rel.h"
52 : : #include "catalog/pg_rewrite.h"
53 : : #include "catalog/pg_statistic_ext.h"
54 : : #include "catalog/pg_tablespace.h"
55 : : #include "catalog/pg_trigger.h"
56 : : #include "catalog/pg_type.h"
57 : : #include "catalog/storage.h"
58 : : #include "catalog/storage_xlog.h"
59 : : #include "catalog/toasting.h"
60 : : #include "commands/comment.h"
61 : : #include "commands/defrem.h"
62 : : #include "commands/event_trigger.h"
63 : : #include "commands/repack.h"
64 : : #include "commands/sequence.h"
65 : : #include "commands/tablecmds.h"
66 : : #include "commands/tablespace.h"
67 : : #include "commands/trigger.h"
68 : : #include "commands/typecmds.h"
69 : : #include "commands/user.h"
70 : : #include "commands/vacuum.h"
71 : : #include "common/int.h"
72 : : #include "executor/executor.h"
73 : : #include "foreign/fdwapi.h"
74 : : #include "foreign/foreign.h"
75 : : #include "miscadmin.h"
76 : : #include "nodes/makefuncs.h"
77 : : #include "nodes/nodeFuncs.h"
78 : : #include "nodes/parsenodes.h"
79 : : #include "optimizer/optimizer.h"
80 : : #include "parser/parse_coerce.h"
81 : : #include "parser/parse_collate.h"
82 : : #include "parser/parse_expr.h"
83 : : #include "parser/parse_relation.h"
84 : : #include "parser/parse_type.h"
85 : : #include "parser/parse_utilcmd.h"
86 : : #include "parser/parser.h"
87 : : #include "partitioning/partbounds.h"
88 : : #include "partitioning/partdesc.h"
89 : : #include "pgstat.h"
90 : : #include "rewrite/rewriteDefine.h"
91 : : #include "rewrite/rewriteHandler.h"
92 : : #include "rewrite/rewriteManip.h"
93 : : #include "storage/bufmgr.h"
94 : : #include "storage/lmgr.h"
95 : : #include "storage/lock.h"
96 : : #include "storage/predicate.h"
97 : : #include "storage/smgr.h"
98 : : #include "tcop/utility.h"
99 : : #include "utils/acl.h"
100 : : #include "utils/builtins.h"
101 : : #include "utils/fmgroids.h"
102 : : #include "utils/inval.h"
103 : : #include "utils/lsyscache.h"
104 : : #include "utils/memutils.h"
105 : : #include "utils/partcache.h"
106 : : #include "utils/relcache.h"
107 : : #include "utils/ruleutils.h"
108 : : #include "utils/snapmgr.h"
109 : : #include "utils/syscache.h"
110 : : #include "utils/timestamp.h"
111 : : #include "utils/typcache.h"
112 : : #include "utils/usercontext.h"
113 : :
114 : : /*
115 : : * ON COMMIT action list
116 : : */
117 : : typedef struct OnCommitItem
118 : : {
119 : : Oid relid; /* relid of relation */
120 : : OnCommitAction oncommit; /* what to do at end of xact */
121 : :
122 : : /*
123 : : * If this entry was created during the current transaction,
124 : : * creating_subid is the ID of the creating subxact; if created in a prior
125 : : * transaction, creating_subid is zero. If deleted during the current
126 : : * transaction, deleting_subid is the ID of the deleting subxact; if no
127 : : * deletion request is pending, deleting_subid is zero.
128 : : */
129 : : SubTransactionId creating_subid;
130 : : SubTransactionId deleting_subid;
131 : : } OnCommitItem;
132 : :
133 : : static List *on_commits = NIL;
134 : :
135 : :
136 : : /*
137 : : * State information for ALTER TABLE
138 : : *
139 : : * The pending-work queue for an ALTER TABLE is a List of AlteredTableInfo
140 : : * structs, one for each table modified by the operation (the named table
141 : : * plus any child tables that are affected). We save lists of subcommands
142 : : * to apply to this table (possibly modified by parse transformation steps);
143 : : * these lists will be executed in Phase 2. If a Phase 3 step is needed,
144 : : * necessary information is stored in the constraints and newvals lists.
145 : : *
146 : : * Phase 2 is divided into multiple passes; subcommands are executed in
147 : : * a pass determined by subcommand type.
148 : : */
149 : :
150 : : typedef enum AlterTablePass
151 : : {
152 : : AT_PASS_UNSET = -1, /* UNSET will cause ERROR */
153 : : AT_PASS_DROP, /* DROP (all flavors) */
154 : : AT_PASS_ALTER_TYPE, /* ALTER COLUMN TYPE */
155 : : AT_PASS_ADD_COL, /* ADD COLUMN */
156 : : AT_PASS_SET_EXPRESSION, /* ALTER SET EXPRESSION */
157 : : AT_PASS_OLD_INDEX, /* re-add existing indexes */
158 : : AT_PASS_OLD_CONSTR, /* re-add existing constraints */
159 : : /* We could support a RENAME COLUMN pass here, but not currently used */
160 : : AT_PASS_ADD_CONSTR, /* ADD constraints (initial examination) */
161 : : AT_PASS_COL_ATTRS, /* set column attributes, eg NOT NULL */
162 : : AT_PASS_ADD_INDEXCONSTR, /* ADD index-based constraints */
163 : : AT_PASS_ADD_INDEX, /* ADD indexes */
164 : : AT_PASS_ADD_OTHERCONSTR, /* ADD other constraints, defaults */
165 : : AT_PASS_MISC, /* other stuff */
166 : : } AlterTablePass;
167 : :
168 : : #define AT_NUM_PASSES (AT_PASS_MISC + 1)
169 : :
170 : : typedef struct AlteredTableInfo
171 : : {
172 : : /* Information saved before any work commences: */
173 : : Oid relid; /* Relation to work on */
174 : : char relkind; /* Its relkind */
175 : : TupleDesc oldDesc; /* Pre-modification tuple descriptor */
176 : :
177 : : /*
178 : : * Transiently set during Phase 2, normally set to NULL.
179 : : *
180 : : * ATRewriteCatalogs sets this when it starts, and closes when ATExecCmd
181 : : * returns control. This can be exploited by ATExecCmd subroutines to
182 : : * close/reopen across transaction boundaries.
183 : : */
184 : : Relation rel;
185 : :
186 : : /* Information saved by Phase 1 for Phase 2: */
187 : : List *subcmds[AT_NUM_PASSES]; /* Lists of AlterTableCmd */
188 : : /* Information saved by Phases 1/2 for Phase 3: */
189 : : List *constraints; /* List of NewConstraint */
190 : : List *newvals; /* List of NewColumnValue */
191 : : List *afterStmts; /* List of utility command parsetrees */
192 : : bool verify_new_notnull; /* T if we should recheck NOT NULL */
193 : : int rewrite; /* Reason for forced rewrite, if any */
194 : : bool chgAccessMethod; /* T if SET ACCESS METHOD is used */
195 : : Oid newAccessMethod; /* new access method; 0 means no change,
196 : : * if above is true */
197 : : Oid newTableSpace; /* new tablespace; 0 means no change */
198 : : bool chgPersistence; /* T if SET LOGGED/UNLOGGED is used */
199 : : char newrelpersistence; /* if above is true */
200 : : Expr *partition_constraint; /* for attach partition validation */
201 : : /* true, if validating default due to some other attach/detach */
202 : : bool validate_default;
203 : : /* Objects to rebuild after ALTER TYPE or SET EXPRESSION operations */
204 : : List *changedConstraintOids; /* OIDs of constraints to rebuild */
205 : : List *changedConstraintDefs; /* string definitions of same */
206 : : List *changedIndexOids; /* OIDs of indexes to rebuild */
207 : : List *changedIndexDefs; /* string definitions of same */
208 : : char *replicaIdentityIndex; /* index to reset as REPLICA IDENTITY */
209 : : char *clusterOnIndex; /* index to use for CLUSTER */
210 : : List *changedStatisticsOids; /* OIDs of statistics to rebuild */
211 : : List *changedStatisticsDefs; /* string definitions of same */
212 : : List *changedStatisticsOwners; /* owners of same */
213 : : } AlteredTableInfo;
214 : :
215 : : /* Struct describing one new constraint to check in Phase 3 scan */
216 : : /* Note: new not-null constraints are handled elsewhere */
217 : : typedef struct NewConstraint
218 : : {
219 : : char *name; /* Constraint name, or NULL if none */
220 : : ConstrType contype; /* CHECK or FOREIGN */
221 : : Oid refrelid; /* PK rel, if FOREIGN */
222 : : Oid refindid; /* OID of PK's index, if FOREIGN */
223 : : bool conwithperiod; /* Whether the new FOREIGN KEY uses PERIOD */
224 : : Oid conid; /* OID of pg_constraint entry, if FOREIGN */
225 : : Node *qual; /* Check expr or CONSTR_FOREIGN Constraint */
226 : : ExprState *qualstate; /* Execution state for CHECK expr */
227 : : } NewConstraint;
228 : :
229 : : /*
230 : : * Struct describing one new column value that needs to be computed during
231 : : * Phase 3 copy (this could be either a new column with a non-null default, or
232 : : * a column that we're changing the type of). Columns without such an entry
233 : : * are just copied from the old table during ATRewriteTable. Note that the
234 : : * expr is an expression over *old* table values, except when is_generated
235 : : * is true; then it is an expression over columns of the *new* tuple.
236 : : */
237 : : typedef struct NewColumnValue
238 : : {
239 : : AttrNumber attnum; /* which column */
240 : : Expr *expr; /* expression to compute */
241 : : ExprState *exprstate; /* execution state */
242 : : bool is_generated; /* is it a GENERATED expression? */
243 : : } NewColumnValue;
244 : :
245 : : /*
246 : : * Error-reporting support for RemoveRelations
247 : : */
248 : : struct dropmsgstrings
249 : : {
250 : : char kind;
251 : : int nonexistent_code;
252 : : const char *nonexistent_msg;
253 : : const char *skipping_msg;
254 : : const char *nota_msg;
255 : : const char *drophint_msg;
256 : : };
257 : :
258 : : static const struct dropmsgstrings dropmsgstringarray[] = {
259 : : {RELKIND_RELATION,
260 : : ERRCODE_UNDEFINED_TABLE,
261 : : gettext_noop("table \"%s\" does not exist"),
262 : : gettext_noop("table \"%s\" does not exist, skipping"),
263 : : gettext_noop("\"%s\" is not a table"),
264 : : gettext_noop("Use DROP TABLE to remove a table.")},
265 : : {RELKIND_SEQUENCE,
266 : : ERRCODE_UNDEFINED_TABLE,
267 : : gettext_noop("sequence \"%s\" does not exist"),
268 : : gettext_noop("sequence \"%s\" does not exist, skipping"),
269 : : gettext_noop("\"%s\" is not a sequence"),
270 : : gettext_noop("Use DROP SEQUENCE to remove a sequence.")},
271 : : {RELKIND_VIEW,
272 : : ERRCODE_UNDEFINED_TABLE,
273 : : gettext_noop("view \"%s\" does not exist"),
274 : : gettext_noop("view \"%s\" does not exist, skipping"),
275 : : gettext_noop("\"%s\" is not a view"),
276 : : gettext_noop("Use DROP VIEW to remove a view.")},
277 : : {RELKIND_MATVIEW,
278 : : ERRCODE_UNDEFINED_TABLE,
279 : : gettext_noop("materialized view \"%s\" does not exist"),
280 : : gettext_noop("materialized view \"%s\" does not exist, skipping"),
281 : : gettext_noop("\"%s\" is not a materialized view"),
282 : : gettext_noop("Use DROP MATERIALIZED VIEW to remove a materialized view.")},
283 : : {RELKIND_INDEX,
284 : : ERRCODE_UNDEFINED_OBJECT,
285 : : gettext_noop("index \"%s\" does not exist"),
286 : : gettext_noop("index \"%s\" does not exist, skipping"),
287 : : gettext_noop("\"%s\" is not an index"),
288 : : gettext_noop("Use DROP INDEX to remove an index.")},
289 : : {RELKIND_COMPOSITE_TYPE,
290 : : ERRCODE_UNDEFINED_OBJECT,
291 : : gettext_noop("type \"%s\" does not exist"),
292 : : gettext_noop("type \"%s\" does not exist, skipping"),
293 : : gettext_noop("\"%s\" is not a type"),
294 : : gettext_noop("Use DROP TYPE to remove a type.")},
295 : : {RELKIND_FOREIGN_TABLE,
296 : : ERRCODE_UNDEFINED_OBJECT,
297 : : gettext_noop("foreign table \"%s\" does not exist"),
298 : : gettext_noop("foreign table \"%s\" does not exist, skipping"),
299 : : gettext_noop("\"%s\" is not a foreign table"),
300 : : gettext_noop("Use DROP FOREIGN TABLE to remove a foreign table.")},
301 : : {RELKIND_PARTITIONED_TABLE,
302 : : ERRCODE_UNDEFINED_TABLE,
303 : : gettext_noop("table \"%s\" does not exist"),
304 : : gettext_noop("table \"%s\" does not exist, skipping"),
305 : : gettext_noop("\"%s\" is not a table"),
306 : : gettext_noop("Use DROP TABLE to remove a table.")},
307 : : {RELKIND_PARTITIONED_INDEX,
308 : : ERRCODE_UNDEFINED_OBJECT,
309 : : gettext_noop("index \"%s\" does not exist"),
310 : : gettext_noop("index \"%s\" does not exist, skipping"),
311 : : gettext_noop("\"%s\" is not an index"),
312 : : gettext_noop("Use DROP INDEX to remove an index.")},
313 : : {'\0', 0, NULL, NULL, NULL, NULL}
314 : : };
315 : :
316 : : /* communication between RemoveRelations and RangeVarCallbackForDropRelation */
317 : : struct DropRelationCallbackState
318 : : {
319 : : /* These fields are set by RemoveRelations: */
320 : : char expected_relkind;
321 : : LOCKMODE heap_lockmode;
322 : : /* These fields are state to track which subsidiary locks are held: */
323 : : Oid heapOid;
324 : : Oid partParentOid;
325 : : /* These fields are passed back by RangeVarCallbackForDropRelation: */
326 : : char actual_relkind;
327 : : char actual_relpersistence;
328 : : };
329 : :
330 : : /* Alter table target-type flags for ATSimplePermissions */
331 : : #define ATT_TABLE 0x0001
332 : : #define ATT_VIEW 0x0002
333 : : #define ATT_MATVIEW 0x0004
334 : : #define ATT_INDEX 0x0008
335 : : #define ATT_COMPOSITE_TYPE 0x0010
336 : : #define ATT_FOREIGN_TABLE 0x0020
337 : : #define ATT_PARTITIONED_INDEX 0x0040
338 : : #define ATT_SEQUENCE 0x0080
339 : : #define ATT_PARTITIONED_TABLE 0x0100
340 : :
341 : : /*
342 : : * ForeignTruncateInfo
343 : : *
344 : : * Information related to truncation of foreign tables. This is used for
345 : : * the elements in a hash table. It uses the server OID as lookup key,
346 : : * and includes a per-server list of all foreign tables involved in the
347 : : * truncation.
348 : : */
349 : : typedef struct ForeignTruncateInfo
350 : : {
351 : : Oid serverid;
352 : : List *rels;
353 : : } ForeignTruncateInfo;
354 : :
355 : : /* Partial or complete FK creation in addFkConstraint() */
356 : : typedef enum addFkConstraintSides
357 : : {
358 : : addFkReferencedSide,
359 : : addFkReferencingSide,
360 : : addFkBothSides,
361 : : } addFkConstraintSides;
362 : :
363 : : /*
364 : : * Partition tables are expected to be dropped when the parent partitioned
365 : : * table gets dropped. Hence for partitioning we use AUTO dependency.
366 : : * Otherwise, for regular inheritance use NORMAL dependency.
367 : : */
368 : : #define child_dependency_type(child_is_partition) \
369 : : ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
370 : :
371 : : static void truncate_check_rel(Oid relid, Form_pg_class reltuple);
372 : : static void truncate_check_perms(Oid relid, Form_pg_class reltuple);
373 : : static void truncate_check_activity(Relation rel);
374 : : static void RangeVarCallbackForTruncate(const RangeVar *relation,
375 : : Oid relId, Oid oldRelId, void *arg);
376 : : static List *MergeAttributes(List *columns, const List *supers, char relpersistence,
377 : : bool is_partition, List **supconstr,
378 : : List **supnotnulls);
379 : : static List *MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced);
380 : : static void MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef);
381 : : static ColumnDef *MergeInheritedAttribute(List *inh_columns, int exist_attno, const ColumnDef *newdef);
382 : : static void MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition);
383 : : static void MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel);
384 : : static void StoreCatalogInheritance(Oid relationId, List *supers,
385 : : bool child_is_partition);
386 : : static void StoreCatalogInheritance1(Oid relationId, Oid parentOid,
387 : : int32 seqNumber, Relation inhRelation,
388 : : bool child_is_partition);
389 : : static int findAttrByName(const char *attributeName, const List *columns);
390 : : static void AlterIndexNamespaces(Relation classRel, Relation rel,
391 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved);
392 : : static void AlterSeqNamespaces(Relation classRel, Relation rel,
393 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
394 : : LOCKMODE lockmode);
395 : : static ObjectAddress ATExecAlterConstraint(List **wqueue, Relation rel,
396 : : ATAlterConstraint *cmdcon,
397 : : bool recurse, LOCKMODE lockmode);
398 : : static bool ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel,
399 : : Relation tgrel, Relation rel, HeapTuple contuple,
400 : : bool recurse, LOCKMODE lockmode);
401 : : static bool ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
402 : : Relation conrel, Relation tgrel,
403 : : Oid fkrelid, Oid pkrelid,
404 : : HeapTuple contuple, LOCKMODE lockmode,
405 : : Oid ReferencedParentDelTrigger,
406 : : Oid ReferencedParentUpdTrigger,
407 : : Oid ReferencingParentInsTrigger,
408 : : Oid ReferencingParentUpdTrigger);
409 : : static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
410 : : Relation conrel, HeapTuple contuple,
411 : : bool recurse, bool recursing,
412 : : List *changing_conids,
413 : : LOCKMODE lockmode);
414 : : static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
415 : : Relation conrel, Relation tgrel, Relation rel,
416 : : HeapTuple contuple, bool recurse,
417 : : List **otherrelids, LOCKMODE lockmode);
418 : : static bool ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
419 : : Relation conrel, Relation rel,
420 : : HeapTuple contuple, LOCKMODE lockmode);
421 : : static void AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
422 : : bool deferrable, bool initdeferred,
423 : : List **otherrelids);
424 : : static void AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
425 : : Relation conrel, Relation tgrel,
426 : : Oid fkrelid, Oid pkrelid,
427 : : HeapTuple contuple, LOCKMODE lockmode,
428 : : Oid ReferencedParentDelTrigger,
429 : : Oid ReferencedParentUpdTrigger,
430 : : Oid ReferencingParentInsTrigger,
431 : : Oid ReferencingParentUpdTrigger);
432 : : static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
433 : : Relation conrel, Oid conrelid,
434 : : bool recurse, bool recursing,
435 : : List *changing_conids,
436 : : LOCKMODE lockmode);
437 : : static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
438 : : Relation conrel, Relation tgrel, Relation rel,
439 : : HeapTuple contuple, bool recurse,
440 : : List **otherrelids, LOCKMODE lockmode);
441 : : static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
442 : : HeapTuple contuple);
443 : : static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel,
444 : : HeapTuple contuple,
445 : : List *changing_conids,
446 : : Oid *enforced_parentoid);
447 : : static ObjectAddress ATExecValidateConstraint(List **wqueue,
448 : : Relation rel, char *constrName,
449 : : bool recurse, bool recursing, LOCKMODE lockmode);
450 : : static void QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
451 : : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode);
452 : : static void QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
453 : : char *constrName, HeapTuple contuple,
454 : : bool recurse, bool recursing, LOCKMODE lockmode);
455 : : static void QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
456 : : HeapTuple contuple, bool recurse, bool recursing,
457 : : LOCKMODE lockmode);
458 : : static bool constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc);
459 : : static int transformColumnNameList(Oid relId, List *colList,
460 : : int16 *attnums, Oid *atttypids, Oid *attcollids);
461 : : static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
462 : : List **attnamelist,
463 : : int16 *attnums, Oid *atttypids, Oid *attcollids,
464 : : Oid *opclasses, bool *pk_has_without_overlaps);
465 : : static Oid transformFkeyCheckAttrs(Relation pkrel,
466 : : int numattrs, int16 *attnums,
467 : : bool with_period, Oid *opclasses,
468 : : bool *pk_has_without_overlaps);
469 : : static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts);
470 : : static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId,
471 : : Oid *funcid);
472 : : static void validateForeignKeyConstraint(char *conname,
473 : : Relation rel, Relation pkrel,
474 : : Oid pkindOid, Oid constraintOid, bool hasperiod);
475 : : static void CheckAlterTableIsSafe(Relation rel);
476 : : static void ATController(AlterTableStmt *parsetree,
477 : : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
478 : : AlterTableUtilityContext *context);
479 : : static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
480 : : bool recurse, bool recursing, LOCKMODE lockmode,
481 : : AlterTableUtilityContext *context);
482 : : static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
483 : : AlterTableUtilityContext *context);
484 : : static void ATExecCmd(List **wqueue, AlteredTableInfo *tab,
485 : : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
486 : : AlterTableUtilityContext *context);
487 : : static AlterTableCmd *ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab,
488 : : Relation rel, AlterTableCmd *cmd,
489 : : bool recurse, LOCKMODE lockmode,
490 : : AlterTablePass cur_pass,
491 : : AlterTableUtilityContext *context);
492 : : static void ATRewriteTables(AlterTableStmt *parsetree,
493 : : List **wqueue, LOCKMODE lockmode,
494 : : AlterTableUtilityContext *context);
495 : : static void ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap);
496 : : static AlteredTableInfo *ATGetQueueEntry(List **wqueue, Relation rel);
497 : : static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets);
498 : : static void ATSimpleRecursion(List **wqueue, Relation rel,
499 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
500 : : AlterTableUtilityContext *context);
501 : : static void ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode);
502 : : static void ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
503 : : LOCKMODE lockmode,
504 : : AlterTableUtilityContext *context);
505 : : static List *find_typed_table_dependencies(Oid typeOid, const char *typeName,
506 : : DropBehavior behavior);
507 : : static void ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
508 : : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
509 : : AlterTableUtilityContext *context);
510 : : static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab,
511 : : Relation rel, AlterTableCmd **cmd,
512 : : bool recurse, bool recursing,
513 : : LOCKMODE lockmode, AlterTablePass cur_pass,
514 : : AlterTableUtilityContext *context);
515 : : static bool check_for_column_name_collision(Relation rel, const char *colname,
516 : : bool if_not_exists);
517 : : static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid);
518 : : static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid);
519 : : static ObjectAddress ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
520 : : LOCKMODE lockmode);
521 : : static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
522 : : bool queue_validation);
523 : : static ObjectAddress ATExecSetNotNull(List **wqueue, Relation rel,
524 : : char *conName, char *colName,
525 : : bool recurse, bool recursing,
526 : : LOCKMODE lockmode);
527 : : static bool NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr);
528 : : static bool ConstraintImpliedByRelConstraint(Relation scanrel,
529 : : List *testConstraint, List *provenConstraint);
530 : : static ObjectAddress ATExecColumnDefault(Relation rel, const char *colName,
531 : : Node *newDefault, LOCKMODE lockmode);
532 : : static ObjectAddress ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
533 : : Node *newDefault);
534 : : static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName,
535 : : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
536 : : static ObjectAddress ATExecSetIdentity(Relation rel, const char *colName,
537 : : Node *def, LOCKMODE lockmode, bool recurse, bool recursing);
538 : : static ObjectAddress ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
539 : : bool recurse, bool recursing);
540 : : static ObjectAddress ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
541 : : Node *newExpr, LOCKMODE lockmode);
542 : : static void ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode);
543 : : static ObjectAddress ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode);
544 : : static ObjectAddress ATExecSetStatistics(Relation rel, const char *colName, int16 colNum,
545 : : Node *newValue, LOCKMODE lockmode);
546 : : static ObjectAddress ATExecSetOptions(Relation rel, const char *colName,
547 : : Node *options, bool isReset, LOCKMODE lockmode);
548 : : static ObjectAddress ATExecSetStorage(Relation rel, const char *colName,
549 : : Node *newValue, LOCKMODE lockmode);
550 : : static void ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
551 : : AlterTableCmd *cmd, LOCKMODE lockmode,
552 : : AlterTableUtilityContext *context);
553 : : static ObjectAddress ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
554 : : DropBehavior behavior,
555 : : bool recurse, bool recursing,
556 : : bool missing_ok, LOCKMODE lockmode,
557 : : ObjectAddresses *addrs);
558 : : static void ATPrepAddPrimaryKey(AlteredTableInfo *tab, Relation rel,
559 : : AlterTableCmd *cmd, LOCKMODE lockmode);
560 : : static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
561 : : static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
562 : : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
563 : : static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
564 : : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
565 : : static ObjectAddress ATExecAddConstraint(List **wqueue,
566 : : AlteredTableInfo *tab, Relation rel,
567 : : Constraint *newConstraint, bool recurse, bool is_readd,
568 : : LOCKMODE lockmode);
569 : : static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
570 : : static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
571 : : IndexStmt *stmt, LOCKMODE lockmode);
572 : : static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
573 : : AlteredTableInfo *tab, Relation rel,
574 : : Constraint *constr,
575 : : bool recurse, bool recursing, bool is_readd,
576 : : LOCKMODE lockmode);
577 : : static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
578 : : Relation rel, Constraint *fkconstraint,
579 : : bool recurse, bool recursing,
580 : : LOCKMODE lockmode);
581 : : static int validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
582 : : int numfksetcols, int16 *fksetcolsattnums,
583 : : List *fksetcols);
584 : : static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
585 : : char *constraintname,
586 : : Constraint *fkconstraint, Relation rel,
587 : : Relation pkrel, Oid indexOid,
588 : : Oid parentConstr,
589 : : int numfks, int16 *pkattnum, int16 *fkattnum,
590 : : Oid *pfeqoperators, Oid *ppeqoperators,
591 : : Oid *ffeqoperators, int numfkdelsetcols,
592 : : int16 *fkdelsetcols, bool is_internal,
593 : : bool with_period);
594 : : static void addFkRecurseReferenced(Constraint *fkconstraint,
595 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
596 : : int numfks, int16 *pkattnum, int16 *fkattnum,
597 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
598 : : int numfkdelsetcols, int16 *fkdelsetcols,
599 : : bool old_check_ok,
600 : : Oid parentDelTrigger, Oid parentUpdTrigger,
601 : : bool with_period);
602 : : static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
603 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
604 : : int numfks, int16 *pkattnum, int16 *fkattnum,
605 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
606 : : int numfkdelsetcols, int16 *fkdelsetcols,
607 : : bool old_check_ok, LOCKMODE lockmode,
608 : : Oid parentInsTrigger, Oid parentUpdTrigger,
609 : : bool with_period);
610 : : static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
611 : : Relation partitionRel);
612 : : static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
613 : : static void CloneFkReferencing(List **wqueue, Relation parentRel,
614 : : Relation partRel);
615 : : static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
616 : : Constraint *fkconstraint, Oid constraintOid,
617 : : Oid indexOid,
618 : : Oid parentInsTrigger, Oid parentUpdTrigger,
619 : : Oid *insertTrigOid, Oid *updateTrigOid);
620 : : static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
621 : : Constraint *fkconstraint, Oid constraintOid,
622 : : Oid indexOid,
623 : : Oid parentDelTrigger, Oid parentUpdTrigger,
624 : : Oid *deleteTrigOid, Oid *updateTrigOid);
625 : : static bool tryAttachPartitionForeignKey(List **wqueue,
626 : : ForeignKeyCacheInfo *fk,
627 : : Relation partition,
628 : : Oid parentConstrOid, int numfks,
629 : : AttrNumber *mapped_conkey, AttrNumber *confkey,
630 : : Oid *conpfeqop,
631 : : Oid parentInsTrigger,
632 : : Oid parentUpdTrigger,
633 : : Relation trigrel);
634 : : static void AttachPartitionForeignKey(List **wqueue, Relation partition,
635 : : Oid partConstrOid, Oid parentConstrOid,
636 : : Oid parentInsTrigger, Oid parentUpdTrigger,
637 : : Relation trigrel);
638 : : static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
639 : : Oid conoid, Oid conrelid);
640 : : static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
641 : : Oid confrelid, Oid conrelid);
642 : : static void GetForeignKeyActionTriggers(Relation trigrel,
643 : : Oid conoid, Oid confrelid, Oid conrelid,
644 : : Oid *deleteTriggerOid,
645 : : Oid *updateTriggerOid);
646 : : static void GetForeignKeyCheckTriggers(Relation trigrel,
647 : : Oid conoid, Oid confrelid, Oid conrelid,
648 : : Oid *insertTriggerOid,
649 : : Oid *updateTriggerOid);
650 : : static void ATExecDropConstraint(Relation rel, const char *constrName,
651 : : DropBehavior behavior, bool recurse,
652 : : bool missing_ok, LOCKMODE lockmode);
653 : : static ObjectAddress dropconstraint_internal(Relation rel,
654 : : HeapTuple constraintTup, DropBehavior behavior,
655 : : bool recurse, bool recursing,
656 : : bool missing_ok, LOCKMODE lockmode);
657 : : static void ATPrepAlterColumnType(List **wqueue,
658 : : AlteredTableInfo *tab, Relation rel,
659 : : bool recurse, bool recursing,
660 : : AlterTableCmd *cmd, LOCKMODE lockmode,
661 : : AlterTableUtilityContext *context);
662 : : static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
663 : : static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
664 : : AlterTableCmd *cmd, LOCKMODE lockmode);
665 : : static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
666 : : Relation rel, AttrNumber attnum, const char *colName);
667 : : static void RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, Relation rel);
668 : : static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
669 : : static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
670 : : static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
671 : : static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
672 : : LOCKMODE lockmode);
673 : : static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
674 : : const char *cmdstring, List **wqueue,
675 : : LOCKMODE lockmode, bool rewrite);
676 : : static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
677 : : Oid objid, Relation rel, List *domname,
678 : : const char *conname);
679 : : static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
680 : : static void TryReuseForeignKey(Oid oldId, Constraint *con);
681 : : static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
682 : : List *options, LOCKMODE lockmode);
683 : : static void change_owner_fix_column_acls(Oid relationOid,
684 : : Oid oldOwnerId, Oid newOwnerId);
685 : : static void change_owner_recurse_to_sequences(Oid relationOid,
686 : : Oid newOwnerId, LOCKMODE lockmode);
687 : : static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
688 : : LOCKMODE lockmode);
689 : : static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
690 : : static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
691 : : static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
692 : : static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
693 : : bool toLogged);
694 : : static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
695 : : const char *tablespacename, LOCKMODE lockmode);
696 : : static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
697 : : static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
698 : : static void ATExecSetRelOptions(Relation rel, List *defList,
699 : : AlterTableType operation,
700 : : LOCKMODE lockmode);
701 : : static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
702 : : char fires_when, bool skip_system, bool recurse,
703 : : LOCKMODE lockmode);
704 : : static void ATExecEnableDisableRule(Relation rel, const char *rulename,
705 : : char fires_when, LOCKMODE lockmode);
706 : : static void ATPrepChangeInherit(Relation child_rel);
707 : : static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
708 : : static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
709 : : static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
710 : : DependencyType deptype);
711 : : static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
712 : : static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
713 : : static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
714 : : static void ATExecGenericOptions(Relation rel, List *options);
715 : : static void ATExecSetRowSecurity(Relation rel, bool rls);
716 : : static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
717 : : static ObjectAddress ATExecSetCompression(Relation rel,
718 : : const char *column, Node *newValue, LOCKMODE lockmode);
719 : :
720 : : static void index_copy_data(Relation rel, RelFileLocator newrlocator);
721 : : static const char *storage_name(char c);
722 : :
723 : : static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
724 : : Oid oldRelOid, void *arg);
725 : : static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
726 : : Oid oldrelid, void *arg);
727 : : static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
728 : : static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
729 : : List **partexprs, Oid *partopclass, Oid *partcollation,
730 : : PartitionStrategy strategy);
731 : : static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
732 : : static void RemoveInheritance(Relation child_rel, Relation parent_rel,
733 : : bool expect_detached);
734 : : static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
735 : : PartitionCmd *cmd,
736 : : AlterTableUtilityContext *context);
737 : : static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
738 : : static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
739 : : List *partConstraint,
740 : : bool validate_default);
741 : : static void CloneRowTriggersToPartition(Relation parent, Relation partition);
742 : : static void DropClonedTriggersFromPartition(Oid partitionId);
743 : : static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
744 : : Relation rel, RangeVar *name,
745 : : bool concurrent);
746 : : static void DetachPartitionFinalize(Relation rel, Relation partRel,
747 : : bool concurrent, Oid defaultPartOid);
748 : : static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
749 : : static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
750 : : RangeVar *name);
751 : : static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
752 : : static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
753 : : Relation partitionTbl);
754 : : static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
755 : : static List *GetParentedForeignKeyRefs(Relation partition);
756 : : static void ATDetachCheckNoForeignKeyRefs(Relation partition);
757 : : static char GetAttributeCompression(Oid atttypid, const char *compression);
758 : : static char GetAttributeStorage(Oid atttypid, const char *storagemode);
759 : :
760 : :
761 : : /* ----------------------------------------------------------------
762 : : * DefineRelation
763 : : * Creates a new relation.
764 : : *
765 : : * stmt carries parsetree information from an ordinary CREATE TABLE statement.
766 : : * The other arguments are used to extend the behavior for other cases:
767 : : * relkind: relkind to assign to the new relation
768 : : * ownerId: if not InvalidOid, use this as the new relation's owner.
769 : : * typaddress: if not null, it's set to the pg_type entry's address.
770 : : * queryString: for error reporting
771 : : *
772 : : * Note that permissions checks are done against current user regardless of
773 : : * ownerId. A nonzero ownerId is used when someone is creating a relation
774 : : * "on behalf of" someone else, so we still want to see that the current user
775 : : * has permissions to do it.
776 : : *
777 : : * If successful, returns the address of the new relation.
778 : : * ----------------------------------------------------------------
779 : : */
780 : : ObjectAddress
781 : 41141 : DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
782 : : ObjectAddress *typaddress, const char *queryString)
783 : : {
784 : : char relname[NAMEDATALEN];
785 : : Oid namespaceId;
786 : : Oid relationId;
787 : : Oid tablespaceId;
788 : : Relation rel;
789 : : TupleDesc descriptor;
790 : : List *inheritOids;
791 : : List *old_constraints;
792 : : List *old_notnulls;
793 : : List *rawDefaults;
794 : : List *cookedDefaults;
795 : : List *nncols;
796 : 41141 : List *connames = NIL;
797 : : Datum reloptions;
798 : : ListCell *listptr;
799 : : AttrNumber attnum;
800 : : bool partitioned;
801 : 41141 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
802 : : Oid ofTypeId;
803 : : ObjectAddress address;
804 : : LOCKMODE parentLockmode;
805 : 41141 : Oid accessMethodId = InvalidOid;
806 : :
807 : : /*
808 : : * Truncate relname to appropriate length (probably a waste of time, as
809 : : * parser should have done this already).
810 : : */
811 : 41141 : strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
812 : :
813 : : /*
814 : : * Check consistency of arguments
815 : : */
816 [ + + ]: 41141 : if (stmt->oncommit != ONCOMMIT_NOOP
817 [ + + ]: 124 : && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
818 [ + - ]: 8 : ereport(ERROR,
819 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
820 : : errmsg("ON COMMIT can only be used on temporary tables")));
821 : :
822 [ + + ]: 41133 : if (stmt->partspec != NULL)
823 : : {
824 [ - + ]: 3443 : if (relkind != RELKIND_RELATION)
825 [ # # ]: 0 : elog(ERROR, "unexpected relkind: %d", (int) relkind);
826 : :
827 : 3443 : relkind = RELKIND_PARTITIONED_TABLE;
828 : 3443 : partitioned = true;
829 : : }
830 : : else
831 : 37690 : partitioned = false;
832 : :
833 [ + + ]: 41133 : if (relkind == RELKIND_PARTITIONED_TABLE &&
834 [ + + ]: 3443 : stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
835 [ + - ]: 4 : ereport(ERROR,
836 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
837 : : errmsg("partitioned tables cannot be unlogged")));
838 : :
839 : : /*
840 : : * Look up the namespace in which we are supposed to create the relation,
841 : : * check we have permission to create there, lock it against concurrent
842 : : * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
843 : : * namespace is selected.
844 : : */
845 : : namespaceId =
846 : 41129 : RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
847 : :
848 : : /*
849 : : * Security check: disallow creating temp tables from security-restricted
850 : : * code. This is needed because calling code might not expect untrusted
851 : : * tables to appear in pg_temp at the front of its search path.
852 : : */
853 [ + + ]: 41129 : if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
854 [ - + ]: 2365 : && InSecurityRestrictedOperation())
855 [ # # ]: 0 : ereport(ERROR,
856 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
857 : : errmsg("cannot create temporary table within security-restricted operation")));
858 : :
859 : : /*
860 : : * Determine the lockmode to use when scanning parents. A self-exclusive
861 : : * lock is needed here.
862 : : *
863 : : * For regular inheritance, if two backends attempt to add children to the
864 : : * same parent simultaneously, and that parent has no pre-existing
865 : : * children, then both will attempt to update the parent's relhassubclass
866 : : * field, leading to a "tuple concurrently updated" error. Also, this
867 : : * interlocks against a concurrent ANALYZE on the parent table, which
868 : : * might otherwise be attempting to clear the parent's relhassubclass
869 : : * field, if its previous children were recently dropped.
870 : : *
871 : : * If the child table is a partition, then we instead grab an exclusive
872 : : * lock on the parent because its partition descriptor will be changed by
873 : : * addition of the new partition.
874 : : */
875 [ + + ]: 41129 : parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
876 : : ShareUpdateExclusiveLock);
877 : :
878 : : /* Determine the list of OIDs of the parents. */
879 : 41129 : inheritOids = NIL;
880 [ + + + + : 48827 : foreach(listptr, stmt->inhRelations)
+ + ]
881 : : {
882 : 7698 : RangeVar *rv = (RangeVar *) lfirst(listptr);
883 : : Oid parentOid;
884 : :
885 : 7698 : parentOid = RangeVarGetRelid(rv, parentLockmode, false);
886 : :
887 : : /*
888 : : * Reject duplications in the list of parents.
889 : : */
890 [ - + ]: 7698 : if (list_member_oid(inheritOids, parentOid))
891 [ # # ]: 0 : ereport(ERROR,
892 : : (errcode(ERRCODE_DUPLICATE_TABLE),
893 : : errmsg("relation \"%s\" would be inherited from more than once",
894 : : get_rel_name(parentOid))));
895 : :
896 : 7698 : inheritOids = lappend_oid(inheritOids, parentOid);
897 : : }
898 : :
899 : : /*
900 : : * Select tablespace to use: an explicitly indicated one, or (in the case
901 : : * of a partitioned table) the parent's, if it has one.
902 : : */
903 [ + + ]: 41129 : if (stmt->tablespacename)
904 : : {
905 : 83 : tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
906 : :
907 [ + + + + ]: 79 : if (partitioned && tablespaceId == MyDatabaseTableSpace)
908 [ + - ]: 4 : ereport(ERROR,
909 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
910 : : errmsg("cannot specify default tablespace for partitioned relations")));
911 : : }
912 [ + + ]: 41046 : else if (stmt->partbound)
913 : : {
914 : : Assert(list_length(inheritOids) == 1);
915 : 6020 : tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
916 : : }
917 : : else
918 : 35026 : tablespaceId = InvalidOid;
919 : :
920 : : /* still nothing? use the default */
921 [ + + ]: 41121 : if (!OidIsValid(tablespaceId))
922 : 41032 : tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
923 : : partitioned);
924 : :
925 : : /* Check permissions except when using database's default */
926 [ + + + + ]: 41117 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
927 : : {
928 : : AclResult aclresult;
929 : :
930 : 105 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
931 : : ACL_CREATE);
932 [ + + ]: 105 : if (aclresult != ACLCHECK_OK)
933 : 3 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
934 : 3 : get_tablespace_name(tablespaceId));
935 : : }
936 : :
937 : : /* In all cases disallow placing user relations in pg_global */
938 [ + + ]: 41114 : if (tablespaceId == GLOBALTABLESPACE_OID)
939 [ + - ]: 12 : ereport(ERROR,
940 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
941 : : errmsg("only shared relations can be placed in pg_global tablespace")));
942 : :
943 : : /* Identify user ID that will own the table */
944 [ + + ]: 41102 : if (!OidIsValid(ownerId))
945 : 40947 : ownerId = GetUserId();
946 : :
947 : : /*
948 : : * Parse and validate reloptions, if any.
949 : : */
950 : 41102 : reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
951 : : true, false);
952 : :
953 [ + + + ]: 41090 : switch (relkind)
954 : : {
955 : 10541 : case RELKIND_VIEW:
956 : 10541 : (void) view_reloptions(reloptions, true);
957 : 10529 : break;
958 : 3427 : case RELKIND_PARTITIONED_TABLE:
959 : 3427 : (void) partitioned_table_reloptions(reloptions, true);
960 : 3419 : break;
961 : 27122 : default:
962 : 27122 : (void) heap_reloptions(relkind, reloptions, true);
963 : : }
964 : :
965 [ + + ]: 41002 : if (stmt->ofTypename)
966 : : {
967 : : AclResult aclresult;
968 : :
969 : 57 : ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
970 : :
971 : 57 : aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
972 [ + + ]: 57 : if (aclresult != ACLCHECK_OK)
973 : 4 : aclcheck_error_type(aclresult, ofTypeId);
974 : : }
975 : : else
976 : 40945 : ofTypeId = InvalidOid;
977 : :
978 : : /*
979 : : * Look up inheritance ancestors and generate relation schema, including
980 : : * inherited attributes. (Note that stmt->tableElts is destructively
981 : : * modified by MergeAttributes.)
982 : : */
983 : 40834 : stmt->tableElts =
984 : 40998 : MergeAttributes(stmt->tableElts, inheritOids,
985 : 40998 : stmt->relation->relpersistence,
986 : 40998 : stmt->partbound != NULL,
987 : : &old_constraints, &old_notnulls);
988 : :
989 : : /*
990 : : * NB: The defaults and constraints we just inherited are already cooked,
991 : : * so they don't get the USAGE checks that AddRelationNewConstraints()
992 : : * applies to raw ones. That's intentional: the parent's own catalog
993 : : * entries already depend on those types, so copying them pins nothing
994 : : * new, and creating a child requires owning the parent, anyway.
995 : : */
996 : :
997 : : /*
998 : : * Create a tuple descriptor from the relation schema. Note that this
999 : : * deals with column names, types, and in-descriptor NOT NULL flags, but
1000 : : * not default values, NOT NULL or CHECK constraints; we handle those
1001 : : * below.
1002 : : */
1003 : 40834 : descriptor = BuildDescForRelation(stmt->tableElts);
1004 : :
1005 : : /*
1006 : : * Find columns with default values and prepare for insertion of the
1007 : : * defaults. Pre-cooked (that is, inherited) defaults go into a list of
1008 : : * CookedConstraint structs that we'll pass to heap_create_with_catalog,
1009 : : * while raw defaults go into a list of RawColumnDefault structs that will
1010 : : * be processed by AddRelationNewConstraints. (We can't deal with raw
1011 : : * expressions until we can do transformExpr.)
1012 : : */
1013 : 40802 : rawDefaults = NIL;
1014 : 40802 : cookedDefaults = NIL;
1015 : 40802 : attnum = 0;
1016 : :
1017 [ + + + + : 204391 : foreach(listptr, stmt->tableElts)
+ + ]
1018 : : {
1019 : 163589 : ColumnDef *colDef = lfirst(listptr);
1020 : :
1021 : 163589 : attnum++;
1022 [ + + ]: 163589 : if (colDef->raw_default != NULL)
1023 : : {
1024 : : RawColumnDefault *rawEnt;
1025 : :
1026 : : Assert(colDef->cooked_default == NULL);
1027 : :
1028 : 2145 : rawEnt = palloc_object(RawColumnDefault);
1029 : 2145 : rawEnt->attnum = attnum;
1030 : 2145 : rawEnt->raw_default = colDef->raw_default;
1031 : 2145 : rawEnt->generated = colDef->generated;
1032 : 2145 : rawDefaults = lappend(rawDefaults, rawEnt);
1033 : : }
1034 [ + + ]: 161444 : else if (colDef->cooked_default != NULL)
1035 : : {
1036 : : CookedConstraint *cooked;
1037 : :
1038 : 274 : cooked = palloc_object(CookedConstraint);
1039 : 274 : cooked->contype = CONSTR_DEFAULT;
1040 : 274 : cooked->conoid = InvalidOid; /* until created */
1041 : 274 : cooked->name = NULL;
1042 : 274 : cooked->attnum = attnum;
1043 : 274 : cooked->expr = colDef->cooked_default;
1044 : 274 : cooked->is_enforced = true;
1045 : 274 : cooked->skip_validation = false;
1046 : 274 : cooked->is_local = true; /* not used for defaults */
1047 : 274 : cooked->inhcount = 0; /* ditto */
1048 : 274 : cooked->is_no_inherit = false;
1049 : 274 : cookedDefaults = lappend(cookedDefaults, cooked);
1050 : : }
1051 : : }
1052 : :
1053 : 40802 : TupleDescFinalize(descriptor);
1054 : :
1055 : : /*
1056 : : * For relations with table AM and partitioned tables, select access
1057 : : * method to use: an explicitly indicated one, or (in the case of a
1058 : : * partitioned table) the parent's, if it has one.
1059 : : */
1060 [ + + ]: 40802 : if (stmt->accessMethod != NULL)
1061 : : {
1062 : : Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
1063 : 79 : accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1064 : : }
1065 [ + + + - : 40723 : else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
+ + + + ]
1066 : : {
1067 [ + + ]: 26298 : if (stmt->partbound)
1068 : : {
1069 : : Assert(list_length(inheritOids) == 1);
1070 : 5893 : accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1071 : : }
1072 : :
1073 [ + + + - : 26298 : if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
+ + + + ]
1074 : 22870 : accessMethodId = get_table_am_oid(default_table_access_method, false);
1075 : : }
1076 : :
1077 : : /*
1078 : : * Create the relation. Inherited defaults and CHECK constraints are
1079 : : * passed in for immediate handling --- since they don't need parsing,
1080 : : * they can be stored immediately.
1081 : : */
1082 : 40790 : relationId = heap_create_with_catalog(relname,
1083 : : namespaceId,
1084 : : tablespaceId,
1085 : : InvalidOid,
1086 : : InvalidOid,
1087 : : ofTypeId,
1088 : : ownerId,
1089 : : accessMethodId,
1090 : : descriptor,
1091 : : list_concat(cookedDefaults,
1092 : : old_constraints),
1093 : : relkind,
1094 : 40790 : stmt->relation->relpersistence,
1095 : : false,
1096 : : false,
1097 : : stmt->oncommit,
1098 : : reloptions,
1099 : : true,
1100 : : allowSystemTableMods,
1101 : : false,
1102 : : InvalidOid,
1103 : : typaddress);
1104 : :
1105 : : /*
1106 : : * We must bump the command counter to make the newly-created relation
1107 : : * tuple visible for opening.
1108 : : */
1109 : 40757 : CommandCounterIncrement();
1110 : :
1111 : : /*
1112 : : * Open the new relation and acquire exclusive lock on it. This isn't
1113 : : * really necessary for locking out other backends (since they can't see
1114 : : * the new rel anyway until we commit), but it keeps the lock manager from
1115 : : * complaining about deadlock risks.
1116 : : */
1117 : 40757 : rel = relation_open(relationId, AccessExclusiveLock);
1118 : :
1119 : : /*
1120 : : * Now add any newly specified column default and generation expressions
1121 : : * to the new relation. These are passed to us in the form of raw
1122 : : * parsetrees; we need to transform them to executable expression trees
1123 : : * before they can be added. The most convenient way to do that is to
1124 : : * apply the parser's transformExpr routine, but transformExpr doesn't
1125 : : * work unless we have a pre-existing relation. So, the transformation has
1126 : : * to be postponed to this final step of CREATE TABLE.
1127 : : *
1128 : : * This needs to be before processing the partitioning clauses because
1129 : : * those could refer to generated columns.
1130 : : */
1131 [ + + ]: 40757 : if (rawDefaults)
1132 : 1839 : AddRelationNewConstraints(rel, rawDefaults, NIL,
1133 : : true, true, false, queryString);
1134 : :
1135 : : /*
1136 : : * Make column generation expressions visible for use by partitioning.
1137 : : */
1138 : 40625 : CommandCounterIncrement();
1139 : :
1140 : : /* Process and store partition bound, if any. */
1141 [ + + ]: 40625 : if (stmt->partbound)
1142 : : {
1143 : : PartitionBoundSpec *bound;
1144 : : ParseState *pstate;
1145 : 5968 : Oid parentId = linitial_oid(inheritOids),
1146 : : defaultPartOid;
1147 : : Relation parent,
1148 : 5968 : defaultRel = NULL;
1149 : : ParseNamespaceItem *nsitem;
1150 : :
1151 : : /* Already have strong enough lock on the parent */
1152 : 5968 : parent = table_open(parentId, NoLock);
1153 : :
1154 : : /*
1155 : : * We are going to try to validate the partition bound specification
1156 : : * against the partition key of parentRel, so it better have one.
1157 : : */
1158 [ + + ]: 5968 : if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1159 [ + - ]: 12 : ereport(ERROR,
1160 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1161 : : errmsg("\"%s\" is not partitioned",
1162 : : RelationGetRelationName(parent))));
1163 : :
1164 : : /*
1165 : : * The partition constraint of the default partition depends on the
1166 : : * partition bounds of every other partition. It is possible that
1167 : : * another backend might be about to execute a query on the default
1168 : : * partition table, and that the query relies on previously cached
1169 : : * default partition constraints. We must therefore take a table lock
1170 : : * strong enough to prevent all queries on the default partition from
1171 : : * proceeding until we commit and send out a shared-cache-inval notice
1172 : : * that will make them update their index lists.
1173 : : *
1174 : : * Order of locking: The relation being added won't be visible to
1175 : : * other backends until it is committed, hence here in
1176 : : * DefineRelation() the order of locking the default partition and the
1177 : : * relation being added does not matter. But at all other places we
1178 : : * need to lock the default relation before we lock the relation being
1179 : : * added or removed i.e. we should take the lock in same order at all
1180 : : * the places such that lock parent, lock default partition and then
1181 : : * lock the partition so as to avoid a deadlock.
1182 : : */
1183 : : defaultPartOid =
1184 : 5956 : get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
1185 : : true));
1186 [ + + ]: 5956 : if (OidIsValid(defaultPartOid))
1187 : 271 : defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1188 : :
1189 : : /* Transform the bound values */
1190 : 5956 : pstate = make_parsestate(NULL);
1191 : 5956 : pstate->p_sourcetext = queryString;
1192 : :
1193 : : /*
1194 : : * Add an nsitem containing this relation, so that transformExpr
1195 : : * called on partition bound expressions is able to report errors
1196 : : * using a proper context.
1197 : : */
1198 : 5956 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1199 : : NULL, false, false);
1200 : 5956 : addNSItemToQuery(pstate, nsitem, false, true, true);
1201 : :
1202 : 5956 : bound = transformPartitionBound(pstate, parent, stmt->partbound);
1203 : :
1204 : : /*
1205 : : * Check first that the new partition's bound is valid and does not
1206 : : * overlap with any of existing partitions of the parent.
1207 : : */
1208 : 5820 : check_new_partition_bound(relname, parent, bound, pstate);
1209 : :
1210 : : /*
1211 : : * If the default partition exists, its partition constraints will
1212 : : * change after the addition of this new partition such that it won't
1213 : : * allow any row that qualifies for this new partition. So, check that
1214 : : * the existing data in the default partition satisfies the constraint
1215 : : * as it will exist after adding this partition.
1216 : : */
1217 [ + + ]: 5744 : if (OidIsValid(defaultPartOid))
1218 : : {
1219 : 251 : check_default_partition_contents(parent, defaultRel, bound);
1220 : : /* Keep the lock until commit. */
1221 : 239 : table_close(defaultRel, NoLock);
1222 : : }
1223 : :
1224 : : /* Update the pg_class entry. */
1225 : 5732 : StorePartitionBound(rel, parent, bound);
1226 : :
1227 : 5732 : table_close(parent, NoLock);
1228 : : }
1229 : :
1230 : : /* Store inheritance information for new rel. */
1231 : 40389 : StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1232 : :
1233 : : /*
1234 : : * Process the partitioning specification (if any) and store the partition
1235 : : * key information into the catalog.
1236 : : */
1237 [ + + ]: 40389 : if (partitioned)
1238 : : {
1239 : : ParseState *pstate;
1240 : : int partnatts;
1241 : : AttrNumber partattrs[PARTITION_MAX_KEYS];
1242 : : Oid partopclass[PARTITION_MAX_KEYS];
1243 : : Oid partcollation[PARTITION_MAX_KEYS];
1244 : 3418 : List *partexprs = NIL;
1245 : :
1246 : 3418 : pstate = make_parsestate(NULL);
1247 : 3418 : pstate->p_sourcetext = queryString;
1248 : :
1249 : 3418 : partnatts = list_length(stmt->partspec->partParams);
1250 : :
1251 : : /* Protect fixed-size arrays here and in executor */
1252 [ - + ]: 3418 : if (partnatts > PARTITION_MAX_KEYS)
1253 [ # # ]: 0 : ereport(ERROR,
1254 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
1255 : : errmsg("cannot partition using more than %d columns",
1256 : : PARTITION_MAX_KEYS)));
1257 : :
1258 : : /*
1259 : : * We need to transform the raw parsetrees corresponding to partition
1260 : : * expressions into executable expression trees. Like column defaults
1261 : : * and CHECK constraints, we could not have done the transformation
1262 : : * earlier.
1263 : : */
1264 : 3418 : stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1265 : :
1266 : 3398 : ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1267 : : partattrs, &partexprs, partopclass,
1268 : 3398 : partcollation, stmt->partspec->strategy);
1269 : :
1270 : 3310 : StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1271 : : partexprs,
1272 : : partopclass, partcollation);
1273 : :
1274 : : /* make it all visible */
1275 : 3306 : CommandCounterIncrement();
1276 : : }
1277 : :
1278 : : /*
1279 : : * If we're creating a partition, create now all the indexes, triggers,
1280 : : * FKs defined in the parent.
1281 : : *
1282 : : * We can't do it earlier, because DefineIndex wants to know the partition
1283 : : * key which we just stored.
1284 : : */
1285 [ + + ]: 40277 : if (stmt->partbound)
1286 : : {
1287 : 5728 : Oid parentId = linitial_oid(inheritOids);
1288 : : Relation parent;
1289 : : List *idxlist;
1290 : : ListCell *cell;
1291 : :
1292 : : /* Already have strong enough lock on the parent */
1293 : 5728 : parent = table_open(parentId, NoLock);
1294 : 5728 : idxlist = RelationGetIndexList(parent);
1295 : :
1296 : : /*
1297 : : * For each index in the parent table, create one in the partition
1298 : : */
1299 [ + + + + : 6685 : foreach(cell, idxlist)
+ + ]
1300 : : {
1301 : 969 : Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1302 : : AttrMap *attmap;
1303 : : IndexStmt *idxstmt;
1304 : : Oid constraintOid;
1305 : :
1306 [ + + ]: 969 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1307 : : {
1308 [ + + ]: 36 : if (idxRel->rd_index->indisunique)
1309 [ + - ]: 8 : ereport(ERROR,
1310 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1311 : : errmsg("cannot create foreign partition of partitioned table \"%s\"",
1312 : : RelationGetRelationName(parent)),
1313 : : errdetail("Table \"%s\" contains indexes that are unique.",
1314 : : RelationGetRelationName(parent))));
1315 : : else
1316 : : {
1317 : 28 : index_close(idxRel, AccessShareLock);
1318 : 28 : continue;
1319 : : }
1320 : : }
1321 : :
1322 : 933 : attmap = build_attrmap_by_name(RelationGetDescr(rel),
1323 : : RelationGetDescr(parent),
1324 : : false);
1325 : : idxstmt =
1326 : 933 : generateClonedIndexStmt(NULL, idxRel,
1327 : : attmap, &constraintOid);
1328 : 933 : DefineIndex(NULL,
1329 : : RelationGetRelid(rel),
1330 : : idxstmt,
1331 : : InvalidOid,
1332 : : RelationGetRelid(idxRel),
1333 : : constraintOid,
1334 : : -1,
1335 : : false, false, false, false, false);
1336 : :
1337 : 929 : index_close(idxRel, AccessShareLock);
1338 : : }
1339 : :
1340 : 5716 : list_free(idxlist);
1341 : :
1342 : : /*
1343 : : * If there are any row-level triggers, clone them to the new
1344 : : * partition.
1345 : : */
1346 [ + + ]: 5716 : if (parent->trigdesc != NULL)
1347 : 232 : CloneRowTriggersToPartition(parent, rel);
1348 : :
1349 : : /*
1350 : : * And foreign keys too. Note that because we're freshly creating the
1351 : : * table, there is no need to verify these new constraints.
1352 : : */
1353 : 5716 : CloneForeignKeyConstraints(NULL, parent, rel);
1354 : :
1355 : 5716 : table_close(parent, NoLock);
1356 : : }
1357 : :
1358 : : /*
1359 : : * Now add any newly specified CHECK constraints to the new relation. Same
1360 : : * as for defaults above, but these need to come after partitioning is set
1361 : : * up. We save the constraint names that were used, to avoid dupes below.
1362 : : */
1363 [ + + ]: 40265 : if (stmt->constraints)
1364 : : {
1365 : : List *conlist;
1366 : :
1367 : 530 : conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1368 : : true, true, false, queryString);
1369 [ + + + + : 1593 : foreach_ptr(CookedConstraint, cons, conlist)
+ + ]
1370 : : {
1371 [ + - ]: 581 : if (cons->name != NULL)
1372 : 581 : connames = lappend(connames, cons->name);
1373 : : }
1374 : : }
1375 : :
1376 : : /*
1377 : : * Finally, merge the not-null constraints that are declared directly with
1378 : : * those that come from parent relations (making sure to count inheritance
1379 : : * appropriately for each), create them, and set the attnotnull flag on
1380 : : * columns that don't yet have it.
1381 : : */
1382 : 40241 : nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1383 : : old_notnulls, connames);
1384 [ + + + + : 90091 : foreach_int(attrnum, nncols)
+ + ]
1385 : 9721 : set_attnotnull(NULL, rel, attrnum, false);
1386 : :
1387 : 40185 : ObjectAddressSet(address, RelationRelationId, relationId);
1388 : :
1389 : : /*
1390 : : * Clean up. We keep lock on new relation (although it shouldn't be
1391 : : * visible to anyone else anyway, until commit).
1392 : : */
1393 : 40185 : relation_close(rel, NoLock);
1394 : :
1395 : 40185 : return address;
1396 : : }
1397 : :
1398 : : /*
1399 : : * BuildDescForRelation
1400 : : *
1401 : : * Given a list of ColumnDef nodes, build a TupleDesc.
1402 : : *
1403 : : * Note: This is only for the limited purpose of table and view creation. Not
1404 : : * everything is filled in. A real tuple descriptor should be obtained from
1405 : : * the relcache.
1406 : : */
1407 : : TupleDesc
1408 : 42972 : BuildDescForRelation(const List *columns)
1409 : : {
1410 : : int natts;
1411 : : AttrNumber attnum;
1412 : : ListCell *l;
1413 : : TupleDesc desc;
1414 : : char *attname;
1415 : : Oid atttypid;
1416 : : int32 atttypmod;
1417 : : Oid attcollation;
1418 : : int attdim;
1419 : :
1420 : : /*
1421 : : * allocate a new tuple descriptor
1422 : : */
1423 : 42972 : natts = list_length(columns);
1424 : 42972 : desc = CreateTemplateTupleDesc(natts);
1425 : :
1426 : 42972 : attnum = 0;
1427 : :
1428 [ + + + + : 208923 : foreach(l, columns)
+ + ]
1429 : : {
1430 : 165991 : ColumnDef *entry = lfirst(l);
1431 : : AclResult aclresult;
1432 : : Form_pg_attribute att;
1433 : :
1434 : : /*
1435 : : * for each entry in the list, get the name and type information from
1436 : : * the list and have TupleDescInitEntry fill in the attribute
1437 : : * information we need.
1438 : : */
1439 : 165991 : attnum++;
1440 : :
1441 : 165991 : attname = entry->colname;
1442 : 165991 : typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1443 : :
1444 : 165991 : aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1445 [ + + ]: 165991 : if (aclresult != ACLCHECK_OK)
1446 : 28 : aclcheck_error_type(aclresult, atttypid);
1447 : :
1448 : 165963 : attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1449 : 165963 : attdim = list_length(entry->typeName->arrayBounds);
1450 [ - + ]: 165963 : if (attdim > PG_INT16_MAX)
1451 [ # # ]: 0 : ereport(ERROR,
1452 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1453 : : errmsg("too many array dimensions"));
1454 : :
1455 [ - + ]: 165963 : if (entry->typeName->setof)
1456 [ # # ]: 0 : ereport(ERROR,
1457 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1458 : : errmsg("column \"%s\" cannot be declared SETOF",
1459 : : attname)));
1460 : :
1461 : 165963 : TupleDescInitEntry(desc, attnum, attname,
1462 : : atttypid, atttypmod, attdim);
1463 : 165963 : att = TupleDescAttr(desc, attnum - 1);
1464 : :
1465 : : /* Override TupleDescInitEntry's settings as requested */
1466 : 165963 : TupleDescInitEntryCollation(desc, attnum, attcollation);
1467 : :
1468 : : /* Fill in additional stuff not handled by TupleDescInitEntry */
1469 : 165963 : att->attnotnull = entry->is_not_null;
1470 : 165963 : att->attislocal = entry->is_local;
1471 : 165963 : att->attinhcount = entry->inhcount;
1472 : 165963 : att->attidentity = entry->identity;
1473 : 165963 : att->attgenerated = entry->generated;
1474 : 165963 : att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1475 [ + + ]: 165955 : if (entry->storage)
1476 : 14175 : att->attstorage = entry->storage;
1477 [ + + ]: 151780 : else if (entry->storage_name)
1478 : 25 : att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1479 : :
1480 : 165951 : populate_compact_attribute(desc, attnum - 1);
1481 : : }
1482 : :
1483 : 42932 : TupleDescFinalize(desc);
1484 : :
1485 : 42932 : return desc;
1486 : : }
1487 : :
1488 : : /*
1489 : : * Emit the right error or warning message for a "DROP" command issued on a
1490 : : * non-existent relation
1491 : : */
1492 : : static void
1493 : 619 : DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
1494 : : {
1495 : : const struct dropmsgstrings *rentry;
1496 : :
1497 [ + + + + ]: 699 : if (rel->schemaname != NULL &&
1498 : 80 : !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
1499 : : {
1500 [ - + ]: 28 : if (!missing_ok)
1501 : : {
1502 [ # # ]: 0 : ereport(ERROR,
1503 : : (errcode(ERRCODE_UNDEFINED_SCHEMA),
1504 : : errmsg("schema \"%s\" does not exist", rel->schemaname)));
1505 : : }
1506 : : else
1507 : : {
1508 [ + - ]: 28 : ereport(NOTICE,
1509 : : (errmsg("schema \"%s\" does not exist, skipping",
1510 : : rel->schemaname)));
1511 : : }
1512 : 28 : return;
1513 : : }
1514 : :
1515 [ + - ]: 804 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1516 : : {
1517 [ + + ]: 804 : if (rentry->kind == rightkind)
1518 : : {
1519 [ + + ]: 591 : if (!missing_ok)
1520 : : {
1521 [ + - ]: 86 : ereport(ERROR,
1522 : : (errcode(rentry->nonexistent_code),
1523 : : errmsg(rentry->nonexistent_msg, rel->relname)));
1524 : : }
1525 : : else
1526 : : {
1527 [ + + ]: 505 : ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
1528 : 505 : break;
1529 : : }
1530 : : }
1531 : : }
1532 : :
1533 : : Assert(rentry->kind != '\0'); /* Should be impossible */
1534 : : }
1535 : :
1536 : : /*
1537 : : * Emit the right error message for a "DROP" command issued on a
1538 : : * relation of the wrong type
1539 : : */
1540 : : static void
1541 : 0 : DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
1542 : : {
1543 : : const struct dropmsgstrings *rentry;
1544 : : const struct dropmsgstrings *wentry;
1545 : :
1546 [ # # ]: 0 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1547 [ # # ]: 0 : if (rentry->kind == rightkind)
1548 : 0 : break;
1549 : : Assert(rentry->kind != '\0');
1550 : :
1551 [ # # ]: 0 : for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
1552 [ # # ]: 0 : if (wentry->kind == wrongkind)
1553 : 0 : break;
1554 : : /* wrongkind could be something we don't have in our table... */
1555 : :
1556 [ # # # # ]: 0 : ereport(ERROR,
1557 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1558 : : errmsg(rentry->nota_msg, relname),
1559 : : (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
1560 : : }
1561 : :
1562 : : /*
1563 : : * RemoveRelations
1564 : : * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
1565 : : * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
1566 : : */
1567 : : void
1568 : 11546 : RemoveRelations(DropStmt *drop)
1569 : : {
1570 : : ObjectAddresses *objects;
1571 : : char relkind;
1572 : : ListCell *cell;
1573 : 11546 : int flags = 0;
1574 : 11546 : LOCKMODE lockmode = AccessExclusiveLock;
1575 : :
1576 : : /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1577 [ + + ]: 11546 : if (drop->concurrent)
1578 : : {
1579 : : /*
1580 : : * Note that for temporary relations this lock may get upgraded later
1581 : : * on, but as no other session can access a temporary relation, this
1582 : : * is actually fine.
1583 : : */
1584 : 116 : lockmode = ShareUpdateExclusiveLock;
1585 : : Assert(drop->removeType == OBJECT_INDEX);
1586 [ + + ]: 116 : if (list_length(drop->objects) != 1)
1587 [ + - ]: 4 : ereport(ERROR,
1588 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1589 : : errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1590 [ - + ]: 112 : if (drop->behavior == DROP_CASCADE)
1591 [ # # ]: 0 : ereport(ERROR,
1592 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1593 : : errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1594 : : }
1595 : :
1596 : : /*
1597 : : * First we identify all the relations, then we delete them in a single
1598 : : * performMultipleDeletions() call. This is to avoid unwanted DROP
1599 : : * RESTRICT errors if one of the relations depends on another.
1600 : : */
1601 : :
1602 : : /* Determine required relkind */
1603 [ + + + + : 11542 : switch (drop->removeType)
+ + - ]
1604 : : {
1605 : 9982 : case OBJECT_TABLE:
1606 : 9982 : relkind = RELKIND_RELATION;
1607 : 9982 : break;
1608 : :
1609 : 563 : case OBJECT_INDEX:
1610 : 563 : relkind = RELKIND_INDEX;
1611 : 563 : break;
1612 : :
1613 : 123 : case OBJECT_SEQUENCE:
1614 : 123 : relkind = RELKIND_SEQUENCE;
1615 : 123 : break;
1616 : :
1617 : 676 : case OBJECT_VIEW:
1618 : 676 : relkind = RELKIND_VIEW;
1619 : 676 : break;
1620 : :
1621 : 84 : case OBJECT_MATVIEW:
1622 : 84 : relkind = RELKIND_MATVIEW;
1623 : 84 : break;
1624 : :
1625 : 114 : case OBJECT_FOREIGN_TABLE:
1626 : 114 : relkind = RELKIND_FOREIGN_TABLE;
1627 : 114 : break;
1628 : :
1629 : 0 : default:
1630 [ # # ]: 0 : elog(ERROR, "unrecognized drop object type: %d",
1631 : : (int) drop->removeType);
1632 : : relkind = 0; /* keep compiler quiet */
1633 : : break;
1634 : : }
1635 : :
1636 : : /* Lock and validate each relation; build a list of object addresses */
1637 : 11542 : objects = new_object_addresses();
1638 : :
1639 [ + - + + : 25583 : foreach(cell, drop->objects)
+ + ]
1640 : : {
1641 : 14148 : RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1642 : : Oid relOid;
1643 : : ObjectAddress obj;
1644 : : struct DropRelationCallbackState state;
1645 : :
1646 : : /*
1647 : : * These next few steps are a great deal like relation_openrv, but we
1648 : : * don't bother building a relcache entry since we don't need it.
1649 : : *
1650 : : * Check for shared-cache-inval messages before trying to access the
1651 : : * relation. This is needed to cover the case where the name
1652 : : * identifies a rel that has been dropped and recreated since the
1653 : : * start of our transaction: if we don't flush the old syscache entry,
1654 : : * then we'll latch onto that entry and suffer an error later.
1655 : : */
1656 : 14148 : AcceptInvalidationMessages();
1657 : :
1658 : : /* Look up the appropriate relation using namespace search. */
1659 : 14148 : state.expected_relkind = relkind;
1660 : 28296 : state.heap_lockmode = drop->concurrent ?
1661 [ + + ]: 14148 : ShareUpdateExclusiveLock : AccessExclusiveLock;
1662 : : /* We must initialize these fields to show that no locks are held: */
1663 : 14148 : state.heapOid = InvalidOid;
1664 : 14148 : state.partParentOid = InvalidOid;
1665 : :
1666 : 14148 : relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1667 : : RangeVarCallbackForDropRelation,
1668 : : &state);
1669 : :
1670 : : /* Not there? */
1671 [ + + ]: 14131 : if (!OidIsValid(relOid))
1672 : : {
1673 : 619 : DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1674 : 533 : continue;
1675 : : }
1676 : :
1677 : : /*
1678 : : * Decide if concurrent mode needs to be used here or not. The
1679 : : * callback retrieved the rel's persistence for us.
1680 : : */
1681 [ + + ]: 13512 : if (drop->concurrent &&
1682 [ + + ]: 108 : state.actual_relpersistence != RELPERSISTENCE_TEMP)
1683 : : {
1684 : : Assert(list_length(drop->objects) == 1 &&
1685 : : drop->removeType == OBJECT_INDEX);
1686 : 96 : flags |= PERFORM_DELETION_CONCURRENTLY;
1687 : : }
1688 : :
1689 : : /*
1690 : : * Concurrent index drop cannot be used with partitioned indexes,
1691 : : * either.
1692 : : */
1693 [ + + ]: 13512 : if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1694 [ + + ]: 96 : state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1695 [ + - ]: 4 : ereport(ERROR,
1696 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1697 : : errmsg("cannot drop partitioned index \"%s\" concurrently",
1698 : : rel->relname)));
1699 : :
1700 : : /*
1701 : : * If we're told to drop a partitioned index, we must acquire lock on
1702 : : * all the children of its parent partitioned table before proceeding.
1703 : : * Otherwise we'd try to lock the child index partitions before their
1704 : : * tables, leading to potential deadlock against other sessions that
1705 : : * will lock those objects in the other order.
1706 : : */
1707 [ + + ]: 13508 : if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1708 : 50 : (void) find_all_inheritors(state.heapOid,
1709 : : state.heap_lockmode,
1710 : : NULL);
1711 : :
1712 : : /* OK, we're ready to delete this one */
1713 : 13508 : obj.classId = RelationRelationId;
1714 : 13508 : obj.objectId = relOid;
1715 : 13508 : obj.objectSubId = 0;
1716 : :
1717 : 13508 : add_exact_object_address(&obj, objects);
1718 : : }
1719 : :
1720 : 11435 : performMultipleDeletions(objects, drop->behavior, flags);
1721 : :
1722 : 11340 : free_object_addresses(objects);
1723 : 11340 : }
1724 : :
1725 : : /*
1726 : : * Before acquiring a table lock, check whether we have sufficient rights.
1727 : : * In the case of DROP INDEX, also try to lock the table before the index.
1728 : : * Also, if the table to be dropped is a partition, we try to lock the parent
1729 : : * first.
1730 : : */
1731 : : static void
1732 : 14360 : RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
1733 : : void *arg)
1734 : : {
1735 : : HeapTuple tuple;
1736 : : struct DropRelationCallbackState *state;
1737 : : char expected_relkind;
1738 : : bool is_partition;
1739 : : Form_pg_class classform;
1740 : : LOCKMODE heap_lockmode;
1741 : 14360 : bool invalid_system_index = false;
1742 : :
1743 : 14360 : state = (struct DropRelationCallbackState *) arg;
1744 : 14360 : heap_lockmode = state->heap_lockmode;
1745 : :
1746 : : /*
1747 : : * If we previously locked some other index's heap, and the name we're
1748 : : * looking up no longer refers to that relation, release the now-useless
1749 : : * lock.
1750 : : */
1751 [ + + - + ]: 14360 : if (relOid != oldRelOid && OidIsValid(state->heapOid))
1752 : : {
1753 : 0 : UnlockRelationOid(state->heapOid, heap_lockmode);
1754 : 0 : state->heapOid = InvalidOid;
1755 : : }
1756 : :
1757 : : /*
1758 : : * Similarly, if we previously locked some other partition's heap, and the
1759 : : * name we're looking up no longer refers to that relation, release the
1760 : : * now-useless lock.
1761 : : */
1762 [ + + - + ]: 14360 : if (relOid != oldRelOid && OidIsValid(state->partParentOid))
1763 : : {
1764 : 0 : UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
1765 : 0 : state->partParentOid = InvalidOid;
1766 : : }
1767 : :
1768 : : /* Didn't find a relation, so no need for locking or permission checks. */
1769 [ + + ]: 14360 : if (!OidIsValid(relOid))
1770 : 622 : return;
1771 : :
1772 : 13738 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1773 [ - + ]: 13738 : if (!HeapTupleIsValid(tuple))
1774 : 0 : return; /* concurrently dropped, so nothing to do */
1775 : 13738 : classform = (Form_pg_class) GETSTRUCT(tuple);
1776 : 13738 : is_partition = classform->relispartition;
1777 : :
1778 : : /* Pass back some data to save lookups in RemoveRelations */
1779 : 13738 : state->actual_relkind = classform->relkind;
1780 : 13738 : state->actual_relpersistence = classform->relpersistence;
1781 : :
1782 : : /*
1783 : : * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
1784 : : * but RemoveRelations() can only pass one relkind for a given relation.
1785 : : * It chooses RELKIND_RELATION for both regular and partitioned tables.
1786 : : * That means we must be careful before giving the wrong type error when
1787 : : * the relation is RELKIND_PARTITIONED_TABLE. An equivalent problem
1788 : : * exists with indexes.
1789 : : */
1790 [ + + ]: 13738 : if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1791 : 2013 : expected_relkind = RELKIND_RELATION;
1792 [ + + ]: 11725 : else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1793 : 56 : expected_relkind = RELKIND_INDEX;
1794 : : else
1795 : 11669 : expected_relkind = classform->relkind;
1796 : :
1797 [ - + ]: 13738 : if (state->expected_relkind != expected_relkind)
1798 : 0 : DropErrorMsgWrongType(rel->relname, classform->relkind,
1799 : 0 : state->expected_relkind);
1800 : :
1801 : : /* Allow DROP to either table owner or schema owner */
1802 [ + + ]: 13738 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
1803 [ + - ]: 12 : !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
1804 : 12 : aclcheck_error(ACLCHECK_NOT_OWNER,
1805 : 12 : get_relkind_objtype(classform->relkind),
1806 : 12 : rel->relname);
1807 : :
1808 : : /*
1809 : : * Check the case of a system index that might have been invalidated by a
1810 : : * failed concurrent process and allow its drop. For the time being, this
1811 : : * only concerns indexes of toast relations that became invalid during a
1812 : : * REINDEX CONCURRENTLY process.
1813 : : */
1814 [ + + - + ]: 13726 : if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
1815 : : {
1816 : : HeapTuple locTuple;
1817 : : Form_pg_index indexform;
1818 : : bool indisvalid;
1819 : :
1820 : 0 : locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
1821 [ # # ]: 0 : if (!HeapTupleIsValid(locTuple))
1822 : : {
1823 : 0 : ReleaseSysCache(tuple);
1824 : 0 : return;
1825 : : }
1826 : :
1827 : 0 : indexform = (Form_pg_index) GETSTRUCT(locTuple);
1828 : 0 : indisvalid = indexform->indisvalid;
1829 : 0 : ReleaseSysCache(locTuple);
1830 : :
1831 : : /* Mark object as being an invalid index of system catalogs */
1832 [ # # ]: 0 : if (!indisvalid)
1833 : 0 : invalid_system_index = true;
1834 : : }
1835 : :
1836 : : /* In the case of an invalid index, it is fine to bypass this check */
1837 [ + - + + : 13726 : if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
+ + ]
1838 [ + - ]: 5 : ereport(ERROR,
1839 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1840 : : errmsg("permission denied: \"%s\" is a system catalog",
1841 : : rel->relname)));
1842 : :
1843 : 13721 : ReleaseSysCache(tuple);
1844 : :
1845 : : /*
1846 : : * In DROP INDEX, attempt to acquire lock on the parent table before
1847 : : * locking the index. index_drop() will need this anyway, and since
1848 : : * regular queries lock tables before their indexes, we risk deadlock if
1849 : : * we do it the other way around. No error if we don't find a pg_index
1850 : : * entry, though --- the relation may have been dropped. Note that this
1851 : : * code will execute for either plain or partitioned indexes.
1852 : : */
1853 [ + + + + ]: 13721 : if (expected_relkind == RELKIND_INDEX &&
1854 : : relOid != oldRelOid)
1855 : : {
1856 : 555 : state->heapOid = IndexGetRelation(relOid, true);
1857 [ + - ]: 555 : if (OidIsValid(state->heapOid))
1858 : 555 : LockRelationOid(state->heapOid, heap_lockmode);
1859 : : }
1860 : :
1861 : : /*
1862 : : * Similarly, if the relation is a partition, we must acquire lock on its
1863 : : * parent before locking the partition. That's because queries lock the
1864 : : * parent before its partitions, so we risk deadlock if we do it the other
1865 : : * way around.
1866 : : */
1867 [ + + + + ]: 13721 : if (is_partition && relOid != oldRelOid)
1868 : : {
1869 : 411 : state->partParentOid = get_partition_parent(relOid, true);
1870 [ + - ]: 411 : if (OidIsValid(state->partParentOid))
1871 : 411 : LockRelationOid(state->partParentOid, AccessExclusiveLock);
1872 : : }
1873 : : }
1874 : :
1875 : : /*
1876 : : * ExecuteTruncate
1877 : : * Executes a TRUNCATE command.
1878 : : *
1879 : : * This is a multi-relation truncate. We first open and grab exclusive
1880 : : * lock on all relations involved, checking permissions and otherwise
1881 : : * verifying that the relation is OK for truncation. Note that if relations
1882 : : * are foreign tables, at this stage, we have not yet checked that their
1883 : : * foreign data in external data sources are OK for truncation. These are
1884 : : * checked when foreign data are actually truncated later. In CASCADE mode,
1885 : : * relations having FK references to the targeted relations are automatically
1886 : : * added to the group; in RESTRICT mode, we check that all FK references are
1887 : : * internal to the group that's being truncated. Finally all the relations
1888 : : * are truncated and reindexed.
1889 : : */
1890 : : void
1891 : 1176 : ExecuteTruncate(TruncateStmt *stmt)
1892 : : {
1893 : 1176 : List *rels = NIL;
1894 : 1176 : List *relids = NIL;
1895 : 1176 : List *relids_logged = NIL;
1896 : : ListCell *cell;
1897 : :
1898 : : /*
1899 : : * Open, exclusive-lock, and check all the explicitly-specified relations
1900 : : */
1901 [ + - + + : 2488 : foreach(cell, stmt->relations)
+ + ]
1902 : : {
1903 : 1348 : RangeVar *rv = lfirst(cell);
1904 : : Relation rel;
1905 : 1348 : bool recurse = rv->inh;
1906 : : Oid myrelid;
1907 : 1348 : LOCKMODE lockmode = AccessExclusiveLock;
1908 : :
1909 : 1348 : myrelid = RangeVarGetRelidExtended(rv, lockmode,
1910 : : 0, RangeVarCallbackForTruncate,
1911 : : NULL);
1912 : :
1913 : : /* don't throw error for "TRUNCATE foo, foo" */
1914 [ + + ]: 1325 : if (list_member_oid(relids, myrelid))
1915 : 1 : continue;
1916 : :
1917 : : /* open the relation, we already hold a lock on it */
1918 : 1324 : rel = table_open(myrelid, NoLock);
1919 : :
1920 : : /*
1921 : : * RangeVarGetRelidExtended() has done most checks with its callback,
1922 : : * but other checks with the now-opened Relation remain.
1923 : : */
1924 : 1324 : truncate_check_activity(rel);
1925 : :
1926 : 1319 : rels = lappend(rels, rel);
1927 : 1319 : relids = lappend_oid(relids, myrelid);
1928 : :
1929 : : /* Log this relation only if needed for logical decoding */
1930 [ + + - + : 1319 : if (RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ + ]
1931 : 39 : relids_logged = lappend_oid(relids_logged, myrelid);
1932 : :
1933 [ + + ]: 1319 : if (recurse)
1934 : : {
1935 : : ListCell *child;
1936 : : List *children;
1937 : :
1938 : 1284 : children = find_all_inheritors(myrelid, lockmode, NULL);
1939 : :
1940 [ + - + + : 3788 : foreach(child, children)
+ + ]
1941 : : {
1942 : 2504 : Oid childrelid = lfirst_oid(child);
1943 : :
1944 [ + + ]: 2504 : if (list_member_oid(relids, childrelid))
1945 : 1284 : continue;
1946 : :
1947 : : /* find_all_inheritors already got lock */
1948 : 1220 : rel = table_open(childrelid, NoLock);
1949 : :
1950 : : /*
1951 : : * It is possible that the parent table has children that are
1952 : : * temp tables of other backends. We cannot safely access
1953 : : * such tables (because of buffering issues), and the best
1954 : : * thing to do is to silently ignore them. Note that this
1955 : : * check is the same as one of the checks done in
1956 : : * truncate_check_activity() called below, still it is kept
1957 : : * here for simplicity.
1958 : : */
1959 [ + + + + ]: 1220 : if (RELATION_IS_OTHER_TEMP(rel))
1960 : : {
1961 : 4 : table_close(rel, lockmode);
1962 : 4 : continue;
1963 : : }
1964 : :
1965 : : /*
1966 : : * Inherited TRUNCATE commands perform access permission
1967 : : * checks on the parent table only. So we skip checking the
1968 : : * children's permissions and don't call
1969 : : * truncate_check_perms() here.
1970 : : */
1971 : 1216 : truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
1972 : 1216 : truncate_check_activity(rel);
1973 : :
1974 : 1216 : rels = lappend(rels, rel);
1975 : 1216 : relids = lappend_oid(relids, childrelid);
1976 : :
1977 : : /* Log this relation only if needed for logical decoding */
1978 [ + + - + : 1216 : if (RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ - ]
1979 : 11 : relids_logged = lappend_oid(relids_logged, childrelid);
1980 : : }
1981 : : }
1982 [ + + ]: 35 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1983 [ + - ]: 8 : ereport(ERROR,
1984 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1985 : : errmsg("cannot truncate only a partitioned table"),
1986 : : errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1987 : : }
1988 : :
1989 : 1140 : ExecuteTruncateGuts(rels, relids, relids_logged,
1990 : 1140 : stmt->behavior, stmt->restart_seqs, false);
1991 : :
1992 : : /* And close the rels */
1993 [ + - + + : 3513 : foreach(cell, rels)
+ + ]
1994 : : {
1995 : 2426 : Relation rel = (Relation) lfirst(cell);
1996 : :
1997 : 2426 : table_close(rel, NoLock);
1998 : : }
1999 : 1087 : }
2000 : :
2001 : : /*
2002 : : * ExecuteTruncateGuts
2003 : : *
2004 : : * Internal implementation of TRUNCATE. This is called by the actual TRUNCATE
2005 : : * command (see above) as well as replication subscribers that execute a
2006 : : * replicated TRUNCATE action.
2007 : : *
2008 : : * explicit_rels is the list of Relations to truncate that the command
2009 : : * specified. relids is the list of Oids corresponding to explicit_rels.
2010 : : * relids_logged is the list of Oids (a subset of relids) that require
2011 : : * WAL-logging. This is all a bit redundant, but the existing callers have
2012 : : * this information handy in this form.
2013 : : */
2014 : : void
2015 : 1160 : ExecuteTruncateGuts(List *explicit_rels,
2016 : : List *relids,
2017 : : List *relids_logged,
2018 : : DropBehavior behavior, bool restart_seqs,
2019 : : bool run_as_table_owner)
2020 : : {
2021 : : List *rels;
2022 : 1160 : List *seq_relids = NIL;
2023 : 1160 : HTAB *ft_htab = NULL;
2024 : : EState *estate;
2025 : : ResultRelInfo *resultRelInfos;
2026 : : ResultRelInfo *resultRelInfo;
2027 : : SubTransactionId mySubid;
2028 : : ListCell *cell;
2029 : : Oid *logrelids;
2030 : :
2031 : : /*
2032 : : * Check the explicitly-specified relations.
2033 : : *
2034 : : * In CASCADE mode, suck in all referencing relations as well. This
2035 : : * requires multiple iterations to find indirectly-dependent relations. At
2036 : : * each phase, we need to exclusive-lock new rels before looking for their
2037 : : * dependencies, else we might miss something. Also, we check each rel as
2038 : : * soon as we open it, to avoid a faux pas such as holding lock for a long
2039 : : * time on a rel we have no permissions for.
2040 : : */
2041 : 1160 : rels = list_copy(explicit_rels);
2042 [ + + ]: 1160 : if (behavior == DROP_CASCADE)
2043 : : {
2044 : : for (;;)
2045 : 26 : {
2046 : : List *newrelids;
2047 : :
2048 : 51 : newrelids = heap_truncate_find_FKs(relids);
2049 [ + + ]: 51 : if (newrelids == NIL)
2050 : 25 : break; /* nothing else to add */
2051 : :
2052 [ + - + + : 88 : foreach(cell, newrelids)
+ + ]
2053 : : {
2054 : 62 : Oid relid = lfirst_oid(cell);
2055 : : Relation rel;
2056 : :
2057 : 62 : rel = table_open(relid, AccessExclusiveLock);
2058 [ + - ]: 62 : ereport(NOTICE,
2059 : : (errmsg("truncate cascades to table \"%s\"",
2060 : : RelationGetRelationName(rel))));
2061 : 62 : truncate_check_rel(relid, rel->rd_rel);
2062 : 62 : truncate_check_perms(relid, rel->rd_rel);
2063 : 62 : truncate_check_activity(rel);
2064 : 62 : rels = lappend(rels, rel);
2065 : 62 : relids = lappend_oid(relids, relid);
2066 : :
2067 : : /* Log this relation only if needed for logical decoding */
2068 [ + - - + : 62 : if (RelationIsLogicallyLogged(rel))
- - - - -
- - - - -
- - ]
2069 : 0 : relids_logged = lappend_oid(relids_logged, relid);
2070 : : }
2071 : : }
2072 : : }
2073 : :
2074 : : /*
2075 : : * Check foreign key references. In CASCADE mode, this should be
2076 : : * unnecessary since we just pulled in all the references; but as a
2077 : : * cross-check, do it anyway if in an Assert-enabled build.
2078 : : */
2079 : : #ifdef USE_ASSERT_CHECKING
2080 : : heap_truncate_check_FKs(rels, false);
2081 : : #else
2082 [ + + ]: 1160 : if (behavior == DROP_RESTRICT)
2083 : 1135 : heap_truncate_check_FKs(rels, false);
2084 : : #endif
2085 : :
2086 : : /*
2087 : : * If we are asked to restart sequences, find all the sequences, lock them
2088 : : * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2089 : : * We want to do this early since it's pointless to do all the truncation
2090 : : * work only to fail on sequence permissions.
2091 : : */
2092 [ + + ]: 1111 : if (restart_seqs)
2093 : : {
2094 [ + - + + : 30 : foreach(cell, rels)
+ + ]
2095 : : {
2096 : 15 : Relation rel = (Relation) lfirst(cell);
2097 : 15 : List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2098 : : ListCell *seqcell;
2099 : :
2100 [ + + + + : 37 : foreach(seqcell, seqlist)
+ + ]
2101 : : {
2102 : 22 : Oid seq_relid = lfirst_oid(seqcell);
2103 : : Relation seq_rel;
2104 : :
2105 : 22 : seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2106 : :
2107 : : /* This check must match AlterSequence! */
2108 [ - + ]: 22 : if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2109 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
2110 : 0 : RelationGetRelationName(seq_rel));
2111 : :
2112 : 22 : seq_relids = lappend_oid(seq_relids, seq_relid);
2113 : :
2114 : 22 : relation_close(seq_rel, NoLock);
2115 : : }
2116 : : }
2117 : : }
2118 : :
2119 : : /* Prepare to catch AFTER triggers. */
2120 : 1111 : AfterTriggerBeginQuery();
2121 : :
2122 : : /*
2123 : : * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2124 : : * each relation. We don't need to call ExecOpenIndices, though.
2125 : : *
2126 : : * We put the ResultRelInfos in the es_opened_result_relations list, even
2127 : : * though we don't have a range table and don't populate the
2128 : : * es_result_relations array. That's a bit bogus, but it's enough to make
2129 : : * ExecGetTriggerResultRel() find them.
2130 : : */
2131 : 1111 : estate = CreateExecutorState();
2132 : 1111 : resultRelInfos = palloc_array(ResultRelInfo, list_length(rels));
2133 : 1111 : resultRelInfo = resultRelInfos;
2134 [ + - + + : 3639 : foreach(cell, rels)
+ + ]
2135 : : {
2136 : 2528 : Relation rel = (Relation) lfirst(cell);
2137 : :
2138 : 2528 : InitResultRelInfo(resultRelInfo,
2139 : : rel,
2140 : : 0, /* dummy rangetable index */
2141 : : NULL,
2142 : : 0);
2143 : 2528 : estate->es_opened_result_relations =
2144 : 2528 : lappend(estate->es_opened_result_relations, resultRelInfo);
2145 : 2528 : resultRelInfo++;
2146 : : }
2147 : :
2148 : : /*
2149 : : * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2150 : : * truncating (this is because one of them might throw an error). Also, if
2151 : : * we were to allow them to prevent statement execution, that would need
2152 : : * to be handled here.
2153 : : */
2154 : 1111 : resultRelInfo = resultRelInfos;
2155 [ + - + + : 3639 : foreach(cell, rels)
+ + ]
2156 : : {
2157 : : UserContext ucxt;
2158 : :
2159 [ + + ]: 2528 : if (run_as_table_owner)
2160 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2161 : : &ucxt);
2162 : 2528 : ExecBSTruncateTriggers(estate, resultRelInfo);
2163 [ + + ]: 2528 : if (run_as_table_owner)
2164 : 36 : RestoreUserContext(&ucxt);
2165 : 2528 : resultRelInfo++;
2166 : : }
2167 : :
2168 : : /*
2169 : : * OK, truncate each table.
2170 : : */
2171 : 1111 : mySubid = GetCurrentSubTransactionId();
2172 : :
2173 [ + - + + : 3639 : foreach(cell, rels)
+ + ]
2174 : : {
2175 : 2528 : Relation rel = (Relation) lfirst(cell);
2176 : :
2177 : : /* Skip partitioned tables as there is nothing to do */
2178 [ + + ]: 2528 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2179 : 477 : continue;
2180 : :
2181 : : /*
2182 : : * Build the lists of foreign tables belonging to each foreign server
2183 : : * and pass each list to the foreign data wrapper's callback function,
2184 : : * so that each server can truncate its all foreign tables in bulk.
2185 : : * Each list is saved as a single entry in a hash table that uses the
2186 : : * server OID as lookup key.
2187 : : */
2188 [ + + ]: 2051 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2189 : 17 : {
2190 : 17 : Oid serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
2191 : : bool found;
2192 : : ForeignTruncateInfo *ft_info;
2193 : :
2194 : : /* First time through, initialize hashtable for foreign tables */
2195 [ + + ]: 17 : if (!ft_htab)
2196 : : {
2197 : : HASHCTL hctl;
2198 : :
2199 : 15 : memset(&hctl, 0, sizeof(HASHCTL));
2200 : 15 : hctl.keysize = sizeof(Oid);
2201 : 15 : hctl.entrysize = sizeof(ForeignTruncateInfo);
2202 : 15 : hctl.hcxt = CurrentMemoryContext;
2203 : :
2204 : 15 : ft_htab = hash_create("TRUNCATE for Foreign Tables",
2205 : : 32, /* start small and extend */
2206 : : &hctl,
2207 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2208 : : }
2209 : :
2210 : : /* Find or create cached entry for the foreign table */
2211 : 17 : ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2212 [ + + ]: 17 : if (!found)
2213 : 15 : ft_info->rels = NIL;
2214 : :
2215 : : /*
2216 : : * Save the foreign table in the entry of the server that the
2217 : : * foreign table belongs to.
2218 : : */
2219 : 17 : ft_info->rels = lappend(ft_info->rels, rel);
2220 : 17 : continue;
2221 : : }
2222 : :
2223 : : /*
2224 : : * Normally, we need a transaction-safe truncation here. However, if
2225 : : * the table was either created in the current (sub)transaction or has
2226 : : * a new relfilenumber in the current (sub)transaction, then we can
2227 : : * just truncate it in-place, because a rollback would cause the whole
2228 : : * table or the current physical file to be thrown away anyway.
2229 : : */
2230 [ + + ]: 2034 : if (rel->rd_createSubid == mySubid ||
2231 [ + + ]: 2018 : rel->rd_newRelfilelocatorSubid == mySubid)
2232 : : {
2233 : : /* Immediate, non-rollbackable truncation is OK */
2234 : 48 : heap_truncate_one_rel(rel);
2235 : : }
2236 : : else
2237 : : {
2238 : : Oid heap_relid;
2239 : : Oid toast_relid;
2240 : 1986 : ReindexParams reindex_params = {0};
2241 : :
2242 : : /*
2243 : : * This effectively deletes all rows in the table, and may be done
2244 : : * in a serializable transaction. In that case we must record a
2245 : : * rw-conflict in to this transaction from each transaction
2246 : : * holding a predicate lock on the table.
2247 : : */
2248 : 1986 : CheckTableForSerializableConflictIn(rel);
2249 : :
2250 : : /*
2251 : : * Need the full transaction-safe pushups.
2252 : : *
2253 : : * Create a new empty storage file for the relation, and assign it
2254 : : * as the relfilenumber value. The old storage file is scheduled
2255 : : * for deletion at commit.
2256 : : */
2257 : 1986 : RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2258 : :
2259 : 1986 : heap_relid = RelationGetRelid(rel);
2260 : :
2261 : : /*
2262 : : * The same for the toast table, if any.
2263 : : */
2264 : 1986 : toast_relid = rel->rd_rel->reltoastrelid;
2265 [ + + ]: 1986 : if (OidIsValid(toast_relid))
2266 : : {
2267 : 1201 : Relation toastrel = relation_open(toast_relid,
2268 : : AccessExclusiveLock);
2269 : :
2270 : 1201 : RelationSetNewRelfilenumber(toastrel,
2271 : 1201 : toastrel->rd_rel->relpersistence);
2272 : 1201 : table_close(toastrel, NoLock);
2273 : : }
2274 : :
2275 : : /*
2276 : : * Reconstruct the indexes to match, and we're done.
2277 : : */
2278 : 1986 : reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2279 : : &reindex_params);
2280 : : }
2281 : :
2282 : 2034 : pgstat_count_truncate(rel);
2283 : : }
2284 : :
2285 : : /* Now go through the hash table, and truncate foreign tables */
2286 [ + + ]: 1111 : if (ft_htab)
2287 : : {
2288 : : ForeignTruncateInfo *ft_info;
2289 : : HASH_SEQ_STATUS seq;
2290 : :
2291 : 15 : hash_seq_init(&seq, ft_htab);
2292 : :
2293 [ + + ]: 15 : PG_TRY();
2294 : : {
2295 [ + + ]: 26 : while ((ft_info = hash_seq_search(&seq)) != NULL)
2296 : : {
2297 : 15 : FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2298 : :
2299 : : /* truncate_check_rel() has checked that already */
2300 : : Assert(routine->ExecForeignTruncate != NULL);
2301 : :
2302 : 15 : routine->ExecForeignTruncate(ft_info->rels,
2303 : : behavior,
2304 : : restart_seqs);
2305 : : }
2306 : : }
2307 : 4 : PG_FINALLY();
2308 : : {
2309 : 15 : hash_destroy(ft_htab);
2310 : : }
2311 [ + + ]: 15 : PG_END_TRY();
2312 : : }
2313 : :
2314 : : /*
2315 : : * Restart owned sequences if we were asked to.
2316 : : */
2317 [ + + + + : 1129 : foreach(cell, seq_relids)
+ + ]
2318 : : {
2319 : 22 : Oid seq_relid = lfirst_oid(cell);
2320 : :
2321 : 22 : ResetSequence(seq_relid);
2322 : : }
2323 : :
2324 : : /*
2325 : : * Write a WAL record to allow this set of actions to be logically
2326 : : * decoded.
2327 : : *
2328 : : * Assemble an array of relids so we can write a single WAL record for the
2329 : : * whole action.
2330 : : */
2331 [ + + ]: 1107 : if (relids_logged != NIL)
2332 : : {
2333 : : xl_heap_truncate xlrec;
2334 : 33 : int i = 0;
2335 : :
2336 : : /* should only get here if effective_wal_level is 'logical' */
2337 : : Assert(XLogLogicalInfoActive());
2338 : :
2339 : 33 : logrelids = palloc_array(Oid, list_length(relids_logged));
2340 [ + - + + : 84 : foreach(cell, relids_logged)
+ + ]
2341 : 51 : logrelids[i++] = lfirst_oid(cell);
2342 : :
2343 : 33 : xlrec.dbId = MyDatabaseId;
2344 : 33 : xlrec.nrelids = list_length(relids_logged);
2345 : 33 : xlrec.flags = 0;
2346 [ + + ]: 33 : if (behavior == DROP_CASCADE)
2347 : 1 : xlrec.flags |= XLH_TRUNCATE_CASCADE;
2348 [ + + ]: 33 : if (restart_seqs)
2349 : 2 : xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
2350 : :
2351 : 33 : XLogBeginInsert();
2352 : 33 : XLogRegisterData(&xlrec, SizeOfHeapTruncate);
2353 : 33 : XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
2354 : :
2355 : 33 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2356 : :
2357 : 33 : (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2358 : : }
2359 : :
2360 : : /*
2361 : : * Process all AFTER STATEMENT TRUNCATE triggers.
2362 : : */
2363 : 1107 : resultRelInfo = resultRelInfos;
2364 [ + - + + : 3631 : foreach(cell, rels)
+ + ]
2365 : : {
2366 : : UserContext ucxt;
2367 : :
2368 [ + + ]: 2524 : if (run_as_table_owner)
2369 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2370 : : &ucxt);
2371 : 2524 : ExecASTruncateTriggers(estate, resultRelInfo);
2372 [ + + ]: 2524 : if (run_as_table_owner)
2373 : 36 : RestoreUserContext(&ucxt);
2374 : 2524 : resultRelInfo++;
2375 : : }
2376 : :
2377 : : /* Handle queued AFTER triggers */
2378 : 1107 : AfterTriggerEndQuery(estate);
2379 : :
2380 : : /* We can clean up the EState now */
2381 : 1107 : FreeExecutorState(estate);
2382 : :
2383 : : /*
2384 : : * Close any rels opened by CASCADE (can't do this while EState still
2385 : : * holds refs)
2386 : : */
2387 : 1107 : rels = list_difference_ptr(rels, explicit_rels);
2388 [ + + + + : 1169 : foreach(cell, rels)
+ + ]
2389 : : {
2390 : 62 : Relation rel = (Relation) lfirst(cell);
2391 : :
2392 : 62 : table_close(rel, NoLock);
2393 : : }
2394 : 1107 : }
2395 : :
2396 : : /*
2397 : : * Check that a given relation is safe to truncate. Subroutine for
2398 : : * ExecuteTruncate() and RangeVarCallbackForTruncate().
2399 : : */
2400 : : static void
2401 : 2702 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
2402 : : {
2403 : 2702 : char *relname = NameStr(reltuple->relname);
2404 : :
2405 : : /*
2406 : : * Only allow truncate on regular tables, foreign tables using foreign
2407 : : * data wrappers supporting TRUNCATE and partitioned tables (although, the
2408 : : * latter are only being included here for the following checks; no
2409 : : * physical truncation will occur in their case.).
2410 : : */
2411 [ + + ]: 2702 : if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
2412 : : {
2413 : 19 : Oid serverid = GetForeignServerIdByRelId(relid);
2414 : 19 : FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
2415 : :
2416 [ + + ]: 18 : if (!fdwroutine->ExecForeignTruncate)
2417 [ + - ]: 1 : ereport(ERROR,
2418 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2419 : : errmsg("cannot truncate foreign table \"%s\"",
2420 : : relname)));
2421 : : }
2422 [ + + ]: 2683 : else if (reltuple->relkind != RELKIND_RELATION &&
2423 [ - + ]: 487 : reltuple->relkind != RELKIND_PARTITIONED_TABLE)
2424 [ # # ]: 0 : ereport(ERROR,
2425 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2426 : : errmsg("\"%s\" is not a table", relname)));
2427 : :
2428 : : /*
2429 : : * Most system catalogs can't be truncated at all, or at least not unless
2430 : : * allow_system_table_mods=on. As an exception, however, we allow
2431 : : * pg_largeobject and pg_largeobject_metadata to be truncated as part of
2432 : : * pg_upgrade, because we need to change its relfilenode to match the old
2433 : : * cluster, and allowing a TRUNCATE command to be executed is the easiest
2434 : : * way of doing that. We also allow TRUNCATE on the conflict log tables,
2435 : : * to permit users to manually prune conflict data to manage disk space.
2436 : : */
2437 [ + + + + ]: 2700 : if (!allowSystemTableMods && IsSystemClass(relid, reltuple) &&
2438 [ + + ]: 73 : !IsConflictLogTableClass(reltuple)
2439 [ + + + + ]: 65 : && (!IsBinaryUpgrade ||
2440 [ - + ]: 32 : (relid != LargeObjectRelationId &&
2441 : : relid != LargeObjectMetadataRelationId)))
2442 [ + - ]: 1 : ereport(ERROR,
2443 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2444 : : errmsg("permission denied: \"%s\" is a system catalog",
2445 : : relname)));
2446 : :
2447 [ - + ]: 2699 : InvokeObjectTruncateHook(relid);
2448 : 2699 : }
2449 : :
2450 : : /*
2451 : : * Check that current user has the permission to truncate given relation.
2452 : : */
2453 : : static void
2454 : 1483 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
2455 : : {
2456 : 1483 : char *relname = NameStr(reltuple->relname);
2457 : : AclResult aclresult;
2458 : :
2459 : : /* Permissions checks */
2460 : 1483 : aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2461 [ + + ]: 1483 : if (aclresult != ACLCHECK_OK)
2462 : 20 : aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2463 : : relname);
2464 : 1463 : }
2465 : :
2466 : : /*
2467 : : * Set of extra sanity checks to check if a given relation is safe to
2468 : : * truncate. This is split with truncate_check_rel() as
2469 : : * RangeVarCallbackForTruncate() cannot open a Relation yet.
2470 : : */
2471 : : static void
2472 : 2602 : truncate_check_activity(Relation rel)
2473 : : {
2474 : : /*
2475 : : * Don't allow truncate on temp tables of other backends ... their local
2476 : : * buffer manager is not going to cope.
2477 : : */
2478 [ + + + + ]: 2602 : if (RELATION_IS_OTHER_TEMP(rel))
2479 [ + - ]: 1 : ereport(ERROR,
2480 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2481 : : errmsg("cannot truncate temporary tables of other sessions")));
2482 : :
2483 : : /*
2484 : : * Also check for active uses of the relation in the current transaction,
2485 : : * including open scans and pending AFTER trigger events.
2486 : : */
2487 : 2601 : CheckTableNotInUse(rel, "TRUNCATE");
2488 : 2597 : }
2489 : :
2490 : : /*
2491 : : * storage_name
2492 : : * returns the name corresponding to a typstorage/attstorage enum value
2493 : : */
2494 : : static const char *
2495 : 16 : storage_name(char c)
2496 : : {
2497 [ - - + + : 16 : switch (c)
- ]
2498 : : {
2499 : 0 : case TYPSTORAGE_PLAIN:
2500 : 0 : return "PLAIN";
2501 : 0 : case TYPSTORAGE_EXTERNAL:
2502 : 0 : return "EXTERNAL";
2503 : 8 : case TYPSTORAGE_EXTENDED:
2504 : 8 : return "EXTENDED";
2505 : 8 : case TYPSTORAGE_MAIN:
2506 : 8 : return "MAIN";
2507 : 0 : default:
2508 : 0 : return "???";
2509 : : }
2510 : : }
2511 : :
2512 : : /*----------
2513 : : * MergeAttributes
2514 : : * Returns new schema given initial schema and superclasses.
2515 : : *
2516 : : * Input arguments:
2517 : : * 'columns' is the column/attribute definition for the table. (It's a list
2518 : : * of ColumnDef's.) It is destructively changed.
2519 : : * 'supers' is a list of OIDs of parent relations, already locked by caller.
2520 : : * 'relpersistence' is the persistence type of the table.
2521 : : * 'is_partition' tells if the table is a partition.
2522 : : *
2523 : : * Output arguments:
2524 : : * 'supconstr' receives a list of CookedConstraint representing
2525 : : * CHECK constraints belonging to parent relations, updated as
2526 : : * necessary to be valid for the child.
2527 : : * 'supnotnulls' receives a list of CookedConstraint representing
2528 : : * not-null constraints based on those from parent relations.
2529 : : *
2530 : : * Return value:
2531 : : * Completed schema list.
2532 : : *
2533 : : * Notes:
2534 : : * The order in which the attributes are inherited is very important.
2535 : : * Intuitively, the inherited attributes should come first. If a table
2536 : : * inherits from multiple parents, the order of those attributes are
2537 : : * according to the order of the parents specified in CREATE TABLE.
2538 : : *
2539 : : * Here's an example:
2540 : : *
2541 : : * create table person (name text, age int4, location point);
2542 : : * create table emp (salary int4, manager text) inherits(person);
2543 : : * create table student (gpa float8) inherits (person);
2544 : : * create table stud_emp (percent int4) inherits (emp, student);
2545 : : *
2546 : : * The order of the attributes of stud_emp is:
2547 : : *
2548 : : * person {1:name, 2:age, 3:location}
2549 : : * / \
2550 : : * {6:gpa} student emp {4:salary, 5:manager}
2551 : : * \ /
2552 : : * stud_emp {7:percent}
2553 : : *
2554 : : * If the same attribute name appears multiple times, then it appears
2555 : : * in the result table in the proper location for its first appearance.
2556 : : *
2557 : : * Constraints (including not-null constraints) for the child table
2558 : : * are the union of all relevant constraints, from both the child schema
2559 : : * and parent tables. In addition, in legacy inheritance, each column that
2560 : : * appears in a primary key in any of the parents also gets a NOT NULL
2561 : : * constraint (partitioning doesn't need this, because the PK itself gets
2562 : : * inherited.)
2563 : : *
2564 : : * The default value for a child column is defined as:
2565 : : * (1) If the child schema specifies a default, that value is used.
2566 : : * (2) If neither the child nor any parent specifies a default, then
2567 : : * the column will not have a default.
2568 : : * (3) If conflicting defaults are inherited from different parents
2569 : : * (and not overridden by the child), an error is raised.
2570 : : * (4) Otherwise the inherited default is used.
2571 : : *
2572 : : * Note that the default-value infrastructure is used for generated
2573 : : * columns' expressions too, so most of the preceding paragraph applies
2574 : : * to generation expressions too. We insist that a child column be
2575 : : * generated if and only if its parent(s) are, but it need not have
2576 : : * the same generation expression.
2577 : : *----------
2578 : : */
2579 : : static List *
2580 : 40998 : MergeAttributes(List *columns, const List *supers, char relpersistence,
2581 : : bool is_partition, List **supconstr, List **supnotnulls)
2582 : : {
2583 : 40998 : List *inh_columns = NIL;
2584 : 40998 : List *constraints = NIL;
2585 : 40998 : List *nnconstraints = NIL;
2586 : 40998 : bool have_bogus_defaults = false;
2587 : : int child_attno;
2588 : : static Node bogus_marker = {0}; /* marks conflicting defaults */
2589 : 40998 : List *saved_columns = NIL;
2590 : : ListCell *lc;
2591 : :
2592 : : /*
2593 : : * Check for and reject tables with too many columns. We perform this
2594 : : * check relatively early for two reasons: (a) we don't run the risk of
2595 : : * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
2596 : : * okay if we're processing <= 1600 columns, but could take minutes to
2597 : : * execute if the user attempts to create a table with hundreds of
2598 : : * thousands of columns.
2599 : : *
2600 : : * Note that we also need to check that we do not exceed this figure after
2601 : : * including columns from inherited relations.
2602 : : */
2603 [ - + ]: 40998 : if (list_length(columns) > MaxHeapAttributeNumber)
2604 [ # # ]: 0 : ereport(ERROR,
2605 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2606 : : errmsg("tables can have at most %d columns",
2607 : : MaxHeapAttributeNumber)));
2608 : :
2609 : : /*
2610 : : * Check for duplicate names in the explicit list of attributes.
2611 : : *
2612 : : * Although we might consider merging such entries in the same way that we
2613 : : * handle name conflicts for inherited attributes, it seems to make more
2614 : : * sense to assume such conflicts are errors.
2615 : : *
2616 : : * We don't use foreach() here because we have two nested loops over the
2617 : : * columns list, with possible element deletions in the inner one. If we
2618 : : * used foreach_delete_current() it could only fix up the state of one of
2619 : : * the loops, so it seems cleaner to use looping over list indexes for
2620 : : * both loops. Note that any deletion will happen beyond where the outer
2621 : : * loop is, so its index never needs adjustment.
2622 : : */
2623 [ + + ]: 191028 : for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
2624 : : {
2625 : 150046 : ColumnDef *coldef = list_nth_node(ColumnDef, columns, coldefpos);
2626 : :
2627 [ + + + + ]: 150046 : if (!is_partition && coldef->typeName == NULL)
2628 : : {
2629 : : /*
2630 : : * Typed table column option that does not belong to a column from
2631 : : * the type. This works because the columns from the type come
2632 : : * first in the list. (We omit this check for partition column
2633 : : * lists; those are processed separately below.)
2634 : : */
2635 [ + - ]: 4 : ereport(ERROR,
2636 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
2637 : : errmsg("column \"%s\" does not exist",
2638 : : coldef->colname)));
2639 : : }
2640 : :
2641 : : /* restpos scans all entries beyond coldef; incr is in loop body */
2642 [ + + ]: 4111272 : for (int restpos = coldefpos + 1; restpos < list_length(columns);)
2643 : : {
2644 : 3961242 : ColumnDef *restdef = list_nth_node(ColumnDef, columns, restpos);
2645 : :
2646 [ + + ]: 3961242 : if (strcmp(coldef->colname, restdef->colname) == 0)
2647 : : {
2648 [ + + ]: 33 : if (coldef->is_from_type)
2649 : : {
2650 : : /*
2651 : : * merge the column options into the column from the type
2652 : : */
2653 : 21 : coldef->is_not_null = restdef->is_not_null;
2654 : 21 : coldef->raw_default = restdef->raw_default;
2655 : 21 : coldef->cooked_default = restdef->cooked_default;
2656 : 21 : coldef->constraints = restdef->constraints;
2657 : 21 : coldef->is_from_type = false;
2658 : 21 : columns = list_delete_nth_cell(columns, restpos);
2659 : : }
2660 : : else
2661 [ + - ]: 12 : ereport(ERROR,
2662 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
2663 : : errmsg("column \"%s\" specified more than once",
2664 : : coldef->colname)));
2665 : : }
2666 : : else
2667 : 3961209 : restpos++;
2668 : : }
2669 : : }
2670 : :
2671 : : /*
2672 : : * In case of a partition, there are no new column definitions, only dummy
2673 : : * ColumnDefs created for column constraints. Set them aside for now and
2674 : : * process them at the end.
2675 : : */
2676 [ + + ]: 40982 : if (is_partition)
2677 : : {
2678 : 6012 : saved_columns = columns;
2679 : 6012 : columns = NIL;
2680 : : }
2681 : :
2682 : : /*
2683 : : * Scan the parents left-to-right, and merge their attributes to form a
2684 : : * list of inherited columns (inh_columns).
2685 : : */
2686 : 40982 : child_attno = 0;
2687 [ + + + + : 48604 : foreach(lc, supers)
+ + ]
2688 : : {
2689 : 7682 : Oid parent = lfirst_oid(lc);
2690 : : Relation relation;
2691 : : TupleDesc tupleDesc;
2692 : : TupleConstr *constr;
2693 : : AttrMap *newattmap;
2694 : : List *inherited_defaults;
2695 : : List *cols_with_defaults;
2696 : : List *nnconstrs;
2697 : : ListCell *lc1;
2698 : : ListCell *lc2;
2699 : 7682 : Bitmapset *nncols = NULL;
2700 : :
2701 : : /* caller already got lock */
2702 : 7682 : relation = table_open(parent, NoLock);
2703 : :
2704 : : /*
2705 : : * Check for active uses of the parent partitioned table in the
2706 : : * current transaction, such as being used in some manner by an
2707 : : * enclosing command.
2708 : : */
2709 [ + + ]: 7682 : if (is_partition)
2710 : 6012 : CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
2711 : :
2712 : : /*
2713 : : * We do not allow partitioned tables and partitions to participate in
2714 : : * regular inheritance.
2715 : : */
2716 [ + + + + ]: 7678 : if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
2717 [ + - ]: 4 : ereport(ERROR,
2718 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2719 : : errmsg("cannot inherit from partitioned table \"%s\"",
2720 : : RelationGetRelationName(relation))));
2721 [ + + + + ]: 7674 : if (relation->rd_rel->relispartition && !is_partition)
2722 [ + - ]: 4 : ereport(ERROR,
2723 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2724 : : errmsg("cannot inherit from partition \"%s\"",
2725 : : RelationGetRelationName(relation))));
2726 : :
2727 : : /*
2728 : : * Conflict log tables are managed by the system for logical
2729 : : * replication and should not be used as parent tables, as inheritance
2730 : : * could interfere with the logging behavior.
2731 : : */
2732 [ + + ]: 7670 : if (IsConflictLogTableNamespace(relation->rd_rel->relnamespace))
2733 [ + - ]: 4 : ereport(ERROR,
2734 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2735 : : errmsg("cannot inherit from conflict log table \"%s\"",
2736 : : RelationGetRelationName(relation)),
2737 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
2738 : :
2739 [ + + ]: 7666 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2740 [ + + ]: 6008 : relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2741 [ - + ]: 5996 : relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2742 [ # # ]: 0 : ereport(ERROR,
2743 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2744 : : errmsg("inherited relation \"%s\" is not a table or foreign table",
2745 : : RelationGetRelationName(relation))));
2746 : :
2747 : : /*
2748 : : * If the parent is permanent, so must be all of its partitions. Note
2749 : : * that inheritance allows that case.
2750 : : */
2751 [ + + ]: 7666 : if (is_partition &&
2752 [ + + + + ]: 6008 : relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
2753 : : relpersistence == RELPERSISTENCE_TEMP)
2754 [ + - ]: 4 : ereport(ERROR,
2755 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2756 : : errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
2757 : : RelationGetRelationName(relation))));
2758 : :
2759 : : /* Permanent rels cannot inherit from temporary ones */
2760 [ + + ]: 7662 : if (relpersistence != RELPERSISTENCE_TEMP &&
2761 [ + + ]: 7424 : relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
2762 [ + - + + ]: 16 : ereport(ERROR,
2763 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2764 : : errmsg(!is_partition
2765 : : ? "cannot inherit from temporary relation \"%s\""
2766 : : : "cannot create a permanent relation as partition of temporary relation \"%s\"",
2767 : : RelationGetRelationName(relation))));
2768 : :
2769 : : /* If existing rel is temp, it must belong to this session */
2770 [ + + - + ]: 7646 : if (RELATION_IS_OTHER_TEMP(relation))
2771 [ # # # # ]: 0 : ereport(ERROR,
2772 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2773 : : errmsg(!is_partition
2774 : : ? "cannot inherit from temporary relation of another session"
2775 : : : "cannot create as partition of temporary relation of another session")));
2776 : :
2777 : : /*
2778 : : * We should have an UNDER permission flag for this, but for now,
2779 : : * demand that creator of a child table own the parent.
2780 : : */
2781 [ - + ]: 7646 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
2782 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
2783 : 0 : RelationGetRelationName(relation));
2784 : :
2785 : 7646 : tupleDesc = RelationGetDescr(relation);
2786 : 7646 : constr = tupleDesc->constr;
2787 : :
2788 : : /*
2789 : : * newattmap->attnums[] will contain the child-table attribute numbers
2790 : : * for the attributes of this parent table. (They are not the same
2791 : : * for parents after the first one, nor if we have dropped columns.)
2792 : : */
2793 : 7646 : newattmap = make_attrmap(tupleDesc->natts);
2794 : :
2795 : : /* We can't process inherited defaults until newattmap is complete. */
2796 : 7646 : inherited_defaults = cols_with_defaults = NIL;
2797 : :
2798 : : /*
2799 : : * Request attnotnull on columns that have a not-null constraint
2800 : : * that's not marked NO INHERIT (even if not valid).
2801 : : */
2802 : 7646 : nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
2803 : : true, false);
2804 [ + + + + : 16932 : foreach_ptr(CookedConstraint, cc, nnconstrs)
+ + ]
2805 : 1640 : nncols = bms_add_member(nncols, cc->attnum);
2806 : :
2807 [ + + ]: 22332 : for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
2808 : 14686 : parent_attno++)
2809 : : {
2810 : 14710 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2811 : : parent_attno - 1);
2812 : 14710 : char *attributeName = NameStr(attribute->attname);
2813 : : int exist_attno;
2814 : : ColumnDef *newdef;
2815 : : ColumnDef *mergeddef;
2816 : :
2817 : : /*
2818 : : * Ignore dropped columns in the parent.
2819 : : */
2820 [ + + ]: 14710 : if (attribute->attisdropped)
2821 : 132 : continue; /* leave newattmap->attnums entry as zero */
2822 : :
2823 : : /*
2824 : : * Create new column definition
2825 : : */
2826 : 14578 : newdef = makeColumnDef(attributeName, attribute->atttypid,
2827 : : attribute->atttypmod, attribute->attcollation);
2828 : 14578 : newdef->storage = attribute->attstorage;
2829 : 14578 : newdef->generated = attribute->attgenerated;
2830 [ + + ]: 14578 : if (CompressionMethodIsValid(attribute->attcompression))
2831 : 24 : newdef->compression =
2832 : 24 : pstrdup(GetCompressionMethodName(attribute->attcompression));
2833 : :
2834 : : /*
2835 : : * Regular inheritance children are independent enough not to
2836 : : * inherit identity columns. But partitions are integral part of
2837 : : * a partitioned table and inherit identity column.
2838 : : */
2839 [ + + ]: 14578 : if (is_partition)
2840 : 11622 : newdef->identity = attribute->attidentity;
2841 : :
2842 : : /*
2843 : : * Does it match some previously considered column from another
2844 : : * parent?
2845 : : */
2846 : 14578 : exist_attno = findAttrByName(attributeName, inh_columns);
2847 [ + + ]: 14578 : if (exist_attno > 0)
2848 : : {
2849 : : /*
2850 : : * Yes, try to merge the two column definitions.
2851 : : */
2852 : 253 : mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
2853 : :
2854 : 229 : newattmap->attnums[parent_attno - 1] = exist_attno;
2855 : :
2856 : : /*
2857 : : * Partitions have only one parent, so conflict should never
2858 : : * occur.
2859 : : */
2860 : : Assert(!is_partition);
2861 : : }
2862 : : else
2863 : : {
2864 : : /*
2865 : : * No, create a new inherited column
2866 : : */
2867 : 14325 : newdef->inhcount = 1;
2868 : 14325 : newdef->is_local = false;
2869 : 14325 : inh_columns = lappend(inh_columns, newdef);
2870 : :
2871 : 14325 : newattmap->attnums[parent_attno - 1] = ++child_attno;
2872 : 14325 : mergeddef = newdef;
2873 : : }
2874 : :
2875 : : /*
2876 : : * mark attnotnull if parent has it
2877 : : */
2878 [ + + ]: 14554 : if (bms_is_member(parent_attno, nncols))
2879 : 1640 : mergeddef->is_not_null = true;
2880 : :
2881 : : /*
2882 : : * Locate default/generation expression if any
2883 : : */
2884 [ + + ]: 14554 : if (attribute->atthasdef)
2885 : : {
2886 : : Node *this_default;
2887 : :
2888 : 470 : this_default = TupleDescGetDefault(tupleDesc, parent_attno);
2889 [ - + ]: 470 : if (this_default == NULL)
2890 [ # # ]: 0 : elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
2891 : : parent_attno, RelationGetRelationName(relation));
2892 : :
2893 : : /*
2894 : : * If it's a GENERATED default, it might contain Vars that
2895 : : * need to be mapped to the inherited column(s)' new numbers.
2896 : : * We can't do that till newattmap is ready, so just remember
2897 : : * all the inherited default expressions for the moment.
2898 : : */
2899 : 470 : inherited_defaults = lappend(inherited_defaults, this_default);
2900 : 470 : cols_with_defaults = lappend(cols_with_defaults, mergeddef);
2901 : : }
2902 : : }
2903 : :
2904 : : /*
2905 : : * Now process any inherited default expressions, adjusting attnos
2906 : : * using the completed newattmap map.
2907 : : */
2908 [ + + + + : 8092 : forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
+ + + + +
+ + - +
+ ]
2909 : : {
2910 : 470 : Node *this_default = (Node *) lfirst(lc1);
2911 : 470 : ColumnDef *def = (ColumnDef *) lfirst(lc2);
2912 : : bool found_whole_row;
2913 : :
2914 : : /* Adjust Vars to match new table's column numbering */
2915 : 470 : this_default = map_variable_attnos(this_default,
2916 : : 1, 0,
2917 : : newattmap,
2918 : : InvalidOid, &found_whole_row);
2919 : :
2920 : : /*
2921 : : * For the moment we have to reject whole-row variables. We could
2922 : : * convert them, if we knew the new table's rowtype OID, but that
2923 : : * hasn't been assigned yet. (A variable could only appear in a
2924 : : * generation expression, so the error message is correct.)
2925 : : */
2926 [ - + ]: 470 : if (found_whole_row)
2927 [ # # ]: 0 : ereport(ERROR,
2928 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2929 : : errmsg("cannot convert whole-row table reference"),
2930 : : errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
2931 : : def->colname,
2932 : : RelationGetRelationName(relation))));
2933 : :
2934 : : /*
2935 : : * If we already had a default from some prior parent, check to
2936 : : * see if they are the same. If so, no problem; if not, mark the
2937 : : * column as having a bogus default. Below, we will complain if
2938 : : * the bogus default isn't overridden by the child columns.
2939 : : */
2940 : : Assert(def->raw_default == NULL);
2941 [ + + ]: 470 : if (def->cooked_default == NULL)
2942 : 442 : def->cooked_default = this_default;
2943 [ + + ]: 28 : else if (!equal(def->cooked_default, this_default))
2944 : : {
2945 : 24 : def->cooked_default = &bogus_marker;
2946 : 24 : have_bogus_defaults = true;
2947 : : }
2948 : : }
2949 : :
2950 : : /*
2951 : : * Now copy the CHECK constraints of this parent, adjusting attnos
2952 : : * using the completed newattmap map. Identically named constraints
2953 : : * are merged if possible, else we throw error.
2954 : : */
2955 [ + + + + ]: 7622 : if (constr && constr->num_check > 0)
2956 : : {
2957 : 281 : ConstrCheck *check = constr->check;
2958 : :
2959 [ + + ]: 842 : for (int i = 0; i < constr->num_check; i++)
2960 : : {
2961 : 561 : char *name = check[i].ccname;
2962 : : Node *expr;
2963 : : bool found_whole_row;
2964 : :
2965 : : /* ignore if the constraint is non-inheritable */
2966 [ + + ]: 561 : if (check[i].ccnoinherit)
2967 : 32 : continue;
2968 : :
2969 : : /* Adjust Vars to match new table's column numbering */
2970 : 529 : expr = map_variable_attnos(stringToNode(check[i].ccbin),
2971 : : 1, 0,
2972 : : newattmap,
2973 : : InvalidOid, &found_whole_row);
2974 : :
2975 : : /*
2976 : : * For the moment we have to reject whole-row variables. We
2977 : : * could convert them, if we knew the new table's rowtype OID,
2978 : : * but that hasn't been assigned yet.
2979 : : */
2980 [ - + ]: 529 : if (found_whole_row)
2981 [ # # ]: 0 : ereport(ERROR,
2982 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2983 : : errmsg("cannot convert whole-row table reference"),
2984 : : errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
2985 : : name,
2986 : : RelationGetRelationName(relation))));
2987 : :
2988 : 529 : constraints = MergeCheckConstraint(constraints, name, expr,
2989 : 529 : check[i].ccenforced);
2990 : : }
2991 : : }
2992 : :
2993 : : /*
2994 : : * Also copy the not-null constraints from this parent. The
2995 : : * attnotnull markings were already installed above.
2996 : : */
2997 [ + + + + : 16884 : foreach_ptr(CookedConstraint, nn, nnconstrs)
+ + ]
2998 : : {
2999 : : Assert(nn->contype == CONSTR_NOTNULL);
3000 : :
3001 : 1640 : nn->attnum = newattmap->attnums[nn->attnum - 1];
3002 : :
3003 : 1640 : nnconstraints = lappend(nnconstraints, nn);
3004 : : }
3005 : :
3006 : 7622 : free_attrmap(newattmap);
3007 : :
3008 : : /*
3009 : : * Close the parent rel, but keep our lock on it until xact commit.
3010 : : * That will prevent someone else from deleting or ALTERing the parent
3011 : : * before the child is committed.
3012 : : */
3013 : 7622 : table_close(relation, NoLock);
3014 : : }
3015 : :
3016 : : /*
3017 : : * If we had no inherited attributes, the result columns are just the
3018 : : * explicitly declared columns. Otherwise, we need to merge the declared
3019 : : * columns into the inherited column list. Although, we never have any
3020 : : * explicitly declared columns if the table is a partition.
3021 : : */
3022 [ + + ]: 40922 : if (inh_columns != NIL)
3023 : : {
3024 : 7324 : int newcol_attno = 0;
3025 : :
3026 [ + + + + : 7972 : foreach(lc, columns)
+ + ]
3027 : : {
3028 : 700 : ColumnDef *newdef = lfirst_node(ColumnDef, lc);
3029 : 700 : char *attributeName = newdef->colname;
3030 : : int exist_attno;
3031 : :
3032 : : /*
3033 : : * Partitions have only one parent and have no column definitions
3034 : : * of their own, so conflict should never occur.
3035 : : */
3036 : : Assert(!is_partition);
3037 : :
3038 : 700 : newcol_attno++;
3039 : :
3040 : : /*
3041 : : * Does it match some inherited column?
3042 : : */
3043 : 700 : exist_attno = findAttrByName(attributeName, inh_columns);
3044 [ + + ]: 700 : if (exist_attno > 0)
3045 : : {
3046 : : /*
3047 : : * Yes, try to merge the two column definitions.
3048 : : */
3049 : 251 : MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
3050 : : }
3051 : : else
3052 : : {
3053 : : /*
3054 : : * No, attach new column unchanged to result columns.
3055 : : */
3056 : 449 : inh_columns = lappend(inh_columns, newdef);
3057 : : }
3058 : : }
3059 : :
3060 : 7272 : columns = inh_columns;
3061 : :
3062 : : /*
3063 : : * Check that we haven't exceeded the legal # of columns after merging
3064 : : * in inherited columns.
3065 : : */
3066 [ - + ]: 7272 : if (list_length(columns) > MaxHeapAttributeNumber)
3067 [ # # ]: 0 : ereport(ERROR,
3068 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
3069 : : errmsg("tables can have at most %d columns",
3070 : : MaxHeapAttributeNumber)));
3071 : : }
3072 : :
3073 : : /*
3074 : : * Now that we have the column definition list for a partition, we can
3075 : : * check whether the columns referenced in the column constraint specs
3076 : : * actually exist. Also, merge column defaults.
3077 : : */
3078 [ + + ]: 40870 : if (is_partition)
3079 : : {
3080 [ + + + + : 6123 : foreach(lc, saved_columns)
+ + ]
3081 : : {
3082 : 155 : ColumnDef *restdef = lfirst(lc);
3083 : 155 : bool found = false;
3084 : : ListCell *l;
3085 : :
3086 [ + - + + : 561 : foreach(l, columns)
+ + ]
3087 : : {
3088 : 430 : ColumnDef *coldef = lfirst(l);
3089 : :
3090 [ + + ]: 430 : if (strcmp(coldef->colname, restdef->colname) == 0)
3091 : : {
3092 : 155 : found = true;
3093 : :
3094 : : /*
3095 : : * Check for conflicts related to generated columns.
3096 : : *
3097 : : * Same rules as above: generated-ness has to match the
3098 : : * parent, but the contents of the generation expression
3099 : : * can be different.
3100 : : */
3101 [ + + ]: 155 : if (coldef->generated)
3102 : : {
3103 [ + - + + ]: 84 : if (restdef->raw_default && !restdef->generated)
3104 [ + - ]: 8 : ereport(ERROR,
3105 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3106 : : errmsg("column \"%s\" inherits from generated column but specifies default",
3107 : : restdef->colname)));
3108 [ - + ]: 76 : if (restdef->identity)
3109 [ # # ]: 0 : ereport(ERROR,
3110 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3111 : : errmsg("column \"%s\" inherits from generated column but specifies identity",
3112 : : restdef->colname)));
3113 : : }
3114 : : else
3115 : : {
3116 [ + + ]: 71 : if (restdef->generated)
3117 [ + - ]: 8 : ereport(ERROR,
3118 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3119 : : errmsg("child column \"%s\" specifies generation expression",
3120 : : restdef->colname),
3121 : : errhint("A child table column cannot be generated unless its parent column is.")));
3122 : : }
3123 : :
3124 [ + + + - : 139 : if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
+ + ]
3125 [ + - + + : 8 : ereport(ERROR,
+ + ]
3126 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3127 : : errmsg("column \"%s\" inherits from generated column of different kind",
3128 : : restdef->colname),
3129 : : errdetail("Parent column is %s, child column is %s.",
3130 : : coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3131 : : restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3132 : :
3133 : : /*
3134 : : * Override the parent's default value for this column
3135 : : * (coldef->cooked_default) with the partition's local
3136 : : * definition (restdef->raw_default), if there's one. It
3137 : : * should be physically impossible to get a cooked default
3138 : : * in the local definition or a raw default in the
3139 : : * inherited definition, but make sure they're nulls, for
3140 : : * future-proofing.
3141 : : */
3142 : : Assert(restdef->cooked_default == NULL);
3143 : : Assert(coldef->raw_default == NULL);
3144 [ + + ]: 131 : if (restdef->raw_default)
3145 : : {
3146 : 83 : coldef->raw_default = restdef->raw_default;
3147 : 83 : coldef->cooked_default = NULL;
3148 : : }
3149 : : }
3150 : : }
3151 : :
3152 : : /* complain for constraints on columns not in parent */
3153 [ - + ]: 131 : if (!found)
3154 [ # # ]: 0 : ereport(ERROR,
3155 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3156 : : errmsg("column \"%s\" does not exist",
3157 : : restdef->colname)));
3158 : : }
3159 : : }
3160 : :
3161 : : /*
3162 : : * If we found any conflicting parent default values, check to make sure
3163 : : * they were overridden by the child.
3164 : : */
3165 [ + + ]: 40846 : if (have_bogus_defaults)
3166 : : {
3167 [ + - + + : 60 : foreach(lc, columns)
+ + ]
3168 : : {
3169 : 48 : ColumnDef *def = lfirst(lc);
3170 : :
3171 [ + + ]: 48 : if (def->cooked_default == &bogus_marker)
3172 : : {
3173 [ + + ]: 12 : if (def->generated)
3174 [ + - ]: 8 : ereport(ERROR,
3175 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3176 : : errmsg("column \"%s\" inherits conflicting generation expressions",
3177 : : def->colname),
3178 : : errhint("To resolve the conflict, specify a generation expression explicitly.")));
3179 : : else
3180 [ + - ]: 4 : ereport(ERROR,
3181 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3182 : : errmsg("column \"%s\" inherits conflicting default values",
3183 : : def->colname),
3184 : : errhint("To resolve the conflict, specify a default explicitly.")));
3185 : : }
3186 : : }
3187 : : }
3188 : :
3189 : 40834 : *supconstr = constraints;
3190 : 40834 : *supnotnulls = nnconstraints;
3191 : :
3192 : 40834 : return columns;
3193 : : }
3194 : :
3195 : :
3196 : : /*
3197 : : * MergeCheckConstraint
3198 : : * Try to merge an inherited CHECK constraint with previous ones
3199 : : *
3200 : : * If we inherit identically-named constraints from multiple parents, we must
3201 : : * merge them, or throw an error if they don't have identical definitions.
3202 : : *
3203 : : * constraints is a list of CookedConstraint structs for previous constraints.
3204 : : *
3205 : : * If the new constraint matches an existing one, then the existing
3206 : : * constraint's inheritance count is updated. If there is a conflict (same
3207 : : * name but different expression), throw an error. If the constraint neither
3208 : : * matches nor conflicts with an existing one, a new constraint is appended to
3209 : : * the list.
3210 : : */
3211 : : static List *
3212 : 529 : MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
3213 : : {
3214 : : ListCell *lc;
3215 : : CookedConstraint *newcon;
3216 : :
3217 [ + + + + : 1557 : foreach(lc, constraints)
+ + ]
3218 : : {
3219 : 1136 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
3220 : :
3221 : : Assert(ccon->contype == CONSTR_CHECK);
3222 : :
3223 : : /* Non-matching names never conflict */
3224 [ + + ]: 1136 : if (strcmp(ccon->name, name) != 0)
3225 : 1028 : continue;
3226 : :
3227 [ + - ]: 108 : if (equal(expr, ccon->expr))
3228 : : {
3229 : : /* OK to merge constraint with existing */
3230 [ - + ]: 108 : if (pg_add_s16_overflow(ccon->inhcount, 1,
3231 : : &ccon->inhcount))
3232 [ # # ]: 0 : ereport(ERROR,
3233 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3234 : : errmsg("too many inheritance parents"));
3235 : :
3236 : : /*
3237 : : * When enforceability differs, the merged constraint should be
3238 : : * marked as ENFORCED because one of the parents is ENFORCED.
3239 : : */
3240 [ + + + + ]: 108 : if (!ccon->is_enforced && is_enforced)
3241 : : {
3242 : 32 : ccon->is_enforced = true;
3243 : 32 : ccon->skip_validation = false;
3244 : : }
3245 : :
3246 : 108 : return constraints;
3247 : : }
3248 : :
3249 [ # # ]: 0 : ereport(ERROR,
3250 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3251 : : errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
3252 : : name)));
3253 : : }
3254 : :
3255 : : /*
3256 : : * Constraint couldn't be merged with an existing one and also didn't
3257 : : * conflict with an existing one, so add it as a new one to the list.
3258 : : */
3259 : 421 : newcon = palloc0_object(CookedConstraint);
3260 : 421 : newcon->contype = CONSTR_CHECK;
3261 : 421 : newcon->name = pstrdup(name);
3262 : 421 : newcon->expr = expr;
3263 : 421 : newcon->inhcount = 1;
3264 : 421 : newcon->is_enforced = is_enforced;
3265 : 421 : newcon->skip_validation = !is_enforced;
3266 : 421 : return lappend(constraints, newcon);
3267 : : }
3268 : :
3269 : : /*
3270 : : * MergeChildAttribute
3271 : : * Merge given child attribute definition into given inherited attribute.
3272 : : *
3273 : : * Input arguments:
3274 : : * 'inh_columns' is the list of inherited ColumnDefs.
3275 : : * 'exist_attno' is the number of the inherited attribute in inh_columns
3276 : : * 'newcol_attno' is the attribute number in child table's schema definition
3277 : : * 'newdef' is the column/attribute definition from the child table.
3278 : : *
3279 : : * The ColumnDef in 'inh_columns' list is modified. The child attribute's
3280 : : * ColumnDef remains unchanged.
3281 : : *
3282 : : * Notes:
3283 : : * - The attribute is merged according to the rules laid out in the prologue
3284 : : * of MergeAttributes().
3285 : : * - If matching inherited attribute exists but the child attribute can not be
3286 : : * merged into it, the function throws respective errors.
3287 : : * - A partition can not have its own column definitions. Hence this function
3288 : : * is applicable only to a regular inheritance child.
3289 : : */
3290 : : static void
3291 : 251 : MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
3292 : : {
3293 : 251 : char *attributeName = newdef->colname;
3294 : : ColumnDef *inhdef;
3295 : : Oid inhtypeid,
3296 : : newtypeid;
3297 : : int32 inhtypmod,
3298 : : newtypmod;
3299 : : Oid inhcollid,
3300 : : newcollid;
3301 : :
3302 [ + + ]: 251 : if (exist_attno == newcol_attno)
3303 [ + - ]: 229 : ereport(NOTICE,
3304 : : (errmsg("merging column \"%s\" with inherited definition",
3305 : : attributeName)));
3306 : : else
3307 [ + - ]: 22 : ereport(NOTICE,
3308 : : (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
3309 : : errdetail("User-specified column moved to the position of the inherited column.")));
3310 : :
3311 : 251 : inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3312 : :
3313 : : /*
3314 : : * Must have the same type and typmod
3315 : : */
3316 : 251 : typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
3317 : 251 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3318 [ + + + + ]: 251 : if (inhtypeid != newtypeid || inhtypmod != newtypmod)
3319 [ + - ]: 8 : ereport(ERROR,
3320 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3321 : : errmsg("column \"%s\" has a type conflict",
3322 : : attributeName),
3323 : : errdetail("%s versus %s",
3324 : : format_type_with_typemod(inhtypeid, inhtypmod),
3325 : : format_type_with_typemod(newtypeid, newtypmod))));
3326 : :
3327 : : /*
3328 : : * Must have the same collation
3329 : : */
3330 : 243 : inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
3331 : 243 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3332 [ + + ]: 243 : if (inhcollid != newcollid)
3333 [ + - ]: 4 : ereport(ERROR,
3334 : : (errcode(ERRCODE_COLLATION_MISMATCH),
3335 : : errmsg("column \"%s\" has a collation conflict",
3336 : : attributeName),
3337 : : errdetail("\"%s\" versus \"%s\"",
3338 : : get_collation_name(inhcollid),
3339 : : get_collation_name(newcollid))));
3340 : :
3341 : : /*
3342 : : * Identity is never inherited by a regular inheritance child. Pick
3343 : : * child's identity definition if there's one.
3344 : : */
3345 : 239 : inhdef->identity = newdef->identity;
3346 : :
3347 : : /*
3348 : : * Copy storage parameter
3349 : : */
3350 [ - + ]: 239 : if (inhdef->storage == 0)
3351 : 0 : inhdef->storage = newdef->storage;
3352 [ + + + + ]: 239 : else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
3353 [ + - ]: 4 : ereport(ERROR,
3354 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3355 : : errmsg("column \"%s\" has a storage parameter conflict",
3356 : : attributeName),
3357 : : errdetail("%s versus %s",
3358 : : storage_name(inhdef->storage),
3359 : : storage_name(newdef->storage))));
3360 : :
3361 : : /*
3362 : : * Copy compression parameter
3363 : : */
3364 [ + + ]: 235 : if (inhdef->compression == NULL)
3365 : 231 : inhdef->compression = newdef->compression;
3366 [ + - ]: 4 : else if (newdef->compression != NULL)
3367 : : {
3368 [ + - ]: 4 : if (strcmp(inhdef->compression, newdef->compression) != 0)
3369 [ + - ]: 4 : ereport(ERROR,
3370 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3371 : : errmsg("column \"%s\" has a compression method conflict",
3372 : : attributeName),
3373 : : errdetail("%s versus %s", inhdef->compression, newdef->compression)));
3374 : : }
3375 : :
3376 : : /*
3377 : : * Merge of not-null constraints = OR 'em together
3378 : : */
3379 : 231 : inhdef->is_not_null |= newdef->is_not_null;
3380 : :
3381 : : /*
3382 : : * Check for conflicts related to generated columns.
3383 : : *
3384 : : * If the parent column is generated, the child column will be made a
3385 : : * generated column if it isn't already. If it is a generated column,
3386 : : * we'll take its generation expression in preference to the parent's. We
3387 : : * must check that the child column doesn't specify a default value or
3388 : : * identity, which matches the rules for a single column in
3389 : : * parse_utilcmd.c.
3390 : : *
3391 : : * Conversely, if the parent column is not generated, the child column
3392 : : * can't be either. (We used to allow that, but it results in being able
3393 : : * to override the generation expression via UPDATEs through the parent.)
3394 : : */
3395 [ + + ]: 231 : if (inhdef->generated)
3396 : : {
3397 [ + + + + ]: 41 : if (newdef->raw_default && !newdef->generated)
3398 [ + - ]: 8 : ereport(ERROR,
3399 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3400 : : errmsg("column \"%s\" inherits from generated column but specifies default",
3401 : : inhdef->colname)));
3402 [ + + ]: 33 : if (newdef->identity)
3403 [ + - ]: 8 : ereport(ERROR,
3404 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3405 : : errmsg("column \"%s\" inherits from generated column but specifies identity",
3406 : : inhdef->colname)));
3407 : : }
3408 : : else
3409 : : {
3410 [ + + ]: 190 : if (newdef->generated)
3411 [ + - ]: 8 : ereport(ERROR,
3412 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3413 : : errmsg("child column \"%s\" specifies generation expression",
3414 : : inhdef->colname),
3415 : : errhint("A child table column cannot be generated unless its parent column is.")));
3416 : : }
3417 : :
3418 [ + + + + : 207 : if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
+ + ]
3419 [ + - + + : 8 : ereport(ERROR,
+ + ]
3420 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3421 : : errmsg("column \"%s\" inherits from generated column of different kind",
3422 : : inhdef->colname),
3423 : : errdetail("Parent column is %s, child column is %s.",
3424 : : inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3425 : : newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3426 : :
3427 : : /*
3428 : : * If new def has a default, override previous default
3429 : : */
3430 [ + + ]: 199 : if (newdef->raw_default != NULL)
3431 : : {
3432 : 20 : inhdef->raw_default = newdef->raw_default;
3433 : 20 : inhdef->cooked_default = newdef->cooked_default;
3434 : : }
3435 : :
3436 : : /* Mark the column as locally defined */
3437 : 199 : inhdef->is_local = true;
3438 : 199 : }
3439 : :
3440 : : /*
3441 : : * MergeInheritedAttribute
3442 : : * Merge given parent attribute definition into specified attribute
3443 : : * inherited from the previous parents.
3444 : : *
3445 : : * Input arguments:
3446 : : * 'inh_columns' is the list of previously inherited ColumnDefs.
3447 : : * 'exist_attno' is the number the existing matching attribute in inh_columns.
3448 : : * 'newdef' is the new parent column/attribute definition to be merged.
3449 : : *
3450 : : * The matching ColumnDef in 'inh_columns' list is modified and returned.
3451 : : *
3452 : : * Notes:
3453 : : * - The attribute is merged according to the rules laid out in the prologue
3454 : : * of MergeAttributes().
3455 : : * - If matching inherited attribute exists but the new attribute can not be
3456 : : * merged into it, the function throws respective errors.
3457 : : * - A partition inherits from only a single parent. Hence this function is
3458 : : * applicable only to a regular inheritance.
3459 : : */
3460 : : static ColumnDef *
3461 : 253 : MergeInheritedAttribute(List *inh_columns,
3462 : : int exist_attno,
3463 : : const ColumnDef *newdef)
3464 : : {
3465 : 253 : char *attributeName = newdef->colname;
3466 : : ColumnDef *prevdef;
3467 : : Oid prevtypeid,
3468 : : newtypeid;
3469 : : int32 prevtypmod,
3470 : : newtypmod;
3471 : : Oid prevcollid,
3472 : : newcollid;
3473 : :
3474 [ + - ]: 253 : ereport(NOTICE,
3475 : : (errmsg("merging multiple inherited definitions of column \"%s\"",
3476 : : attributeName)));
3477 : 253 : prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3478 : :
3479 : : /*
3480 : : * Must have the same type and typmod
3481 : : */
3482 : 253 : typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
3483 : 253 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3484 [ + - - + ]: 253 : if (prevtypeid != newtypeid || prevtypmod != newtypmod)
3485 [ # # ]: 0 : ereport(ERROR,
3486 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3487 : : errmsg("inherited column \"%s\" has a type conflict",
3488 : : attributeName),
3489 : : errdetail("%s versus %s",
3490 : : format_type_with_typemod(prevtypeid, prevtypmod),
3491 : : format_type_with_typemod(newtypeid, newtypmod))));
3492 : :
3493 : : /*
3494 : : * Must have the same collation
3495 : : */
3496 : 253 : prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
3497 : 253 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3498 [ - + ]: 253 : if (prevcollid != newcollid)
3499 [ # # ]: 0 : ereport(ERROR,
3500 : : (errcode(ERRCODE_COLLATION_MISMATCH),
3501 : : errmsg("inherited column \"%s\" has a collation conflict",
3502 : : attributeName),
3503 : : errdetail("\"%s\" versus \"%s\"",
3504 : : get_collation_name(prevcollid),
3505 : : get_collation_name(newcollid))));
3506 : :
3507 : : /*
3508 : : * Copy/check storage parameter
3509 : : */
3510 [ - + ]: 253 : if (prevdef->storage == 0)
3511 : 0 : prevdef->storage = newdef->storage;
3512 [ + + ]: 253 : else if (prevdef->storage != newdef->storage)
3513 [ + - ]: 4 : ereport(ERROR,
3514 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3515 : : errmsg("inherited column \"%s\" has a storage parameter conflict",
3516 : : attributeName),
3517 : : errdetail("%s versus %s",
3518 : : storage_name(prevdef->storage),
3519 : : storage_name(newdef->storage))));
3520 : :
3521 : : /*
3522 : : * Copy/check compression parameter
3523 : : */
3524 [ + + ]: 249 : if (prevdef->compression == NULL)
3525 : 237 : prevdef->compression = newdef->compression;
3526 [ + + ]: 12 : else if (newdef->compression != NULL)
3527 : : {
3528 [ + - ]: 4 : if (strcmp(prevdef->compression, newdef->compression) != 0)
3529 [ + - ]: 4 : ereport(ERROR,
3530 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3531 : : errmsg("column \"%s\" has a compression method conflict",
3532 : : attributeName),
3533 : : errdetail("%s versus %s",
3534 : : prevdef->compression, newdef->compression)));
3535 : : }
3536 : :
3537 : : /*
3538 : : * Check for GENERATED conflicts
3539 : : */
3540 [ + + ]: 245 : if (prevdef->generated != newdef->generated)
3541 [ + - ]: 16 : ereport(ERROR,
3542 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3543 : : errmsg("inherited column \"%s\" has a generation conflict",
3544 : : attributeName)));
3545 : :
3546 : : /*
3547 : : * Default and other constraints are handled by the caller.
3548 : : */
3549 : :
3550 [ - + ]: 229 : if (pg_add_s16_overflow(prevdef->inhcount, 1,
3551 : : &prevdef->inhcount))
3552 [ # # ]: 0 : ereport(ERROR,
3553 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3554 : : errmsg("too many inheritance parents"));
3555 : :
3556 : 229 : return prevdef;
3557 : : }
3558 : :
3559 : : /*
3560 : : * StoreCatalogInheritance
3561 : : * Updates the system catalogs with proper inheritance information.
3562 : : *
3563 : : * supers is a list of the OIDs of the new relation's direct ancestors.
3564 : : */
3565 : : static void
3566 : 40389 : StoreCatalogInheritance(Oid relationId, List *supers,
3567 : : bool child_is_partition)
3568 : : {
3569 : : Relation relation;
3570 : : int32 seqNumber;
3571 : : ListCell *entry;
3572 : :
3573 : : /*
3574 : : * sanity checks
3575 : : */
3576 : : Assert(OidIsValid(relationId));
3577 : :
3578 [ + + ]: 40389 : if (supers == NIL)
3579 : 33357 : return;
3580 : :
3581 : : /*
3582 : : * Store INHERITS information in pg_inherits using direct ancestors only.
3583 : : * Also enter dependencies on the direct ancestors, and make sure they are
3584 : : * marked with relhassubclass = true.
3585 : : *
3586 : : * (Once upon a time, both direct and indirect ancestors were found here
3587 : : * and then entered into pg_ipl. Since that catalog doesn't exist
3588 : : * anymore, there's no need to look for indirect ancestors.)
3589 : : */
3590 : 7032 : relation = table_open(InheritsRelationId, RowExclusiveLock);
3591 : :
3592 : 7032 : seqNumber = 1;
3593 [ + - + + : 14294 : foreach(entry, supers)
+ + ]
3594 : : {
3595 : 7262 : Oid parentOid = lfirst_oid(entry);
3596 : :
3597 : 7262 : StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
3598 : : child_is_partition);
3599 : 7262 : seqNumber++;
3600 : : }
3601 : :
3602 : 7032 : table_close(relation, RowExclusiveLock);
3603 : : }
3604 : :
3605 : : /*
3606 : : * Make catalog entries showing relationId as being an inheritance child
3607 : : * of parentOid. inhRelation is the already-opened pg_inherits catalog.
3608 : : */
3609 : : static void
3610 : 8828 : StoreCatalogInheritance1(Oid relationId, Oid parentOid,
3611 : : int32 seqNumber, Relation inhRelation,
3612 : : bool child_is_partition)
3613 : : {
3614 : : ObjectAddress childobject,
3615 : : parentobject;
3616 : :
3617 : : /* store the pg_inherits row */
3618 : 8828 : StoreSingleInheritance(relationId, parentOid, seqNumber);
3619 : :
3620 : : /*
3621 : : * Store a dependency too
3622 : : */
3623 : 8828 : parentobject.classId = RelationRelationId;
3624 : 8828 : parentobject.objectId = parentOid;
3625 : 8828 : parentobject.objectSubId = 0;
3626 : 8828 : childobject.classId = RelationRelationId;
3627 : 8828 : childobject.objectId = relationId;
3628 : 8828 : childobject.objectSubId = 0;
3629 : :
3630 [ + + ]: 8828 : recordDependencyOn(&childobject, &parentobject,
3631 : : child_dependency_type(child_is_partition));
3632 : :
3633 : : /*
3634 : : * Post creation hook of this inheritance. Since object_access_hook
3635 : : * doesn't take multiple object identifiers, we relay oid of parent
3636 : : * relation using auxiliary_id argument.
3637 : : */
3638 [ - + ]: 8828 : InvokeObjectPostAlterHookArg(InheritsRelationId,
3639 : : relationId, 0,
3640 : : parentOid, false);
3641 : :
3642 : : /*
3643 : : * Mark the parent as having subclasses.
3644 : : */
3645 : 8828 : SetRelationHasSubclass(parentOid, true);
3646 : 8828 : }
3647 : :
3648 : : /*
3649 : : * Look for an existing column entry with the given name.
3650 : : *
3651 : : * Returns the index (starting with 1) if attribute already exists in columns,
3652 : : * 0 if it doesn't.
3653 : : */
3654 : : static int
3655 : 15278 : findAttrByName(const char *attributeName, const List *columns)
3656 : : {
3657 : : ListCell *lc;
3658 : 15278 : int i = 1;
3659 : :
3660 [ + + + + : 26669 : foreach(lc, columns)
+ + ]
3661 : : {
3662 [ + + ]: 11895 : if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
3663 : 504 : return i;
3664 : :
3665 : 11391 : i++;
3666 : : }
3667 : 14774 : return 0;
3668 : : }
3669 : :
3670 : :
3671 : : /*
3672 : : * SetRelationHasSubclass
3673 : : * Set the value of the relation's relhassubclass field in pg_class.
3674 : : *
3675 : : * It's always safe to set this field to true, because all SQL commands are
3676 : : * ready to see true and then find no children. On the other hand, commands
3677 : : * generally assume zero children if this is false.
3678 : : *
3679 : : * Caller must hold any self-exclusive lock until end of transaction. If the
3680 : : * new value is false, caller must have acquired that lock before reading the
3681 : : * evidence that justified the false value. That way, it properly waits if
3682 : : * another backend is simultaneously concluding no need to change the tuple
3683 : : * (new and old values are true).
3684 : : *
3685 : : * NOTE: an important side-effect of this operation is that an SI invalidation
3686 : : * message is sent out to all backends --- including me --- causing plans
3687 : : * referencing the relation to be rebuilt with the new list of children.
3688 : : * This must happen even if we find that no change is needed in the pg_class
3689 : : * row.
3690 : : */
3691 : : void
3692 : 10890 : SetRelationHasSubclass(Oid relationId, bool relhassubclass)
3693 : : {
3694 : : Relation relationRelation;
3695 : : HeapTuple tuple;
3696 : : Form_pg_class classtuple;
3697 : :
3698 : : Assert(CheckRelationOidLockedByMe(relationId,
3699 : : ShareUpdateExclusiveLock, false) ||
3700 : : CheckRelationOidLockedByMe(relationId,
3701 : : ShareRowExclusiveLock, true));
3702 : :
3703 : : /*
3704 : : * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3705 : : */
3706 : 10890 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3707 : 10890 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3708 [ - + ]: 10890 : if (!HeapTupleIsValid(tuple))
3709 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationId);
3710 : 10890 : classtuple = (Form_pg_class) GETSTRUCT(tuple);
3711 : :
3712 [ + + ]: 10890 : if (classtuple->relhassubclass != relhassubclass)
3713 : : {
3714 : 5290 : classtuple->relhassubclass = relhassubclass;
3715 : 5290 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3716 : : }
3717 : : else
3718 : : {
3719 : : /* no need to change tuple, but force relcache rebuild anyway */
3720 : 5600 : CacheInvalidateRelcacheByTuple(tuple);
3721 : : }
3722 : :
3723 : 10890 : heap_freetuple(tuple);
3724 : 10890 : table_close(relationRelation, RowExclusiveLock);
3725 : 10890 : }
3726 : :
3727 : : /*
3728 : : * CheckRelationTableSpaceMove
3729 : : * Check if relation can be moved to new tablespace.
3730 : : *
3731 : : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3732 : : *
3733 : : * Returns true if the relation can be moved to the new tablespace; raises
3734 : : * an error if it is not possible to do the move; returns false if the move
3735 : : * would have no effect.
3736 : : */
3737 : : bool
3738 : 155 : CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
3739 : : {
3740 : : Oid oldTableSpaceId;
3741 : :
3742 : : /*
3743 : : * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3744 : : * stored as 0.
3745 : : */
3746 : 155 : oldTableSpaceId = rel->rd_rel->reltablespace;
3747 [ + + ]: 155 : if (newTableSpaceId == oldTableSpaceId ||
3748 [ + + + + ]: 150 : (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3749 : 10 : return false;
3750 : :
3751 : : /*
3752 : : * We cannot support moving mapped relations into different tablespaces.
3753 : : * (In particular this eliminates all shared catalogs.)
3754 : : */
3755 [ + + + + : 145 : if (RelationIsMapped(rel))
+ - + + +
+ - + ]
3756 [ # # ]: 0 : ereport(ERROR,
3757 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3758 : : errmsg("cannot move system relation \"%s\"",
3759 : : RelationGetRelationName(rel))));
3760 : :
3761 : : /* Cannot move a non-shared relation into pg_global */
3762 [ + + ]: 145 : if (newTableSpaceId == GLOBALTABLESPACE_OID)
3763 [ + - ]: 8 : ereport(ERROR,
3764 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3765 : : errmsg("only shared relations can be placed in pg_global tablespace")));
3766 : :
3767 : : /*
3768 : : * Do not allow moving temp tables of other backends ... their local
3769 : : * buffer manager is not going to cope.
3770 : : */
3771 [ + + - + ]: 137 : if (RELATION_IS_OTHER_TEMP(rel))
3772 [ # # ]: 0 : ereport(ERROR,
3773 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3774 : : errmsg("cannot move temporary tables of other sessions")));
3775 : :
3776 : 137 : return true;
3777 : : }
3778 : :
3779 : : /*
3780 : : * SetRelationTableSpace
3781 : : * Set new reltablespace and relfilenumber in pg_class entry.
3782 : : *
3783 : : * newTableSpaceId is the new tablespace for the relation, and
3784 : : * newRelFilenumber its new filenumber. If newRelFilenumber is
3785 : : * InvalidRelFileNumber, this field is not updated.
3786 : : *
3787 : : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3788 : : *
3789 : : * The caller of this routine had better check if a relation can be
3790 : : * moved to this new tablespace by calling CheckRelationTableSpaceMove()
3791 : : * first, and is responsible for making the change visible with
3792 : : * CommandCounterIncrement().
3793 : : */
3794 : : void
3795 : 137 : SetRelationTableSpace(Relation rel,
3796 : : Oid newTableSpaceId,
3797 : : RelFileNumber newRelFilenumber)
3798 : : {
3799 : : Relation pg_class;
3800 : : HeapTuple tuple;
3801 : : ItemPointerData otid;
3802 : : Form_pg_class rd_rel;
3803 : 137 : Oid reloid = RelationGetRelid(rel);
3804 : :
3805 : : Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3806 : :
3807 : : /* Get a modifiable copy of the relation's pg_class row. */
3808 : 137 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
3809 : :
3810 : 137 : tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3811 [ - + ]: 137 : if (!HeapTupleIsValid(tuple))
3812 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
3813 : 137 : otid = tuple->t_self;
3814 : 137 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3815 : :
3816 : : /* Update the pg_class row. */
3817 : 274 : rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3818 [ + + ]: 137 : InvalidOid : newTableSpaceId;
3819 [ + + ]: 137 : if (RelFileNumberIsValid(newRelFilenumber))
3820 : 108 : rd_rel->relfilenode = newRelFilenumber;
3821 : 137 : CatalogTupleUpdate(pg_class, &otid, tuple);
3822 : 137 : UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3823 : :
3824 : : /*
3825 : : * Record dependency on tablespace. This is only required for relations
3826 : : * that have no physical storage.
3827 : : */
3828 [ + + + + : 137 : if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
+ - + + +
+ ]
3829 : 20 : changeDependencyOnTablespace(RelationRelationId, reloid,
3830 : : rd_rel->reltablespace);
3831 : :
3832 : 137 : heap_freetuple(tuple);
3833 : 137 : table_close(pg_class, RowExclusiveLock);
3834 : 137 : }
3835 : :
3836 : : /*
3837 : : * renameatt_check - basic sanity checks before attribute rename
3838 : : */
3839 : : static void
3840 : 682 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3841 : : {
3842 : 682 : char relkind = classform->relkind;
3843 : :
3844 [ + + + + ]: 682 : if (classform->reloftype && !recursing)
3845 [ + - ]: 4 : ereport(ERROR,
3846 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3847 : : errmsg("cannot rename column of typed table")));
3848 : :
3849 : : /*
3850 : : * Renaming the columns of sequences or toast tables doesn't actually
3851 : : * break anything from the system's point of view, since internal
3852 : : * references are by attnum. But it doesn't seem right to allow users to
3853 : : * change names that are hardcoded into the system, hence the following
3854 : : * restriction.
3855 : : */
3856 [ + + + + ]: 678 : if (relkind != RELKIND_RELATION &&
3857 [ + - ]: 56 : relkind != RELKIND_VIEW &&
3858 [ + + ]: 56 : relkind != RELKIND_MATVIEW &&
3859 [ + - ]: 24 : relkind != RELKIND_COMPOSITE_TYPE &&
3860 [ + - ]: 24 : relkind != RELKIND_INDEX &&
3861 [ - + ]: 24 : relkind != RELKIND_PARTITIONED_INDEX &&
3862 [ # # ]: 0 : relkind != RELKIND_FOREIGN_TABLE &&
3863 : : relkind != RELKIND_PARTITIONED_TABLE)
3864 [ # # ]: 0 : ereport(ERROR,
3865 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3866 : : errmsg("cannot rename columns of relation \"%s\"",
3867 : : NameStr(classform->relname)),
3868 : : errdetail_relkind_not_supported(relkind)));
3869 : :
3870 : : /*
3871 : : * permissions checking. only the owner of a class can change its schema.
3872 : : */
3873 [ - + ]: 678 : if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
3874 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
3875 : 0 : NameStr(classform->relname));
3876 : :
3877 : : /*
3878 : : * Conflict log tables are used internally for logical replication
3879 : : * conflict logging and should not be modified directly, as it could
3880 : : * disrupt conflict logging.
3881 : : */
3882 [ + + ]: 678 : if (IsConflictLogTableClass(classform))
3883 [ + - ]: 4 : ereport(ERROR,
3884 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3885 : : errmsg("cannot rename columns of conflict log table \"%s\"",
3886 : : NameStr(classform->relname)),
3887 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
3888 : :
3889 [ + + + + ]: 674 : if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
3890 [ + - ]: 1 : ereport(ERROR,
3891 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3892 : : errmsg("permission denied: \"%s\" is a system catalog",
3893 : : NameStr(classform->relname))));
3894 : 673 : }
3895 : :
3896 : : /*
3897 : : * renameatt_internal - workhorse for renameatt
3898 : : *
3899 : : * Return value is the attribute number in the 'myrelid' relation.
3900 : : */
3901 : : static AttrNumber
3902 : 366 : renameatt_internal(Oid myrelid,
3903 : : const char *oldattname,
3904 : : const char *newattname,
3905 : : bool recurse,
3906 : : bool recursing,
3907 : : int expected_parents,
3908 : : DropBehavior behavior)
3909 : : {
3910 : : Relation targetrelation;
3911 : : Relation attrelation;
3912 : : HeapTuple atttup;
3913 : : Form_pg_attribute attform;
3914 : : AttrNumber attnum;
3915 : :
3916 : : /*
3917 : : * Grab an exclusive lock on the target table, which we will NOT release
3918 : : * until end of transaction.
3919 : : */
3920 : 366 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
3921 : 366 : renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
3922 : :
3923 : : /*
3924 : : * if the 'recurse' flag is set then we are supposed to rename this
3925 : : * attribute in all classes that inherit from 'relname' (as well as in
3926 : : * 'relname').
3927 : : *
3928 : : * any permissions or problems with duplicate attributes will cause the
3929 : : * whole transaction to abort, which is what we want -- all or nothing.
3930 : : */
3931 [ + + ]: 366 : if (recurse)
3932 : : {
3933 : : List *child_oids,
3934 : : *child_numparents;
3935 : : ListCell *lo,
3936 : : *li;
3937 : :
3938 : : /*
3939 : : * we need the number of parents for each child so that the recursive
3940 : : * calls to renameatt() can determine whether there are any parents
3941 : : * outside the inheritance hierarchy being processed.
3942 : : */
3943 : 164 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3944 : : &child_numparents);
3945 : :
3946 : : /*
3947 : : * find_all_inheritors does the recursive search of the inheritance
3948 : : * hierarchy, so all we have to do is process all of the relids in the
3949 : : * list that it returns.
3950 : : */
3951 [ + - + + : 486 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
3952 : : {
3953 : 342 : Oid childrelid = lfirst_oid(lo);
3954 : 342 : int numparents = lfirst_int(li);
3955 : :
3956 [ + + ]: 342 : if (childrelid == myrelid)
3957 : 164 : continue;
3958 : : /* note we need not recurse again */
3959 : 178 : renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
3960 : : }
3961 : : }
3962 : : else
3963 : : {
3964 : : /*
3965 : : * If we are told not to recurse, there had better not be any child
3966 : : * tables; else the rename would put them out of step.
3967 : : *
3968 : : * expected_parents will only be 0 if we are not already recursing.
3969 : : */
3970 [ + + + + ]: 226 : if (expected_parents == 0 &&
3971 : 24 : find_inheritance_children(myrelid, NoLock) != NIL)
3972 [ + - ]: 8 : ereport(ERROR,
3973 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3974 : : errmsg("inherited column \"%s\" must be renamed in child tables too",
3975 : : oldattname)));
3976 : : }
3977 : :
3978 : : /* rename attributes in typed tables of composite type */
3979 [ + + ]: 338 : if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
3980 : : {
3981 : : List *child_oids;
3982 : : ListCell *lo;
3983 : :
3984 : 16 : child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
3985 : 16 : RelationGetRelationName(targetrelation),
3986 : : behavior);
3987 : :
3988 [ + + + + : 16 : foreach(lo, child_oids)
+ + ]
3989 : 4 : renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
3990 : : }
3991 : :
3992 : 334 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
3993 : :
3994 : 334 : atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
3995 [ + + ]: 334 : if (!HeapTupleIsValid(atttup))
3996 [ + - ]: 16 : ereport(ERROR,
3997 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3998 : : errmsg("column \"%s\" does not exist",
3999 : : oldattname)));
4000 : 318 : attform = (Form_pg_attribute) GETSTRUCT(atttup);
4001 : :
4002 : 318 : attnum = attform->attnum;
4003 [ - + ]: 318 : if (attnum <= 0)
4004 [ # # ]: 0 : ereport(ERROR,
4005 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4006 : : errmsg("cannot rename system column \"%s\"",
4007 : : oldattname)));
4008 : :
4009 : : /*
4010 : : * if the attribute is inherited, forbid the renaming. if this is a
4011 : : * top-level call to renameatt(), then expected_parents will be 0, so the
4012 : : * effect of this code will be to prohibit the renaming if the attribute
4013 : : * is inherited at all. if this is a recursive call to renameatt(),
4014 : : * expected_parents will be the number of parents the current relation has
4015 : : * within the inheritance hierarchy being processed, so we'll prohibit the
4016 : : * renaming only if there are additional parents from elsewhere.
4017 : : */
4018 [ + + ]: 318 : if (attform->attinhcount > expected_parents)
4019 [ + - ]: 20 : ereport(ERROR,
4020 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4021 : : errmsg("cannot rename inherited column \"%s\"",
4022 : : oldattname)));
4023 : :
4024 : : /* new name should not already exist */
4025 : 298 : (void) check_for_column_name_collision(targetrelation, newattname, false);
4026 : :
4027 : : /* apply the update */
4028 : 290 : namestrcpy(&(attform->attname), newattname);
4029 : :
4030 : 290 : CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
4031 : :
4032 [ - + ]: 290 : InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
4033 : :
4034 : 290 : heap_freetuple(atttup);
4035 : :
4036 : 290 : table_close(attrelation, RowExclusiveLock);
4037 : :
4038 : 290 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4039 : :
4040 : 290 : return attnum;
4041 : : }
4042 : :
4043 : : /*
4044 : : * Perform permissions and integrity checks before acquiring a relation lock.
4045 : : */
4046 : : static void
4047 : 281 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
4048 : : void *arg)
4049 : : {
4050 : : HeapTuple tuple;
4051 : : Form_pg_class form;
4052 : :
4053 : 281 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
4054 [ + + ]: 281 : if (!HeapTupleIsValid(tuple))
4055 : 25 : return; /* concurrently dropped */
4056 : 256 : form = (Form_pg_class) GETSTRUCT(tuple);
4057 : 256 : renameatt_check(relid, form, false);
4058 : 247 : ReleaseSysCache(tuple);
4059 : : }
4060 : :
4061 : : /*
4062 : : * renameatt - changes the name of an attribute in a relation
4063 : : *
4064 : : * The returned ObjectAddress is that of the renamed column.
4065 : : */
4066 : : ObjectAddress
4067 : 213 : renameatt(RenameStmt *stmt)
4068 : : {
4069 : : Oid relid;
4070 : : AttrNumber attnum;
4071 : : ObjectAddress address;
4072 : :
4073 : : /* lock level taken here should match renameatt_internal */
4074 : 213 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4075 : 213 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4076 : : RangeVarCallbackForRenameAttribute,
4077 : : NULL);
4078 : :
4079 [ + + ]: 200 : if (!OidIsValid(relid))
4080 : : {
4081 [ + - ]: 16 : ereport(NOTICE,
4082 : : (errmsg("relation \"%s\" does not exist, skipping",
4083 : : stmt->relation->relname)));
4084 : 16 : return InvalidObjectAddress;
4085 : : }
4086 : :
4087 : : attnum =
4088 : 184 : renameatt_internal(relid,
4089 : 184 : stmt->subname, /* old att name */
4090 : 184 : stmt->newname, /* new att name */
4091 : 184 : stmt->relation->inh, /* recursive? */
4092 : : false, /* recursing? */
4093 : : 0, /* expected inhcount */
4094 : : stmt->behavior);
4095 : :
4096 : 128 : ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4097 : :
4098 : 128 : return address;
4099 : : }
4100 : :
4101 : : /*
4102 : : * same logic as renameatt_internal
4103 : : */
4104 : : static ObjectAddress
4105 : 64 : rename_constraint_internal(Oid myrelid,
4106 : : Oid mytypid,
4107 : : const char *oldconname,
4108 : : const char *newconname,
4109 : : bool recurse,
4110 : : bool recursing,
4111 : : int expected_parents)
4112 : : {
4113 : 64 : Relation targetrelation = NULL;
4114 : : Oid constraintOid;
4115 : : HeapTuple tuple;
4116 : : Form_pg_constraint con;
4117 : : ObjectAddress address;
4118 : :
4119 : : Assert(!myrelid || !mytypid);
4120 : :
4121 [ + + ]: 64 : if (mytypid)
4122 : : {
4123 : 4 : constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
4124 : : }
4125 : : else
4126 : : {
4127 : 60 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
4128 : :
4129 : : /*
4130 : : * don't tell it whether we're recursing; we allow changing typed
4131 : : * tables here
4132 : : */
4133 : 60 : renameatt_check(myrelid, RelationGetForm(targetrelation), false);
4134 : :
4135 : 60 : constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
4136 : : }
4137 : :
4138 : 64 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
4139 [ - + ]: 64 : if (!HeapTupleIsValid(tuple))
4140 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
4141 : : constraintOid);
4142 : 64 : con = (Form_pg_constraint) GETSTRUCT(tuple);
4143 : :
4144 [ + + ]: 64 : if (myrelid &&
4145 [ + + ]: 60 : (con->contype == CONSTRAINT_CHECK ||
4146 [ + + ]: 20 : con->contype == CONSTRAINT_NOTNULL) &&
4147 [ + + ]: 44 : !con->connoinherit)
4148 : : {
4149 [ + + ]: 36 : if (recurse)
4150 : : {
4151 : : List *child_oids,
4152 : : *child_numparents;
4153 : : ListCell *lo,
4154 : : *li;
4155 : :
4156 : 24 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
4157 : : &child_numparents);
4158 : :
4159 [ + - + + : 56 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
4160 : : {
4161 : 32 : Oid childrelid = lfirst_oid(lo);
4162 : 32 : int numparents = lfirst_int(li);
4163 : :
4164 [ + + ]: 32 : if (childrelid == myrelid)
4165 : 24 : continue;
4166 : :
4167 : 8 : rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
4168 : : }
4169 : : }
4170 : : else
4171 : : {
4172 [ + + + - ]: 16 : if (expected_parents == 0 &&
4173 : 4 : find_inheritance_children(myrelid, NoLock) != NIL)
4174 [ + - ]: 4 : ereport(ERROR,
4175 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4176 : : errmsg("inherited constraint \"%s\" must be renamed in child tables too",
4177 : : oldconname)));
4178 : : }
4179 : :
4180 [ + + ]: 32 : if (con->coninhcount > expected_parents)
4181 [ + - ]: 4 : ereport(ERROR,
4182 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4183 : : errmsg("cannot rename inherited constraint \"%s\"",
4184 : : oldconname)));
4185 : : }
4186 : :
4187 [ + + ]: 56 : if (con->conindid
4188 [ + + ]: 16 : && (con->contype == CONSTRAINT_PRIMARY
4189 [ + + ]: 8 : || con->contype == CONSTRAINT_UNIQUE
4190 [ - + ]: 4 : || con->contype == CONSTRAINT_EXCLUSION))
4191 : : /* rename the index; this renames the constraint as well */
4192 : 12 : RenameRelationInternal(con->conindid, newconname, false, true);
4193 : : else
4194 : 44 : RenameConstraintById(constraintOid, newconname);
4195 : :
4196 : 56 : ObjectAddressSet(address, ConstraintRelationId, constraintOid);
4197 : :
4198 : 56 : ReleaseSysCache(tuple);
4199 : :
4200 [ + + ]: 56 : if (targetrelation)
4201 : : {
4202 : : /*
4203 : : * Invalidate relcache so as others can see the new constraint name.
4204 : : */
4205 : 52 : CacheInvalidateRelcache(targetrelation);
4206 : :
4207 : 52 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4208 : : }
4209 : :
4210 : 56 : return address;
4211 : : }
4212 : :
4213 : : ObjectAddress
4214 : 60 : RenameConstraint(RenameStmt *stmt)
4215 : : {
4216 : 60 : Oid relid = InvalidOid;
4217 : 60 : Oid typid = InvalidOid;
4218 : :
4219 [ + + ]: 60 : if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4220 : : {
4221 : : Relation rel;
4222 : : HeapTuple tup;
4223 : :
4224 : 4 : typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4225 : 4 : rel = table_open(TypeRelationId, RowExclusiveLock);
4226 : 4 : tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4227 [ - + ]: 4 : if (!HeapTupleIsValid(tup))
4228 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", typid);
4229 : 4 : checkDomainOwner(tup);
4230 : 4 : ReleaseSysCache(tup);
4231 : 4 : table_close(rel, NoLock);
4232 : : }
4233 : : else
4234 : : {
4235 : : /* lock level taken here should match rename_constraint_internal */
4236 : 56 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4237 : 56 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4238 : : RangeVarCallbackForRenameAttribute,
4239 : : NULL);
4240 [ + + ]: 56 : if (!OidIsValid(relid))
4241 : : {
4242 [ + - ]: 4 : ereport(NOTICE,
4243 : : (errmsg("relation \"%s\" does not exist, skipping",
4244 : : stmt->relation->relname)));
4245 : 4 : return InvalidObjectAddress;
4246 : : }
4247 : : }
4248 : :
4249 : : return
4250 : 56 : rename_constraint_internal(relid, typid,
4251 : 56 : stmt->subname,
4252 : 56 : stmt->newname,
4253 [ + + ]: 108 : (stmt->relation &&
4254 [ + + ]: 52 : stmt->relation->inh), /* recursive? */
4255 : : false, /* recursing? */
4256 : 56 : 0 /* expected inhcount */ );
4257 : : }
4258 : :
4259 : : /*
4260 : : * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
4261 : : * RENAME
4262 : : */
4263 : : ObjectAddress
4264 : 303 : RenameRelation(RenameStmt *stmt)
4265 : : {
4266 : 303 : bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4267 : : Oid relid;
4268 : : ObjectAddress address;
4269 : :
4270 : : /*
4271 : : * Grab an exclusive lock on the target table, index, sequence, view,
4272 : : * materialized view, or foreign table, which we will NOT release until
4273 : : * end of transaction.
4274 : : *
4275 : : * Lock level used here should match RenameRelationInternal, to avoid lock
4276 : : * escalation. However, because ALTER INDEX can be used with any relation
4277 : : * type, we mustn't believe without verification.
4278 : : */
4279 : : for (;;)
4280 : 8 : {
4281 : : LOCKMODE lockmode;
4282 : : char relkind;
4283 : : bool obj_is_index;
4284 : :
4285 [ + + ]: 311 : lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4286 : :
4287 : 311 : relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4288 : 311 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4289 : : RangeVarCallbackForAlterRelation,
4290 : : stmt);
4291 : :
4292 [ + + ]: 278 : if (!OidIsValid(relid))
4293 : : {
4294 [ + - ]: 12 : ereport(NOTICE,
4295 : : (errmsg("relation \"%s\" does not exist, skipping",
4296 : : stmt->relation->relname)));
4297 : 12 : return InvalidObjectAddress;
4298 : : }
4299 : :
4300 : : /*
4301 : : * We allow mismatched statement and object types (e.g., ALTER INDEX
4302 : : * to rename a table), but we might've used the wrong lock level. If
4303 : : * that happens, retry with the correct lock level. We don't bother
4304 : : * if we already acquired AccessExclusiveLock with an index, however.
4305 : : */
4306 : 266 : relkind = get_rel_relkind(relid);
4307 [ + + + + ]: 266 : obj_is_index = (relkind == RELKIND_INDEX ||
4308 : : relkind == RELKIND_PARTITIONED_INDEX);
4309 [ + + + + ]: 266 : if (obj_is_index || is_index_stmt == obj_is_index)
4310 : : break;
4311 : :
4312 : 8 : UnlockRelationOid(relid, lockmode);
4313 : 8 : is_index_stmt = obj_is_index;
4314 : : }
4315 : :
4316 : : /* Do the work */
4317 : 258 : RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4318 : :
4319 : 250 : ObjectAddressSet(address, RelationRelationId, relid);
4320 : :
4321 : 250 : return address;
4322 : : }
4323 : :
4324 : : /*
4325 : : * RenameRelationInternal - change the name of a relation
4326 : : */
4327 : : void
4328 : 1056 : RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
4329 : : {
4330 : : Relation targetrelation;
4331 : : Relation relrelation; /* for RELATION relation */
4332 : : ItemPointerData otid;
4333 : : HeapTuple reltup;
4334 : : Form_pg_class relform;
4335 : : Oid namespaceId;
4336 : :
4337 : : /*
4338 : : * Grab a lock on the target relation, which we will NOT release until end
4339 : : * of transaction. We need at least a self-exclusive lock so that
4340 : : * concurrent DDL doesn't overwrite the rename if they start updating
4341 : : * while still seeing the old version. The lock also guards against
4342 : : * triggering relcache reloads in concurrent sessions, which might not
4343 : : * handle this information changing under them. For indexes, we can use a
4344 : : * reduced lock level because RelationReloadIndexInfo() handles indexes
4345 : : * specially.
4346 : : */
4347 [ + + ]: 1056 : targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4348 : 1056 : namespaceId = RelationGetNamespace(targetrelation);
4349 : :
4350 : : /*
4351 : : * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4352 : : */
4353 : 1056 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4354 : :
4355 : 1056 : reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
4356 [ - + ]: 1056 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4357 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4358 : 1056 : otid = reltup->t_self;
4359 : 1056 : relform = (Form_pg_class) GETSTRUCT(reltup);
4360 : :
4361 [ + + ]: 1056 : if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4362 [ + - ]: 8 : ereport(ERROR,
4363 : : (errcode(ERRCODE_DUPLICATE_TABLE),
4364 : : errmsg("relation \"%s\" already exists",
4365 : : newrelname)));
4366 : :
4367 : : /*
4368 : : * RenameRelation is careful not to believe the caller's idea of the
4369 : : * relation kind being handled. We don't have to worry about this, but
4370 : : * let's not be totally oblivious to it. We can process an index as
4371 : : * not-an-index, but not the other way around.
4372 : : */
4373 : : Assert(!is_index ||
4374 : : is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4375 : : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4376 : :
4377 : : /*
4378 : : * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4379 : : * because it's a copy...)
4380 : : */
4381 : 1048 : namestrcpy(&(relform->relname), newrelname);
4382 : :
4383 : 1048 : CatalogTupleUpdate(relrelation, &otid, reltup);
4384 : 1048 : UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
4385 : :
4386 [ - + ]: 1048 : InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4387 : : InvalidOid, is_internal);
4388 : :
4389 : 1048 : heap_freetuple(reltup);
4390 : 1048 : table_close(relrelation, RowExclusiveLock);
4391 : :
4392 : : /*
4393 : : * Also rename the associated type, if any.
4394 : : */
4395 [ + + ]: 1048 : if (OidIsValid(targetrelation->rd_rel->reltype))
4396 : 86 : RenameTypeInternal(targetrelation->rd_rel->reltype,
4397 : : newrelname, namespaceId);
4398 : :
4399 : : /*
4400 : : * Also rename the associated constraint, if any.
4401 : : */
4402 [ + + ]: 1048 : if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4403 [ + + ]: 553 : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4404 : : {
4405 : 507 : Oid constraintId = get_index_constraint(myrelid);
4406 : :
4407 [ + + ]: 507 : if (OidIsValid(constraintId))
4408 : 24 : RenameConstraintById(constraintId, newrelname);
4409 : : }
4410 : :
4411 : : /*
4412 : : * Close rel, but keep lock!
4413 : : */
4414 : 1048 : relation_close(targetrelation, NoLock);
4415 : 1048 : }
4416 : :
4417 : : /*
4418 : : * ResetRelRewrite - reset relrewrite
4419 : : */
4420 : : void
4421 : 386 : ResetRelRewrite(Oid myrelid)
4422 : : {
4423 : : Relation relrelation; /* for RELATION relation */
4424 : : HeapTuple reltup;
4425 : : Form_pg_class relform;
4426 : :
4427 : : /*
4428 : : * Find relation's pg_class tuple.
4429 : : */
4430 : 386 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4431 : :
4432 : 386 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4433 [ - + ]: 386 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4434 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4435 : 386 : relform = (Form_pg_class) GETSTRUCT(reltup);
4436 : :
4437 : : /*
4438 : : * Update pg_class tuple.
4439 : : */
4440 : 386 : relform->relrewrite = InvalidOid;
4441 : :
4442 : 386 : CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4443 : :
4444 : 386 : heap_freetuple(reltup);
4445 : 386 : table_close(relrelation, RowExclusiveLock);
4446 : 386 : }
4447 : :
4448 : : /*
4449 : : * Disallow ALTER TABLE (and similar commands) when the current backend has
4450 : : * any open reference to the target table besides the one just acquired by
4451 : : * the calling command; this implies there's an open cursor or active plan.
4452 : : * We need this check because our lock doesn't protect us against stomping
4453 : : * on our own foot, only other people's feet!
4454 : : *
4455 : : * For ALTER TABLE, the only case known to cause serious trouble is ALTER
4456 : : * COLUMN TYPE, and some changes are obviously pretty benign, so this could
4457 : : * possibly be relaxed to only error out for certain types of alterations.
4458 : : * But the use-case for allowing any of these things is not obvious, so we
4459 : : * won't work hard at it for now.
4460 : : *
4461 : : * We also reject these commands if there are any pending AFTER trigger events
4462 : : * for the rel. This is certainly necessary for the rewriting variants of
4463 : : * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
4464 : : * events would try to fetch the wrong tuples. It might be overly cautious
4465 : : * in other cases, but again it seems better to err on the side of paranoia.
4466 : : *
4467 : : * REINDEX calls this with "rel" referencing the index to be rebuilt; here
4468 : : * we are worried about active indexscans on the index. The trigger-event
4469 : : * check can be skipped, since we are doing no damage to the parent table.
4470 : : *
4471 : : * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
4472 : : */
4473 : : void
4474 : 112249 : CheckTableNotInUse(Relation rel, const char *stmt)
4475 : : {
4476 : : int expected_refcnt;
4477 : :
4478 [ + + ]: 112249 : expected_refcnt = rel->rd_isnailed ? 2 : 1;
4479 [ + + ]: 112249 : if (rel->rd_refcnt != expected_refcnt)
4480 [ + - ]: 28 : ereport(ERROR,
4481 : : (errcode(ERRCODE_OBJECT_IN_USE),
4482 : : /* translator: first %s is a SQL command, eg ALTER TABLE */
4483 : : errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4484 : : stmt, RelationGetRelationName(rel))));
4485 : :
4486 [ + + ]: 112221 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
4487 [ + + + + ]: 183496 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4488 : 91036 : AfterTriggerPendingOnRel(RelationGetRelid(rel)))
4489 [ + - ]: 12 : ereport(ERROR,
4490 : : (errcode(ERRCODE_OBJECT_IN_USE),
4491 : : /* translator: first %s is a SQL command, eg ALTER TABLE */
4492 : : errmsg("cannot %s \"%s\" because it has pending trigger events",
4493 : : stmt, RelationGetRelationName(rel))));
4494 : 112209 : }
4495 : :
4496 : : /*
4497 : : * CheckAlterTableIsSafe
4498 : : * Verify that it's safe to allow ALTER TABLE on this relation.
4499 : : *
4500 : : * This consists of CheckTableNotInUse() plus a check that the relation
4501 : : * isn't another session's temp table. We must split out the temp-table
4502 : : * check because there are callers of CheckTableNotInUse() that don't want
4503 : : * that, notably DROP TABLE. (We must allow DROP or we couldn't clean out
4504 : : * an orphaned temp schema.) Compare truncate_check_activity().
4505 : : */
4506 : : static void
4507 : 39619 : CheckAlterTableIsSafe(Relation rel)
4508 : : {
4509 : : /*
4510 : : * Don't allow ALTER on temp tables of other backends. Their local buffer
4511 : : * manager is not going to cope if we need to change the table's contents.
4512 : : * Even if we don't, there may be optimizations that assume temp tables
4513 : : * aren't subject to such interference.
4514 : : */
4515 [ + + + + ]: 39619 : if (RELATION_IS_OTHER_TEMP(rel))
4516 [ + - ]: 2 : ereport(ERROR,
4517 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4518 : : errmsg("cannot alter temporary tables of other sessions")));
4519 : :
4520 : : /*
4521 : : * Also check for active uses of the relation in the current transaction,
4522 : : * including open scans and pending AFTER trigger events.
4523 : : */
4524 : 39617 : CheckTableNotInUse(rel, "ALTER TABLE");
4525 : 39593 : }
4526 : :
4527 : : /*
4528 : : * AlterTableLookupRelation
4529 : : * Look up, and lock, the OID for the relation named by an alter table
4530 : : * statement.
4531 : : */
4532 : : Oid
4533 : 21080 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
4534 : : {
4535 : 42094 : return RangeVarGetRelidExtended(stmt->relation, lockmode,
4536 : 21080 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4537 : : RangeVarCallbackForAlterRelation,
4538 : : stmt);
4539 : : }
4540 : :
4541 : : /*
4542 : : * AlterTable
4543 : : * Execute ALTER TABLE, which can be a list of subcommands
4544 : : *
4545 : : * ALTER TABLE is performed in three phases:
4546 : : * 1. Examine subcommands and perform pre-transformation checking.
4547 : : * 2. Validate and transform subcommands, and update system catalogs.
4548 : : * 3. Scan table(s) to check new constraints, and optionally recopy
4549 : : * the data into new table(s).
4550 : : * Phase 3 is not performed unless one or more of the subcommands requires
4551 : : * it. The intention of this design is to allow multiple independent
4552 : : * updates of the table schema to be performed with only one pass over the
4553 : : * data.
4554 : : *
4555 : : * ATPrepCmd performs phase 1. A "work queue" entry is created for
4556 : : * each table to be affected (there may be multiple affected tables if the
4557 : : * commands traverse a table inheritance hierarchy). Also we do preliminary
4558 : : * validation of the subcommands. Because earlier subcommands may change
4559 : : * the catalog state seen by later commands, there are limits to what can
4560 : : * be done in this phase. Generally, this phase acquires table locks,
4561 : : * checks permissions and relkind, and recurses to find child tables.
4562 : : *
4563 : : * ATRewriteCatalogs performs phase 2 for each affected table.
4564 : : * Certain subcommands need to be performed before others to avoid
4565 : : * unnecessary conflicts; for example, DROP COLUMN should come before
4566 : : * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
4567 : : * lists, one for each logical "pass" of phase 2.
4568 : : *
4569 : : * ATRewriteTables performs phase 3 for those tables that need it.
4570 : : *
4571 : : * For most subcommand types, phases 2 and 3 do no explicit recursion,
4572 : : * since phase 1 already does it. However, for certain subcommand types
4573 : : * it is only possible to determine how to recurse at phase 2 time; for
4574 : : * those cases, phase 1 sets the cmd->recurse flag.
4575 : : *
4576 : : * Thanks to the magic of MVCC, an error anywhere along the way rolls back
4577 : : * the whole operation; we don't have to do anything special to clean up.
4578 : : *
4579 : : * The caller must lock the relation, with an appropriate lock level
4580 : : * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
4581 : : * or higher. We pass the lock level down
4582 : : * so that we can apply it recursively to inherited tables. Note that the
4583 : : * lock level we want as we recurse might well be higher than required for
4584 : : * that specific subcommand. So we pass down the overall lock requirement,
4585 : : * rather than reassess it at lower levels.
4586 : : *
4587 : : * The caller also provides a "context" which is to be passed back to
4588 : : * utility.c when we need to execute a subcommand such as CREATE INDEX.
4589 : : * Some of the fields therein, such as the relid, are used here as well.
4590 : : */
4591 : : void
4592 : 20906 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
4593 : : AlterTableUtilityContext *context)
4594 : : {
4595 : : Relation rel;
4596 : :
4597 : : /* Caller is required to provide an adequate lock. */
4598 : 20906 : rel = relation_open(context->relid, NoLock);
4599 : :
4600 : 20906 : CheckAlterTableIsSafe(rel);
4601 : :
4602 : 20892 : ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4603 : 18164 : }
4604 : :
4605 : : /*
4606 : : * AlterTableInternal
4607 : : *
4608 : : * ALTER TABLE with target specified by OID
4609 : : *
4610 : : * We do not reject if the relation is already open, because it's quite
4611 : : * likely that one or more layers of caller have it open. That means it
4612 : : * is unsafe to use this entry point for alterations that could break
4613 : : * existing query plans. On the assumption it's not used for such, we
4614 : : * don't have to reject pending AFTER triggers, either.
4615 : : *
4616 : : * Also, since we don't have an AlterTableUtilityContext, this cannot be
4617 : : * used for any subcommand types that require parse transformation or
4618 : : * could generate subcommands that have to be passed to ProcessUtility.
4619 : : */
4620 : : void
4621 : 193 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
4622 : : {
4623 : : Relation rel;
4624 : 193 : LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4625 : :
4626 : 193 : rel = relation_open(relid, lockmode);
4627 : :
4628 : 193 : EventTriggerAlterTableRelid(relid);
4629 : :
4630 : 193 : ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4631 : 193 : }
4632 : :
4633 : : /*
4634 : : * AlterTableGetLockLevel
4635 : : *
4636 : : * Sets the overall lock level required for the supplied list of subcommands.
4637 : : * Policy for doing this set according to needs of AlterTable(), see
4638 : : * comments there for overall explanation.
4639 : : *
4640 : : * Function is called before and after parsing, so it must give same
4641 : : * answer each time it is called. Some subcommands are transformed
4642 : : * into other subcommand types, so the transform must never be made to a
4643 : : * lower lock level than previously assigned. All transforms are noted below.
4644 : : *
4645 : : * Since this is called before we lock the table we cannot use table metadata
4646 : : * to influence the type of lock we acquire.
4647 : : *
4648 : : * There should be no lockmodes hardcoded into the subcommand functions. All
4649 : : * lockmode decisions for ALTER TABLE are made here only. The one exception is
4650 : : * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
4651 : : * and does not travel through this section of code and cannot be combined with
4652 : : * any of the subcommands given here.
4653 : : *
4654 : : * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
4655 : : * so any changes that might affect SELECTs running on standbys need to use
4656 : : * AccessExclusiveLocks even if you think a lesser lock would do, unless you
4657 : : * have a solution for that also.
4658 : : *
4659 : : * Also note that pg_dump uses only an AccessShareLock, meaning that anything
4660 : : * that takes a lock less than AccessExclusiveLock can change object definitions
4661 : : * while pg_dump is running. Be careful to check that the appropriate data is
4662 : : * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
4663 : : * otherwise we might end up with an inconsistent dump that can't restore.
4664 : : */
4665 : : LOCKMODE
4666 : 21273 : AlterTableGetLockLevel(List *cmds)
4667 : : {
4668 : : /*
4669 : : * This only works if we read catalog tables using MVCC snapshots.
4670 : : */
4671 : : ListCell *lcmd;
4672 : 21273 : LOCKMODE lockmode = ShareUpdateExclusiveLock;
4673 : :
4674 [ + - + + : 43404 : foreach(lcmd, cmds)
+ + ]
4675 : : {
4676 : 22131 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4677 : 22131 : LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4678 : :
4679 [ + + + + : 22131 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + + + +
- ]
4680 : : {
4681 : : /*
4682 : : * These subcommands rewrite the heap, so require full locks.
4683 : : */
4684 : 2629 : case AT_AddColumn: /* may rewrite heap, in some cases and visible
4685 : : * to SELECT */
4686 : : case AT_SetAccessMethod: /* must rewrite heap */
4687 : : case AT_SetTableSpace: /* must rewrite heap */
4688 : : case AT_AlterColumnType: /* must rewrite heap */
4689 : 2629 : cmd_lockmode = AccessExclusiveLock;
4690 : 2629 : break;
4691 : :
4692 : : /*
4693 : : * These subcommands may require addition of toast tables. If
4694 : : * we add a toast table to a table currently being scanned, we
4695 : : * might miss data added to the new toast table by concurrent
4696 : : * insert transactions.
4697 : : */
4698 : 221 : case AT_SetStorage: /* may add toast tables, see
4699 : : * ATRewriteCatalogs() */
4700 : 221 : cmd_lockmode = AccessExclusiveLock;
4701 : 221 : break;
4702 : :
4703 : : /*
4704 : : * Removing constraints can affect SELECTs that have been
4705 : : * optimized assuming the constraint holds true. See also
4706 : : * CloneFkReferenced.
4707 : : */
4708 : 793 : case AT_DropConstraint: /* as DROP INDEX */
4709 : : case AT_DropNotNull: /* may change some SQL plans */
4710 : 793 : cmd_lockmode = AccessExclusiveLock;
4711 : 793 : break;
4712 : :
4713 : : /*
4714 : : * Subcommands that may be visible to concurrent SELECTs
4715 : : */
4716 : 1180 : case AT_DropColumn: /* change visible to SELECT */
4717 : : case AT_AddColumnToView: /* CREATE VIEW */
4718 : : case AT_DropOids: /* used to equiv to DropColumn */
4719 : : case AT_EnableAlwaysRule: /* may change SELECT rules */
4720 : : case AT_EnableReplicaRule: /* may change SELECT rules */
4721 : : case AT_EnableRule: /* may change SELECT rules */
4722 : : case AT_DisableRule: /* may change SELECT rules */
4723 : 1180 : cmd_lockmode = AccessExclusiveLock;
4724 : 1180 : break;
4725 : :
4726 : : /*
4727 : : * Changing owner may remove implicit SELECT privileges
4728 : : */
4729 : 1152 : case AT_ChangeOwner: /* change visible to SELECT */
4730 : 1152 : cmd_lockmode = AccessExclusiveLock;
4731 : 1152 : break;
4732 : :
4733 : : /*
4734 : : * Changing foreign table options may affect optimization.
4735 : : */
4736 : 144 : case AT_GenericOptions:
4737 : : case AT_AlterColumnGenericOptions:
4738 : 144 : cmd_lockmode = AccessExclusiveLock;
4739 : 144 : break;
4740 : :
4741 : : /*
4742 : : * These subcommands affect write operations only.
4743 : : */
4744 : 191 : case AT_EnableTrig:
4745 : : case AT_EnableAlwaysTrig:
4746 : : case AT_EnableReplicaTrig:
4747 : : case AT_EnableTrigAll:
4748 : : case AT_EnableTrigUser:
4749 : : case AT_DisableTrig:
4750 : : case AT_DisableTrigAll:
4751 : : case AT_DisableTrigUser:
4752 : 191 : cmd_lockmode = ShareRowExclusiveLock;
4753 : 191 : break;
4754 : :
4755 : : /*
4756 : : * These subcommands affect write operations only. XXX
4757 : : * Theoretically, these could be ShareRowExclusiveLock.
4758 : : */
4759 : 2174 : case AT_ColumnDefault:
4760 : : case AT_CookedColumnDefault:
4761 : : case AT_AlterConstraint:
4762 : : case AT_AddIndex: /* from ADD CONSTRAINT */
4763 : : case AT_AddIndexConstraint:
4764 : : case AT_ReplicaIdentity:
4765 : : case AT_SetNotNull:
4766 : : case AT_EnableRowSecurity:
4767 : : case AT_DisableRowSecurity:
4768 : : case AT_ForceRowSecurity:
4769 : : case AT_NoForceRowSecurity:
4770 : : case AT_AddIdentity:
4771 : : case AT_DropIdentity:
4772 : : case AT_SetIdentity:
4773 : : case AT_SetExpression:
4774 : : case AT_DropExpression:
4775 : : case AT_SetCompression:
4776 : 2174 : cmd_lockmode = AccessExclusiveLock;
4777 : 2174 : break;
4778 : :
4779 : 9776 : case AT_AddConstraint:
4780 : : case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4781 : : case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4782 [ + - ]: 9776 : if (IsA(cmd->def, Constraint))
4783 : : {
4784 : 9776 : Constraint *con = (Constraint *) cmd->def;
4785 : :
4786 [ + + + ]: 9776 : switch (con->contype)
4787 : : {
4788 : 7173 : case CONSTR_EXCLUSION:
4789 : : case CONSTR_PRIMARY:
4790 : : case CONSTR_UNIQUE:
4791 : :
4792 : : /*
4793 : : * Cases essentially the same as CREATE INDEX. We
4794 : : * could reduce the lock strength to ShareLock if
4795 : : * we can work out how to allow concurrent catalog
4796 : : * updates. XXX Might be set down to
4797 : : * ShareRowExclusiveLock but requires further
4798 : : * analysis.
4799 : : */
4800 : 7173 : cmd_lockmode = AccessExclusiveLock;
4801 : 7173 : break;
4802 : 1820 : case CONSTR_FOREIGN:
4803 : :
4804 : : /*
4805 : : * We add triggers to both tables when we add a
4806 : : * Foreign Key, so the lock level must be at least
4807 : : * as strong as CREATE TRIGGER.
4808 : : */
4809 : 1820 : cmd_lockmode = ShareRowExclusiveLock;
4810 : 1820 : break;
4811 : :
4812 : 783 : default:
4813 : 783 : cmd_lockmode = AccessExclusiveLock;
4814 : : }
4815 : : }
4816 : 9776 : break;
4817 : :
4818 : : /*
4819 : : * These subcommands affect inheritance behaviour. Queries
4820 : : * started before us will continue to see the old inheritance
4821 : : * behaviour, while queries started after we commit will see
4822 : : * new behaviour. No need to prevent reads or writes to the
4823 : : * subtable while we hook it up though. Changing the TupDesc
4824 : : * may be a problem, so keep highest lock.
4825 : : */
4826 : 378 : case AT_AddInherit:
4827 : : case AT_DropInherit:
4828 : 378 : cmd_lockmode = AccessExclusiveLock;
4829 : 378 : break;
4830 : :
4831 : : /*
4832 : : * These subcommands affect implicit row type conversion. They
4833 : : * have affects similar to CREATE/DROP CAST on queries. don't
4834 : : * provide for invalidating parse trees as a result of such
4835 : : * changes, so we keep these at AccessExclusiveLock.
4836 : : */
4837 : 54 : case AT_AddOf:
4838 : : case AT_DropOf:
4839 : 54 : cmd_lockmode = AccessExclusiveLock;
4840 : 54 : break;
4841 : :
4842 : : /*
4843 : : * Only used by CREATE OR REPLACE VIEW which must conflict
4844 : : * with an SELECTs currently using the view.
4845 : : */
4846 : 137 : case AT_ReplaceRelOptions:
4847 : 137 : cmd_lockmode = AccessExclusiveLock;
4848 : 137 : break;
4849 : :
4850 : : /*
4851 : : * These subcommands affect general strategies for performance
4852 : : * and maintenance, though don't change the semantic results
4853 : : * from normal data reads and writes. Delaying an ALTER TABLE
4854 : : * behind currently active writes only delays the point where
4855 : : * the new strategy begins to take effect, so there is no
4856 : : * benefit in waiting. In this case the minimum restriction
4857 : : * applies: we don't currently allow concurrent catalog
4858 : : * updates.
4859 : : */
4860 : 160 : case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4861 : : case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4862 : : case AT_DropCluster: /* Uses MVCC in getIndexes() */
4863 : : case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4864 : : case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4865 : 160 : cmd_lockmode = ShareUpdateExclusiveLock;
4866 : 160 : break;
4867 : :
4868 : 79 : case AT_SetLogged:
4869 : : case AT_SetUnLogged:
4870 : 79 : cmd_lockmode = AccessExclusiveLock;
4871 : 79 : break;
4872 : :
4873 : 292 : case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4874 : 292 : cmd_lockmode = ShareUpdateExclusiveLock;
4875 : 292 : break;
4876 : :
4877 : : /*
4878 : : * Rel options are more complex than first appears. Options
4879 : : * are set here for tables, views and indexes; for historical
4880 : : * reasons these can all be used with ALTER TABLE, so we can't
4881 : : * decide between them using the basic grammar.
4882 : : */
4883 : 541 : case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4884 : : * getTables() */
4885 : : case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4886 : : * getTables() */
4887 : 541 : cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4888 : 541 : break;
4889 : :
4890 : 1845 : case AT_AttachPartition:
4891 : 1845 : cmd_lockmode = ShareUpdateExclusiveLock;
4892 : 1845 : break;
4893 : :
4894 : 374 : case AT_DetachPartition:
4895 [ + + ]: 374 : if (((PartitionCmd *) cmd->def)->concurrent)
4896 : 88 : cmd_lockmode = ShareUpdateExclusiveLock;
4897 : : else
4898 : 286 : cmd_lockmode = AccessExclusiveLock;
4899 : 374 : break;
4900 : :
4901 : 11 : case AT_DetachPartitionFinalize:
4902 : 11 : cmd_lockmode = ShareUpdateExclusiveLock;
4903 : 11 : break;
4904 : :
4905 : 0 : default: /* oops */
4906 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
4907 : : (int) cmd->subtype);
4908 : : break;
4909 : : }
4910 : :
4911 : : /*
4912 : : * Take the greatest lockmode from any subcommand
4913 : : */
4914 [ + + ]: 22131 : if (cmd_lockmode > lockmode)
4915 : 18454 : lockmode = cmd_lockmode;
4916 : : }
4917 : :
4918 : 21273 : return lockmode;
4919 : : }
4920 : :
4921 : : /*
4922 : : * ATController provides top level control over the phases.
4923 : : *
4924 : : * parsetree is passed in to allow it to be passed to event triggers
4925 : : * when requested.
4926 : : */
4927 : : static void
4928 : 21085 : ATController(AlterTableStmt *parsetree,
4929 : : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4930 : : AlterTableUtilityContext *context)
4931 : : {
4932 : 21085 : List *wqueue = NIL;
4933 : : ListCell *lcmd;
4934 : :
4935 : : /* Phase 1: preliminary examination of commands, create work queue */
4936 [ + - + + : 42739 : foreach(lcmd, cmds)
+ + ]
4937 : : {
4938 : 21939 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4939 : :
4940 : 21939 : ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4941 : : }
4942 : :
4943 : : /* Close the relation, but keep lock until commit */
4944 : 20800 : relation_close(rel, NoLock);
4945 : :
4946 : : /* Phase 2: update system catalogs */
4947 : 20800 : ATRewriteCatalogs(&wqueue, lockmode, context);
4948 : :
4949 : : /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4950 : 18774 : ATRewriteTables(parsetree, &wqueue, lockmode, context);
4951 : 18357 : }
4952 : :
4953 : : /*
4954 : : * ATPrepCmd
4955 : : *
4956 : : * Traffic cop for ALTER TABLE Phase 1 operations, including simple
4957 : : * recursion and permission checks.
4958 : : *
4959 : : * Caller must have acquired appropriate lock type on relation already.
4960 : : * This lock should be held until commit.
4961 : : */
4962 : : static void
4963 : 22263 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4964 : : bool recurse, bool recursing, LOCKMODE lockmode,
4965 : : AlterTableUtilityContext *context)
4966 : : {
4967 : : AlteredTableInfo *tab;
4968 : 22263 : AlterTablePass pass = AT_PASS_UNSET;
4969 : :
4970 : : /* Find or create work queue entry for this table */
4971 : 22263 : tab = ATGetQueueEntry(wqueue, rel);
4972 : :
4973 : : /*
4974 : : * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
4975 : : * partitions that are pending detach.
4976 : : */
4977 [ + + ]: 22263 : if (rel->rd_rel->relispartition &&
4978 [ + - + + ]: 1752 : cmd->subtype != AT_DetachPartitionFinalize &&
4979 : 876 : PartitionHasPendingDetach(RelationGetRelid(rel)))
4980 [ + - ]: 1 : ereport(ERROR,
4981 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4982 : : errmsg("cannot alter partition \"%s\" with an incomplete detach",
4983 : : RelationGetRelationName(rel)),
4984 : : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
4985 : :
4986 : : /*
4987 : : * Copy the original subcommand for each table, so we can scribble on it.
4988 : : * This avoids conflicts when different child tables need to make
4989 : : * different parse transformations (for example, the same column may have
4990 : : * different column numbers in different children).
4991 : : */
4992 : 22262 : cmd = copyObject(cmd);
4993 : :
4994 : : /*
4995 : : * Do permissions and relkind checking, recursion to child tables if
4996 : : * needed, and any additional phase-1 processing needed. (But beware of
4997 : : * adding any processing that looks at table details that another
4998 : : * subcommand could change. In some cases we reject multiple subcommands
4999 : : * that could try to change the same state in contrary ways.)
5000 : : */
5001 [ + + + + : 22262 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + - + -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - ]
5002 : : {
5003 : 1578 : case AT_AddColumn: /* ADD COLUMN */
5004 : 1578 : ATSimplePermissions(cmd->subtype, rel,
5005 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5006 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5007 : 1578 : ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
5008 : : lockmode, context);
5009 : : /* Recursion occurs during execution phase */
5010 : 1570 : pass = AT_PASS_ADD_COL;
5011 : 1570 : break;
5012 : 21 : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5013 : 21 : ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
5014 : 21 : ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
5015 : : lockmode, context);
5016 : : /* Recursion occurs during execution phase */
5017 : 21 : pass = AT_PASS_ADD_COL;
5018 : 21 : break;
5019 : 411 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5020 : :
5021 : : /*
5022 : : * We allow defaults on views so that INSERT into a view can have
5023 : : * default-ish behavior. This works because the rewriter
5024 : : * substitutes default values into INSERTs before it expands
5025 : : * rules.
5026 : : */
5027 : 411 : ATSimplePermissions(cmd->subtype, rel,
5028 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5029 : : ATT_FOREIGN_TABLE);
5030 : 411 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5031 : : /* No command-specific prep needed */
5032 [ + + ]: 411 : pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
5033 : 411 : break;
5034 : 57 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5035 : : /* This is currently used only in CREATE TABLE */
5036 : : /* (so the permission check really isn't necessary) */
5037 : 57 : ATSimplePermissions(cmd->subtype, rel,
5038 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5039 : : /* This command never recurses */
5040 : 57 : pass = AT_PASS_ADD_OTHERCONSTR;
5041 : 57 : break;
5042 : 107 : case AT_AddIdentity:
5043 : 107 : ATSimplePermissions(cmd->subtype, rel,
5044 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5045 : : ATT_FOREIGN_TABLE);
5046 : : /* Set up recursion for phase 2; no other prep needed */
5047 [ + + ]: 107 : if (recurse)
5048 : 103 : cmd->recurse = true;
5049 : 107 : pass = AT_PASS_ADD_OTHERCONSTR;
5050 : 107 : break;
5051 : 41 : case AT_SetIdentity:
5052 : 41 : ATSimplePermissions(cmd->subtype, rel,
5053 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5054 : : ATT_FOREIGN_TABLE);
5055 : : /* Set up recursion for phase 2; no other prep needed */
5056 [ + + ]: 41 : if (recurse)
5057 : 37 : cmd->recurse = true;
5058 : : /* This should run after AddIdentity, so do it in MISC pass */
5059 : 41 : pass = AT_PASS_MISC;
5060 : 41 : break;
5061 : 37 : case AT_DropIdentity:
5062 : 37 : ATSimplePermissions(cmd->subtype, rel,
5063 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5064 : : ATT_FOREIGN_TABLE);
5065 : : /* Set up recursion for phase 2; no other prep needed */
5066 [ + + ]: 37 : if (recurse)
5067 : 33 : cmd->recurse = true;
5068 : 37 : pass = AT_PASS_DROP;
5069 : 37 : break;
5070 : 201 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5071 : 201 : ATSimplePermissions(cmd->subtype, rel,
5072 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5073 : : /* Set up recursion for phase 2; no other prep needed */
5074 [ + + ]: 197 : if (recurse)
5075 : 185 : cmd->recurse = true;
5076 : 197 : pass = AT_PASS_DROP;
5077 : 197 : break;
5078 : 276 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5079 : 276 : ATSimplePermissions(cmd->subtype, rel,
5080 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5081 : : /* Set up recursion for phase 2; no other prep needed */
5082 [ + + ]: 272 : if (recurse)
5083 : 252 : cmd->recurse = true;
5084 : 272 : pass = AT_PASS_COL_ATTRS;
5085 : 272 : break;
5086 : 193 : case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */
5087 : 193 : ATSimplePermissions(cmd->subtype, rel,
5088 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5089 : 193 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5090 : 193 : pass = AT_PASS_SET_EXPRESSION;
5091 : 193 : break;
5092 : 93 : case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
5093 : 93 : ATSimplePermissions(cmd->subtype, rel,
5094 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5095 : 93 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5096 : 93 : ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
5097 : 69 : pass = AT_PASS_DROP;
5098 : 69 : break;
5099 : 113 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5100 : 113 : ATSimplePermissions(cmd->subtype, rel,
5101 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
5102 : : ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
5103 : 113 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5104 : : /* No command-specific prep needed */
5105 : 113 : pass = AT_PASS_MISC;
5106 : 113 : break;
5107 : 29 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5108 : : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5109 : 29 : ATSimplePermissions(cmd->subtype, rel,
5110 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5111 : : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5112 : : /* This command never recurses */
5113 : 21 : pass = AT_PASS_MISC;
5114 : 21 : break;
5115 : 235 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5116 : 235 : ATSimplePermissions(cmd->subtype, rel,
5117 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5118 : : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5119 : 235 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5120 : : /* No command-specific prep needed */
5121 : 235 : pass = AT_PASS_MISC;
5122 : 235 : break;
5123 : 49 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5124 : 49 : ATSimplePermissions(cmd->subtype, rel,
5125 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5126 : : /* This command never recurses */
5127 : : /* No command-specific prep needed */
5128 : 49 : pass = AT_PASS_MISC;
5129 : 49 : break;
5130 : 1106 : case AT_DropColumn: /* DROP COLUMN */
5131 : 1106 : ATSimplePermissions(cmd->subtype, rel,
5132 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5133 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5134 : 1102 : ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
5135 : : lockmode, context);
5136 : : /* Recursion occurs during execution phase */
5137 : 1094 : pass = AT_PASS_DROP;
5138 : 1094 : break;
5139 : 0 : case AT_AddIndex: /* ADD INDEX */
5140 : 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5141 : : /* This command never recurses */
5142 : : /* No command-specific prep needed */
5143 : 0 : pass = AT_PASS_ADD_INDEX;
5144 : 0 : break;
5145 : 9758 : case AT_AddConstraint: /* ADD CONSTRAINT */
5146 : 9758 : ATSimplePermissions(cmd->subtype, rel,
5147 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5148 [ + + ]: 9758 : if (recurse)
5149 : : {
5150 : : /* recurses at exec time; lock descendants and set flag */
5151 : 9542 : (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5152 : 9542 : cmd->recurse = true;
5153 : : }
5154 : 9758 : pass = AT_PASS_ADD_CONSTR;
5155 : 9758 : break;
5156 : 0 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5157 : 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5158 : : /* This command never recurses */
5159 : : /* No command-specific prep needed */
5160 : 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5161 : 0 : break;
5162 : 567 : case AT_DropConstraint: /* DROP CONSTRAINT */
5163 : 567 : ATSimplePermissions(cmd->subtype, rel,
5164 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5165 : 567 : ATCheckPartitionsNotInUse(rel, lockmode);
5166 : : /* Other recursion occurs during execution phase */
5167 : : /* No command-specific prep needed except saving recurse flag */
5168 [ + + ]: 563 : if (recurse)
5169 : 539 : cmd->recurse = true;
5170 : 563 : pass = AT_PASS_DROP;
5171 : 563 : break;
5172 : 963 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5173 : 963 : ATSimplePermissions(cmd->subtype, rel,
5174 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5175 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5176 : : /* See comments for ATPrepAlterColumnType */
5177 : 963 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
5178 : : AT_PASS_UNSET, context);
5179 : : Assert(cmd != NULL);
5180 : : /* Performs own recursion */
5181 : 959 : ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
5182 : : lockmode, context);
5183 : 828 : pass = AT_PASS_ALTER_TYPE;
5184 : 828 : break;
5185 : 94 : case AT_AlterColumnGenericOptions:
5186 : 94 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5187 : : /* This command never recurses */
5188 : : /* No command-specific prep needed */
5189 : 94 : pass = AT_PASS_MISC;
5190 : 94 : break;
5191 : 1132 : case AT_ChangeOwner: /* ALTER OWNER */
5192 : : /* This command never recurses */
5193 : : /* No command-specific prep needed */
5194 : 1132 : pass = AT_PASS_MISC;
5195 : 1132 : break;
5196 : 43 : case AT_ClusterOn: /* CLUSTER ON */
5197 : : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5198 : 43 : ATSimplePermissions(cmd->subtype, rel,
5199 : : ATT_TABLE | ATT_MATVIEW);
5200 : : /* These commands never recurse */
5201 : : /* No command-specific prep needed */
5202 : 35 : pass = AT_PASS_MISC;
5203 : 35 : break;
5204 : 79 : case AT_SetLogged: /* SET LOGGED */
5205 : : case AT_SetUnLogged: /* SET UNLOGGED */
5206 : 79 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
5207 [ - + ]: 71 : if (tab->chgPersistence)
5208 [ # # ]: 0 : ereport(ERROR,
5209 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5210 : : errmsg("cannot change persistence setting twice")));
5211 : 71 : ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
5212 : 59 : pass = AT_PASS_MISC;
5213 : 59 : break;
5214 : 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5215 : 4 : ATSimplePermissions(cmd->subtype, rel,
5216 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5217 : 4 : pass = AT_PASS_DROP;
5218 : 4 : break;
5219 : 85 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5220 : 85 : ATSimplePermissions(cmd->subtype, rel,
5221 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5222 : :
5223 : : /* check if another access method change was already requested */
5224 [ + + ]: 85 : if (tab->chgAccessMethod)
5225 [ + - ]: 12 : ereport(ERROR,
5226 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5227 : : errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
5228 : :
5229 : 73 : ATPrepSetAccessMethod(tab, rel, cmd->name);
5230 : 73 : pass = AT_PASS_MISC; /* does not matter; no work in Phase 2 */
5231 : 73 : break;
5232 : 103 : case AT_SetTableSpace: /* SET TABLESPACE */
5233 : 103 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
5234 : : ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
5235 : : /* This command never recurses */
5236 : 103 : ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
5237 : 103 : pass = AT_PASS_MISC; /* doesn't actually matter */
5238 : 103 : break;
5239 : 676 : case AT_SetRelOptions: /* SET (...) */
5240 : : case AT_ResetRelOptions: /* RESET (...) */
5241 : : case AT_ReplaceRelOptions: /* reset them all, then set just these */
5242 : 676 : ATSimplePermissions(cmd->subtype, rel,
5243 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5244 : : ATT_MATVIEW | ATT_INDEX);
5245 : : /* This command never recurses */
5246 : : /* No command-specific prep needed */
5247 : 675 : pass = AT_PASS_MISC;
5248 : 675 : break;
5249 : 305 : case AT_AddInherit: /* INHERIT */
5250 : 305 : ATSimplePermissions(cmd->subtype, rel,
5251 : : ATT_TABLE | ATT_FOREIGN_TABLE);
5252 : : /* This command never recurses */
5253 : 301 : ATPrepChangeInherit(rel);
5254 : 289 : pass = AT_PASS_MISC;
5255 : 289 : break;
5256 : 73 : case AT_DropInherit: /* NO INHERIT */
5257 : 73 : ATSimplePermissions(cmd->subtype, rel,
5258 : : ATT_TABLE | ATT_FOREIGN_TABLE);
5259 : : /* This command never recurses */
5260 : 69 : ATPrepChangeInherit(rel);
5261 : 61 : pass = AT_PASS_MISC;
5262 : 61 : break;
5263 : 348 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5264 : 348 : ATSimplePermissions(cmd->subtype, rel,
5265 : : ATT_TABLE | ATT_PARTITIONED_TABLE);
5266 : : /* Recursion occurs during execution phase */
5267 [ + + ]: 344 : if (recurse)
5268 : 332 : cmd->recurse = true;
5269 : 344 : pass = AT_PASS_MISC;
5270 : 344 : break;
5271 : 292 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5272 : 292 : ATSimplePermissions(cmd->subtype, rel,
5273 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5274 : : /* Recursion occurs during execution phase */
5275 : : /* No command-specific prep needed except saving recurse flag */
5276 [ + - ]: 292 : if (recurse)
5277 : 292 : cmd->recurse = true;
5278 : 292 : pass = AT_PASS_MISC;
5279 : 292 : break;
5280 : 322 : case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
5281 : 322 : ATSimplePermissions(cmd->subtype, rel,
5282 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5283 : 322 : pass = AT_PASS_MISC;
5284 : : /* This command never recurses */
5285 : : /* No command-specific prep needed */
5286 : 322 : break;
5287 : 191 : case AT_EnableTrig: /* ENABLE TRIGGER variants */
5288 : : case AT_EnableAlwaysTrig:
5289 : : case AT_EnableReplicaTrig:
5290 : : case AT_EnableTrigAll:
5291 : : case AT_EnableTrigUser:
5292 : : case AT_DisableTrig: /* DISABLE TRIGGER variants */
5293 : : case AT_DisableTrigAll:
5294 : : case AT_DisableTrigUser:
5295 : 191 : ATSimplePermissions(cmd->subtype, rel,
5296 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5297 : : /* Set up recursion for phase 2; no other prep needed */
5298 [ + + ]: 191 : if (recurse)
5299 : 174 : cmd->recurse = true;
5300 : 191 : pass = AT_PASS_MISC;
5301 : 191 : break;
5302 : 424 : case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
5303 : : case AT_EnableAlwaysRule:
5304 : : case AT_EnableReplicaRule:
5305 : : case AT_DisableRule:
5306 : : case AT_AddOf: /* OF */
5307 : : case AT_DropOf: /* NOT OF */
5308 : : case AT_EnableRowSecurity:
5309 : : case AT_DisableRowSecurity:
5310 : : case AT_ForceRowSecurity:
5311 : : case AT_NoForceRowSecurity:
5312 : 424 : ATSimplePermissions(cmd->subtype, rel,
5313 : : ATT_TABLE | ATT_PARTITIONED_TABLE);
5314 : : /* These commands never recurse */
5315 : : /* No command-specific prep needed */
5316 : 424 : pass = AT_PASS_MISC;
5317 : 424 : break;
5318 : 34 : case AT_GenericOptions:
5319 : 34 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5320 : : /* No command-specific prep needed */
5321 : 34 : pass = AT_PASS_MISC;
5322 : 34 : break;
5323 : 1837 : case AT_AttachPartition:
5324 : 1837 : ATSimplePermissions(cmd->subtype, rel,
5325 : : ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
5326 : : /* No command-specific prep needed */
5327 : 1833 : pass = AT_PASS_MISC;
5328 : 1833 : break;
5329 : 374 : case AT_DetachPartition:
5330 : 374 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5331 : : /* No command-specific prep needed */
5332 : 362 : pass = AT_PASS_MISC;
5333 : 362 : break;
5334 : 11 : case AT_DetachPartitionFinalize:
5335 : 11 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5336 : : /* No command-specific prep needed */
5337 : 7 : pass = AT_PASS_MISC;
5338 : 7 : break;
5339 : 0 : default: /* oops */
5340 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
5341 : : (int) cmd->subtype);
5342 : : pass = AT_PASS_UNSET; /* keep compiler quiet */
5343 : : break;
5344 : : }
5345 : : Assert(pass > AT_PASS_UNSET);
5346 : :
5347 : : /* Add the subcommand to the appropriate list for phase 2 */
5348 : 21970 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
5349 : 21970 : }
5350 : :
5351 : : /*
5352 : : * ATRewriteCatalogs
5353 : : *
5354 : : * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
5355 : : * dispatched in a "safe" execution order (designed to avoid unnecessary
5356 : : * conflicts).
5357 : : */
5358 : : static void
5359 : 20800 : ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
5360 : : AlterTableUtilityContext *context)
5361 : : {
5362 : : ListCell *ltab;
5363 : :
5364 : : /*
5365 : : * We process all the tables "in parallel", one pass at a time. This is
5366 : : * needed because we may have to propagate work from one table to another
5367 : : * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
5368 : : * re-adding of the foreign key constraint to the other table). Work can
5369 : : * only be propagated into later passes, however.
5370 : : */
5371 [ + + ]: 261107 : for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
5372 : : {
5373 : : /* Go through each table that needs to be processed */
5374 [ + - + + : 494031 : foreach(ltab, *wqueue)
+ + ]
5375 : : {
5376 : 253724 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5377 : 253724 : List *subcmds = tab->subcmds[pass];
5378 : : ListCell *lcmd;
5379 : :
5380 [ + + ]: 253724 : if (subcmds == NIL)
5381 : 218092 : continue;
5382 : :
5383 : : /*
5384 : : * Open the relation and store it in tab. This allows subroutines
5385 : : * close and reopen, if necessary. Appropriate lock was obtained
5386 : : * by phase 1, needn't get it again.
5387 : : */
5388 : 35632 : tab->rel = relation_open(tab->relid, NoLock);
5389 : :
5390 [ + - + + : 71330 : foreach(lcmd, subcmds)
+ + ]
5391 : 37704 : ATExecCmd(wqueue, tab,
5392 : 37704 : lfirst_node(AlterTableCmd, lcmd),
5393 : : lockmode, pass, context);
5394 : :
5395 : : /*
5396 : : * For ADD PRIMARY KEY without USING INDEX, queue any required NOT
5397 : : * NULL constraints after transforming all explicit constraints.
5398 : : * This lets a named NOT NULL constraint take precedence
5399 : : * regardless of subcommand order. USING INDEX is handled during
5400 : : * transformation.
5401 : : */
5402 [ + + ]: 33626 : if (pass == AT_PASS_ADD_CONSTR)
5403 : : {
5404 [ + - + + : 28944 : foreach_node(AlterTableCmd, cmd, subcmds)
+ + ]
5405 : 9738 : ATPrepAddPrimaryKey(tab, tab->rel, cmd, lockmode);
5406 : : }
5407 : :
5408 : : /*
5409 : : * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
5410 : : * (this is not done in ATExecAlterColumnType since it should be
5411 : : * done only once if multiple columns of a table are altered).
5412 : : */
5413 [ + + + + ]: 33606 : if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
5414 : 925 : ATPostAlterTypeCleanup(wqueue, tab, lockmode);
5415 : :
5416 [ + - ]: 33606 : if (tab->rel)
5417 : : {
5418 : 33606 : relation_close(tab->rel, NoLock);
5419 : 33606 : tab->rel = NULL;
5420 : : }
5421 : : }
5422 : : }
5423 : :
5424 : : /* Check to see if a toast table must be added. */
5425 [ + - + + : 40454 : foreach(ltab, *wqueue)
+ + ]
5426 : : {
5427 : 21680 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5428 : :
5429 : : /*
5430 : : * If the table is source table of ATTACH PARTITION command, we did
5431 : : * not modify anything about it that will change its toasting
5432 : : * requirement, so no need to check.
5433 : : */
5434 [ + + ]: 21680 : if (((tab->relkind == RELKIND_RELATION ||
5435 [ + + ]: 4011 : tab->relkind == RELKIND_PARTITIONED_TABLE) &&
5436 [ + + ]: 20438 : tab->partition_constraint == NULL) ||
5437 [ + + ]: 2566 : tab->relkind == RELKIND_MATVIEW)
5438 : 19143 : AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
5439 : : }
5440 : 18774 : }
5441 : :
5442 : : /*
5443 : : * ATExecCmd: dispatch a subcommand to appropriate execution routine
5444 : : */
5445 : : static void
5446 : 37704 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
5447 : : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
5448 : : AlterTableUtilityContext *context)
5449 : : {
5450 : 37704 : ObjectAddress address = InvalidObjectAddress;
5451 : 37704 : Relation rel = tab->rel;
5452 : :
5453 [ + + + + : 37704 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + - + -
+ + - + +
+ + + + +
+ + + + +
+ + + - ]
5454 : : {
5455 : 1587 : case AT_AddColumn: /* ADD COLUMN */
5456 : : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5457 : 1587 : address = ATExecAddColumn(wqueue, tab, rel, &cmd,
5458 : 1587 : cmd->recurse, false,
5459 : : lockmode, cur_pass, context);
5460 : 1419 : break;
5461 : 387 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5462 : 387 : address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
5463 : 339 : break;
5464 : 57 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5465 : 57 : address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
5466 : 53 : break;
5467 : 107 : case AT_AddIdentity:
5468 : 107 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5469 : : cur_pass, context);
5470 : : Assert(cmd != NULL);
5471 : 99 : address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5472 : 63 : break;
5473 : 41 : case AT_SetIdentity:
5474 : 41 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5475 : : cur_pass, context);
5476 : : Assert(cmd != NULL);
5477 : 41 : address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5478 : 25 : break;
5479 : 37 : case AT_DropIdentity:
5480 : 37 : address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
5481 : 25 : break;
5482 : 197 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5483 : 197 : address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
5484 : 129 : break;
5485 : 272 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5486 : 272 : address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
5487 : 272 : cmd->recurse, false, lockmode);
5488 : 252 : break;
5489 : 193 : case AT_SetExpression:
5490 : 193 : address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
5491 : 181 : break;
5492 : 61 : case AT_DropExpression:
5493 : 61 : address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
5494 : 45 : break;
5495 : 113 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5496 : 113 : address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
5497 : 81 : break;
5498 : 17 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5499 : 17 : address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
5500 : 17 : break;
5501 : 4 : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5502 : 4 : address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
5503 : 4 : break;
5504 : 235 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5505 : 235 : address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
5506 : 227 : break;
5507 : 49 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5508 : 49 : address = ATExecSetCompression(rel, cmd->name, cmd->def,
5509 : : lockmode);
5510 : 45 : break;
5511 : 1094 : case AT_DropColumn: /* DROP COLUMN */
5512 : 1094 : address = ATExecDropColumn(wqueue, rel, cmd->name,
5513 : 1094 : cmd->behavior, cmd->recurse, false,
5514 : 1094 : cmd->missing_ok, lockmode,
5515 : : NULL);
5516 : 974 : break;
5517 : 795 : case AT_AddIndex: /* ADD INDEX */
5518 : 795 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
5519 : : lockmode);
5520 : 682 : break;
5521 : 330 : case AT_ReAddIndex: /* ADD INDEX */
5522 : 330 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
5523 : : lockmode);
5524 : 330 : break;
5525 : 57 : case AT_ReAddStatistics: /* ADD STATISTICS */
5526 : 57 : address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
5527 : : true, lockmode);
5528 : 57 : break;
5529 : 17701 : case AT_AddConstraint: /* ADD CONSTRAINT */
5530 : : /* Transform the command only during initial examination */
5531 [ + + ]: 17701 : if (cur_pass == AT_PASS_ADD_CONSTR)
5532 : 9738 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
5533 : 9758 : cmd->recurse, lockmode,
5534 : : cur_pass, context);
5535 : : /* Depending on constraint type, might be no more work to do now */
5536 [ + + ]: 17681 : if (cmd != NULL)
5537 : : address =
5538 : 7943 : ATExecAddConstraint(wqueue, tab, rel,
5539 : 7943 : (Constraint *) cmd->def,
5540 : 7943 : cmd->recurse, false, lockmode);
5541 : 17220 : break;
5542 : 269 : case AT_ReAddConstraint: /* Re-add pre-existing check constraint */
5543 : : address =
5544 : 269 : ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
5545 : : true, true, lockmode);
5546 : 261 : break;
5547 : 13 : case AT_ReAddDomainConstraint: /* Re-add pre-existing domain check
5548 : : * constraint */
5549 : : address =
5550 : 13 : AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
5551 : 13 : ((AlterDomainStmt *) cmd->def)->def,
5552 : : NULL, true);
5553 : 9 : break;
5554 : 52 : case AT_ReAddComment: /* Re-add existing comment */
5555 : 52 : address = CommentObject((CommentStmt *) cmd->def);
5556 : 52 : break;
5557 : 6323 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5558 : 6323 : address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
5559 : : lockmode);
5560 : 6315 : break;
5561 : 344 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5562 : 344 : address = ATExecAlterConstraint(wqueue, rel,
5563 : 344 : castNode(ATAlterConstraint, cmd->def),
5564 : 344 : cmd->recurse, lockmode);
5565 : 260 : break;
5566 : 292 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5567 : 292 : address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
5568 : : false, lockmode);
5569 : 288 : break;
5570 : 563 : case AT_DropConstraint: /* DROP CONSTRAINT */
5571 : 563 : ATExecDropConstraint(rel, cmd->name, cmd->behavior,
5572 : 563 : cmd->recurse,
5573 : 563 : cmd->missing_ok, lockmode);
5574 : 423 : break;
5575 : 804 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5576 : : /* parse transformation was done earlier */
5577 : 804 : address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
5578 : 776 : break;
5579 : 94 : case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
5580 : : address =
5581 : 94 : ATExecAlterColumnGenericOptions(rel, cmd->name,
5582 : 94 : (List *) cmd->def, lockmode);
5583 : 90 : break;
5584 : 1132 : case AT_ChangeOwner: /* ALTER OWNER */
5585 : 1129 : ATExecChangeOwner(RelationGetRelid(rel),
5586 : 1132 : get_rolespec_oid(cmd->newowner, false),
5587 : : false, lockmode);
5588 : 1121 : break;
5589 : 39 : case AT_ClusterOn: /* CLUSTER ON */
5590 : 39 : address = ATExecClusterOn(rel, cmd->name, lockmode);
5591 : 39 : break;
5592 : 8 : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5593 : 8 : ATExecDropCluster(rel, lockmode);
5594 : 8 : break;
5595 : 59 : case AT_SetLogged: /* SET LOGGED */
5596 : : case AT_SetUnLogged: /* SET UNLOGGED */
5597 : 59 : break;
5598 : 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5599 : : /* nothing to do here, oid columns don't exist anymore */
5600 : 4 : break;
5601 : 61 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5602 : :
5603 : : /*
5604 : : * Only do this for partitioned tables, for which this is just a
5605 : : * catalog change. Tables with storage are handled by Phase 3.
5606 : : */
5607 [ + + ]: 61 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
5608 [ + + ]: 33 : tab->chgAccessMethod)
5609 : 29 : ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
5610 : 61 : break;
5611 : 103 : case AT_SetTableSpace: /* SET TABLESPACE */
5612 : :
5613 : : /*
5614 : : * Only do this for partitioned tables and indexes, for which this
5615 : : * is just a catalog change. Other relation types which have
5616 : : * storage are handled by Phase 3.
5617 : : */
5618 [ + + ]: 103 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
5619 [ + + ]: 95 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
5620 : 24 : ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
5621 : :
5622 : 99 : break;
5623 : 675 : case AT_SetRelOptions: /* SET (...) */
5624 : : case AT_ResetRelOptions: /* RESET (...) */
5625 : : case AT_ReplaceRelOptions: /* replace entire option list */
5626 : 675 : ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
5627 : 641 : break;
5628 : 65 : case AT_EnableTrig: /* ENABLE TRIGGER name */
5629 : 65 : ATExecEnableDisableTrigger(rel, cmd->name,
5630 : : TRIGGER_FIRES_ON_ORIGIN, false,
5631 : 65 : cmd->recurse,
5632 : : lockmode);
5633 : 65 : break;
5634 : 27 : case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
5635 : 27 : ATExecEnableDisableTrigger(rel, cmd->name,
5636 : : TRIGGER_FIRES_ALWAYS, false,
5637 : 27 : cmd->recurse,
5638 : : lockmode);
5639 : 27 : break;
5640 : 8 : case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
5641 : 8 : ATExecEnableDisableTrigger(rel, cmd->name,
5642 : : TRIGGER_FIRES_ON_REPLICA, false,
5643 : 8 : cmd->recurse,
5644 : : lockmode);
5645 : 8 : break;
5646 : 75 : case AT_DisableTrig: /* DISABLE TRIGGER name */
5647 : 75 : ATExecEnableDisableTrigger(rel, cmd->name,
5648 : : TRIGGER_DISABLED, false,
5649 : 75 : cmd->recurse,
5650 : : lockmode);
5651 : 75 : break;
5652 : 0 : case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
5653 : 0 : ATExecEnableDisableTrigger(rel, NULL,
5654 : : TRIGGER_FIRES_ON_ORIGIN, false,
5655 : 0 : cmd->recurse,
5656 : : lockmode);
5657 : 0 : break;
5658 : 8 : case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
5659 : 8 : ATExecEnableDisableTrigger(rel, NULL,
5660 : : TRIGGER_DISABLED, false,
5661 : 8 : cmd->recurse,
5662 : : lockmode);
5663 : 8 : break;
5664 : 0 : case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
5665 : 0 : ATExecEnableDisableTrigger(rel, NULL,
5666 : : TRIGGER_FIRES_ON_ORIGIN, true,
5667 : 0 : cmd->recurse,
5668 : : lockmode);
5669 : 0 : break;
5670 : 8 : case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
5671 : 8 : ATExecEnableDisableTrigger(rel, NULL,
5672 : : TRIGGER_DISABLED, true,
5673 : 8 : cmd->recurse,
5674 : : lockmode);
5675 : 8 : break;
5676 : :
5677 : 5 : case AT_EnableRule: /* ENABLE RULE name */
5678 : 5 : ATExecEnableDisableRule(rel, cmd->name,
5679 : : RULE_FIRES_ON_ORIGIN, lockmode);
5680 : 5 : break;
5681 : 0 : case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
5682 : 0 : ATExecEnableDisableRule(rel, cmd->name,
5683 : : RULE_FIRES_ALWAYS, lockmode);
5684 : 0 : break;
5685 : 4 : case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
5686 : 4 : ATExecEnableDisableRule(rel, cmd->name,
5687 : : RULE_FIRES_ON_REPLICA, lockmode);
5688 : 4 : break;
5689 : 20 : case AT_DisableRule: /* DISABLE RULE name */
5690 : 20 : ATExecEnableDisableRule(rel, cmd->name,
5691 : : RULE_DISABLED, lockmode);
5692 : 20 : break;
5693 : :
5694 : 289 : case AT_AddInherit:
5695 : 289 : address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
5696 : 209 : break;
5697 : 61 : case AT_DropInherit:
5698 : 61 : address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
5699 : 57 : break;
5700 : 50 : case AT_AddOf:
5701 : 50 : address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
5702 : 22 : break;
5703 : 4 : case AT_DropOf:
5704 : 4 : ATExecDropOf(rel, lockmode);
5705 : 4 : break;
5706 : 334 : case AT_ReplicaIdentity:
5707 : 334 : ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
5708 : 298 : break;
5709 : 250 : case AT_EnableRowSecurity:
5710 : 250 : ATExecSetRowSecurity(rel, true);
5711 : 250 : break;
5712 : 6 : case AT_DisableRowSecurity:
5713 : 6 : ATExecSetRowSecurity(rel, false);
5714 : 6 : break;
5715 : 65 : case AT_ForceRowSecurity:
5716 : 65 : ATExecForceNoForceRowSecurity(rel, true);
5717 : 65 : break;
5718 : 20 : case AT_NoForceRowSecurity:
5719 : 20 : ATExecForceNoForceRowSecurity(rel, false);
5720 : 20 : break;
5721 : 34 : case AT_GenericOptions:
5722 : 34 : ATExecGenericOptions(rel, (List *) cmd->def);
5723 : 33 : break;
5724 : 1833 : case AT_AttachPartition:
5725 : 1833 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5726 : : cur_pass, context);
5727 : : Assert(cmd != NULL);
5728 [ + + ]: 1817 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5729 : 1537 : address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
5730 : : context);
5731 : : else
5732 : 280 : address = ATExecAttachPartitionIdx(wqueue, rel,
5733 : 280 : ((PartitionCmd *) cmd->def)->name);
5734 : 1549 : break;
5735 : 362 : case AT_DetachPartition:
5736 : 362 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5737 : : cur_pass, context);
5738 : : Assert(cmd != NULL);
5739 : : /* ATPrepCmd ensures it must be a table */
5740 : : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5741 : 362 : address = ATExecDetachPartition(wqueue, tab, rel,
5742 : 362 : ((PartitionCmd *) cmd->def)->name,
5743 : 362 : ((PartitionCmd *) cmd->def)->concurrent);
5744 : 284 : break;
5745 : 7 : case AT_DetachPartitionFinalize:
5746 : 7 : address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
5747 : 7 : break;
5748 : 0 : default: /* oops */
5749 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
5750 : : (int) cmd->subtype);
5751 : : break;
5752 : : }
5753 : :
5754 : : /*
5755 : : * Report the subcommand to interested event triggers.
5756 : : */
5757 [ + + ]: 35698 : if (cmd)
5758 : 25960 : EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
5759 : :
5760 : : /*
5761 : : * Bump the command counter to ensure the next subcommand in the sequence
5762 : : * can see the changes so far
5763 : : */
5764 : 35698 : CommandCounterIncrement();
5765 : 35698 : }
5766 : :
5767 : : /*
5768 : : * ATParseTransformCmd: perform parse transformation for one subcommand
5769 : : *
5770 : : * Returns the transformed subcommand tree, if there is one, else NULL.
5771 : : *
5772 : : * The parser may hand back additional AlterTableCmd(s) and/or other
5773 : : * utility statements, either before or after the original subcommand.
5774 : : * Other AlterTableCmds are scheduled into the appropriate slot of the
5775 : : * AlteredTableInfo (they had better be for later passes than the current one).
5776 : : * Utility statements that are supposed to happen before the AlterTableCmd
5777 : : * are executed immediately. Those that are supposed to happen afterwards
5778 : : * are added to the tab->afterStmts list to be done at the very end.
5779 : : */
5780 : : static AlterTableCmd *
5781 : 14558 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
5782 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
5783 : : AlterTablePass cur_pass, AlterTableUtilityContext *context)
5784 : : {
5785 : 14558 : AlterTableCmd *newcmd = NULL;
5786 : 14558 : AlterTableStmt *atstmt = makeNode(AlterTableStmt);
5787 : : List *beforeStmts;
5788 : : List *afterStmts;
5789 : : ListCell *lc;
5790 : :
5791 : : /* Gin up an AlterTableStmt with just this subcommand and this table */
5792 : 14558 : atstmt->relation =
5793 : 14558 : makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5794 : 14558 : pstrdup(RelationGetRelationName(rel)),
5795 : : -1);
5796 : 14558 : atstmt->relation->inh = recurse;
5797 : 14558 : atstmt->cmds = list_make1(cmd);
5798 : 14558 : atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
5799 : 14558 : atstmt->missing_ok = false;
5800 : :
5801 : : /* Transform the AlterTableStmt */
5802 : 14558 : atstmt = transformAlterTableStmt(RelationGetRelid(rel),
5803 : : atstmt,
5804 : : context->queryString,
5805 : : &beforeStmts,
5806 : : &afterStmts);
5807 : :
5808 : : /* Execute any statements that should happen before these subcommand(s) */
5809 [ + + + + : 14821 : foreach(lc, beforeStmts)
+ + ]
5810 : : {
5811 : 315 : Node *stmt = (Node *) lfirst(lc);
5812 : :
5813 : 315 : ProcessUtilityForAlterTable(stmt, context);
5814 : 307 : CommandCounterIncrement();
5815 : : }
5816 : :
5817 : : /* Examine the transformed subcommands and schedule them appropriately */
5818 [ + - + + : 34039 : foreach(lc, atstmt->cmds)
+ + ]
5819 : : {
5820 : 19533 : AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
5821 : : AlterTablePass pass;
5822 : :
5823 : : /*
5824 : : * This switch need only cover the subcommand types that can be added
5825 : : * by parse_utilcmd.c; otherwise, we'll use the default strategy of
5826 : : * executing the subcommand immediately, as a substitute for the
5827 : : * original subcommand. (Note, however, that this does cause
5828 : : * AT_AddConstraint subcommands to be rescheduled into later passes,
5829 : : * which is important for index and foreign key constraints.)
5830 : : *
5831 : : * We assume we needn't do any phase-1 checks for added subcommands.
5832 : : */
5833 [ + + + - : 19533 : switch (cmd2->subtype)
+ ]
5834 : : {
5835 : 831 : case AT_AddIndex:
5836 : 831 : pass = AT_PASS_ADD_INDEX;
5837 : 831 : break;
5838 : 6323 : case AT_AddIndexConstraint:
5839 : 6323 : pass = AT_PASS_ADD_INDEXCONSTR;
5840 : 6323 : break;
5841 : 7611 : case AT_AddConstraint:
5842 : : /* Recursion occurs during execution phase */
5843 [ + + ]: 7611 : if (recurse)
5844 : 7584 : cmd2->recurse = true;
5845 [ + - + ]: 7611 : switch (castNode(Constraint, cmd2->def)->contype)
5846 : : {
5847 : 5143 : case CONSTR_NOTNULL:
5848 : 5143 : pass = AT_PASS_COL_ATTRS;
5849 : 5143 : break;
5850 : 0 : case CONSTR_PRIMARY:
5851 : : case CONSTR_UNIQUE:
5852 : : case CONSTR_EXCLUSION:
5853 : 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5854 : 0 : break;
5855 : 2468 : default:
5856 : 2468 : pass = AT_PASS_ADD_OTHERCONSTR;
5857 : 2468 : break;
5858 : : }
5859 : 7611 : break;
5860 : 0 : case AT_AlterColumnGenericOptions:
5861 : : /* This command never recurses */
5862 : : /* No command-specific prep needed */
5863 : 0 : pass = AT_PASS_MISC;
5864 : 0 : break;
5865 : 4768 : default:
5866 : 4768 : pass = cur_pass;
5867 : 4768 : break;
5868 : : }
5869 : :
5870 [ - + ]: 19533 : if (pass < cur_pass)
5871 : : {
5872 : : /* Cannot schedule into a pass we already finished */
5873 [ # # ]: 0 : elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
5874 : : pass);
5875 : : }
5876 [ + + ]: 19533 : else if (pass > cur_pass)
5877 : : {
5878 : : /* OK, queue it up for later */
5879 : 14765 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
5880 : : }
5881 : : else
5882 : : {
5883 : : /*
5884 : : * We should see at most one subcommand for the current pass,
5885 : : * which is the transformed version of the original subcommand.
5886 : : */
5887 [ + - + - ]: 4768 : if (newcmd == NULL && cmd->subtype == cmd2->subtype)
5888 : : {
5889 : : /* Found the transformed version of our subcommand */
5890 : 4768 : newcmd = cmd2;
5891 : : }
5892 : : else
5893 [ # # ]: 0 : elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
5894 : : pass);
5895 : : }
5896 : : }
5897 : :
5898 : : /* Queue up any after-statements to happen at the end */
5899 : 14506 : tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
5900 : :
5901 : 14506 : return newcmd;
5902 : : }
5903 : :
5904 : : /*
5905 : : * ATRewriteTables: ALTER TABLE phase 3
5906 : : */
5907 : : static void
5908 : 18774 : ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
5909 : : AlterTableUtilityContext *context)
5910 : : {
5911 : : ListCell *ltab;
5912 : :
5913 : : /* Go through each table that needs to be checked or rewritten */
5914 [ + - + + : 40040 : foreach(ltab, *wqueue)
+ + ]
5915 : : {
5916 : 21596 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5917 : :
5918 : : /* Relations without storage may be ignored here */
5919 [ + + + + : 21596 : if (!RELKIND_HAS_STORAGE(tab->relkind))
+ + + - +
+ ]
5920 : 3827 : continue;
5921 : :
5922 : : /*
5923 : : * If we change column data types, the operation has to be propagated
5924 : : * to tables that use this table's rowtype as a column type.
5925 : : * tab->newvals will also be non-NULL in the case where we're adding a
5926 : : * column with a default. We choose to forbid that case as well,
5927 : : * since composite types might eventually support defaults.
5928 : : *
5929 : : * (Eventually we'll probably need to check for composite type
5930 : : * dependencies even when we're just scanning the table without a
5931 : : * rewrite, but at the moment a composite type does not enforce any
5932 : : * constraints, so it's not necessary/appropriate to enforce them just
5933 : : * during ALTER.)
5934 : : */
5935 [ + + + + : 17769 : if (tab->newvals != NIL || (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE))
+ + ]
5936 : : {
5937 : : Relation rel;
5938 : :
5939 : 1310 : rel = table_open(tab->relid, NoLock);
5940 : 1310 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
5941 : 1274 : table_close(rel, NoLock);
5942 : : }
5943 : :
5944 : : /*
5945 : : * We only need to rewrite the table if at least one column needs to
5946 : : * be recomputed, or we are changing its persistence or access method.
5947 : : *
5948 : : * There are two reasons for requiring a rewrite when changing
5949 : : * persistence: on one hand, we need to ensure that the buffers
5950 : : * belonging to each of the two relations are marked with or without
5951 : : * BM_PERMANENT properly. On the other hand, since rewriting creates
5952 : : * and assigns a new relfilenumber, we automatically create or drop an
5953 : : * init fork for the relation as appropriate.
5954 : : */
5955 [ + + + + ]: 17733 : if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
5956 : 724 : {
5957 : : /* Build a temporary relation and copy data */
5958 : : Relation OldHeap;
5959 : : Oid OIDNewHeap;
5960 : : Oid NewAccessMethod;
5961 : : Oid NewTableSpace;
5962 : : char persistence;
5963 : :
5964 : 785 : OldHeap = table_open(tab->relid, NoLock);
5965 : :
5966 : : /*
5967 : : * We don't support rewriting of system catalogs; there are too
5968 : : * many corner cases and too little benefit. In particular this
5969 : : * is certainly not going to work for mapped catalogs.
5970 : : */
5971 [ - + ]: 785 : if (IsSystemRelation(OldHeap))
5972 [ # # ]: 0 : ereport(ERROR,
5973 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5974 : : errmsg("cannot rewrite system relation \"%s\"",
5975 : : RelationGetRelationName(OldHeap))));
5976 : :
5977 [ + + - + : 785 : if (RelationIsUsedAsCatalogTable(OldHeap))
- - + + ]
5978 [ + - ]: 1 : ereport(ERROR,
5979 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5980 : : errmsg("cannot rewrite table \"%s\" used as a catalog table",
5981 : : RelationGetRelationName(OldHeap))));
5982 : :
5983 : : /*
5984 : : * Don't allow rewrite on temp tables of other backends ... their
5985 : : * local buffer manager is not going to cope. (This is redundant
5986 : : * with the check in CheckAlterTableIsSafe, but for safety we'll
5987 : : * check here too.)
5988 : : */
5989 [ + + - + ]: 784 : if (RELATION_IS_OTHER_TEMP(OldHeap))
5990 [ # # ]: 0 : ereport(ERROR,
5991 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5992 : : errmsg("cannot rewrite temporary tables of other sessions")));
5993 : :
5994 : : /*
5995 : : * Select destination tablespace (same as original unless user
5996 : : * requested a change)
5997 : : */
5998 [ - + ]: 784 : if (tab->newTableSpace)
5999 : 0 : NewTableSpace = tab->newTableSpace;
6000 : : else
6001 : 784 : NewTableSpace = OldHeap->rd_rel->reltablespace;
6002 : :
6003 : : /*
6004 : : * Select destination access method (same as original unless user
6005 : : * requested a change)
6006 : : */
6007 [ + + ]: 784 : if (tab->chgAccessMethod)
6008 : 24 : NewAccessMethod = tab->newAccessMethod;
6009 : : else
6010 : 760 : NewAccessMethod = OldHeap->rd_rel->relam;
6011 : :
6012 : : /*
6013 : : * Select persistence of transient table (same as original unless
6014 : : * user requested a change)
6015 : : */
6016 [ + + ]: 784 : persistence = tab->chgPersistence ?
6017 : 749 : tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
6018 : :
6019 : 784 : table_close(OldHeap, NoLock);
6020 : :
6021 : : /*
6022 : : * Fire off an Event Trigger now, before actually rewriting the
6023 : : * table.
6024 : : *
6025 : : * We don't support Event Trigger for nested commands anywhere,
6026 : : * here included, and parsetree is given NULL when coming from
6027 : : * AlterTableInternal.
6028 : : *
6029 : : * And fire it only once.
6030 : : */
6031 [ + - ]: 784 : if (parsetree)
6032 : 784 : EventTriggerTableRewrite((Node *) parsetree,
6033 : : tab->relid,
6034 : : tab->rewrite);
6035 : :
6036 : : /*
6037 : : * Create transient table that will receive the modified data.
6038 : : *
6039 : : * Ensure it is marked correctly as logged or unlogged. We have
6040 : : * to do this here so that buffers for the new relfilenumber will
6041 : : * have the right persistence set, and at the same time ensure
6042 : : * that the original filenumbers's buffers will get read in with
6043 : : * the correct setting (i.e. the original one). Otherwise a
6044 : : * rollback after the rewrite would possibly result with buffers
6045 : : * for the original filenumbers having the wrong persistence
6046 : : * setting.
6047 : : *
6048 : : * NB: This relies on swap_relation_files() also swapping the
6049 : : * persistence. That wouldn't work for pg_class, but that can't be
6050 : : * unlogged anyway.
6051 : : */
6052 : 780 : OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
6053 : : persistence, lockmode);
6054 : :
6055 : : /*
6056 : : * Copy the heap data into the new table with the desired
6057 : : * modifications, and test the current data within the table
6058 : : * against new constraints generated by ALTER TABLE commands.
6059 : : */
6060 : 780 : ATRewriteTable(tab, OIDNewHeap);
6061 : :
6062 : : /*
6063 : : * Swap the physical files of the old and new heaps, then rebuild
6064 : : * indexes and discard the old heap. We can use RecentXmin for
6065 : : * the table's new relfrozenxid because we rewrote all the tuples
6066 : : * in ATRewriteTable, so no older Xid remains in the table. Also,
6067 : : * we never try to swap toast tables by content, since we have no
6068 : : * interest in letting this code work on system catalogs.
6069 : : */
6070 : 728 : finish_heap_swap(tab->relid, OIDNewHeap,
6071 : : false, false, true,
6072 : 728 : !OidIsValid(tab->newTableSpace),
6073 : : true, /* reindex */
6074 : : RecentXmin,
6075 : : ReadNextMultiXactId(),
6076 : : persistence);
6077 : :
6078 [ - + ]: 724 : InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
6079 : : }
6080 [ + + + - ]: 16948 : else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
6081 : : {
6082 [ + - ]: 16 : if (tab->chgPersistence)
6083 : 16 : SequenceChangePersistence(tab->relid, tab->newrelpersistence);
6084 : : }
6085 : : else
6086 : : {
6087 : : /*
6088 : : * If required, test the current data within the table against new
6089 : : * constraints generated by ALTER TABLE commands, but don't
6090 : : * rebuild data.
6091 : : */
6092 [ + + + + ]: 16932 : if (tab->constraints != NIL || tab->verify_new_notnull ||
6093 [ + + ]: 14767 : tab->partition_constraint != NULL)
6094 : 3391 : ATRewriteTable(tab, InvalidOid);
6095 : :
6096 : : /*
6097 : : * If we had SET TABLESPACE but no reason to reconstruct tuples,
6098 : : * just do a block-by-block copy.
6099 : : */
6100 [ + + ]: 16699 : if (tab->newTableSpace)
6101 : 79 : ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
6102 : : }
6103 : :
6104 : : /*
6105 : : * Also change persistence of owned sequences, so that it matches the
6106 : : * table persistence.
6107 : : */
6108 [ + + ]: 17439 : if (tab->chgPersistence)
6109 : : {
6110 : 51 : List *seqlist = getOwnedSequences(tab->relid);
6111 : : ListCell *lc;
6112 : :
6113 [ + + + + : 83 : foreach(lc, seqlist)
+ + ]
6114 : : {
6115 : 32 : Oid seq_relid = lfirst_oid(lc);
6116 : :
6117 : 32 : SequenceChangePersistence(seq_relid, tab->newrelpersistence);
6118 : : }
6119 : : }
6120 : : }
6121 : :
6122 : : /*
6123 : : * Foreign key constraints are checked in a final pass, since (a) it's
6124 : : * generally best to examine each one separately, and (b) it's at least
6125 : : * theoretically possible that we have changed both relations of the
6126 : : * foreign key, and we'd better have finished both rewrites before we try
6127 : : * to read the tables.
6128 : : */
6129 [ + - + + : 39445 : foreach(ltab, *wqueue)
+ + ]
6130 : : {
6131 : 21088 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6132 : 21088 : Relation rel = NULL;
6133 : : ListCell *lcon;
6134 : :
6135 : : /* Relations without storage may be ignored here too */
6136 [ + + + + : 21088 : if (!RELKIND_HAS_STORAGE(tab->relkind))
+ + + - +
+ ]
6137 : 3722 : continue;
6138 : :
6139 [ + + + + : 18688 : foreach(lcon, tab->constraints)
+ + ]
6140 : : {
6141 : 1409 : NewConstraint *con = lfirst(lcon);
6142 : :
6143 [ + + ]: 1409 : if (con->contype == CONSTR_FOREIGN)
6144 : : {
6145 : 839 : Constraint *fkconstraint = (Constraint *) con->qual;
6146 : : Relation refrel;
6147 : :
6148 [ + + ]: 839 : if (rel == NULL)
6149 : : {
6150 : : /* Long since locked, no need for another */
6151 : 831 : rel = table_open(tab->relid, NoLock);
6152 : : }
6153 : :
6154 : 839 : refrel = table_open(con->refrelid, RowShareLock);
6155 : :
6156 : 839 : validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
6157 : : con->refindid,
6158 : : con->conid,
6159 : 839 : con->conwithperiod);
6160 : :
6161 : : /*
6162 : : * No need to mark the constraint row as validated, we did
6163 : : * that when we inserted the row earlier.
6164 : : */
6165 : :
6166 : 752 : table_close(refrel, NoLock);
6167 : : }
6168 : : }
6169 : :
6170 [ + + ]: 17279 : if (rel)
6171 : 744 : table_close(rel, NoLock);
6172 : : }
6173 : :
6174 : : /* Finally, run any afterStmts that were queued up */
6175 [ + - + + : 39331 : foreach(ltab, *wqueue)
+ + ]
6176 : : {
6177 : 20974 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6178 : : ListCell *lc;
6179 : :
6180 [ + + + + : 21030 : foreach(lc, tab->afterStmts)
+ + ]
6181 : : {
6182 : 56 : Node *stmt = (Node *) lfirst(lc);
6183 : :
6184 : 56 : ProcessUtilityForAlterTable(stmt, context);
6185 : 56 : CommandCounterIncrement();
6186 : : }
6187 : : }
6188 : 18357 : }
6189 : :
6190 : : /*
6191 : : * ATRewriteTable: scan or rewrite one table
6192 : : *
6193 : : * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
6194 : : * must already hold AccessExclusiveLock on it.
6195 : : */
6196 : : static void
6197 : 4171 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
6198 : : {
6199 : : Relation oldrel;
6200 : : Relation newrel;
6201 : : TupleDesc oldTupDesc;
6202 : : TupleDesc newTupDesc;
6203 : 4171 : bool needscan = false;
6204 : : List *notnull_attrs;
6205 : : List *notnull_virtual_attrs;
6206 : : int i;
6207 : : ListCell *l;
6208 : : EState *estate;
6209 : : CommandId mycid;
6210 : : BulkInsertState bistate;
6211 : : uint32 ti_options;
6212 : 4171 : ExprState *partqualstate = NULL;
6213 : :
6214 : : /*
6215 : : * Open the relation(s). We have surely already locked the existing
6216 : : * table.
6217 : : */
6218 : 4171 : oldrel = table_open(tab->relid, NoLock);
6219 : 4171 : oldTupDesc = tab->oldDesc;
6220 : 4171 : newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
6221 : :
6222 [ + + ]: 4171 : if (OidIsValid(OIDNewHeap))
6223 : : {
6224 : : Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
6225 : : false));
6226 : 780 : newrel = table_open(OIDNewHeap, NoLock);
6227 : : }
6228 : : else
6229 : 3391 : newrel = NULL;
6230 : :
6231 : : /*
6232 : : * Prepare a BulkInsertState and options for table_tuple_insert. The FSM
6233 : : * is empty, so don't bother using it.
6234 : : */
6235 [ + + ]: 4171 : if (newrel)
6236 : : {
6237 : 780 : mycid = GetCurrentCommandId(true);
6238 : 780 : bistate = GetBulkInsertState();
6239 : 780 : ti_options = TABLE_INSERT_SKIP_FSM;
6240 : : }
6241 : : else
6242 : : {
6243 : : /* keep compiler quiet about using these uninitialized */
6244 : 3391 : mycid = 0;
6245 : 3391 : bistate = NULL;
6246 : 3391 : ti_options = 0;
6247 : : }
6248 : :
6249 : : /*
6250 : : * Generate the constraint and default execution states
6251 : : */
6252 : :
6253 : 4171 : estate = CreateExecutorState();
6254 : :
6255 : : /* Build the needed expression execution states */
6256 [ + + + + : 5744 : foreach(l, tab->constraints)
+ + ]
6257 : : {
6258 : 1573 : NewConstraint *con = lfirst(l);
6259 : :
6260 [ + + - ]: 1573 : switch (con->contype)
6261 : : {
6262 : 730 : case CONSTR_CHECK:
6263 : 730 : needscan = true;
6264 : 730 : con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
6265 : 730 : break;
6266 : 843 : case CONSTR_FOREIGN:
6267 : : /* Nothing to do here */
6268 : 843 : break;
6269 : 0 : default:
6270 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
6271 : : (int) con->contype);
6272 : : }
6273 : : }
6274 : :
6275 : : /* Build expression execution states for partition check quals */
6276 [ + + ]: 4171 : if (tab->partition_constraint)
6277 : : {
6278 : 1320 : needscan = true;
6279 : 1320 : partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
6280 : : }
6281 : :
6282 [ + + + + : 5012 : foreach(l, tab->newvals)
+ + ]
6283 : : {
6284 : 841 : NewColumnValue *ex = lfirst(l);
6285 : :
6286 : : /* expr already planned */
6287 : 841 : ex->exprstate = ExecInitExpr(ex->expr, NULL);
6288 : : }
6289 : :
6290 : 4171 : notnull_attrs = notnull_virtual_attrs = NIL;
6291 [ + + + + ]: 4171 : if (newrel || tab->verify_new_notnull)
6292 : : {
6293 : : /*
6294 : : * If we are rebuilding the tuples OR if we added any new but not
6295 : : * verified not-null constraints, check all *valid* not-null
6296 : : * constraints. This is a bit of overkill but it minimizes risk of
6297 : : * bugs.
6298 : : *
6299 : : * notnull_attrs does *not* collect attribute numbers for valid
6300 : : * not-null constraints over virtual generated columns; instead, they
6301 : : * are collected in notnull_virtual_attrs for verification elsewhere.
6302 : : */
6303 [ + + ]: 5415 : for (i = 0; i < newTupDesc->natts; i++)
6304 : : {
6305 : 3922 : CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
6306 : :
6307 [ + + ]: 3922 : if (attr->attnullability == ATTNULLABLE_VALID &&
6308 [ + - ]: 1492 : !attr->attisdropped)
6309 : : {
6310 : 1492 : Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
6311 : :
6312 [ + + ]: 1492 : if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
6313 : 1428 : notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
6314 : : else
6315 : 64 : notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
6316 : 64 : wholeatt->attnum);
6317 : : }
6318 : : }
6319 [ + + + + ]: 1493 : if (notnull_attrs || notnull_virtual_attrs)
6320 : 1095 : needscan = true;
6321 : : }
6322 : :
6323 [ + + + + ]: 4171 : if (newrel || needscan)
6324 : : {
6325 : : ExprContext *econtext;
6326 : : TupleTableSlot *oldslot;
6327 : : TupleTableSlot *newslot;
6328 : : TableScanDesc scan;
6329 : : MemoryContext oldCxt;
6330 : 3458 : List *dropped_attrs = NIL;
6331 : : ListCell *lc;
6332 : : Snapshot snapshot;
6333 : 3458 : ResultRelInfo *rInfo = NULL;
6334 : :
6335 : : /*
6336 : : * When adding or changing a virtual generated column with a not-null
6337 : : * constraint, we need to evaluate whether the generation expression
6338 : : * is null. For that, we borrow ExecRelGenVirtualNotNull(). Here, we
6339 : : * prepare a dummy ResultRelInfo.
6340 : : */
6341 [ + + ]: 3458 : if (notnull_virtual_attrs != NIL)
6342 : : {
6343 : : MemoryContext oldcontext;
6344 : :
6345 : : Assert(newTupDesc->constr->has_generated_virtual);
6346 : : Assert(newTupDesc->constr->has_not_null);
6347 : 44 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
6348 : 44 : rInfo = makeNode(ResultRelInfo);
6349 : 44 : InitResultRelInfo(rInfo,
6350 : : oldrel,
6351 : : 0, /* dummy rangetable index */
6352 : : NULL,
6353 : : estate->es_instrument);
6354 : 44 : MemoryContextSwitchTo(oldcontext);
6355 : : }
6356 : :
6357 [ + + ]: 3458 : if (newrel)
6358 [ - + ]: 780 : ereport(DEBUG1,
6359 : : (errmsg_internal("rewriting table \"%s\"",
6360 : : RelationGetRelationName(oldrel))));
6361 : : else
6362 [ + + ]: 2678 : ereport(DEBUG1,
6363 : : (errmsg_internal("verifying table \"%s\"",
6364 : : RelationGetRelationName(oldrel))));
6365 : :
6366 [ + + ]: 3458 : if (newrel)
6367 : : {
6368 : : /*
6369 : : * All predicate locks on the tuples or pages are about to be made
6370 : : * invalid, because we move tuples around. Promote them to
6371 : : * relation locks.
6372 : : */
6373 : 780 : TransferPredicateLocksToHeapRelation(oldrel);
6374 : : }
6375 : :
6376 [ - + ]: 3458 : econtext = GetPerTupleExprContext(estate);
6377 : :
6378 : : /*
6379 : : * Create necessary tuple slots. When rewriting, two slots are needed,
6380 : : * otherwise one suffices. In the case where one slot suffices, we
6381 : : * need to use the new tuple descriptor, otherwise some constraints
6382 : : * can't be evaluated. Note that even when the tuple layout is the
6383 : : * same and no rewrite is required, the tupDescs might not be
6384 : : * (consider ADD COLUMN without a default).
6385 : : */
6386 [ + + ]: 3458 : if (tab->rewrite)
6387 : : {
6388 : : Assert(newrel != NULL);
6389 : 780 : oldslot = MakeSingleTupleTableSlot(oldTupDesc,
6390 : : table_slot_callbacks(oldrel));
6391 : 780 : newslot = MakeSingleTupleTableSlot(newTupDesc,
6392 : : table_slot_callbacks(newrel));
6393 : :
6394 : : /*
6395 : : * Set all columns in the new slot to NULL initially, to ensure
6396 : : * columns added as part of the rewrite are initialized to NULL.
6397 : : * That is necessary as tab->newvals will not contain an
6398 : : * expression for columns with a NULL default, e.g. when adding a
6399 : : * column without a default together with a column with a default
6400 : : * requiring an actual rewrite.
6401 : : */
6402 : 780 : ExecStoreAllNullTuple(newslot);
6403 : : }
6404 : : else
6405 : : {
6406 : 2678 : oldslot = MakeSingleTupleTableSlot(newTupDesc,
6407 : : table_slot_callbacks(oldrel));
6408 : 2678 : newslot = NULL;
6409 : : }
6410 : :
6411 : : /*
6412 : : * Any attributes that are dropped according to the new tuple
6413 : : * descriptor can be set to NULL. We precompute the list of dropped
6414 : : * attributes to avoid needing to do so in the per-tuple loop.
6415 : : */
6416 [ + + ]: 12012 : for (i = 0; i < newTupDesc->natts; i++)
6417 : : {
6418 [ + + ]: 8554 : if (TupleDescAttr(newTupDesc, i)->attisdropped)
6419 : 520 : dropped_attrs = lappend_int(dropped_attrs, i);
6420 : : }
6421 : :
6422 : : /*
6423 : : * Scan through the rows, generating a new row if needed and then
6424 : : * checking all the constraints.
6425 : : */
6426 : 3458 : snapshot = RegisterSnapshot(GetLatestSnapshot());
6427 : 3458 : scan = table_beginscan(oldrel, snapshot, 0, NULL,
6428 : : SO_NONE);
6429 : :
6430 : : /*
6431 : : * Switch to per-tuple memory context and reset it for each tuple
6432 : : * produced, so we don't leak memory.
6433 : : */
6434 [ + - ]: 3458 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6435 : :
6436 [ + + ]: 490843 : while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
6437 : : {
6438 : : TupleTableSlot *insertslot;
6439 : :
6440 [ + + ]: 484212 : if (tab->rewrite > 0)
6441 : : {
6442 : : /* Extract data from old tuple */
6443 : 67479 : slot_getallattrs(oldslot);
6444 : 67479 : ExecClearTuple(newslot);
6445 : :
6446 : : /* copy attributes */
6447 : 67479 : memcpy(newslot->tts_values, oldslot->tts_values,
6448 : 67479 : sizeof(Datum) * oldslot->tts_nvalid);
6449 : 67479 : memcpy(newslot->tts_isnull, oldslot->tts_isnull,
6450 : 67479 : sizeof(bool) * oldslot->tts_nvalid);
6451 : :
6452 : : /* Set dropped attributes to null in new tuple */
6453 [ + + + + : 67564 : foreach(lc, dropped_attrs)
+ + ]
6454 : 85 : newslot->tts_isnull[lfirst_int(lc)] = true;
6455 : :
6456 : : /*
6457 : : * Constraints and GENERATED expressions might reference the
6458 : : * tableoid column, so fill tts_tableOid with the desired
6459 : : * value. (We must do this each time, because it gets
6460 : : * overwritten with newrel's OID during storing.)
6461 : : */
6462 : 67479 : newslot->tts_tableOid = RelationGetRelid(oldrel);
6463 : :
6464 : : /*
6465 : : * Process supplied expressions to replace selected columns.
6466 : : *
6467 : : * First, evaluate expressions whose inputs come from the old
6468 : : * tuple.
6469 : : */
6470 : 67479 : econtext->ecxt_scantuple = oldslot;
6471 : :
6472 [ + + + + : 137950 : foreach(l, tab->newvals)
+ + ]
6473 : : {
6474 : 70479 : NewColumnValue *ex = lfirst(l);
6475 : :
6476 [ + + ]: 70479 : if (ex->is_generated)
6477 : 284 : continue;
6478 : :
6479 : 70195 : newslot->tts_values[ex->attnum - 1]
6480 : 70187 : = ExecEvalExpr(ex->exprstate,
6481 : : econtext,
6482 : 70195 : &newslot->tts_isnull[ex->attnum - 1]);
6483 : : }
6484 : :
6485 : 67471 : ExecStoreVirtualTuple(newslot);
6486 : :
6487 : : /*
6488 : : * Now, evaluate any expressions whose inputs come from the
6489 : : * new tuple. We assume these columns won't reference each
6490 : : * other, so that there's no ordering dependency.
6491 : : */
6492 : 67471 : econtext->ecxt_scantuple = newslot;
6493 : :
6494 [ + + + + : 137942 : foreach(l, tab->newvals)
+ + ]
6495 : : {
6496 : 70471 : NewColumnValue *ex = lfirst(l);
6497 : :
6498 [ + + ]: 70471 : if (!ex->is_generated)
6499 : 70187 : continue;
6500 : :
6501 : 284 : newslot->tts_values[ex->attnum - 1]
6502 : 284 : = ExecEvalExpr(ex->exprstate,
6503 : : econtext,
6504 : 284 : &newslot->tts_isnull[ex->attnum - 1]);
6505 : : }
6506 : :
6507 : 67471 : insertslot = newslot;
6508 : : }
6509 : : else
6510 : : {
6511 : : /*
6512 : : * If there's no rewrite, old and new table are guaranteed to
6513 : : * have the same AM, so we can just use the old slot to verify
6514 : : * new constraints etc.
6515 : : */
6516 : 416733 : insertslot = oldslot;
6517 : : }
6518 : :
6519 : : /* Now check any constraints on the possibly-changed tuple */
6520 : 484204 : econtext->ecxt_scantuple = insertslot;
6521 : :
6522 [ + + + + : 2579274 : foreach_int(attn, notnull_attrs)
+ + ]
6523 : : {
6524 [ + + ]: 1611042 : if (slot_attisnull(insertslot, attn))
6525 : : {
6526 : 88 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
6527 : :
6528 [ + - ]: 88 : ereport(ERROR,
6529 : : (errcode(ERRCODE_NOT_NULL_VIOLATION),
6530 : : errmsg("column \"%s\" of relation \"%s\" contains null values",
6531 : : NameStr(attr->attname),
6532 : : RelationGetRelationName(oldrel)),
6533 : : errtablecol(oldrel, attn)));
6534 : : }
6535 : : }
6536 : :
6537 [ + + ]: 484116 : if (notnull_virtual_attrs != NIL)
6538 : : {
6539 : : AttrNumber attnum;
6540 : :
6541 : 60 : attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
6542 : : estate,
6543 : : notnull_virtual_attrs);
6544 [ + + ]: 60 : if (attnum != InvalidAttrNumber)
6545 : : {
6546 : 20 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
6547 : :
6548 [ + - ]: 20 : ereport(ERROR,
6549 : : errcode(ERRCODE_NOT_NULL_VIOLATION),
6550 : : errmsg("column \"%s\" of relation \"%s\" contains null values",
6551 : : NameStr(attr->attname),
6552 : : RelationGetRelationName(oldrel)),
6553 : : errtablecol(oldrel, attnum));
6554 : : }
6555 : : }
6556 : :
6557 [ + + + + : 489321 : foreach(l, tab->constraints)
+ + ]
6558 : : {
6559 : 5345 : NewConstraint *con = lfirst(l);
6560 : :
6561 [ + + - ]: 5345 : switch (con->contype)
6562 : : {
6563 : 5279 : case CONSTR_CHECK:
6564 [ + + ]: 5279 : if (!ExecCheck(con->qualstate, econtext))
6565 [ + - ]: 120 : ereport(ERROR,
6566 : : (errcode(ERRCODE_CHECK_VIOLATION),
6567 : : errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
6568 : : con->name,
6569 : : RelationGetRelationName(oldrel)),
6570 : : errtableconstraint(oldrel, con->name)));
6571 : 5159 : break;
6572 : 66 : case CONSTR_NOTNULL:
6573 : : case CONSTR_FOREIGN:
6574 : : /* Nothing to do here */
6575 : 66 : break;
6576 : 0 : default:
6577 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
6578 : : (int) con->contype);
6579 : : }
6580 : : }
6581 : :
6582 [ + + + + ]: 483976 : if (partqualstate && !ExecCheck(partqualstate, econtext))
6583 : : {
6584 [ + + ]: 49 : if (tab->validate_default)
6585 [ + - ]: 17 : ereport(ERROR,
6586 : : (errcode(ERRCODE_CHECK_VIOLATION),
6587 : : errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
6588 : : RelationGetRelationName(oldrel)),
6589 : : errtable(oldrel)));
6590 : : else
6591 [ + - ]: 32 : ereport(ERROR,
6592 : : (errcode(ERRCODE_CHECK_VIOLATION),
6593 : : errmsg("partition constraint of relation \"%s\" is violated by some row",
6594 : : RelationGetRelationName(oldrel)),
6595 : : errtable(oldrel)));
6596 : : }
6597 : :
6598 : : /* Write the tuple out to the new relation */
6599 [ + + ]: 483927 : if (newrel)
6600 : 67427 : table_tuple_insert(newrel, insertslot, mycid,
6601 : : ti_options, bistate);
6602 : :
6603 : 483927 : ResetExprContext(econtext);
6604 : :
6605 [ - + ]: 483927 : CHECK_FOR_INTERRUPTS();
6606 : : }
6607 : :
6608 : 3173 : MemoryContextSwitchTo(oldCxt);
6609 : 3173 : table_endscan(scan);
6610 : 3173 : UnregisterSnapshot(snapshot);
6611 : :
6612 : 3173 : ExecDropSingleTupleTableSlot(oldslot);
6613 [ + + ]: 3173 : if (newslot)
6614 : 728 : ExecDropSingleTupleTableSlot(newslot);
6615 : : }
6616 : :
6617 : 3886 : FreeExecutorState(estate);
6618 : :
6619 : 3886 : table_close(oldrel, NoLock);
6620 [ + + ]: 3886 : if (newrel)
6621 : : {
6622 : 728 : FreeBulkInsertState(bistate);
6623 : :
6624 : 728 : table_finish_bulk_insert(newrel, ti_options);
6625 : :
6626 : 728 : table_close(newrel, NoLock);
6627 : : }
6628 : 3886 : }
6629 : :
6630 : : /*
6631 : : * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
6632 : : */
6633 : : static AlteredTableInfo *
6634 : 27321 : ATGetQueueEntry(List **wqueue, Relation rel)
6635 : : {
6636 : 27321 : Oid relid = RelationGetRelid(rel);
6637 : : AlteredTableInfo *tab;
6638 : : ListCell *ltab;
6639 : :
6640 [ + + + + : 34054 : foreach(ltab, *wqueue)
+ + ]
6641 : : {
6642 : 9963 : tab = (AlteredTableInfo *) lfirst(ltab);
6643 [ + + ]: 9963 : if (tab->relid == relid)
6644 : 3230 : return tab;
6645 : : }
6646 : :
6647 : : /*
6648 : : * Not there, so add it. Note that we make a copy of the relation's
6649 : : * existing descriptor before anything interesting can happen to it.
6650 : : */
6651 : 24091 : tab = palloc0_object(AlteredTableInfo);
6652 : 24091 : tab->relid = relid;
6653 : 24091 : tab->rel = NULL; /* set later */
6654 : 24091 : tab->relkind = rel->rd_rel->relkind;
6655 : 24091 : tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
6656 : 24091 : tab->newAccessMethod = InvalidOid;
6657 : 24091 : tab->chgAccessMethod = false;
6658 : 24091 : tab->newTableSpace = InvalidOid;
6659 : 24091 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
6660 : 24091 : tab->chgPersistence = false;
6661 : :
6662 : 24091 : *wqueue = lappend(*wqueue, tab);
6663 : :
6664 : 24091 : return tab;
6665 : : }
6666 : :
6667 : : static const char *
6668 : 69 : alter_table_type_to_string(AlterTableType cmdtype)
6669 : : {
6670 [ - - + + : 69 : switch (cmdtype)
- - - + -
- - + - -
+ - - - -
- - + + -
+ + - - +
- - - - -
- - - - -
- - - - +
+ - - - -
- - - - +
+ + - - -
- - ]
6671 : : {
6672 : 0 : case AT_AddColumn:
6673 : : case AT_AddColumnToView:
6674 : 0 : return "ADD COLUMN";
6675 : 0 : case AT_ColumnDefault:
6676 : : case AT_CookedColumnDefault:
6677 : 0 : return "ALTER COLUMN ... SET DEFAULT";
6678 : 4 : case AT_DropNotNull:
6679 : 4 : return "ALTER COLUMN ... DROP NOT NULL";
6680 : 4 : case AT_SetNotNull:
6681 : 4 : return "ALTER COLUMN ... SET NOT NULL";
6682 : 0 : case AT_SetExpression:
6683 : 0 : return "ALTER COLUMN ... SET EXPRESSION";
6684 : 0 : case AT_DropExpression:
6685 : 0 : return "ALTER COLUMN ... DROP EXPRESSION";
6686 : 0 : case AT_SetStatistics:
6687 : 0 : return "ALTER COLUMN ... SET STATISTICS";
6688 : 8 : case AT_SetOptions:
6689 : 8 : return "ALTER COLUMN ... SET";
6690 : 0 : case AT_ResetOptions:
6691 : 0 : return "ALTER COLUMN ... RESET";
6692 : 0 : case AT_SetStorage:
6693 : 0 : return "ALTER COLUMN ... SET STORAGE";
6694 : 0 : case AT_SetCompression:
6695 : 0 : return "ALTER COLUMN ... SET COMPRESSION";
6696 : 4 : case AT_DropColumn:
6697 : 4 : return "DROP COLUMN";
6698 : 0 : case AT_AddIndex:
6699 : : case AT_ReAddIndex:
6700 : 0 : return NULL; /* not real grammar */
6701 : 0 : case AT_AddConstraint:
6702 : : case AT_ReAddConstraint:
6703 : : case AT_ReAddDomainConstraint:
6704 : : case AT_AddIndexConstraint:
6705 : 0 : return "ADD CONSTRAINT";
6706 : 4 : case AT_AlterConstraint:
6707 : 4 : return "ALTER CONSTRAINT";
6708 : 0 : case AT_ValidateConstraint:
6709 : 0 : return "VALIDATE CONSTRAINT";
6710 : 0 : case AT_DropConstraint:
6711 : 0 : return "DROP CONSTRAINT";
6712 : 0 : case AT_ReAddComment:
6713 : 0 : return NULL; /* not real grammar */
6714 : 0 : case AT_AlterColumnType:
6715 : 0 : return "ALTER COLUMN ... SET DATA TYPE";
6716 : 0 : case AT_AlterColumnGenericOptions:
6717 : 0 : return "ALTER COLUMN ... OPTIONS";
6718 : 0 : case AT_ChangeOwner:
6719 : 0 : return "OWNER TO";
6720 : 4 : case AT_ClusterOn:
6721 : 4 : return "CLUSTER ON";
6722 : 4 : case AT_DropCluster:
6723 : 4 : return "SET WITHOUT CLUSTER";
6724 : 0 : case AT_SetAccessMethod:
6725 : 0 : return "SET ACCESS METHOD";
6726 : 4 : case AT_SetLogged:
6727 : 4 : return "SET LOGGED";
6728 : 4 : case AT_SetUnLogged:
6729 : 4 : return "SET UNLOGGED";
6730 : 0 : case AT_DropOids:
6731 : 0 : return "SET WITHOUT OIDS";
6732 : 0 : case AT_SetTableSpace:
6733 : 0 : return "SET TABLESPACE";
6734 : 1 : case AT_SetRelOptions:
6735 : 1 : return "SET";
6736 : 0 : case AT_ResetRelOptions:
6737 : 0 : return "RESET";
6738 : 0 : case AT_ReplaceRelOptions:
6739 : 0 : return NULL; /* not real grammar */
6740 : 0 : case AT_EnableTrig:
6741 : 0 : return "ENABLE TRIGGER";
6742 : 0 : case AT_EnableAlwaysTrig:
6743 : 0 : return "ENABLE ALWAYS TRIGGER";
6744 : 0 : case AT_EnableReplicaTrig:
6745 : 0 : return "ENABLE REPLICA TRIGGER";
6746 : 0 : case AT_DisableTrig:
6747 : 0 : return "DISABLE TRIGGER";
6748 : 0 : case AT_EnableTrigAll:
6749 : 0 : return "ENABLE TRIGGER ALL";
6750 : 0 : case AT_DisableTrigAll:
6751 : 0 : return "DISABLE TRIGGER ALL";
6752 : 0 : case AT_EnableTrigUser:
6753 : 0 : return "ENABLE TRIGGER USER";
6754 : 0 : case AT_DisableTrigUser:
6755 : 0 : return "DISABLE TRIGGER USER";
6756 : 0 : case AT_EnableRule:
6757 : 0 : return "ENABLE RULE";
6758 : 0 : case AT_EnableAlwaysRule:
6759 : 0 : return "ENABLE ALWAYS RULE";
6760 : 0 : case AT_EnableReplicaRule:
6761 : 0 : return "ENABLE REPLICA RULE";
6762 : 0 : case AT_DisableRule:
6763 : 0 : return "DISABLE RULE";
6764 : 4 : case AT_AddInherit:
6765 : 4 : return "INHERIT";
6766 : 4 : case AT_DropInherit:
6767 : 4 : return "NO INHERIT";
6768 : 0 : case AT_AddOf:
6769 : 0 : return "OF";
6770 : 0 : case AT_DropOf:
6771 : 0 : return "NOT OF";
6772 : 0 : case AT_ReplicaIdentity:
6773 : 0 : return "REPLICA IDENTITY";
6774 : 0 : case AT_EnableRowSecurity:
6775 : 0 : return "ENABLE ROW SECURITY";
6776 : 0 : case AT_DisableRowSecurity:
6777 : 0 : return "DISABLE ROW SECURITY";
6778 : 0 : case AT_ForceRowSecurity:
6779 : 0 : return "FORCE ROW SECURITY";
6780 : 0 : case AT_NoForceRowSecurity:
6781 : 0 : return "NO FORCE ROW SECURITY";
6782 : 0 : case AT_GenericOptions:
6783 : 0 : return "OPTIONS";
6784 : 4 : case AT_AttachPartition:
6785 : 4 : return "ATTACH PARTITION";
6786 : 12 : case AT_DetachPartition:
6787 : 12 : return "DETACH PARTITION";
6788 : 4 : case AT_DetachPartitionFinalize:
6789 : 4 : return "DETACH PARTITION ... FINALIZE";
6790 : 0 : case AT_AddIdentity:
6791 : 0 : return "ALTER COLUMN ... ADD IDENTITY";
6792 : 0 : case AT_SetIdentity:
6793 : 0 : return "ALTER COLUMN ... SET";
6794 : 0 : case AT_DropIdentity:
6795 : 0 : return "ALTER COLUMN ... DROP IDENTITY";
6796 : 0 : case AT_ReAddStatistics:
6797 : 0 : return NULL; /* not real grammar */
6798 : : }
6799 : :
6800 : 0 : return NULL;
6801 : : }
6802 : :
6803 : : /*
6804 : : * ATSimplePermissions
6805 : : *
6806 : : * - Ensure that it is a relation (or possibly a view)
6807 : : * - Ensure this user is the owner
6808 : : * - Ensure that it is not a system table
6809 : : */
6810 : : static void
6811 : 24809 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
6812 : : {
6813 : : int actual_target;
6814 : :
6815 [ + + + + : 24809 : switch (rel->rd_rel->relkind)
+ + + + +
+ ]
6816 : : {
6817 : 19607 : case RELKIND_RELATION:
6818 : 19607 : actual_target = ATT_TABLE;
6819 : 19607 : break;
6820 : 3685 : case RELKIND_PARTITIONED_TABLE:
6821 : 3685 : actual_target = ATT_PARTITIONED_TABLE;
6822 : 3685 : break;
6823 : 280 : case RELKIND_VIEW:
6824 : 280 : actual_target = ATT_VIEW;
6825 : 280 : break;
6826 : 29 : case RELKIND_MATVIEW:
6827 : 29 : actual_target = ATT_MATVIEW;
6828 : 29 : break;
6829 : 142 : case RELKIND_INDEX:
6830 : 142 : actual_target = ATT_INDEX;
6831 : 142 : break;
6832 : 308 : case RELKIND_PARTITIONED_INDEX:
6833 : 308 : actual_target = ATT_PARTITIONED_INDEX;
6834 : 308 : break;
6835 : 149 : case RELKIND_COMPOSITE_TYPE:
6836 : 149 : actual_target = ATT_COMPOSITE_TYPE;
6837 : 149 : break;
6838 : 592 : case RELKIND_FOREIGN_TABLE:
6839 : 592 : actual_target = ATT_FOREIGN_TABLE;
6840 : 592 : break;
6841 : 16 : case RELKIND_SEQUENCE:
6842 : 16 : actual_target = ATT_SEQUENCE;
6843 : 16 : break;
6844 : 1 : default:
6845 : 1 : actual_target = 0;
6846 : 1 : break;
6847 : : }
6848 : :
6849 : : /* Wrong target type? */
6850 [ + + ]: 24809 : if ((actual_target & allowed_targets) == 0)
6851 : : {
6852 : 69 : const char *action_str = alter_table_type_to_string(cmdtype);
6853 : :
6854 [ + - ]: 69 : if (action_str)
6855 [ + - ]: 69 : ereport(ERROR,
6856 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6857 : : /* translator: %s is a group of some SQL keywords */
6858 : : errmsg("ALTER action %s cannot be performed on relation \"%s\"",
6859 : : action_str, RelationGetRelationName(rel)),
6860 : : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
6861 : : else
6862 : : /* internal error? */
6863 [ # # ]: 0 : elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
6864 : : RelationGetRelationName(rel));
6865 : : }
6866 : :
6867 : : /* Permissions checks */
6868 [ + + ]: 24740 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
6869 : 8 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
6870 : 8 : RelationGetRelationName(rel));
6871 : :
6872 : : /*
6873 : : * Conflict log tables are used internally for logical replication
6874 : : * conflict logging and should not be altered directly, as it could
6875 : : * disrupt conflict logging. Direct ALTER commands are already rejected
6876 : : * during relation lookup in RangeVarCallbackForAlterRelation(), and
6877 : : * AlterTableMoveAll() skips these tables, so a conflict log table does
6878 : : * not normally reach here; this check guards any internal caller that
6879 : : * arrives via AlterTableInternal().
6880 : : */
6881 [ - + ]: 24732 : if (IsConflictLogTableClass(rel->rd_rel))
6882 [ # # ]: 0 : ereport(ERROR,
6883 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6884 : : errmsg("cannot alter conflict log table \"%s\"",
6885 : : RelationGetRelationName(rel)),
6886 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
6887 : :
6888 [ + + - + ]: 24732 : if (!allowSystemTableMods && IsSystemRelation(rel))
6889 [ # # ]: 0 : ereport(ERROR,
6890 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6891 : : errmsg("permission denied: \"%s\" is a system catalog",
6892 : : RelationGetRelationName(rel))));
6893 : 24732 : }
6894 : :
6895 : : /*
6896 : : * ATSimpleRecursion
6897 : : *
6898 : : * Simple table recursion sufficient for most ALTER TABLE operations.
6899 : : * All direct and indirect children are processed in an unspecified order.
6900 : : * Note that if a child inherits from the original table via multiple
6901 : : * inheritance paths, it will be visited just once.
6902 : : */
6903 : : static void
6904 : 1045 : ATSimpleRecursion(List **wqueue, Relation rel,
6905 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
6906 : : AlterTableUtilityContext *context)
6907 : : {
6908 : : /*
6909 : : * Propagate to children, if desired and if there are (or might be) any
6910 : : * children.
6911 : : */
6912 [ + + + + ]: 1045 : if (recurse && rel->rd_rel->relhassubclass)
6913 : : {
6914 : 71 : Oid relid = RelationGetRelid(rel);
6915 : : ListCell *child;
6916 : : List *children;
6917 : :
6918 : 71 : children = find_all_inheritors(relid, lockmode, NULL);
6919 : :
6920 : : /*
6921 : : * find_all_inheritors does the recursive search of the inheritance
6922 : : * hierarchy, so all we have to do is process all of the relids in the
6923 : : * list that it returns.
6924 : : */
6925 [ + - + + : 300 : foreach(child, children)
+ + ]
6926 : : {
6927 : 229 : Oid childrelid = lfirst_oid(child);
6928 : : Relation childrel;
6929 : :
6930 [ + + ]: 229 : if (childrelid == relid)
6931 : 71 : continue;
6932 : : /* find_all_inheritors already got lock */
6933 : 158 : childrel = relation_open(childrelid, NoLock);
6934 : 158 : CheckAlterTableIsSafe(childrel);
6935 : 158 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
6936 : 158 : relation_close(childrel, NoLock);
6937 : : }
6938 : : }
6939 : 1045 : }
6940 : :
6941 : : /*
6942 : : * Obtain list of partitions of the given table, locking them all at the given
6943 : : * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
6944 : : *
6945 : : * This function is a no-op if the given relation is not a partitioned table;
6946 : : * in particular, nothing is done if it's a legacy inheritance parent.
6947 : : */
6948 : : static void
6949 : 567 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
6950 : : {
6951 [ + + ]: 567 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6952 : : {
6953 : : List *inh;
6954 : : ListCell *cell;
6955 : :
6956 : 121 : inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
6957 : : /* first element is the parent rel; must ignore it */
6958 [ + - + + : 398 : for_each_from(cell, inh, 1)
+ + ]
6959 : : {
6960 : : Relation childrel;
6961 : :
6962 : : /* find_all_inheritors already got lock */
6963 : 281 : childrel = table_open(lfirst_oid(cell), NoLock);
6964 : 281 : CheckAlterTableIsSafe(childrel);
6965 : 277 : table_close(childrel, NoLock);
6966 : : }
6967 : 117 : list_free(inh);
6968 : : }
6969 : 563 : }
6970 : :
6971 : : /*
6972 : : * ATTypedTableRecursion
6973 : : *
6974 : : * Propagate ALTER TYPE operations to the typed tables of that type.
6975 : : * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
6976 : : * recursion to inheritance children of the typed tables.
6977 : : */
6978 : : static void
6979 : 133 : ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
6980 : : LOCKMODE lockmode, AlterTableUtilityContext *context)
6981 : : {
6982 : : ListCell *child;
6983 : : List *children;
6984 : :
6985 : : Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6986 : :
6987 : 133 : children = find_typed_table_dependencies(rel->rd_rel->reltype,
6988 : 133 : RelationGetRelationName(rel),
6989 : : cmd->behavior);
6990 : :
6991 [ + + + + : 141 : foreach(child, children)
+ + ]
6992 : : {
6993 : 20 : Oid childrelid = lfirst_oid(child);
6994 : : Relation childrel;
6995 : :
6996 : 20 : childrel = relation_open(childrelid, lockmode);
6997 : 20 : CheckAlterTableIsSafe(childrel);
6998 : 20 : ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
6999 : 20 : relation_close(childrel, NoLock);
7000 : : }
7001 : 121 : }
7002 : :
7003 : :
7004 : : /*
7005 : : * find_composite_type_dependencies
7006 : : *
7007 : : * Check to see if the type "typeOid" is being used as a column in some table
7008 : : * (possibly nested several levels deep in composite types, arrays, etc!).
7009 : : * Eventually, we'd like to propagate the check or rewrite operation
7010 : : * into such tables, but for now, just error out if we find any.
7011 : : *
7012 : : * Caller should provide either the associated relation of a rowtype,
7013 : : * or a type name (not both) for use in the error message, if any.
7014 : : *
7015 : : * Note that "typeOid" is not necessarily a composite type; it could also be
7016 : : * another container type such as an array or range, or a domain over one of
7017 : : * these things. The name of this function is therefore somewhat historical,
7018 : : * but it's not worth changing.
7019 : : *
7020 : : * We assume that functions and views depending on the type are not reasons
7021 : : * to reject the ALTER. (How safe is this really?)
7022 : : */
7023 : : void
7024 : 3354 : find_composite_type_dependencies(Oid typeOid, Relation origRelation,
7025 : : const char *origTypeName)
7026 : : {
7027 : : Relation depRel;
7028 : : ScanKeyData key[2];
7029 : : SysScanDesc depScan;
7030 : : HeapTuple depTup;
7031 : :
7032 : : Assert(OidIsValid(typeOid));
7033 : :
7034 : : /* since this function recurses, it could be driven to stack overflow */
7035 : 3354 : 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 : 3354 : depRel = table_open(DependRelationId, AccessShareLock);
7042 : :
7043 : 3354 : ScanKeyInit(&key[0],
7044 : : Anum_pg_depend_refclassid,
7045 : : BTEqualStrategyNumber, F_OIDEQ,
7046 : : ObjectIdGetDatum(TypeRelationId));
7047 : 3354 : ScanKeyInit(&key[1],
7048 : : Anum_pg_depend_refobjid,
7049 : : BTEqualStrategyNumber, F_OIDEQ,
7050 : : ObjectIdGetDatum(typeOid));
7051 : :
7052 : 3354 : depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
7053 : : NULL, 2, key);
7054 : :
7055 [ + + ]: 5158 : while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
7056 : : {
7057 : 1908 : 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 [ + + ]: 1908 : 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 : 1630 : find_composite_type_dependencies(pg_depend->objid,
7072 : : origRelation, origTypeName);
7073 : 1614 : continue;
7074 : : }
7075 : :
7076 : : /* Else, ignore dependees that aren't relations */
7077 [ + + ]: 278 : if (pg_depend->classid != RelationRelationId)
7078 : 85 : continue;
7079 : :
7080 : 193 : rel = relation_open(pg_depend->objid, AccessShareLock);
7081 : 193 : 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 [ + + + - ]: 193 : if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
7097 : 84 : att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
7098 : : else
7099 : : {
7100 : 109 : att = NULL;
7101 [ + + ]: 286 : for (int attno = 1; attno <= tupleDesc->natts; attno++)
7102 : : {
7103 : 181 : att = TupleDescAttr(tupleDesc, attno - 1);
7104 [ + + + - ]: 181 : if (att->atttypid == typeOid && !att->attisdropped)
7105 : 4 : break;
7106 : 177 : att = NULL;
7107 : : }
7108 [ + + ]: 109 : if (att == NULL)
7109 : : {
7110 : : /* No such column, so assume OK */
7111 : 105 : relation_close(rel, AccessShareLock);
7112 : 105 : 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 : 3250 : systable_endscan(depScan);
7171 : :
7172 : 3250 : relation_close(depRel, AccessShareLock);
7173 : 3250 : }
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 : 149 : 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 : 149 : List *result = NIL;
7191 : :
7192 : 149 : classRel = table_open(RelationRelationId, AccessShareLock);
7193 : :
7194 : 149 : ScanKeyInit(&key[0],
7195 : : Anum_pg_class_reloftype,
7196 : : BTEqualStrategyNumber, F_OIDEQ,
7197 : : ObjectIdGetDatum(typeOid));
7198 : :
7199 : 149 : scan = table_beginscan_catalog(classRel, 1, key);
7200 : :
7201 [ + + ]: 173 : 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 : 133 : table_endscan(scan);
7216 : 133 : table_close(classRel, AccessShareLock);
7217 : :
7218 : 133 : 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 : 127 : check_of_type(HeapTuple typetuple)
7234 : : {
7235 : 127 : Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7236 : 127 : bool typeOk = false;
7237 : :
7238 [ + + ]: 127 : if (typ->typtype == TYPTYPE_COMPOSITE)
7239 : : {
7240 : : Relation typeRelation;
7241 : :
7242 : : Assert(OidIsValid(typ->typrelid));
7243 : 123 : typeRelation = relation_open(typ->typrelid, AccessShareLock);
7244 : 123 : 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 : 123 : relation_close(typeRelation, NoLock);
7252 : :
7253 [ + + ]: 123 : 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 : 119 : }
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 : 1599 : ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
7284 : : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
7285 : : AlterTableUtilityContext *context)
7286 : : {
7287 [ + + + + ]: 1599 : 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 [ + + ]: 1595 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7293 : 42 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
7294 : :
7295 [ + + + + ]: 1591 : if (recurse && !is_view)
7296 : 1516 : cmd->recurse = true;
7297 : 1591 : }
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 : 2101 : 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 : 2101 : Oid myrelid = RelationGetRelid(rel);
7313 : 2101 : ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
7314 : 2101 : 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 : 2101 : check_stack_depth();
7331 : :
7332 : : /* At top level, permission check was done in ATPrepCmd, else do it */
7333 [ + + ]: 2101 : if (recursing)
7334 : 514 : ATSimplePermissions((*cmd)->subtype, rel,
7335 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
7336 : :
7337 [ + + + + ]: 2101 : 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 : 2093 : 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 [ + + ]: 2093 : 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 [ + + ]: 2053 : 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 [ + + + + ]: 1989 : if (context != NULL && !recursing)
7424 : : {
7425 : 1494 : *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
7426 : : cur_pass, context);
7427 : : Assert(*cmd != NULL);
7428 : 1490 : 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 [ + + + - ]: 1985 : 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 : 1981 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
7449 : :
7450 : 1981 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
7451 [ - + ]: 1981 : if (!HeapTupleIsValid(reltup))
7452 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
7453 : 1981 : relform = (Form_pg_class) GETSTRUCT(reltup);
7454 : 1981 : relkind = relform->relkind;
7455 : :
7456 : : /* Determine the new attribute's number */
7457 : 1981 : newattnum = relform->relnatts + 1;
7458 [ - + ]: 1981 : 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 : 1981 : tupdesc = BuildDescForRelation(list_make1(colDef));
7468 : :
7469 : 1973 : attribute = TupleDescAttr(tupdesc, 0);
7470 : :
7471 : : /* Fix up attribute number */
7472 : 1973 : attribute->attnum = newattnum;
7473 : :
7474 : : /* make sure datatype is legal for a column */
7475 : 3946 : CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
7476 : 1973 : list_make1_oid(rel->rd_rel->reltype),
7477 [ + + ]: 1973 : (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
7478 : :
7479 : 1945 : InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
7480 : :
7481 : 1945 : table_close(attrdesc, RowExclusiveLock);
7482 : :
7483 : : /*
7484 : : * Update pg_class tuple as appropriate
7485 : : */
7486 : 1945 : relform->relnatts = newattnum;
7487 : :
7488 : 1945 : CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
7489 : :
7490 : 1945 : heap_freetuple(reltup);
7491 : :
7492 : : /* Post creation hook for new attribute */
7493 [ - + ]: 1945 : InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
7494 : :
7495 : 1945 : table_close(pgclass, RowExclusiveLock);
7496 : :
7497 : : /* Make the attribute's catalog entry visible */
7498 : 1945 : CommandCounterIncrement();
7499 : :
7500 : : /*
7501 : : * Store the DEFAULT, if any, in the catalogs
7502 : : */
7503 [ + + ]: 1945 : if (colDef->raw_default)
7504 : : {
7505 : : RawColumnDefault *rawEnt;
7506 : :
7507 : 763 : rawEnt = palloc_object(RawColumnDefault);
7508 : 763 : rawEnt->attnum = attribute->attnum;
7509 : 763 : rawEnt->raw_default = copyObject(colDef->raw_default);
7510 : 763 : 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 : 763 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
7517 : : false, true, false, NULL);
7518 : :
7519 : : /* Make the additional catalog changes visible */
7520 : 675 : 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 : : * An exception occurs when the new column is of a domain type: the domain
7533 : : * might have a not-null constraint, or a check constraint that indirectly
7534 : : * rejects nulls. If there are any domain constraints then we construct
7535 : : * an explicit NULL default value that will be passed through
7536 : : * CoerceToDomain processing. (This is a tad inefficient, since it causes
7537 : : * rewriting the table which we really wouldn't have to do; but we do it
7538 : : * to preserve the historical behavior that such a failure will be raised
7539 : : * only if the table currently contains some rows.)
7540 : : *
7541 : : * Note: we use build_column_default, and not just the cooked default
7542 : : * returned by AddRelationNewConstraints, so that the right thing happens
7543 : : * when a datatype's default applies.
7544 : : *
7545 : : * Note: it might seem that this should happen at the end of Phase 2, so
7546 : : * that the effects of subsequent subcommands can be taken into account.
7547 : : * It's intentional that we do it now, though. The new column should be
7548 : : * filled according to what is said in the ADD COLUMN subcommand, so that
7549 : : * the effects are the same as if this subcommand had been run by itself
7550 : : * and the later subcommands had been issued in new ALTER TABLE commands.
7551 : : *
7552 : : * We can skip this entirely for relations without storage, since Phase 3
7553 : : * is certainly not going to touch them.
7554 : : */
7555 [ + + + - : 1857 : if (RELKIND_HAS_STORAGE(relkind))
+ - + - -
+ ]
7556 : : {
7557 : : bool has_domain_constraints;
7558 : 1587 : bool has_missing = false;
7559 : :
7560 : : /*
7561 : : * For an identity column, we can't use build_column_default(),
7562 : : * because the sequence ownership isn't set yet. So do it manually.
7563 : : */
7564 [ + + ]: 1587 : if (colDef->identity)
7565 : : {
7566 : 28 : NextValueExpr *nve = makeNode(NextValueExpr);
7567 : :
7568 : 28 : nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
7569 : 28 : nve->typeId = attribute->atttypid;
7570 : :
7571 : 28 : defval = (Expr *) nve;
7572 : : }
7573 : : else
7574 : 1559 : defval = (Expr *) build_column_default(rel, attribute->attnum);
7575 : :
7576 : : /* Build CoerceToDomain(NULL) expression if needed */
7577 : 1587 : has_domain_constraints = DomainHasConstraints(attribute->atttypid, NULL);
7578 [ + + + + ]: 1587 : if (!defval && has_domain_constraints)
7579 : : {
7580 : : Oid baseTypeId;
7581 : : int32 baseTypeMod;
7582 : : Oid baseTypeColl;
7583 : :
7584 : 4 : baseTypeMod = attribute->atttypmod;
7585 : 4 : baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
7586 : 4 : baseTypeColl = get_typcollation(baseTypeId);
7587 : 4 : defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
7588 : 4 : defval = (Expr *) coerce_to_target_type(NULL,
7589 : : (Node *) defval,
7590 : : baseTypeId,
7591 : : attribute->atttypid,
7592 : : attribute->atttypmod,
7593 : : COERCION_ASSIGNMENT,
7594 : : COERCE_IMPLICIT_CAST,
7595 : : -1);
7596 [ - + ]: 4 : if (defval == NULL) /* should not happen */
7597 [ # # ]: 0 : elog(ERROR, "failed to coerce base type to domain");
7598 : : }
7599 : :
7600 [ + + ]: 1587 : if (defval)
7601 : : {
7602 : : NewColumnValue *newval;
7603 : :
7604 : : /* Prepare defval for execution, either here or in Phase 3 */
7605 : 612 : defval = expression_planner(defval);
7606 : :
7607 : : /* Add the new default to the newvals list */
7608 : 612 : newval = palloc0_object(NewColumnValue);
7609 : 612 : newval->attnum = attribute->attnum;
7610 : 612 : newval->expr = defval;
7611 : 612 : newval->is_generated = (colDef->generated != '\0');
7612 : :
7613 : 612 : tab->newvals = lappend(tab->newvals, newval);
7614 : :
7615 : : /*
7616 : : * Attempt to skip a complete table rewrite by storing the
7617 : : * specified DEFAULT value outside of the heap. This is only
7618 : : * allowed for plain relations and non-generated columns, and the
7619 : : * default expression can't be volatile (stable is OK). Note that
7620 : : * contain_volatile_functions deems CoerceToDomain immutable, but
7621 : : * here we consider that coercion to a domain with constraints is
7622 : : * volatile; else it might fail even when the table is empty.
7623 : : */
7624 [ + - ]: 612 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
7625 [ + + ]: 612 : !colDef->generated &&
7626 [ + + ]: 483 : !has_domain_constraints &&
7627 [ + + ]: 475 : !contain_volatile_functions((Node *) defval))
7628 : 365 : {
7629 : : EState *estate;
7630 : : ExprState *exprState;
7631 : : Datum missingval;
7632 : : bool missingIsNull;
7633 : :
7634 : : /* Evaluate the default expression */
7635 : 365 : estate = CreateExecutorState();
7636 : 365 : exprState = ExecPrepareExpr(defval, estate);
7637 : 365 : missingval = ExecEvalExpr(exprState,
7638 [ - + ]: 365 : GetPerTupleExprContext(estate),
7639 : : &missingIsNull);
7640 : : /* If it turns out NULL, nothing to do; else store it */
7641 [ + - ]: 365 : if (!missingIsNull)
7642 : : {
7643 : 365 : StoreAttrMissingVal(rel, attribute->attnum, missingval);
7644 : : /* Make the additional catalog change visible */
7645 : 365 : CommandCounterIncrement();
7646 : 365 : has_missing = true;
7647 : : }
7648 : 365 : FreeExecutorState(estate);
7649 : : }
7650 : : else
7651 : : {
7652 : : /*
7653 : : * Failed to use missing mode. We have to do a table rewrite
7654 : : * to install the value --- unless it's a virtual generated
7655 : : * column.
7656 : : */
7657 [ + + ]: 247 : if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
7658 : 174 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
7659 : : }
7660 : : }
7661 : :
7662 [ + + ]: 1587 : if (!has_missing)
7663 : : {
7664 : : /*
7665 : : * If the new column is NOT NULL, and there is no missing value,
7666 : : * tell Phase 3 it needs to check for NULLs.
7667 : : */
7668 : 1222 : tab->verify_new_notnull |= colDef->is_not_null;
7669 : : }
7670 : : }
7671 : :
7672 : : /*
7673 : : * Add needed dependency entries for the new column.
7674 : : */
7675 : 1857 : add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
7676 : 1857 : add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
7677 : :
7678 : : /*
7679 : : * Propagate to children as appropriate. Unlike most other ALTER
7680 : : * routines, we have to do this one level of recursion at a time; we can't
7681 : : * use find_all_inheritors to do it in one pass.
7682 : : */
7683 : : children =
7684 : 1857 : find_inheritance_children(RelationGetRelid(rel), lockmode);
7685 : :
7686 : : /*
7687 : : * If we are told not to recurse, there had better not be any child
7688 : : * tables; else the addition would put them out of step.
7689 : : */
7690 [ + + + + ]: 1857 : if (children && !recurse)
7691 [ + - ]: 8 : ereport(ERROR,
7692 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7693 : : errmsg("column must be added to child tables too")));
7694 : :
7695 : : /* Children should see column as singly inherited */
7696 [ + + ]: 1849 : if (!recursing)
7697 : : {
7698 : 1375 : childcmd = copyObject(*cmd);
7699 : 1375 : colDef = castNode(ColumnDef, childcmd->def);
7700 : 1375 : colDef->inhcount = 1;
7701 : 1375 : colDef->is_local = false;
7702 : : }
7703 : : else
7704 : 474 : childcmd = *cmd; /* no need to copy again */
7705 : :
7706 [ + + + + : 2363 : foreach(child, children)
+ + ]
7707 : : {
7708 : 514 : Oid childrelid = lfirst_oid(child);
7709 : : Relation childrel;
7710 : : AlteredTableInfo *childtab;
7711 : :
7712 : : /* find_inheritance_children already got lock */
7713 : 514 : childrel = table_open(childrelid, NoLock);
7714 : 514 : CheckAlterTableIsSafe(childrel);
7715 : :
7716 : : /* Find or create work queue entry for this table */
7717 : 514 : childtab = ATGetQueueEntry(wqueue, childrel);
7718 : :
7719 : : /* Recurse to child; return value is ignored */
7720 : 514 : ATExecAddColumn(wqueue, childtab, childrel,
7721 : : &childcmd, recurse, true,
7722 : : lockmode, cur_pass, context);
7723 : :
7724 : 514 : table_close(childrel, NoLock);
7725 : : }
7726 : :
7727 : 1849 : ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
7728 : 1849 : return address;
7729 : : }
7730 : :
7731 : : /*
7732 : : * If a new or renamed column will collide with the name of an existing
7733 : : * column and if_not_exists is false then error out, else do nothing.
7734 : : */
7735 : : static bool
7736 : 2351 : check_for_column_name_collision(Relation rel, const char *colname,
7737 : : bool if_not_exists)
7738 : : {
7739 : : HeapTuple attTuple;
7740 : : int attnum;
7741 : :
7742 : : /*
7743 : : * this test is deliberately not attisdropped-aware, since if one tries to
7744 : : * add a column matching a dropped column name, it's gonna fail anyway.
7745 : : */
7746 : 2351 : attTuple = SearchSysCache2(ATTNAME,
7747 : : ObjectIdGetDatum(RelationGetRelid(rel)),
7748 : : PointerGetDatum(colname));
7749 [ + + ]: 2351 : if (!HeapTupleIsValid(attTuple))
7750 : 2279 : return true;
7751 : :
7752 : 72 : attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
7753 : 72 : ReleaseSysCache(attTuple);
7754 : :
7755 : : /*
7756 : : * We throw a different error message for conflicts with system column
7757 : : * names, since they are normally not shown and the user might otherwise
7758 : : * be confused about the reason for the conflict.
7759 : : */
7760 [ + + ]: 72 : if (attnum <= 0)
7761 [ + - ]: 8 : ereport(ERROR,
7762 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
7763 : : errmsg("column name \"%s\" conflicts with a system column name",
7764 : : colname)));
7765 : : else
7766 : : {
7767 [ + + ]: 64 : if (if_not_exists)
7768 : : {
7769 [ + - ]: 44 : ereport(NOTICE,
7770 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
7771 : : errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
7772 : : colname, RelationGetRelationName(rel))));
7773 : 44 : return false;
7774 : : }
7775 : :
7776 [ + - ]: 20 : ereport(ERROR,
7777 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
7778 : : errmsg("column \"%s\" of relation \"%s\" already exists",
7779 : : colname, RelationGetRelationName(rel))));
7780 : : }
7781 : :
7782 : : return true;
7783 : : }
7784 : :
7785 : : /*
7786 : : * Install a column's dependency on its datatype.
7787 : : */
7788 : : static void
7789 : 2633 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
7790 : : {
7791 : : ObjectAddress myself,
7792 : : referenced;
7793 : :
7794 : 2633 : myself.classId = RelationRelationId;
7795 : 2633 : myself.objectId = relid;
7796 : 2633 : myself.objectSubId = attnum;
7797 : 2633 : referenced.classId = TypeRelationId;
7798 : 2633 : referenced.objectId = typid;
7799 : 2633 : referenced.objectSubId = 0;
7800 : 2633 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7801 : 2633 : }
7802 : :
7803 : : /*
7804 : : * Install a column's dependency on its collation.
7805 : : */
7806 : : static void
7807 : 2633 : add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
7808 : : {
7809 : : ObjectAddress myself,
7810 : : referenced;
7811 : :
7812 : : /* We know the default collation is pinned, so don't bother recording it */
7813 [ + + + + ]: 2633 : if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
7814 : : {
7815 : 12 : myself.classId = RelationRelationId;
7816 : 12 : myself.objectId = relid;
7817 : 12 : myself.objectSubId = attnum;
7818 : 12 : referenced.classId = CollationRelationId;
7819 : 12 : referenced.objectId = collid;
7820 : 12 : referenced.objectSubId = 0;
7821 : 12 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7822 : : }
7823 : 2633 : }
7824 : :
7825 : : /*
7826 : : * ALTER TABLE ALTER COLUMN DROP NOT NULL
7827 : : *
7828 : : * Return the address of the modified column. If the column was already
7829 : : * nullable, InvalidObjectAddress is returned.
7830 : : */
7831 : : static ObjectAddress
7832 : 197 : ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
7833 : : LOCKMODE lockmode)
7834 : : {
7835 : : HeapTuple tuple;
7836 : : HeapTuple conTup;
7837 : : Form_pg_attribute attTup;
7838 : : AttrNumber attnum;
7839 : : Relation attr_rel;
7840 : : ObjectAddress address;
7841 : :
7842 : : /*
7843 : : * lookup the attribute
7844 : : */
7845 : 197 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7846 : :
7847 : 197 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7848 [ + + ]: 197 : if (!HeapTupleIsValid(tuple))
7849 [ + - ]: 12 : ereport(ERROR,
7850 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
7851 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
7852 : : colName, RelationGetRelationName(rel))));
7853 : 185 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7854 : 185 : attnum = attTup->attnum;
7855 : 185 : ObjectAddressSubSet(address, RelationRelationId,
7856 : : RelationGetRelid(rel), attnum);
7857 : :
7858 : : /* If the column is already nullable there's nothing to do. */
7859 [ - + ]: 185 : if (!attTup->attnotnull)
7860 : : {
7861 : 0 : table_close(attr_rel, RowExclusiveLock);
7862 : 0 : return InvalidObjectAddress;
7863 : : }
7864 : :
7865 : : /* Prevent them from altering a system attribute */
7866 [ - + ]: 185 : if (attnum <= 0)
7867 [ # # ]: 0 : ereport(ERROR,
7868 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7869 : : errmsg("cannot alter system column \"%s\"",
7870 : : colName)));
7871 : :
7872 [ + + ]: 185 : if (attTup->attidentity)
7873 [ + - ]: 12 : ereport(ERROR,
7874 : : (errcode(ERRCODE_SYNTAX_ERROR),
7875 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
7876 : : colName, RelationGetRelationName(rel))));
7877 : :
7878 : : /*
7879 : : * If rel is partition, shouldn't drop NOT NULL if parent has the same.
7880 : : */
7881 [ + + ]: 173 : if (rel->rd_rel->relispartition)
7882 : : {
7883 : 8 : Oid parentId = get_partition_parent(RelationGetRelid(rel), false);
7884 : 8 : Relation parent = table_open(parentId, AccessShareLock);
7885 : 8 : TupleDesc tupDesc = RelationGetDescr(parent);
7886 : : AttrNumber parent_attnum;
7887 : :
7888 : 8 : parent_attnum = get_attnum(parentId, colName);
7889 [ + - ]: 8 : if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
7890 [ + - ]: 8 : ereport(ERROR,
7891 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7892 : : errmsg("column \"%s\" is marked NOT NULL in parent table",
7893 : : colName)));
7894 : 0 : table_close(parent, AccessShareLock);
7895 : : }
7896 : :
7897 : : /*
7898 : : * Find the constraint that makes this column NOT NULL, and drop it.
7899 : : * dropconstraint_internal() resets attnotnull.
7900 : : */
7901 : 165 : conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7902 [ - + ]: 165 : if (conTup == NULL)
7903 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
7904 : : colName, RelationGetRelationName(rel));
7905 : :
7906 : : /* The normal case: we have a pg_constraint row, remove it */
7907 : 165 : dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
7908 : : false, lockmode);
7909 : 129 : heap_freetuple(conTup);
7910 : :
7911 [ - + ]: 129 : InvokeObjectPostAlterHook(RelationRelationId,
7912 : : RelationGetRelid(rel), attnum);
7913 : :
7914 : 129 : table_close(attr_rel, RowExclusiveLock);
7915 : :
7916 : 129 : return address;
7917 : : }
7918 : :
7919 : : /*
7920 : : * set_attnotnull
7921 : : * Helper to update/validate the pg_attribute status of a not-null
7922 : : * constraint
7923 : : *
7924 : : * pg_attribute.attnotnull is set true, if it isn't already.
7925 : : * If queue_validation is true, also set up wqueue to validate the constraint.
7926 : : * wqueue may be given as NULL when validation is not needed (e.g., on table
7927 : : * creation).
7928 : : */
7929 : : static void
7930 : 15895 : set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
7931 : : bool queue_validation)
7932 : : {
7933 : : Form_pg_attribute attr;
7934 : :
7935 : : Assert(!queue_validation || wqueue);
7936 : :
7937 : 15895 : CheckAlterTableIsSafe(rel);
7938 : :
7939 : : /*
7940 : : * Exit quickly by testing attnotnull from the tupledesc's copy of the
7941 : : * attribute.
7942 : : */
7943 : 15895 : attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
7944 [ - + ]: 15895 : if (attr->attisdropped)
7945 : 0 : return;
7946 : :
7947 [ + + ]: 15895 : if (!attr->attnotnull)
7948 : : {
7949 : : Relation attr_rel;
7950 : : HeapTuple tuple;
7951 : :
7952 : 995 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7953 : :
7954 : 995 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
7955 [ - + ]: 995 : if (!HeapTupleIsValid(tuple))
7956 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
7957 : : attnum, RelationGetRelid(rel));
7958 : :
7959 : 995 : attr = (Form_pg_attribute) GETSTRUCT(tuple);
7960 : :
7961 : 995 : attr->attnotnull = true;
7962 : 995 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
7963 : :
7964 : : /*
7965 : : * If the nullness isn't already proven by validated constraints, have
7966 : : * ALTER TABLE phase 3 test for it.
7967 : : */
7968 [ + + + - ]: 995 : if (queue_validation && wqueue &&
7969 [ + + ]: 844 : !NotNullImpliedByRelConstraints(rel, attr))
7970 : : {
7971 : : AlteredTableInfo *tab;
7972 : :
7973 : 812 : tab = ATGetQueueEntry(wqueue, rel);
7974 : 812 : tab->verify_new_notnull = true;
7975 : : }
7976 : :
7977 : 995 : CommandCounterIncrement();
7978 : :
7979 : 995 : table_close(attr_rel, RowExclusiveLock);
7980 : 995 : heap_freetuple(tuple);
7981 : : }
7982 : : else
7983 : : {
7984 : 14900 : CacheInvalidateRelcache(rel);
7985 : : }
7986 : : }
7987 : :
7988 : : /*
7989 : : * ALTER TABLE ALTER COLUMN SET NOT NULL
7990 : : *
7991 : : * Add a not-null constraint to a single table and its children. Returns
7992 : : * the address of the constraint added to the parent relation, if one gets
7993 : : * added, or InvalidObjectAddress otherwise.
7994 : : *
7995 : : * We must recurse to child tables during execution, rather than using
7996 : : * ALTER TABLE's normal prep-time recursion.
7997 : : */
7998 : : static ObjectAddress
7999 : 469 : ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
8000 : : bool recurse, bool recursing, LOCKMODE lockmode)
8001 : : {
8002 : : HeapTuple tuple;
8003 : : AttrNumber attnum;
8004 : : ObjectAddress address;
8005 : : Constraint *constraint;
8006 : : CookedConstraint *ccon;
8007 : : List *cooked;
8008 : 469 : bool is_no_inherit = false;
8009 : :
8010 : : /* Guard against stack overflow due to overly deep inheritance tree. */
8011 : 469 : check_stack_depth();
8012 : :
8013 : : /* At top level, permission check was done in ATPrepCmd, else do it */
8014 [ + + ]: 469 : if (recursing)
8015 : : {
8016 : 197 : ATSimplePermissions(AT_AddConstraint, rel,
8017 : : ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
8018 : : Assert(conName != NULL);
8019 : : }
8020 : :
8021 : 469 : attnum = get_attnum(RelationGetRelid(rel), colName);
8022 [ + + ]: 469 : if (attnum == InvalidAttrNumber)
8023 [ + - ]: 12 : ereport(ERROR,
8024 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8025 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8026 : : colName, RelationGetRelationName(rel))));
8027 : :
8028 : : /* Prevent them from altering a system attribute */
8029 [ - + ]: 457 : if (attnum <= 0)
8030 [ # # ]: 0 : ereport(ERROR,
8031 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8032 : : errmsg("cannot alter system column \"%s\"",
8033 : : colName)));
8034 : :
8035 : : /* See if there's already a constraint */
8036 : 457 : tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
8037 [ + + ]: 457 : if (HeapTupleIsValid(tuple))
8038 : : {
8039 : 105 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
8040 : 105 : bool changed = false;
8041 : :
8042 : : /*
8043 : : * Don't let a NO INHERIT constraint be changed into inherit.
8044 : : */
8045 [ + + + - ]: 105 : if (conForm->connoinherit && recurse)
8046 [ + - ]: 8 : ereport(ERROR,
8047 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8048 : : errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
8049 : : NameStr(conForm->conname),
8050 : : RelationGetRelationName(rel)));
8051 : :
8052 : : /*
8053 : : * If we find an appropriate constraint, we're almost done, but just
8054 : : * need to change some properties on it: if we're recursing, increment
8055 : : * coninhcount; if not, set conislocal if not already set.
8056 : : */
8057 [ + + ]: 97 : if (recursing)
8058 : : {
8059 [ - + ]: 68 : if (pg_add_s16_overflow(conForm->coninhcount, 1,
8060 : : &conForm->coninhcount))
8061 [ # # ]: 0 : ereport(ERROR,
8062 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
8063 : : errmsg("too many inheritance parents"));
8064 : 68 : changed = true;
8065 : : }
8066 [ - + ]: 29 : else if (!conForm->conislocal)
8067 : : {
8068 : 0 : conForm->conislocal = true;
8069 : 0 : changed = true;
8070 : : }
8071 [ + + ]: 29 : else if (!conForm->convalidated)
8072 : : {
8073 : : /*
8074 : : * Flip attnotnull and convalidated, and also validate the
8075 : : * constraint.
8076 : : */
8077 : 16 : return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
8078 : : recurse, recursing, lockmode);
8079 : : }
8080 : :
8081 [ + + ]: 81 : if (changed)
8082 : : {
8083 : : Relation constr_rel;
8084 : :
8085 : 68 : constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
8086 : :
8087 : 68 : CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
8088 : 68 : ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
8089 : 68 : table_close(constr_rel, RowExclusiveLock);
8090 : : }
8091 : :
8092 [ + + ]: 81 : if (changed)
8093 : 68 : return address;
8094 : : else
8095 : 13 : return InvalidObjectAddress;
8096 : : }
8097 : :
8098 : : /*
8099 : : * If we're asked not to recurse, and children exist, raise an error for
8100 : : * partitioned tables. For inheritance, we act as if NO INHERIT had been
8101 : : * specified.
8102 : : */
8103 [ + + + + ]: 372 : if (!recurse &&
8104 : 20 : find_inheritance_children(RelationGetRelid(rel),
8105 : : NoLock) != NIL)
8106 : : {
8107 [ + + ]: 12 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8108 [ + - ]: 4 : ereport(ERROR,
8109 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8110 : : errmsg("constraint must be added to child tables too"),
8111 : : errhint("Do not specify the ONLY keyword."));
8112 : : else
8113 : 8 : is_no_inherit = true;
8114 : : }
8115 : :
8116 : : /*
8117 : : * No constraint exists; we must add one. First determine a name to use,
8118 : : * if we haven't already.
8119 : : */
8120 [ + + ]: 348 : if (!recursing)
8121 : : {
8122 : : Assert(conName == NULL);
8123 : 223 : conName = ChooseConstraintName(RelationGetRelationName(rel),
8124 : : colName, "not_null",
8125 : 223 : RelationGetNamespace(rel),
8126 : : NIL);
8127 : : }
8128 : :
8129 : 348 : constraint = makeNotNullConstraint(makeString(colName));
8130 : 348 : constraint->is_no_inherit = is_no_inherit;
8131 : 348 : constraint->conname = conName;
8132 : :
8133 : : /* and do it */
8134 : 348 : cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
8135 : 348 : false, !recursing, false, NULL);
8136 : 348 : ccon = linitial(cooked);
8137 : 348 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8138 : :
8139 : : /* Mark pg_attribute.attnotnull for the column and queue validation */
8140 : 348 : set_attnotnull(wqueue, rel, attnum, true);
8141 : :
8142 [ - + ]: 348 : InvokeObjectPostAlterHook(RelationRelationId,
8143 : : RelationGetRelid(rel), attnum);
8144 : :
8145 : : /*
8146 : : * Recurse to propagate the constraint to children that don't have one.
8147 : : */
8148 [ + + ]: 348 : if (recurse)
8149 : : {
8150 : : List *children;
8151 : :
8152 : 332 : children = find_inheritance_children(RelationGetRelid(rel),
8153 : : lockmode);
8154 : :
8155 [ + + + + : 817 : foreach_oid(childoid, children)
+ + ]
8156 : : {
8157 : 161 : Relation childrel = table_open(childoid, NoLock);
8158 : :
8159 : 161 : CommandCounterIncrement();
8160 : :
8161 : 161 : ATExecSetNotNull(wqueue, childrel, conName, colName,
8162 : : recurse, true, lockmode);
8163 : 157 : table_close(childrel, NoLock);
8164 : : }
8165 : : }
8166 : :
8167 : 344 : return address;
8168 : : }
8169 : :
8170 : : /*
8171 : : * NotNullImpliedByRelConstraints
8172 : : * Does rel's existing constraints imply NOT NULL for the given attribute?
8173 : : */
8174 : : static bool
8175 : 844 : NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
8176 : : {
8177 : 844 : NullTest *nnulltest = makeNode(NullTest);
8178 : :
8179 : 1688 : nnulltest->arg = (Expr *) makeVar(1,
8180 : 844 : attr->attnum,
8181 : : attr->atttypid,
8182 : : attr->atttypmod,
8183 : : attr->attcollation,
8184 : : 0);
8185 : 844 : nnulltest->nulltesttype = IS_NOT_NULL;
8186 : :
8187 : : /*
8188 : : * argisrow = false is correct even for a composite column, because
8189 : : * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
8190 : : * case, just IS DISTINCT FROM NULL.
8191 : : */
8192 : 844 : nnulltest->argisrow = false;
8193 : 844 : nnulltest->location = -1;
8194 : :
8195 [ + + ]: 844 : if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
8196 : : {
8197 [ + + ]: 32 : ereport(DEBUG1,
8198 : : (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
8199 : : RelationGetRelationName(rel), NameStr(attr->attname))));
8200 : 32 : return true;
8201 : : }
8202 : :
8203 : 812 : return false;
8204 : : }
8205 : :
8206 : : /*
8207 : : * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
8208 : : *
8209 : : * Return the address of the affected column.
8210 : : */
8211 : : static ObjectAddress
8212 : 387 : ATExecColumnDefault(Relation rel, const char *colName,
8213 : : Node *newDefault, LOCKMODE lockmode)
8214 : : {
8215 : 387 : TupleDesc tupdesc = RelationGetDescr(rel);
8216 : : AttrNumber attnum;
8217 : : ObjectAddress address;
8218 : :
8219 : : /*
8220 : : * get the number of the attribute
8221 : : */
8222 : 387 : attnum = get_attnum(RelationGetRelid(rel), colName);
8223 [ + + ]: 387 : if (attnum == InvalidAttrNumber)
8224 [ + - ]: 20 : ereport(ERROR,
8225 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8226 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8227 : : colName, RelationGetRelationName(rel))));
8228 : :
8229 : : /* Prevent them from altering a system attribute */
8230 [ - + ]: 367 : if (attnum <= 0)
8231 [ # # ]: 0 : ereport(ERROR,
8232 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8233 : : errmsg("cannot alter system column \"%s\"",
8234 : : colName)));
8235 : :
8236 [ + + ]: 367 : if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
8237 [ + - - + ]: 12 : ereport(ERROR,
8238 : : (errcode(ERRCODE_SYNTAX_ERROR),
8239 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
8240 : : colName, RelationGetRelationName(rel)),
8241 : : /* translator: %s is an SQL ALTER command */
8242 : : newDefault ? 0 : errhint("Use %s instead.",
8243 : : "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
8244 : :
8245 [ + + ]: 355 : if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
8246 [ + - - + : 8 : ereport(ERROR,
+ + ]
8247 : : (errcode(ERRCODE_SYNTAX_ERROR),
8248 : : errmsg("column \"%s\" of relation \"%s\" is a generated column",
8249 : : colName, RelationGetRelationName(rel)),
8250 : : newDefault ?
8251 : : /* translator: %s is an SQL ALTER command */
8252 : : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
8253 : : (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
8254 : : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
8255 : :
8256 : : /*
8257 : : * Remove any old default for the column. We use RESTRICT here for
8258 : : * safety, but at present we do not expect anything to depend on the
8259 : : * default.
8260 : : *
8261 : : * We treat removing the existing default as an internal operation when it
8262 : : * is preparatory to adding a new default, but as a user-initiated
8263 : : * operation when the user asked for a drop.
8264 : : */
8265 : 347 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8266 : : newDefault != NULL);
8267 : :
8268 [ + + ]: 347 : if (newDefault)
8269 : : {
8270 : : /* SET DEFAULT */
8271 : : RawColumnDefault *rawEnt;
8272 : :
8273 : 231 : rawEnt = palloc_object(RawColumnDefault);
8274 : 231 : rawEnt->attnum = attnum;
8275 : 231 : rawEnt->raw_default = newDefault;
8276 : 231 : rawEnt->generated = '\0';
8277 : :
8278 : : /*
8279 : : * This function is intended for CREATE TABLE, so it processes a
8280 : : * _list_ of defaults, but we just do one.
8281 : : */
8282 : 231 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8283 : : false, true, false, NULL);
8284 : : }
8285 : :
8286 : 339 : ObjectAddressSubSet(address, RelationRelationId,
8287 : : RelationGetRelid(rel), attnum);
8288 : 339 : return address;
8289 : : }
8290 : :
8291 : : /*
8292 : : * Add a pre-cooked default expression.
8293 : : *
8294 : : * Return the address of the affected column.
8295 : : */
8296 : : static ObjectAddress
8297 : 57 : ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
8298 : : Node *newDefault)
8299 : : {
8300 : : ObjectAddress address;
8301 : :
8302 : : /*
8303 : : * This is used for a cooked default copied by CREATE TABLE ... LIKE,
8304 : : * which adds new type dependencies. Such a default doesn't go through
8305 : : * AddRelationNewConstraints(), and StoreAttrDefault() leaves the
8306 : : * privilege checks to its caller, so we must check for USAGE on the types
8307 : : * here.
8308 : : */
8309 : 57 : CheckUsageOnTypesInSingleRelExpr(newDefault, RelationGetRelid(rel), GetUserId());
8310 : :
8311 : : /*
8312 : : * Remove any old default for the column. We use RESTRICT here for
8313 : : * safety, but at present we do not expect anything to depend on the
8314 : : * default. (In ordinary cases, there could not be a default in place
8315 : : * anyway, but it's possible when combining LIKE with inheritance.)
8316 : : */
8317 : 53 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8318 : : true);
8319 : :
8320 : 53 : (void) StoreAttrDefault(rel, attnum, newDefault, true);
8321 : :
8322 : 53 : ObjectAddressSubSet(address, RelationRelationId,
8323 : : RelationGetRelid(rel), attnum);
8324 : 53 : return address;
8325 : : }
8326 : :
8327 : : /*
8328 : : * ALTER TABLE ALTER COLUMN ADD IDENTITY
8329 : : *
8330 : : * Return the address of the affected column.
8331 : : */
8332 : : static ObjectAddress
8333 : 103 : ATExecAddIdentity(Relation rel, const char *colName,
8334 : : Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
8335 : : {
8336 : : Relation attrelation;
8337 : : HeapTuple tuple;
8338 : : Form_pg_attribute attTup;
8339 : : AttrNumber attnum;
8340 : : ObjectAddress address;
8341 : 103 : ColumnDef *cdef = castNode(ColumnDef, def);
8342 : : bool ispartitioned;
8343 : :
8344 : 103 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8345 [ + + + + ]: 103 : if (ispartitioned && !recurse)
8346 [ + - ]: 4 : ereport(ERROR,
8347 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8348 : : errmsg("cannot add identity to a column of only the partitioned table"),
8349 : : errhint("Do not specify the ONLY keyword.")));
8350 : :
8351 [ + + + + ]: 99 : if (rel->rd_rel->relispartition && !recursing)
8352 [ + - ]: 8 : ereport(ERROR,
8353 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8354 : : errmsg("cannot add identity to a column of a partition"));
8355 : :
8356 : 91 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8357 : :
8358 : 91 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8359 [ - + ]: 91 : if (!HeapTupleIsValid(tuple))
8360 [ # # ]: 0 : ereport(ERROR,
8361 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8362 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8363 : : colName, RelationGetRelationName(rel))));
8364 : 91 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8365 : 91 : attnum = attTup->attnum;
8366 : :
8367 : : /* Can't alter a system attribute */
8368 [ - + ]: 91 : if (attnum <= 0)
8369 [ # # ]: 0 : ereport(ERROR,
8370 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8371 : : errmsg("cannot alter system column \"%s\"",
8372 : : colName)));
8373 : :
8374 : : /*
8375 : : * Creating a column as identity implies NOT NULL, so adding the identity
8376 : : * to an existing column that is not NOT NULL would create a state that
8377 : : * cannot be reproduced without contortions.
8378 : : */
8379 [ + + ]: 91 : if (!attTup->attnotnull)
8380 [ + - ]: 4 : ereport(ERROR,
8381 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8382 : : errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
8383 : : colName, RelationGetRelationName(rel))));
8384 : :
8385 : : /*
8386 : : * On the other hand, if a not-null constraint exists, then verify that
8387 : : * it's compatible.
8388 : : */
8389 [ + - ]: 87 : if (attTup->attnotnull)
8390 : : {
8391 : : HeapTuple contup;
8392 : : Form_pg_constraint conForm;
8393 : :
8394 : 87 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel),
8395 : : attnum);
8396 [ - + ]: 87 : if (!HeapTupleIsValid(contup))
8397 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
8398 : : colName, RelationGetRelationName(rel));
8399 : :
8400 : 87 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
8401 [ + + ]: 87 : if (!conForm->convalidated)
8402 [ + - ]: 4 : ereport(ERROR,
8403 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8404 : : errmsg("incompatible NOT VALID constraint \"%s\" on relation \"%s\"",
8405 : : NameStr(conForm->conname), RelationGetRelationName(rel)),
8406 : : errhint("You might need to validate it using %s.",
8407 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
8408 : : }
8409 : :
8410 [ + + ]: 83 : if (attTup->attidentity)
8411 [ + - ]: 12 : ereport(ERROR,
8412 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8413 : : errmsg("column \"%s\" of relation \"%s\" is already an identity column",
8414 : : colName, RelationGetRelationName(rel))));
8415 : :
8416 [ + + ]: 71 : if (attTup->atthasdef)
8417 [ + - ]: 4 : ereport(ERROR,
8418 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8419 : : errmsg("column \"%s\" of relation \"%s\" already has a default value",
8420 : : colName, RelationGetRelationName(rel))));
8421 : :
8422 : 67 : attTup->attidentity = cdef->identity;
8423 : 67 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8424 : :
8425 [ - + ]: 67 : InvokeObjectPostAlterHook(RelationRelationId,
8426 : : RelationGetRelid(rel),
8427 : : attTup->attnum);
8428 : 67 : ObjectAddressSubSet(address, RelationRelationId,
8429 : : RelationGetRelid(rel), attnum);
8430 : 67 : heap_freetuple(tuple);
8431 : :
8432 : 67 : table_close(attrelation, RowExclusiveLock);
8433 : :
8434 : : /*
8435 : : * Recurse to propagate the identity column to partitions. Identity is
8436 : : * not inherited in regular inheritance children.
8437 : : */
8438 [ + - + + ]: 67 : if (recurse && ispartitioned)
8439 : : {
8440 : : List *children;
8441 : : ListCell *lc;
8442 : :
8443 : 6 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8444 : :
8445 [ + + + + : 10 : foreach(lc, children)
+ + ]
8446 : : {
8447 : : Relation childrel;
8448 : :
8449 : 4 : childrel = table_open(lfirst_oid(lc), NoLock);
8450 : 4 : ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
8451 : 4 : table_close(childrel, NoLock);
8452 : : }
8453 : : }
8454 : :
8455 : 67 : return address;
8456 : : }
8457 : :
8458 : : /*
8459 : : * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
8460 : : *
8461 : : * Return the address of the affected column.
8462 : : */
8463 : : static ObjectAddress
8464 : 49 : ATExecSetIdentity(Relation rel, const char *colName, Node *def,
8465 : : LOCKMODE lockmode, bool recurse, bool recursing)
8466 : : {
8467 : : ListCell *option;
8468 : 49 : DefElem *generatedEl = NULL;
8469 : : HeapTuple tuple;
8470 : : Form_pg_attribute attTup;
8471 : : AttrNumber attnum;
8472 : : Relation attrelation;
8473 : : ObjectAddress address;
8474 : : bool ispartitioned;
8475 : :
8476 : 49 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8477 [ + + + + ]: 49 : if (ispartitioned && !recurse)
8478 [ + - ]: 4 : ereport(ERROR,
8479 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8480 : : errmsg("cannot change identity column of only the partitioned table"),
8481 : : errhint("Do not specify the ONLY keyword.")));
8482 : :
8483 [ + + + + ]: 45 : if (rel->rd_rel->relispartition && !recursing)
8484 [ + - ]: 8 : ereport(ERROR,
8485 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8486 : : errmsg("cannot change identity column of a partition"));
8487 : :
8488 [ + + + + : 66 : foreach(option, castNode(List, def))
+ + ]
8489 : : {
8490 : 29 : DefElem *defel = lfirst_node(DefElem, option);
8491 : :
8492 [ + - ]: 29 : if (strcmp(defel->defname, "generated") == 0)
8493 : : {
8494 [ - + ]: 29 : if (generatedEl)
8495 [ # # ]: 0 : ereport(ERROR,
8496 : : (errcode(ERRCODE_SYNTAX_ERROR),
8497 : : errmsg("conflicting or redundant options")));
8498 : 29 : generatedEl = defel;
8499 : : }
8500 : : else
8501 [ # # ]: 0 : elog(ERROR, "option \"%s\" not recognized",
8502 : : defel->defname);
8503 : : }
8504 : :
8505 : : /*
8506 : : * Even if there is nothing to change here, we run all the checks. There
8507 : : * will be a subsequent ALTER SEQUENCE that relies on everything being
8508 : : * there.
8509 : : */
8510 : :
8511 : 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8512 : 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8513 [ - + ]: 37 : if (!HeapTupleIsValid(tuple))
8514 [ # # ]: 0 : ereport(ERROR,
8515 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8516 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8517 : : colName, RelationGetRelationName(rel))));
8518 : :
8519 : 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8520 : 37 : attnum = attTup->attnum;
8521 : :
8522 [ - + ]: 37 : if (attnum <= 0)
8523 [ # # ]: 0 : ereport(ERROR,
8524 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8525 : : errmsg("cannot alter system column \"%s\"",
8526 : : colName)));
8527 : :
8528 [ + + ]: 37 : if (!attTup->attidentity)
8529 [ + - ]: 4 : ereport(ERROR,
8530 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8531 : : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8532 : : colName, RelationGetRelationName(rel))));
8533 : :
8534 [ + + ]: 33 : if (generatedEl)
8535 : : {
8536 : 29 : attTup->attidentity = defGetInt32(generatedEl);
8537 : 29 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8538 : :
8539 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
8540 : : RelationGetRelid(rel),
8541 : : attTup->attnum);
8542 : 29 : ObjectAddressSubSet(address, RelationRelationId,
8543 : : RelationGetRelid(rel), attnum);
8544 : : }
8545 : : else
8546 : 4 : address = InvalidObjectAddress;
8547 : :
8548 : 33 : heap_freetuple(tuple);
8549 : 33 : table_close(attrelation, RowExclusiveLock);
8550 : :
8551 : : /*
8552 : : * Recurse to propagate the identity change to partitions. Identity is not
8553 : : * inherited in regular inheritance children.
8554 : : */
8555 [ + + + - : 33 : if (generatedEl && recurse && ispartitioned)
+ + ]
8556 : : {
8557 : : List *children;
8558 : : ListCell *lc;
8559 : :
8560 : 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8561 : :
8562 [ + - + + : 12 : foreach(lc, children)
+ + ]
8563 : : {
8564 : : Relation childrel;
8565 : :
8566 : 8 : childrel = table_open(lfirst_oid(lc), NoLock);
8567 : 8 : ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
8568 : 8 : table_close(childrel, NoLock);
8569 : : }
8570 : : }
8571 : :
8572 : 33 : return address;
8573 : : }
8574 : :
8575 : : /*
8576 : : * ALTER TABLE ALTER COLUMN DROP IDENTITY
8577 : : *
8578 : : * Return the address of the affected column.
8579 : : */
8580 : : static ObjectAddress
8581 : 45 : ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
8582 : : bool recurse, bool recursing)
8583 : : {
8584 : : HeapTuple tuple;
8585 : : Form_pg_attribute attTup;
8586 : : AttrNumber attnum;
8587 : : Relation attrelation;
8588 : : ObjectAddress address;
8589 : : Oid seqid;
8590 : : ObjectAddress seqaddress;
8591 : : bool ispartitioned;
8592 : :
8593 : 45 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8594 [ + + + + ]: 45 : if (ispartitioned && !recurse)
8595 [ + - ]: 4 : ereport(ERROR,
8596 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8597 : : errmsg("cannot drop identity from a column of only the partitioned table"),
8598 : : errhint("Do not specify the ONLY keyword.")));
8599 : :
8600 [ + + + + ]: 41 : if (rel->rd_rel->relispartition && !recursing)
8601 [ + - ]: 4 : ereport(ERROR,
8602 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8603 : : errmsg("cannot drop identity from a column of a partition"));
8604 : :
8605 : 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8606 : 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8607 [ - + ]: 37 : if (!HeapTupleIsValid(tuple))
8608 [ # # ]: 0 : ereport(ERROR,
8609 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8610 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8611 : : colName, RelationGetRelationName(rel))));
8612 : :
8613 : 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8614 : 37 : attnum = attTup->attnum;
8615 : :
8616 [ - + ]: 37 : if (attnum <= 0)
8617 [ # # ]: 0 : ereport(ERROR,
8618 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8619 : : errmsg("cannot alter system column \"%s\"",
8620 : : colName)));
8621 : :
8622 [ + + ]: 37 : if (!attTup->attidentity)
8623 : : {
8624 [ + + ]: 8 : if (!missing_ok)
8625 [ + - ]: 4 : ereport(ERROR,
8626 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8627 : : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8628 : : colName, RelationGetRelationName(rel))));
8629 : : else
8630 : : {
8631 [ + - ]: 4 : ereport(NOTICE,
8632 : : (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
8633 : : colName, RelationGetRelationName(rel))));
8634 : 4 : heap_freetuple(tuple);
8635 : 4 : table_close(attrelation, RowExclusiveLock);
8636 : 4 : return InvalidObjectAddress;
8637 : : }
8638 : : }
8639 : :
8640 : 29 : attTup->attidentity = '\0';
8641 : 29 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8642 : :
8643 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
8644 : : RelationGetRelid(rel),
8645 : : attTup->attnum);
8646 : 29 : ObjectAddressSubSet(address, RelationRelationId,
8647 : : RelationGetRelid(rel), attnum);
8648 : 29 : heap_freetuple(tuple);
8649 : :
8650 : 29 : table_close(attrelation, RowExclusiveLock);
8651 : :
8652 : : /*
8653 : : * Recurse to drop the identity from column in partitions. Identity is
8654 : : * not inherited in regular inheritance children so ignore them.
8655 : : */
8656 [ + - + + ]: 29 : if (recurse && ispartitioned)
8657 : : {
8658 : : List *children;
8659 : : ListCell *lc;
8660 : :
8661 : 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8662 : :
8663 [ + - + + : 8 : foreach(lc, children)
+ + ]
8664 : : {
8665 : : Relation childrel;
8666 : :
8667 : 4 : childrel = table_open(lfirst_oid(lc), NoLock);
8668 : 4 : ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
8669 : 4 : table_close(childrel, NoLock);
8670 : : }
8671 : : }
8672 : :
8673 [ + + ]: 29 : if (!recursing)
8674 : : {
8675 : : /* drop the internal sequence */
8676 : 21 : seqid = getIdentitySequence(rel, attnum, false);
8677 : 21 : deleteDependencyRecordsForClass(RelationRelationId, seqid,
8678 : : RelationRelationId, DEPENDENCY_INTERNAL);
8679 : 21 : CommandCounterIncrement();
8680 : 21 : seqaddress.classId = RelationRelationId;
8681 : 21 : seqaddress.objectId = seqid;
8682 : 21 : seqaddress.objectSubId = 0;
8683 : 21 : performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8684 : : }
8685 : :
8686 : 29 : return address;
8687 : : }
8688 : :
8689 : : /*
8690 : : * ALTER TABLE ALTER COLUMN SET EXPRESSION
8691 : : *
8692 : : * Return the address of the affected column.
8693 : : */
8694 : : static ObjectAddress
8695 : 193 : ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
8696 : : Node *newExpr, LOCKMODE lockmode)
8697 : : {
8698 : : HeapTuple tuple;
8699 : : Form_pg_attribute attTup;
8700 : : AttrNumber attnum;
8701 : : char attgenerated;
8702 : : bool rewrite;
8703 : : Oid attrdefoid;
8704 : : ObjectAddress address;
8705 : : Expr *defval;
8706 : : NewColumnValue *newval;
8707 : : RawColumnDefault *rawEnt;
8708 : :
8709 : 193 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8710 [ - + ]: 193 : if (!HeapTupleIsValid(tuple))
8711 [ # # ]: 0 : ereport(ERROR,
8712 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8713 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8714 : : colName, RelationGetRelationName(rel))));
8715 : :
8716 : 193 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8717 : :
8718 : 193 : attnum = attTup->attnum;
8719 [ - + ]: 193 : if (attnum <= 0)
8720 [ # # ]: 0 : ereport(ERROR,
8721 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8722 : : errmsg("cannot alter system column \"%s\"",
8723 : : colName)));
8724 : :
8725 : 193 : attgenerated = attTup->attgenerated;
8726 [ + + ]: 193 : if (!attgenerated)
8727 [ + - ]: 8 : ereport(ERROR,
8728 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8729 : : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8730 : : colName, RelationGetRelationName(rel))));
8731 : :
8732 [ + + + + ]: 185 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
8733 : 16 : tab->verify_new_notnull = true;
8734 : :
8735 : : /*
8736 : : * We need to prevent this because a change of expression could affect a
8737 : : * row filter and inject expressions that are not permitted in a row
8738 : : * filter. XXX We could try to have a more precise check to catch only
8739 : : * publications with row filters, or even re-verify the row filter
8740 : : * expressions.
8741 : : */
8742 [ + + + + ]: 273 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
8743 : 88 : GetRelationIncludedPublications(RelationGetRelid(rel)) != NIL)
8744 [ + - ]: 4 : ereport(ERROR,
8745 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8746 : : errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
8747 : : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8748 : : colName, RelationGetRelationName(rel))));
8749 : :
8750 : 181 : rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
8751 : :
8752 : 181 : ReleaseSysCache(tuple);
8753 : :
8754 [ + + ]: 181 : if (rewrite)
8755 : : {
8756 : : /*
8757 : : * Clear all the missing values if we're rewriting the table, since
8758 : : * this renders them pointless.
8759 : : */
8760 : 97 : RelationClearMissing(rel);
8761 : :
8762 : : /* make sure we don't conflict with later attribute modifications */
8763 : 97 : CommandCounterIncrement();
8764 : : }
8765 : :
8766 : : /*
8767 : : * Find everything that depends on the column (constraints, indexes, etc),
8768 : : * and record enough information to let us recreate the objects.
8769 : : */
8770 : 181 : RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
8771 : :
8772 : : /*
8773 : : * Find whole-row referenced objects that depend on the column
8774 : : * (constraints, indexes, etc.), and record enough information to let us
8775 : : * recreate the objects.
8776 : : */
8777 : 181 : RememberWholeRowDependentForRebuilding(tab, AT_SetExpression, rel);
8778 : :
8779 : : /*
8780 : : * Drop the dependency records of the GENERATED expression, in particular
8781 : : * its INTERNAL dependency on the column, which would otherwise cause
8782 : : * dependency.c to refuse to perform the deletion.
8783 : : */
8784 : 181 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8785 [ - + ]: 181 : if (!OidIsValid(attrdefoid))
8786 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8787 : : RelationGetRelid(rel), attnum);
8788 : 181 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8789 : :
8790 : : /* Make above changes visible */
8791 : 181 : CommandCounterIncrement();
8792 : :
8793 : : /*
8794 : : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8795 : : * safety, but at present we do not expect anything to depend on the
8796 : : * expression.
8797 : : */
8798 : 181 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8799 : : false, false);
8800 : :
8801 : : /* Prepare to store the new expression, in the catalogs */
8802 : 181 : rawEnt = palloc_object(RawColumnDefault);
8803 : 181 : rawEnt->attnum = attnum;
8804 : 181 : rawEnt->raw_default = newExpr;
8805 : 181 : rawEnt->generated = attgenerated;
8806 : :
8807 : : /* Store the generated expression */
8808 : 181 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8809 : : false, true, false, NULL);
8810 : :
8811 : : /* Make above new expression visible */
8812 : 181 : CommandCounterIncrement();
8813 : :
8814 [ + + ]: 181 : if (rewrite)
8815 : : {
8816 : : /* Prepare for table rewrite */
8817 : 97 : defval = (Expr *) build_column_default(rel, attnum);
8818 : :
8819 : 97 : newval = palloc0_object(NewColumnValue);
8820 : 97 : newval->attnum = attnum;
8821 : 97 : newval->expr = expression_planner(defval);
8822 : 97 : newval->is_generated = true;
8823 : :
8824 : 97 : tab->newvals = lappend(tab->newvals, newval);
8825 : 97 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
8826 : : }
8827 : :
8828 : : /* Drop any pg_statistic entry for the column */
8829 : 181 : RemoveStatistics(RelationGetRelid(rel), attnum);
8830 : :
8831 [ - + ]: 181 : InvokeObjectPostAlterHook(RelationRelationId,
8832 : : RelationGetRelid(rel), attnum);
8833 : :
8834 : 181 : ObjectAddressSubSet(address, RelationRelationId,
8835 : : RelationGetRelid(rel), attnum);
8836 : 181 : return address;
8837 : : }
8838 : :
8839 : : /*
8840 : : * ALTER TABLE ALTER COLUMN DROP EXPRESSION
8841 : : */
8842 : : static void
8843 : 93 : ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
8844 : : {
8845 : : /*
8846 : : * Reject ONLY if there are child tables -- but only, of course, at the
8847 : : * top of the tree, otherwise it'd be impossible to run this command with
8848 : : * trees deeper than two levels. Caller already got lock.
8849 : : */
8850 [ + + + + : 105 : if (!recurse && !recursing &&
+ - ]
8851 : 12 : find_inheritance_children(RelationGetRelid(rel), NoLock))
8852 [ + - ]: 12 : ereport(ERROR,
8853 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8854 : : errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
8855 : :
8856 : : /*
8857 : : * Cannot drop generation expression from inherited columns.
8858 : : */
8859 [ + + ]: 81 : if (!recursing)
8860 : : {
8861 : : HeapTuple tuple;
8862 : : Form_pg_attribute attTup;
8863 : :
8864 : 53 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
8865 [ - + ]: 53 : if (!HeapTupleIsValid(tuple))
8866 [ # # ]: 0 : ereport(ERROR,
8867 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8868 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8869 : : cmd->name, RelationGetRelationName(rel))));
8870 : :
8871 : 53 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8872 : :
8873 [ + + ]: 53 : if (attTup->attinhcount > 0)
8874 [ + - ]: 12 : ereport(ERROR,
8875 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8876 : : errmsg("cannot drop generation expression from inherited column")));
8877 : : }
8878 : 69 : }
8879 : :
8880 : : /*
8881 : : * Return the address of the affected column.
8882 : : */
8883 : : static ObjectAddress
8884 : 61 : ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
8885 : : {
8886 : : HeapTuple tuple;
8887 : : Form_pg_attribute attTup;
8888 : : AttrNumber attnum;
8889 : : Relation attrelation;
8890 : : Oid attrdefoid;
8891 : : ObjectAddress address;
8892 : :
8893 : 61 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8894 : 61 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8895 [ - + ]: 61 : if (!HeapTupleIsValid(tuple))
8896 [ # # ]: 0 : ereport(ERROR,
8897 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8898 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8899 : : colName, RelationGetRelationName(rel))));
8900 : :
8901 : 61 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8902 : 61 : attnum = attTup->attnum;
8903 : :
8904 [ - + ]: 61 : if (attnum <= 0)
8905 [ # # ]: 0 : ereport(ERROR,
8906 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8907 : : errmsg("cannot alter system column \"%s\"",
8908 : : colName)));
8909 : :
8910 : : /*
8911 : : * TODO: This could be done, but it would need a table rewrite to
8912 : : * materialize the generated values. Note that for the time being, we
8913 : : * still error with missing_ok, so that we don't silently leave the column
8914 : : * as generated.
8915 : : */
8916 [ + + ]: 61 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
8917 [ + - ]: 8 : ereport(ERROR,
8918 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8919 : : errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
8920 : : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8921 : : colName, RelationGetRelationName(rel))));
8922 : :
8923 [ + + ]: 53 : if (!attTup->attgenerated)
8924 : : {
8925 [ + + ]: 16 : if (!missing_ok)
8926 [ + - ]: 8 : ereport(ERROR,
8927 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8928 : : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8929 : : colName, RelationGetRelationName(rel))));
8930 : : else
8931 : : {
8932 [ + - ]: 8 : ereport(NOTICE,
8933 : : (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
8934 : : colName, RelationGetRelationName(rel))));
8935 : 8 : heap_freetuple(tuple);
8936 : 8 : table_close(attrelation, RowExclusiveLock);
8937 : 8 : return InvalidObjectAddress;
8938 : : }
8939 : : }
8940 : :
8941 : : /*
8942 : : * Mark the column as no longer generated. (The atthasdef flag needs to
8943 : : * get cleared too, but RemoveAttrDefault will handle that.)
8944 : : */
8945 : 37 : attTup->attgenerated = '\0';
8946 : 37 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8947 : :
8948 [ - + ]: 37 : InvokeObjectPostAlterHook(RelationRelationId,
8949 : : RelationGetRelid(rel),
8950 : : attnum);
8951 : 37 : heap_freetuple(tuple);
8952 : :
8953 : 37 : table_close(attrelation, RowExclusiveLock);
8954 : :
8955 : : /*
8956 : : * Drop the dependency records of the GENERATED expression, in particular
8957 : : * its INTERNAL dependency on the column, which would otherwise cause
8958 : : * dependency.c to refuse to perform the deletion.
8959 : : */
8960 : 37 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8961 [ - + ]: 37 : if (!OidIsValid(attrdefoid))
8962 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8963 : : RelationGetRelid(rel), attnum);
8964 : 37 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8965 : :
8966 : : /* Make above changes visible */
8967 : 37 : CommandCounterIncrement();
8968 : :
8969 : : /*
8970 : : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8971 : : * safety, but at present we do not expect anything to depend on the
8972 : : * default.
8973 : : */
8974 : 37 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8975 : : false, false);
8976 : :
8977 : 37 : ObjectAddressSubSet(address, RelationRelationId,
8978 : : RelationGetRelid(rel), attnum);
8979 : 37 : return address;
8980 : : }
8981 : :
8982 : : /*
8983 : : * ALTER TABLE ALTER COLUMN SET STATISTICS
8984 : : *
8985 : : * Return value is the address of the modified column
8986 : : */
8987 : : static ObjectAddress
8988 : 113 : ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
8989 : : {
8990 : 113 : int newtarget = 0;
8991 : : bool newtarget_default;
8992 : : Relation attrelation;
8993 : : HeapTuple tuple,
8994 : : newtuple;
8995 : : Form_pg_attribute attrtuple;
8996 : : AttrNumber attnum;
8997 : : ObjectAddress address;
8998 : : Datum repl_val[Natts_pg_attribute];
8999 : : bool repl_null[Natts_pg_attribute];
9000 : : bool repl_repl[Natts_pg_attribute];
9001 : :
9002 : : /*
9003 : : * We allow referencing columns by numbers only for indexes, since table
9004 : : * column numbers could contain gaps if columns are later dropped.
9005 : : */
9006 [ + + ]: 113 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
9007 [ + - - + ]: 69 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
9008 : : !colName)
9009 [ # # ]: 0 : ereport(ERROR,
9010 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9011 : : errmsg("cannot refer to non-index column by number")));
9012 : :
9013 : : /* -1 was used in previous versions for the default setting */
9014 [ + + + + ]: 113 : if (newValue && intVal(newValue) != -1)
9015 : : {
9016 : 82 : newtarget = intVal(newValue);
9017 : 82 : newtarget_default = false;
9018 : : }
9019 : : else
9020 : 31 : newtarget_default = true;
9021 : :
9022 [ + + ]: 113 : if (!newtarget_default)
9023 : : {
9024 : : /*
9025 : : * Limit target to a sane range
9026 : : */
9027 [ - + ]: 82 : if (newtarget < 0)
9028 : : {
9029 [ # # ]: 0 : ereport(ERROR,
9030 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9031 : : errmsg("statistics target %d is too low",
9032 : : newtarget)));
9033 : : }
9034 [ - + ]: 82 : else if (newtarget > MAX_STATISTICS_TARGET)
9035 : : {
9036 : 0 : newtarget = MAX_STATISTICS_TARGET;
9037 [ # # ]: 0 : ereport(WARNING,
9038 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9039 : : errmsg("lowering statistics target to %d",
9040 : : newtarget)));
9041 : : }
9042 : : }
9043 : :
9044 : 113 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9045 : :
9046 [ + + ]: 113 : if (colName)
9047 : : {
9048 : 69 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9049 : :
9050 [ + + ]: 69 : if (!HeapTupleIsValid(tuple))
9051 [ + - ]: 8 : ereport(ERROR,
9052 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9053 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9054 : : colName, RelationGetRelationName(rel))));
9055 : : }
9056 : : else
9057 : : {
9058 : 44 : tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
9059 : :
9060 [ + + ]: 44 : if (!HeapTupleIsValid(tuple))
9061 [ + - ]: 8 : ereport(ERROR,
9062 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9063 : : errmsg("column number %d of relation \"%s\" does not exist",
9064 : : colNum, RelationGetRelationName(rel))));
9065 : : }
9066 : :
9067 : 97 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9068 : :
9069 : 97 : attnum = attrtuple->attnum;
9070 [ - + ]: 97 : if (attnum <= 0)
9071 [ # # ]: 0 : ereport(ERROR,
9072 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9073 : : errmsg("cannot alter system column \"%s\"",
9074 : : colName)));
9075 : :
9076 : : /*
9077 : : * Prevent this as long as the ANALYZE code skips virtual generated
9078 : : * columns.
9079 : : */
9080 [ - + ]: 97 : if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
9081 [ # # ]: 0 : ereport(ERROR,
9082 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9083 : : errmsg("cannot alter statistics on virtual generated column \"%s\"",
9084 : : colName)));
9085 : :
9086 [ + + ]: 97 : if (rel->rd_rel->relkind == RELKIND_INDEX ||
9087 [ - + ]: 61 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
9088 : : {
9089 [ + + ]: 36 : if (attnum > rel->rd_index->indnkeyatts)
9090 [ + - ]: 4 : ereport(ERROR,
9091 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9092 : : errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
9093 : : NameStr(attrtuple->attname), RelationGetRelationName(rel))));
9094 [ + + ]: 32 : else if (rel->rd_index->indkey.values[attnum - 1] != 0)
9095 [ + - ]: 12 : ereport(ERROR,
9096 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9097 : : errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
9098 : : NameStr(attrtuple->attname), RelationGetRelationName(rel)),
9099 : : errhint("Alter statistics on table column instead.")));
9100 : : }
9101 : :
9102 : : /* Build new tuple. */
9103 : 81 : memset(repl_null, false, sizeof(repl_null));
9104 : 81 : memset(repl_repl, false, sizeof(repl_repl));
9105 [ + + ]: 81 : if (!newtarget_default)
9106 : 50 : repl_val[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(newtarget);
9107 : : else
9108 : 31 : repl_null[Anum_pg_attribute_attstattarget - 1] = true;
9109 : 81 : repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
9110 : 81 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9111 : : repl_val, repl_null, repl_repl);
9112 : 81 : CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
9113 : :
9114 [ - + ]: 81 : InvokeObjectPostAlterHook(RelationRelationId,
9115 : : RelationGetRelid(rel),
9116 : : attrtuple->attnum);
9117 : 81 : ObjectAddressSubSet(address, RelationRelationId,
9118 : : RelationGetRelid(rel), attnum);
9119 : :
9120 : 81 : heap_freetuple(newtuple);
9121 : :
9122 : 81 : ReleaseSysCache(tuple);
9123 : :
9124 : 81 : table_close(attrelation, RowExclusiveLock);
9125 : :
9126 : 81 : return address;
9127 : : }
9128 : :
9129 : : /*
9130 : : * Return value is the address of the modified column
9131 : : */
9132 : : static ObjectAddress
9133 : 21 : ATExecSetOptions(Relation rel, const char *colName, Node *options,
9134 : : bool isReset, LOCKMODE lockmode)
9135 : : {
9136 : : Relation attrelation;
9137 : : HeapTuple tuple,
9138 : : newtuple;
9139 : : Form_pg_attribute attrtuple;
9140 : : AttrNumber attnum;
9141 : : Datum datum,
9142 : : newOptions;
9143 : : bool isnull;
9144 : : ObjectAddress address;
9145 : : Datum repl_val[Natts_pg_attribute];
9146 : : bool repl_null[Natts_pg_attribute];
9147 : : bool repl_repl[Natts_pg_attribute];
9148 : :
9149 : 21 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9150 : :
9151 : 21 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9152 : :
9153 [ - + ]: 21 : if (!HeapTupleIsValid(tuple))
9154 [ # # ]: 0 : ereport(ERROR,
9155 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9156 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9157 : : colName, RelationGetRelationName(rel))));
9158 : 21 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9159 : :
9160 : 21 : attnum = attrtuple->attnum;
9161 [ - + ]: 21 : if (attnum <= 0)
9162 [ # # ]: 0 : ereport(ERROR,
9163 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9164 : : errmsg("cannot alter system column \"%s\"",
9165 : : colName)));
9166 : :
9167 : : /* Generate new proposed attoptions (text array) */
9168 : 21 : datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
9169 : : &isnull);
9170 [ + + ]: 21 : newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9171 : : castNode(List, options), NULL, NULL,
9172 : : false, isReset);
9173 : : /* Validate new options */
9174 : 21 : (void) attribute_reloptions(newOptions, true);
9175 : :
9176 : : /* Build new tuple. */
9177 : 21 : memset(repl_null, false, sizeof(repl_null));
9178 : 21 : memset(repl_repl, false, sizeof(repl_repl));
9179 [ + - ]: 21 : if (newOptions != (Datum) 0)
9180 : 21 : repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
9181 : : else
9182 : 0 : repl_null[Anum_pg_attribute_attoptions - 1] = true;
9183 : 21 : repl_repl[Anum_pg_attribute_attoptions - 1] = true;
9184 : 21 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9185 : : repl_val, repl_null, repl_repl);
9186 : :
9187 : : /* Update system catalog. */
9188 : 21 : CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
9189 : :
9190 [ - + ]: 21 : InvokeObjectPostAlterHook(RelationRelationId,
9191 : : RelationGetRelid(rel),
9192 : : attrtuple->attnum);
9193 : 21 : ObjectAddressSubSet(address, RelationRelationId,
9194 : : RelationGetRelid(rel), attnum);
9195 : :
9196 : 21 : heap_freetuple(newtuple);
9197 : :
9198 : 21 : ReleaseSysCache(tuple);
9199 : :
9200 : 21 : table_close(attrelation, RowExclusiveLock);
9201 : :
9202 : 21 : return address;
9203 : : }
9204 : :
9205 : : /*
9206 : : * Helper function for ATExecSetStorage and ATExecSetCompression
9207 : : *
9208 : : * Set the attstorage and/or attcompression fields for index columns
9209 : : * associated with the specified table column.
9210 : : */
9211 : : static void
9212 : 272 : SetIndexStorageProperties(Relation rel, Relation attrelation,
9213 : : AttrNumber attnum,
9214 : : bool setstorage, char newstorage,
9215 : : bool setcompression, char newcompression,
9216 : : LOCKMODE lockmode)
9217 : : {
9218 : : ListCell *lc;
9219 : :
9220 [ + + + + : 335 : foreach(lc, RelationGetIndexList(rel))
+ + ]
9221 : : {
9222 : 63 : Oid indexoid = lfirst_oid(lc);
9223 : : Relation indrel;
9224 : 63 : AttrNumber indattnum = 0;
9225 : : HeapTuple tuple;
9226 : :
9227 : 63 : indrel = index_open(indexoid, lockmode);
9228 : :
9229 [ + + ]: 107 : for (int i = 0; i < indrel->rd_index->indnatts; i++)
9230 : : {
9231 [ + + ]: 67 : if (indrel->rd_index->indkey.values[i] == attnum)
9232 : : {
9233 : 23 : indattnum = i + 1;
9234 : 23 : break;
9235 : : }
9236 : : }
9237 : :
9238 [ + + ]: 63 : if (indattnum == 0)
9239 : : {
9240 : 40 : index_close(indrel, lockmode);
9241 : 40 : continue;
9242 : : }
9243 : :
9244 : 23 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
9245 : :
9246 [ + - ]: 23 : if (HeapTupleIsValid(tuple))
9247 : : {
9248 : 23 : Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9249 : :
9250 [ + + ]: 23 : if (setstorage)
9251 : 15 : attrtuple->attstorage = newstorage;
9252 : :
9253 [ + + ]: 23 : if (setcompression)
9254 : 8 : attrtuple->attcompression = newcompression;
9255 : :
9256 : 23 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9257 : :
9258 [ - + ]: 23 : InvokeObjectPostAlterHook(RelationRelationId,
9259 : : RelationGetRelid(rel),
9260 : : attrtuple->attnum);
9261 : :
9262 : 23 : heap_freetuple(tuple);
9263 : : }
9264 : :
9265 : 23 : index_close(indrel, lockmode);
9266 : : }
9267 : 272 : }
9268 : :
9269 : : /*
9270 : : * ALTER TABLE ALTER COLUMN SET STORAGE
9271 : : *
9272 : : * Return value is the address of the modified column
9273 : : */
9274 : : static ObjectAddress
9275 : 235 : ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
9276 : : {
9277 : : Relation attrelation;
9278 : : HeapTuple tuple;
9279 : : Form_pg_attribute attrtuple;
9280 : : AttrNumber attnum;
9281 : : ObjectAddress address;
9282 : :
9283 : 235 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9284 : :
9285 : 235 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9286 : :
9287 [ + + ]: 235 : if (!HeapTupleIsValid(tuple))
9288 [ + - ]: 8 : ereport(ERROR,
9289 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9290 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9291 : : colName, RelationGetRelationName(rel))));
9292 : 227 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9293 : :
9294 : 227 : attnum = attrtuple->attnum;
9295 [ - + ]: 227 : if (attnum <= 0)
9296 [ # # ]: 0 : ereport(ERROR,
9297 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9298 : : errmsg("cannot alter system column \"%s\"",
9299 : : colName)));
9300 : :
9301 : 227 : attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
9302 : :
9303 : 227 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9304 : :
9305 [ - + ]: 227 : InvokeObjectPostAlterHook(RelationRelationId,
9306 : : RelationGetRelid(rel),
9307 : : attrtuple->attnum);
9308 : :
9309 : : /*
9310 : : * Apply the change to indexes as well (only for simple index columns,
9311 : : * matching behavior of index.c ConstructTupleDescriptor()).
9312 : : */
9313 : 227 : SetIndexStorageProperties(rel, attrelation, attnum,
9314 : 227 : true, attrtuple->attstorage,
9315 : : false, 0,
9316 : : lockmode);
9317 : :
9318 : 227 : heap_freetuple(tuple);
9319 : :
9320 : 227 : table_close(attrelation, RowExclusiveLock);
9321 : :
9322 : 227 : ObjectAddressSubSet(address, RelationRelationId,
9323 : : RelationGetRelid(rel), attnum);
9324 : 227 : return address;
9325 : : }
9326 : :
9327 : :
9328 : : /*
9329 : : * ALTER TABLE DROP COLUMN
9330 : : *
9331 : : * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
9332 : : * because we have to decide at runtime whether to recurse or not depending
9333 : : * on whether attinhcount goes to zero or not. (We can't check this in a
9334 : : * static pre-pass because it won't handle multiple inheritance situations
9335 : : * correctly.)
9336 : : */
9337 : : static void
9338 : 1102 : ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
9339 : : AlterTableCmd *cmd, LOCKMODE lockmode,
9340 : : AlterTableUtilityContext *context)
9341 : : {
9342 [ + + + + ]: 1102 : if (rel->rd_rel->reloftype && !recursing)
9343 [ + - ]: 4 : ereport(ERROR,
9344 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9345 : : errmsg("cannot drop column from typed table")));
9346 : :
9347 [ + + ]: 1098 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
9348 : 54 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
9349 : :
9350 [ + + ]: 1094 : if (recurse)
9351 : 937 : cmd->recurse = true;
9352 : 1094 : }
9353 : :
9354 : : /*
9355 : : * Drops column 'colName' from relation 'rel' and returns the address of the
9356 : : * dropped column. The column is also dropped (or marked as no longer
9357 : : * inherited from relation) from the relation's inheritance children, if any.
9358 : : *
9359 : : * In the recursive invocations for inheritance child relations, instead of
9360 : : * dropping the column directly (if to be dropped at all), its object address
9361 : : * is added to 'addrs', which must be non-NULL in such invocations. All
9362 : : * columns are dropped at the same time after all the children have been
9363 : : * checked recursively.
9364 : : */
9365 : : static ObjectAddress
9366 : 1467 : ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
9367 : : DropBehavior behavior,
9368 : : bool recurse, bool recursing,
9369 : : bool missing_ok, LOCKMODE lockmode,
9370 : : ObjectAddresses *addrs)
9371 : : {
9372 : : HeapTuple tuple;
9373 : : Form_pg_attribute targetatt;
9374 : : AttrNumber attnum;
9375 : : List *children;
9376 : : ObjectAddress object;
9377 : : bool is_expr;
9378 : :
9379 : : /* At top level, permission check was done in ATPrepCmd, else do it */
9380 [ + + ]: 1467 : if (recursing)
9381 : 373 : ATSimplePermissions(AT_DropColumn, rel,
9382 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9383 : :
9384 : : /* Initialize addrs on the first invocation */
9385 : : Assert(!recursing || addrs != NULL);
9386 : :
9387 : : /* since this function recurses, it could be driven to stack overflow */
9388 : 1467 : check_stack_depth();
9389 : :
9390 [ + + ]: 1467 : if (!recursing)
9391 : 1094 : addrs = new_object_addresses();
9392 : :
9393 : : /*
9394 : : * get the number of the attribute
9395 : : */
9396 : 1467 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9397 [ + + ]: 1467 : if (!HeapTupleIsValid(tuple))
9398 : : {
9399 [ + + ]: 40 : if (!missing_ok)
9400 : : {
9401 [ + - ]: 24 : ereport(ERROR,
9402 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9403 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9404 : : colName, RelationGetRelationName(rel))));
9405 : : }
9406 : : else
9407 : : {
9408 [ + - ]: 16 : ereport(NOTICE,
9409 : : (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
9410 : : colName, RelationGetRelationName(rel))));
9411 : 16 : return InvalidObjectAddress;
9412 : : }
9413 : : }
9414 : 1427 : targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
9415 : :
9416 : 1427 : attnum = targetatt->attnum;
9417 : :
9418 : : /* Can't drop a system attribute */
9419 [ + + ]: 1427 : if (attnum <= 0)
9420 [ + - ]: 4 : ereport(ERROR,
9421 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9422 : : errmsg("cannot drop system column \"%s\"",
9423 : : colName)));
9424 : :
9425 : : /*
9426 : : * Don't drop inherited columns, unless recursing (presumably from a drop
9427 : : * of the parent column)
9428 : : */
9429 [ + + + + ]: 1423 : if (targetatt->attinhcount > 0 && !recursing)
9430 [ + - ]: 32 : ereport(ERROR,
9431 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9432 : : errmsg("cannot drop inherited column \"%s\"",
9433 : : colName)));
9434 : :
9435 : : /*
9436 : : * Don't drop columns used in the partition key, either. (If we let this
9437 : : * go through, the key column's dependencies would cause a cascaded drop
9438 : : * of the whole table, which is surely not what the user expected.)
9439 : : */
9440 [ + + ]: 1391 : if (has_partition_attrs(rel,
9441 : : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
9442 : : &is_expr))
9443 [ + - ]: 20 : ereport(ERROR,
9444 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9445 : : errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
9446 : : colName, RelationGetRelationName(rel))));
9447 : :
9448 : 1371 : ReleaseSysCache(tuple);
9449 : :
9450 : : /*
9451 : : * Propagate to children as appropriate. Unlike most other ALTER
9452 : : * routines, we have to do this one level of recursion at a time; we can't
9453 : : * use find_all_inheritors to do it in one pass.
9454 : : */
9455 : : children =
9456 : 1371 : find_inheritance_children(RelationGetRelid(rel), lockmode);
9457 : :
9458 [ + + ]: 1371 : if (children)
9459 : : {
9460 : : Relation attr_rel;
9461 : : ListCell *child;
9462 : :
9463 : : /*
9464 : : * In case of a partitioned table, the column must be dropped from the
9465 : : * partitions as well.
9466 : : */
9467 [ + + + + ]: 204 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
9468 [ + - ]: 4 : ereport(ERROR,
9469 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9470 : : errmsg("cannot drop column from only the partitioned table when partitions exist"),
9471 : : errhint("Do not specify the ONLY keyword.")));
9472 : :
9473 : 200 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
9474 [ + - + + : 593 : foreach(child, children)
+ + ]
9475 : : {
9476 : 397 : Oid childrelid = lfirst_oid(child);
9477 : : Relation childrel;
9478 : : Form_pg_attribute childatt;
9479 : :
9480 : : /* find_inheritance_children already got lock */
9481 : 397 : childrel = table_open(childrelid, NoLock);
9482 : 397 : CheckAlterTableIsSafe(childrel);
9483 : :
9484 : 397 : tuple = SearchSysCacheCopyAttName(childrelid, colName);
9485 [ - + ]: 397 : if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
9486 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
9487 : : colName, childrelid);
9488 : 397 : childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9489 : :
9490 [ - + ]: 397 : if (childatt->attinhcount <= 0) /* shouldn't happen */
9491 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
9492 : : childrelid, colName);
9493 : :
9494 [ + + ]: 397 : if (recurse)
9495 : : {
9496 : : /*
9497 : : * If the child column has other definition sources, just
9498 : : * decrement its inheritance count; if not, recurse to delete
9499 : : * it.
9500 : : */
9501 [ + - + + ]: 381 : if (childatt->attinhcount == 1 && !childatt->attislocal)
9502 : : {
9503 : : /* Time to delete this child column, too */
9504 : 373 : ATExecDropColumn(wqueue, childrel, colName,
9505 : : behavior, true, true,
9506 : : false, lockmode, addrs);
9507 : : }
9508 : : else
9509 : : {
9510 : : /* Child column must survive my deletion */
9511 : 8 : childatt->attinhcount--;
9512 : :
9513 : 8 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9514 : :
9515 : : /* Make update visible */
9516 : 8 : CommandCounterIncrement();
9517 : : }
9518 : : }
9519 : : else
9520 : : {
9521 : : /*
9522 : : * If we were told to drop ONLY in this table (no recursion),
9523 : : * we need to mark the inheritors' attributes as locally
9524 : : * defined rather than inherited.
9525 : : */
9526 : 16 : childatt->attinhcount--;
9527 : 16 : childatt->attislocal = true;
9528 : :
9529 : 16 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9530 : :
9531 : : /* Make update visible */
9532 : 16 : CommandCounterIncrement();
9533 : : }
9534 : :
9535 : 393 : heap_freetuple(tuple);
9536 : :
9537 : 393 : table_close(childrel, NoLock);
9538 : : }
9539 : 196 : table_close(attr_rel, RowExclusiveLock);
9540 : : }
9541 : :
9542 : : /* Add object to delete */
9543 : 1363 : object.classId = RelationRelationId;
9544 : 1363 : object.objectId = RelationGetRelid(rel);
9545 : 1363 : object.objectSubId = attnum;
9546 : 1363 : add_exact_object_address(&object, addrs);
9547 : :
9548 [ + + ]: 1363 : if (!recursing)
9549 : : {
9550 : : /* Recursion has ended, drop everything that was collected */
9551 : 994 : performMultipleDeletions(addrs, behavior, 0);
9552 : 958 : free_object_addresses(addrs);
9553 : : }
9554 : :
9555 : 1327 : return object;
9556 : : }
9557 : :
9558 : : /*
9559 : : * Prepare to add a primary key on a table, by adding not-null constraints
9560 : : * on all columns.
9561 : : *
9562 : : * The not-null constraints for a primary key must cover the whole inheritance
9563 : : * hierarchy (failing to ensure that leads to funny corner cases). For the
9564 : : * normal case where we're asked to recurse, this routine checks if the
9565 : : * not-null constraints exist already, and if not queues a requirement for
9566 : : * them to be created in the AT_PASS_COL_ATTRS pass.
9567 : : *
9568 : : * For the case where we're asked not to recurse, we verify that a not-null
9569 : : * constraint exists on each column of each (direct) child table, throwing an
9570 : : * error if not. Not throwing an error would also work, because a not-null
9571 : : * constraint would be created anyway, but it'd cause a silent scan of the
9572 : : * child table to verify absence of nulls. We prefer to let the user know so
9573 : : * that they can add the constraint manually without having to hold
9574 : : * AccessExclusiveLock while at it.
9575 : : *
9576 : : * However, it's also important that we do not acquire locks on children if
9577 : : * the not-null constraints already exist on the parent, to avoid risking
9578 : : * deadlocks during parallel pg_restore of PKs on partitioned tables.
9579 : : */
9580 : : static void
9581 : 9738 : ATPrepAddPrimaryKey(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd,
9582 : : LOCKMODE lockmode)
9583 : : {
9584 : : Constraint *pkconstr;
9585 : 9738 : List *children = NIL;
9586 : 9738 : bool got_children = false;
9587 : :
9588 : 9738 : pkconstr = castNode(Constraint, cmd->def);
9589 : :
9590 : : /* USING INDEX queues its own NOT NULL constraints during transformation */
9591 [ + + + + ]: 9738 : if (pkconstr->contype != CONSTR_PRIMARY || pkconstr->indexname != NULL)
9592 : 9214 : return;
9593 : :
9594 : : /* Verify that columns are not-null, or request that they be made so */
9595 [ + - + + : 1650 : foreach_node(String, column, pkconstr->keys)
+ + ]
9596 : : {
9597 : : AlterTableCmd *newcmd;
9598 : : Constraint *nnconstr;
9599 : : HeapTuple tuple;
9600 : :
9601 : : /*
9602 : : * First check if a suitable constraint exists. If it does, we don't
9603 : : * need to request another one. We do need to bail out if it's not
9604 : : * valid, though.
9605 : : */
9606 : 642 : tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
9607 [ + + ]: 642 : if (tuple != NULL)
9608 : : {
9609 : 294 : verifyNotNullPKCompatible(tuple, strVal(column));
9610 : :
9611 : : /* All good with this one; don't request another */
9612 : 286 : heap_freetuple(tuple);
9613 : 286 : continue;
9614 : : }
9615 [ + + ]: 348 : else if (!cmd->recurse)
9616 : : {
9617 : : /*
9618 : : * No constraint on this column. Asked not to recurse, we won't
9619 : : * create one here, but verify that all children have one.
9620 : : */
9621 [ + - ]: 24 : if (!got_children)
9622 : : {
9623 : 24 : children = find_inheritance_children(RelationGetRelid(rel),
9624 : : lockmode);
9625 : : /* only search for children on the first time through */
9626 : 24 : got_children = true;
9627 : : }
9628 : :
9629 [ + - + + : 48 : foreach_oid(childrelid, children)
+ + ]
9630 : : {
9631 : : HeapTuple tup;
9632 : :
9633 : 24 : tup = findNotNullConstraint(childrelid, strVal(column));
9634 [ + + ]: 24 : if (!tup)
9635 [ + - ]: 4 : ereport(ERROR,
9636 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9637 : : errmsg("column \"%s\" of table \"%s\" is not marked NOT NULL",
9638 : : strVal(column), get_rel_name(childrelid)));
9639 : : /* verify it's good enough */
9640 : 20 : verifyNotNullPKCompatible(tup, strVal(column));
9641 : : }
9642 : : }
9643 : :
9644 : : /* This column is not already not-null, so add it to the queue */
9645 : 336 : nnconstr = makeNotNullConstraint(column);
9646 : :
9647 : 336 : newcmd = makeNode(AlterTableCmd);
9648 : 336 : newcmd->subtype = AT_AddConstraint;
9649 : : /* note we force recurse=true here; see above */
9650 : 336 : newcmd->recurse = true;
9651 : 336 : newcmd->def = (Node *) nnconstr;
9652 : :
9653 : 336 : tab->subcmds[AT_PASS_COL_ATTRS] =
9654 : 336 : lappend(tab->subcmds[AT_PASS_COL_ATTRS], newcmd);
9655 : : }
9656 : : }
9657 : :
9658 : : /*
9659 : : * Verify whether the given not-null constraint is compatible with a
9660 : : * primary key. If not, an error is thrown.
9661 : : */
9662 : : static void
9663 : 314 : verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
9664 : : {
9665 : 314 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
9666 : :
9667 [ - + ]: 314 : if (conForm->contype != CONSTRAINT_NOTNULL)
9668 [ # # ]: 0 : elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
9669 : :
9670 : : /* a NO INHERIT constraint is no good */
9671 [ + + ]: 314 : if (conForm->connoinherit)
9672 [ + - ]: 8 : ereport(ERROR,
9673 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9674 : : errmsg("cannot create primary key on column \"%s\"", colname),
9675 : : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9676 : : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9677 : : NameStr(conForm->conname), colname,
9678 : : get_rel_name(conForm->conrelid), "NO INHERIT"),
9679 : : errhint("You might need to make the existing constraint inheritable using %s.",
9680 : : "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
9681 : :
9682 : : /* an unvalidated constraint is no good */
9683 [ + + ]: 306 : if (!conForm->convalidated)
9684 [ + - ]: 8 : ereport(ERROR,
9685 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9686 : : errmsg("cannot create primary key on column \"%s\"", colname),
9687 : : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9688 : : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9689 : : NameStr(conForm->conname), colname,
9690 : : get_rel_name(conForm->conrelid), "NOT VALID"),
9691 : : errhint("You might need to validate it using %s.",
9692 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
9693 : 298 : }
9694 : :
9695 : : /*
9696 : : * ALTER TABLE ADD INDEX
9697 : : *
9698 : : * There is no such command in the grammar, but parse_utilcmd.c converts
9699 : : * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
9700 : : * us schedule creation of the index at the appropriate time during ALTER.
9701 : : *
9702 : : * Return value is the address of the new index.
9703 : : */
9704 : : static ObjectAddress
9705 : 1125 : ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
9706 : : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9707 : : {
9708 : : bool check_rights;
9709 : : bool skip_build;
9710 : : bool quiet;
9711 : : ObjectAddress address;
9712 : :
9713 : : Assert(IsA(stmt, IndexStmt));
9714 : : Assert(!stmt->concurrent);
9715 : :
9716 : : /* The IndexStmt has already been through transformIndexStmt */
9717 : : Assert(stmt->transformed);
9718 : :
9719 : : /* suppress schema rights check when rebuilding existing index */
9720 : 1125 : check_rights = !is_rebuild;
9721 : : /* skip index build if phase 3 will do it or we're reusing an old one */
9722 [ + + + + ]: 1125 : skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
9723 : : /* suppress notices when rebuilding existing index */
9724 : 1125 : quiet = is_rebuild;
9725 : :
9726 : 1125 : address = DefineIndex(NULL,
9727 : : RelationGetRelid(rel),
9728 : : stmt,
9729 : : InvalidOid, /* no predefined OID */
9730 : : InvalidOid, /* no parent index */
9731 : : InvalidOid, /* no parent constraint */
9732 : : -1, /* total_parts unknown */
9733 : : true, /* is_alter_table */
9734 : : check_rights,
9735 : : false, /* check_not_in_use - we did it already */
9736 : : skip_build,
9737 : : quiet);
9738 : :
9739 : : /*
9740 : : * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
9741 : : * new index instead of building from scratch. Restore associated fields.
9742 : : * This may store InvalidSubTransactionId in both fields, in which case
9743 : : * relcache.c will assume it can rebuild the relcache entry. Hence, do
9744 : : * this after the CCI that made catalog rows visible to any rebuild. The
9745 : : * DROP of the old edition of this index will have scheduled the storage
9746 : : * for deletion at commit, so cancel that pending deletion.
9747 : : */
9748 [ + + ]: 1012 : if (RelFileNumberIsValid(stmt->oldNumber))
9749 : : {
9750 : 49 : Relation irel = index_open(address.objectId, NoLock);
9751 : :
9752 : 49 : irel->rd_createSubid = stmt->oldCreateSubid;
9753 : 49 : irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
9754 : 49 : RelationPreserveStorage(irel->rd_locator, true);
9755 : 49 : index_close(irel, NoLock);
9756 : : }
9757 : :
9758 : 1012 : return address;
9759 : : }
9760 : :
9761 : : /*
9762 : : * ALTER TABLE ADD STATISTICS
9763 : : *
9764 : : * This is no such command in the grammar, but we use this internally to add
9765 : : * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
9766 : : * column type change.
9767 : : */
9768 : : static ObjectAddress
9769 : 57 : ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
9770 : : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9771 : : {
9772 : : ObjectAddress address;
9773 : :
9774 : : Assert(IsA(stmt, CreateStatsStmt));
9775 : :
9776 : : /* The CreateStatsStmt has already been through transformStatsStmt */
9777 : : Assert(stmt->transformed);
9778 : :
9779 : : /* The owner must be set to the original statistics owner */
9780 : : Assert(OidIsValid(stmt->owner));
9781 : :
9782 : 57 : address = CreateStatistics(list_make1_oid(RelationGetRelid(rel)),
9783 : 57 : stmt, !is_rebuild);
9784 : :
9785 : 57 : return address;
9786 : : }
9787 : :
9788 : : /*
9789 : : * ALTER TABLE ADD CONSTRAINT USING INDEX
9790 : : *
9791 : : * Returns the address of the new constraint.
9792 : : */
9793 : : static ObjectAddress
9794 : 6323 : ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
9795 : : IndexStmt *stmt, LOCKMODE lockmode)
9796 : : {
9797 : 6323 : Oid index_oid = stmt->indexOid;
9798 : : Relation indexRel;
9799 : : char *indexName;
9800 : : IndexInfo *indexInfo;
9801 : : char *constraintName;
9802 : : char constraintType;
9803 : : ObjectAddress address;
9804 : : uint16 flags;
9805 : :
9806 : : Assert(IsA(stmt, IndexStmt));
9807 : : Assert(OidIsValid(index_oid));
9808 : : Assert(stmt->isconstraint);
9809 : :
9810 : : /*
9811 : : * Doing this on partitioned tables is not a simple feature to implement,
9812 : : * so let's punt for now.
9813 : : */
9814 [ + + ]: 6323 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
9815 [ + - ]: 4 : ereport(ERROR,
9816 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9817 : : errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
9818 : :
9819 : 6319 : indexRel = index_open(index_oid, AccessShareLock);
9820 : :
9821 : 6319 : indexName = pstrdup(RelationGetRelationName(indexRel));
9822 : :
9823 : 6319 : indexInfo = BuildIndexInfo(indexRel);
9824 : :
9825 : : /* this should have been checked at parse time */
9826 [ - + ]: 6319 : if (!indexInfo->ii_Unique)
9827 [ # # ]: 0 : elog(ERROR, "index \"%s\" is not unique", indexName);
9828 : :
9829 : : /*
9830 : : * Determine name to assign to constraint. We require a constraint to
9831 : : * have the same name as the underlying index; therefore, use the index's
9832 : : * existing name as the default constraint name, and if the user
9833 : : * explicitly gives some other name for the constraint, rename the index
9834 : : * to match.
9835 : : */
9836 : 6319 : constraintName = stmt->idxname;
9837 [ + + ]: 6319 : if (constraintName == NULL)
9838 : 6302 : constraintName = indexName;
9839 [ + + ]: 17 : else if (strcmp(constraintName, indexName) != 0)
9840 : : {
9841 [ + - ]: 13 : ereport(NOTICE,
9842 : : (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
9843 : : indexName, constraintName)));
9844 : 13 : RenameRelationInternal(index_oid, constraintName, false, true);
9845 : : }
9846 : :
9847 : : /* Extra checks needed if making primary key */
9848 [ + + ]: 6319 : if (stmt->primary)
9849 : 3570 : index_check_primary_key(rel, indexInfo, true, stmt);
9850 : :
9851 : : /* Note we currently don't support EXCLUSION constraints here */
9852 [ + + ]: 6315 : if (stmt->primary)
9853 : 3566 : constraintType = CONSTRAINT_PRIMARY;
9854 : : else
9855 : 2749 : constraintType = CONSTRAINT_UNIQUE;
9856 : :
9857 : : /* Create the catalog entries for the constraint */
9858 : 6315 : flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
9859 : : INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
9860 [ - + ]: 12630 : (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
9861 [ - + ]: 6315 : (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
9862 : 6315 : (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
9863 : :
9864 : 6315 : address = index_constraint_create(rel,
9865 : : index_oid,
9866 : : InvalidOid,
9867 : : indexInfo,
9868 : : constraintName,
9869 : : constraintType,
9870 : : flags,
9871 : : allowSystemTableMods,
9872 : : false); /* is_internal */
9873 : :
9874 : 6315 : index_close(indexRel, NoLock);
9875 : :
9876 : 6315 : return address;
9877 : : }
9878 : :
9879 : : /*
9880 : : * ALTER TABLE ADD CONSTRAINT
9881 : : *
9882 : : * Return value is the address of the new constraint; if no constraint was
9883 : : * added, InvalidObjectAddress is returned.
9884 : : */
9885 : : static ObjectAddress
9886 : 8212 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9887 : : Constraint *newConstraint, bool recurse, bool is_readd,
9888 : : LOCKMODE lockmode)
9889 : : {
9890 : 8212 : ObjectAddress address = InvalidObjectAddress;
9891 : :
9892 : : Assert(IsA(newConstraint, Constraint));
9893 : :
9894 : : /*
9895 : : * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
9896 : : * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
9897 : : * parse_utilcmd.c).
9898 : : */
9899 [ + + - ]: 8212 : switch (newConstraint->contype)
9900 : : {
9901 : 6340 : case CONSTR_CHECK:
9902 : : case CONSTR_NOTNULL:
9903 : : address =
9904 : 6340 : ATAddCheckNNConstraint(wqueue, tab, rel,
9905 : : newConstraint, recurse, false, is_readd,
9906 : : lockmode);
9907 : 6240 : break;
9908 : :
9909 : 1872 : case CONSTR_FOREIGN:
9910 : :
9911 : : /*
9912 : : * Assign or validate constraint name
9913 : : */
9914 [ + + ]: 1872 : if (newConstraint->conname)
9915 : : {
9916 [ - + ]: 754 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
9917 : : RelationGetRelid(rel),
9918 : 754 : newConstraint->conname))
9919 [ # # ]: 0 : ereport(ERROR,
9920 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
9921 : : errmsg("constraint \"%s\" for relation \"%s\" already exists",
9922 : : newConstraint->conname,
9923 : : RelationGetRelationName(rel))));
9924 : : }
9925 : : else
9926 : 1118 : newConstraint->conname =
9927 : 1118 : ChooseConstraintName(RelationGetRelationName(rel),
9928 : 1118 : ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
9929 : : "fkey",
9930 : 1118 : RelationGetNamespace(rel),
9931 : : NIL);
9932 : :
9933 : 1872 : address = ATAddForeignKeyConstraint(wqueue, tab, rel,
9934 : : newConstraint,
9935 : : recurse, false,
9936 : : lockmode);
9937 : 1503 : break;
9938 : :
9939 : 0 : default:
9940 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
9941 : : (int) newConstraint->contype);
9942 : : }
9943 : :
9944 : 7743 : return address;
9945 : : }
9946 : :
9947 : : /*
9948 : : * Generate the column-name portion of the constraint name for a new foreign
9949 : : * key given the list of column names that reference the referenced
9950 : : * table. This will be passed to ChooseConstraintName along with the parent
9951 : : * table name and the "fkey" suffix.
9952 : : *
9953 : : * We know that less than NAMEDATALEN characters will actually be used, so we
9954 : : * can truncate the result once we've generated that many.
9955 : : *
9956 : : * XXX see also ChooseExtendedStatisticNameAddition and
9957 : : * ChooseIndexNameAddition.
9958 : : */
9959 : : static char *
9960 : 1118 : ChooseForeignKeyConstraintNameAddition(List *colnames)
9961 : : {
9962 : : char buf[NAMEDATALEN * 2];
9963 : 1118 : int buflen = 0;
9964 : : ListCell *lc;
9965 : :
9966 : 1118 : buf[0] = '\0';
9967 [ + - + + : 2530 : foreach(lc, colnames)
+ + ]
9968 : : {
9969 : 1412 : const char *name = strVal(lfirst(lc));
9970 : :
9971 [ + + ]: 1412 : if (buflen > 0)
9972 : 294 : buf[buflen++] = '_'; /* insert _ between names */
9973 : :
9974 : : /*
9975 : : * At this point we have buflen <= NAMEDATALEN. name should be less
9976 : : * than NAMEDATALEN already, but use strlcpy for paranoia.
9977 : : */
9978 : 1412 : strlcpy(buf + buflen, name, NAMEDATALEN);
9979 : 1412 : buflen += strlen(buf + buflen);
9980 [ - + ]: 1412 : if (buflen >= NAMEDATALEN)
9981 : 0 : break;
9982 : : }
9983 : 1118 : return pstrdup(buf);
9984 : : }
9985 : :
9986 : : /*
9987 : : * Add a check or not-null constraint to a single table and its children.
9988 : : * Returns the address of the constraint added to the parent relation,
9989 : : * if one gets added, or InvalidObjectAddress otherwise.
9990 : : *
9991 : : * Subroutine for ATExecAddConstraint.
9992 : : *
9993 : : * We must recurse to child tables during execution, rather than using
9994 : : * ALTER TABLE's normal prep-time recursion. The reason is that all the
9995 : : * constraints *must* be given the same name, else they won't be seen as
9996 : : * related later. If the user didn't explicitly specify a name, then
9997 : : * AddRelationNewConstraints would normally assign different names to the
9998 : : * child constraints. To fix that, we must capture the name assigned at
9999 : : * the parent table and pass that down.
10000 : : */
10001 : : static ObjectAddress
10002 : 6950 : ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10003 : : Constraint *constr, bool recurse, bool recursing,
10004 : : bool is_readd, LOCKMODE lockmode)
10005 : : {
10006 : : List *newcons;
10007 : : ListCell *lcon;
10008 : : List *children;
10009 : : ListCell *child;
10010 : 6950 : ObjectAddress address = InvalidObjectAddress;
10011 : :
10012 : : /* Guard against stack overflow due to overly deep inheritance tree. */
10013 : 6950 : check_stack_depth();
10014 : :
10015 : : /* At top level, permission check was done in ATPrepCmd, else do it */
10016 [ + + ]: 6950 : if (recursing)
10017 : 610 : ATSimplePermissions(AT_AddConstraint, rel,
10018 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
10019 : :
10020 : : /*
10021 : : * Call AddRelationNewConstraints to do the work, making sure it works on
10022 : : * a copy of the Constraint so transformExpr can't modify the original. It
10023 : : * returns a list of cooked constraints.
10024 : : *
10025 : : * If the constraint ends up getting merged with a pre-existing one, it's
10026 : : * omitted from the returned list, which is what we want: we do not need
10027 : : * to do any validation work. That can only happen at child tables,
10028 : : * though, since we disallow merging at the top level.
10029 : : */
10030 : 6950 : newcons = AddRelationNewConstraints(rel, NIL,
10031 : : list_make1(copyObject(constr)),
10032 [ + + ]: 6950 : recursing || is_readd, /* allow_merge */
10033 : : !recursing, /* is_local */
10034 : : is_readd, /* is_internal */
10035 [ + + ]: 13900 : NULL); /* queryString not available
10036 : : * here */
10037 : :
10038 : : /* we don't expect more than one constraint here */
10039 : : Assert(list_length(newcons) <= 1);
10040 : :
10041 : : /* Add each to-be-validated constraint to Phase 3's queue */
10042 [ + + + + : 13570 : foreach(lcon, newcons)
+ + ]
10043 : : {
10044 : 6716 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
10045 : :
10046 [ + + + + ]: 6716 : if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
10047 : : {
10048 : : NewConstraint *newcon;
10049 : :
10050 : 695 : newcon = palloc0_object(NewConstraint);
10051 : 695 : newcon->name = ccon->name;
10052 : 695 : newcon->contype = ccon->contype;
10053 : 695 : newcon->qual = ccon->expr;
10054 : :
10055 : 695 : tab->constraints = lappend(tab->constraints, newcon);
10056 : : }
10057 : :
10058 : : /* Save the actually assigned name if it was defaulted */
10059 [ + + ]: 6716 : if (constr->conname == NULL)
10060 : 5399 : constr->conname = ccon->name;
10061 : :
10062 : : /*
10063 : : * If adding a valid not-null constraint, set the pg_attribute flag
10064 : : * and tell phase 3 to verify existing rows, if needed. For an
10065 : : * invalid constraint, just set attnotnull, without queueing
10066 : : * verification.
10067 : : */
10068 [ + + ]: 6716 : if (constr->contype == CONSTR_NOTNULL)
10069 : 5748 : set_attnotnull(wqueue, rel, ccon->attnum,
10070 : 5748 : !constr->skip_validation);
10071 : :
10072 : 6716 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
10073 : : }
10074 : :
10075 : : /* At this point we must have a locked-down name to use */
10076 : : Assert(newcons == NIL || constr->conname != NULL);
10077 : :
10078 : : /* Advance command counter in case same table is visited multiple times */
10079 : 6854 : CommandCounterIncrement();
10080 : :
10081 : : /*
10082 : : * If the constraint got merged with an existing constraint, we're done.
10083 : : * We mustn't recurse to child tables in this case, because they've
10084 : : * already got the constraint, and visiting them again would lead to an
10085 : : * incorrect value for coninhcount.
10086 : : */
10087 [ + + ]: 6854 : if (newcons == NIL)
10088 : 138 : return address;
10089 : :
10090 : : /*
10091 : : * If adding a NO INHERIT constraint, no need to find our children.
10092 : : */
10093 [ + + ]: 6716 : if (constr->is_no_inherit)
10094 : 56 : return address;
10095 : :
10096 : : /*
10097 : : * Propagate to children as appropriate. Unlike most other ALTER
10098 : : * routines, we have to do this one level of recursion at a time; we can't
10099 : : * use find_all_inheritors to do it in one pass.
10100 : : */
10101 : : children =
10102 : 6660 : find_inheritance_children(RelationGetRelid(rel), lockmode);
10103 : :
10104 : : /*
10105 : : * Check if ONLY was specified with ALTER TABLE. If so, allow the
10106 : : * constraint creation only if there are no children currently. Error out
10107 : : * otherwise.
10108 : : */
10109 [ + + + + ]: 6660 : if (!recurse && children != NIL)
10110 [ + - ]: 4 : ereport(ERROR,
10111 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10112 : : errmsg("constraint must be added to child tables too")));
10113 : :
10114 : : /*
10115 : : * Recurse to create the constraint on each child.
10116 : : */
10117 [ + + + + : 7246 : foreach(child, children)
+ + ]
10118 : : {
10119 : 610 : Oid childrelid = lfirst_oid(child);
10120 : : Relation childrel;
10121 : : AlteredTableInfo *childtab;
10122 : :
10123 : : /* find_inheritance_children already got lock */
10124 : 610 : childrel = table_open(childrelid, NoLock);
10125 : 610 : CheckAlterTableIsSafe(childrel);
10126 : :
10127 : : /* Find or create work queue entry for this table */
10128 : 610 : childtab = ATGetQueueEntry(wqueue, childrel);
10129 : :
10130 : : /* Recurse to this child */
10131 : 610 : ATAddCheckNNConstraint(wqueue, childtab, childrel,
10132 : : constr, recurse, true, is_readd, lockmode);
10133 : :
10134 : 590 : table_close(childrel, NoLock);
10135 : : }
10136 : :
10137 : 6636 : return address;
10138 : : }
10139 : :
10140 : : /*
10141 : : * Add a foreign-key constraint to a single table; return the new constraint's
10142 : : * address.
10143 : : *
10144 : : * Subroutine for ATExecAddConstraint. Must already hold exclusive
10145 : : * lock on the rel, and have done appropriate validity checks for it.
10146 : : * We do permissions checks here, however.
10147 : : *
10148 : : * When the referenced or referencing tables (or both) are partitioned,
10149 : : * multiple pg_constraint rows are required -- one for each partitioned table
10150 : : * and each partition on each side (fortunately, not one for every combination
10151 : : * thereof). We also need action triggers on each leaf partition on the
10152 : : * referenced side, and check triggers on each leaf partition on the
10153 : : * referencing side.
10154 : : */
10155 : : static ObjectAddress
10156 : 1872 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10157 : : Constraint *fkconstraint,
10158 : : bool recurse, bool recursing, LOCKMODE lockmode)
10159 : : {
10160 : : Relation pkrel;
10161 : 1872 : int16 pkattnum[INDEX_MAX_KEYS] = {0};
10162 : 1872 : int16 fkattnum[INDEX_MAX_KEYS] = {0};
10163 : 1872 : Oid pktypoid[INDEX_MAX_KEYS] = {0};
10164 : 1872 : Oid fktypoid[INDEX_MAX_KEYS] = {0};
10165 : 1872 : Oid pkcolloid[INDEX_MAX_KEYS] = {0};
10166 : 1872 : Oid fkcolloid[INDEX_MAX_KEYS] = {0};
10167 : 1872 : Oid opclasses[INDEX_MAX_KEYS] = {0};
10168 : 1872 : Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
10169 : 1872 : Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
10170 : 1872 : Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
10171 : 1872 : int16 fkdelsetcols[INDEX_MAX_KEYS] = {0};
10172 : : bool with_period;
10173 : : bool pk_has_without_overlaps;
10174 : : int i;
10175 : : int numfks,
10176 : : numpks,
10177 : : numfkdelsetcols;
10178 : : Oid indexOid;
10179 : : bool old_check_ok;
10180 : : ObjectAddress address;
10181 : 1872 : ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
10182 : :
10183 : : /*
10184 : : * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
10185 : : * delete rows out from under us.
10186 : : */
10187 [ + + ]: 1872 : if (OidIsValid(fkconstraint->old_pktable_oid))
10188 : 48 : pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
10189 : : else
10190 : 1824 : pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
10191 : :
10192 : : /*
10193 : : * Validity checks (permission checks wait till we have the column
10194 : : * numbers)
10195 : : */
10196 [ + + + + ]: 1868 : if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10197 [ + - ]: 4 : ereport(ERROR,
10198 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
10199 : : errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
10200 : : RelationGetRelationName(rel),
10201 : : RelationGetRelationName(pkrel)));
10202 : :
10203 [ + + ]: 1864 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10204 [ - + ]: 226 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10205 [ # # ]: 0 : ereport(ERROR,
10206 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10207 : : errmsg("referenced relation \"%s\" is not a table",
10208 : : RelationGetRelationName(pkrel))));
10209 : :
10210 : : /*
10211 : : * Conflict log tables are used internally for logical replication
10212 : : * conflict logging and should not be referenced by foreign keys, as it
10213 : : * could disrupt conflict logging.
10214 : : */
10215 [ + + ]: 1864 : if (IsConflictLogTableClass(pkrel->rd_rel))
10216 [ + - ]: 4 : ereport(ERROR,
10217 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10218 : : errmsg("cannot reference conflict log table \"%s\"",
10219 : : RelationGetRelationName(pkrel)),
10220 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
10221 : :
10222 [ + + + + ]: 1860 : if (!allowSystemTableMods && IsSystemRelation(pkrel))
10223 [ + - ]: 1 : ereport(ERROR,
10224 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10225 : : errmsg("permission denied: \"%s\" is a system catalog",
10226 : : RelationGetRelationName(pkrel))));
10227 : :
10228 : : /*
10229 : : * References from permanent or unlogged tables to temp tables, and from
10230 : : * permanent tables to unlogged tables, are disallowed because the
10231 : : * referenced data can vanish out from under us. References from temp
10232 : : * tables to any other table type are also disallowed, because other
10233 : : * backends might need to run the RI triggers on the perm table, but they
10234 : : * can't reliably see tuples in the local buffers of other backends.
10235 : : */
10236 [ + + + - ]: 1859 : switch (rel->rd_rel->relpersistence)
10237 : : {
10238 : 1662 : case RELPERSISTENCE_PERMANENT:
10239 [ - + ]: 1662 : if (!RelationIsPermanent(pkrel))
10240 [ # # ]: 0 : ereport(ERROR,
10241 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10242 : : errmsg("constraints on permanent tables may reference only permanent tables")));
10243 : 1662 : break;
10244 : 8 : case RELPERSISTENCE_UNLOGGED:
10245 [ + - ]: 8 : if (!RelationIsPermanent(pkrel)
10246 [ - + ]: 8 : && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
10247 [ # # ]: 0 : ereport(ERROR,
10248 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10249 : : errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
10250 : 8 : break;
10251 : 189 : case RELPERSISTENCE_TEMP:
10252 [ - + ]: 189 : if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10253 [ # # ]: 0 : ereport(ERROR,
10254 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10255 : : errmsg("constraints on temporary tables may reference only temporary tables")));
10256 [ + - - + ]: 189 : if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
10257 [ # # ]: 0 : ereport(ERROR,
10258 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10259 : : errmsg("constraints on temporary tables must involve temporary tables of this session")));
10260 : 189 : break;
10261 : : }
10262 : :
10263 : : /*
10264 : : * Look up the referencing attributes to make sure they exist, and record
10265 : : * their attnums and type and collation OIDs.
10266 : : */
10267 : 1859 : numfks = transformColumnNameList(RelationGetRelid(rel),
10268 : : fkconstraint->fk_attrs,
10269 : : fkattnum, fktypoid, fkcolloid);
10270 [ + + + + ]: 1839 : with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
10271 [ + + + + ]: 1839 : if (with_period && !fkconstraint->fk_with_period)
10272 [ + - ]: 16 : ereport(ERROR,
10273 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10274 : : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10275 : :
10276 : 1823 : numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
10277 : : fkconstraint->fk_del_set_cols,
10278 : : fkdelsetcols, NULL, NULL);
10279 : 1819 : numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
10280 : : numfkdelsetcols,
10281 : : fkdelsetcols,
10282 : : fkconstraint->fk_del_set_cols);
10283 : :
10284 : : /*
10285 : : * If the attribute list for the referenced table was omitted, lookup the
10286 : : * definition of the primary key and use it. Otherwise, validate the
10287 : : * supplied attribute list. In either case, discover the index OID and
10288 : : * index opclasses, and the attnums and type and collation OIDs of the
10289 : : * attributes.
10290 : : */
10291 [ + + ]: 1815 : if (fkconstraint->pk_attrs == NIL)
10292 : : {
10293 : 904 : numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
10294 : : &fkconstraint->pk_attrs,
10295 : : pkattnum, pktypoid, pkcolloid,
10296 : : opclasses, &pk_has_without_overlaps);
10297 : :
10298 : : /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
10299 [ + + + + ]: 904 : if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
10300 [ + - ]: 16 : ereport(ERROR,
10301 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10302 : : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10303 : : }
10304 : : else
10305 : : {
10306 : 911 : numpks = transformColumnNameList(RelationGetRelid(pkrel),
10307 : : fkconstraint->pk_attrs,
10308 : : pkattnum, pktypoid, pkcolloid);
10309 : :
10310 : : /* Since we got pk_attrs, one should be a period. */
10311 [ + + + + ]: 891 : if (with_period && !fkconstraint->pk_with_period)
10312 [ + - ]: 16 : ereport(ERROR,
10313 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10314 : : errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
10315 : :
10316 : : /* Look for an index matching the column list */
10317 : 875 : indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
10318 : : with_period, opclasses, &pk_has_without_overlaps);
10319 : : }
10320 : :
10321 : : /*
10322 : : * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
10323 : : * must use PERIOD.
10324 : : */
10325 [ + + + + ]: 1739 : if (pk_has_without_overlaps && !with_period)
10326 [ + - ]: 8 : ereport(ERROR,
10327 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10328 : : errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
10329 : :
10330 : : /*
10331 : : * Now we can check permissions.
10332 : : */
10333 : 1731 : checkFkeyPermissions(pkrel, pkattnum, numpks);
10334 : :
10335 : : /*
10336 : : * Check some things for generated columns.
10337 : : */
10338 [ + + ]: 4055 : for (i = 0; i < numfks; i++)
10339 : : {
10340 : 2344 : char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
10341 : :
10342 [ + + ]: 2344 : if (attgenerated)
10343 : : {
10344 : : /*
10345 : : * Check restrictions on UPDATE/DELETE actions, per SQL standard
10346 : : */
10347 [ + - ]: 32 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10348 [ + - ]: 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
10349 [ + + ]: 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
10350 [ + - ]: 8 : ereport(ERROR,
10351 : : (errcode(ERRCODE_SYNTAX_ERROR),
10352 : : errmsg("invalid %s action for foreign key constraint containing generated column",
10353 : : "ON UPDATE")));
10354 [ + + ]: 24 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10355 [ - + ]: 16 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10356 [ + - ]: 8 : ereport(ERROR,
10357 : : (errcode(ERRCODE_SYNTAX_ERROR),
10358 : : errmsg("invalid %s action for foreign key constraint containing generated column",
10359 : : "ON DELETE")));
10360 : : }
10361 : :
10362 : : /*
10363 : : * FKs on virtual columns are not supported. This would require
10364 : : * various additional support in ri_triggers.c, including special
10365 : : * handling in ri_NullCheck(), ri_KeysEqual(),
10366 : : * RI_FKey_fk_upd_check_required() (since all virtual columns appear
10367 : : * as NULL there). Also not really practical as long as you can't
10368 : : * index virtual columns.
10369 : : */
10370 [ + + ]: 2328 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
10371 [ + - ]: 4 : ereport(ERROR,
10372 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10373 : : errmsg("foreign key constraints on virtual generated columns are not supported")));
10374 : : }
10375 : :
10376 : : /*
10377 : : * Some actions are currently unsupported for foreign keys using PERIOD.
10378 : : */
10379 [ + + ]: 1711 : if (fkconstraint->fk_with_period)
10380 : : {
10381 [ + + ]: 178 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
10382 [ + + ]: 170 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
10383 [ + + ]: 158 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10384 [ + + ]: 146 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
10385 [ + - ]: 44 : ereport(ERROR,
10386 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10387 : : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10388 : : "ON UPDATE"));
10389 : :
10390 [ + + ]: 134 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
10391 [ + - ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
10392 [ + - ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10393 [ - + ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10394 [ + - ]: 4 : ereport(ERROR,
10395 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10396 : : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10397 : : "ON DELETE"));
10398 : : }
10399 : :
10400 : : /*
10401 : : * Look up the equality operators to use in the constraint.
10402 : : *
10403 : : * Note that we have to be careful about the difference between the actual
10404 : : * PK column type and the opclass' declared input type, which might be
10405 : : * only binary-compatible with it. The declared opcintype is the right
10406 : : * thing to probe pg_amop with.
10407 : : */
10408 [ - + ]: 1663 : if (numfks != numpks)
10409 [ # # ]: 0 : ereport(ERROR,
10410 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
10411 : : errmsg("number of referencing and referenced columns for foreign key disagree")));
10412 : :
10413 : : /*
10414 : : * On the strength of a previous constraint, we might avoid scanning
10415 : : * tables to validate this one. See below.
10416 : : */
10417 : 1663 : old_check_ok = (fkconstraint->old_conpfeqop != NIL);
10418 : : Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
10419 : :
10420 [ + + ]: 3635 : for (i = 0; i < numpks; i++)
10421 : : {
10422 : 2132 : Oid pktype = pktypoid[i];
10423 : 2132 : Oid fktype = fktypoid[i];
10424 : : Oid fktyped;
10425 : 2132 : Oid pkcoll = pkcolloid[i];
10426 : 2132 : Oid fkcoll = fkcolloid[i];
10427 : : HeapTuple cla_ht;
10428 : : Form_pg_opclass cla_tup;
10429 : : Oid amid;
10430 : : Oid opfamily;
10431 : : Oid opcintype;
10432 : : bool for_overlaps;
10433 : : CompareType cmptype;
10434 : : Oid pfeqop;
10435 : : Oid ppeqop;
10436 : : Oid ffeqop;
10437 : : int16 eqstrategy;
10438 : : Oid pfeqop_right;
10439 : :
10440 : : /* We need several fields out of the pg_opclass entry */
10441 : 2132 : cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
10442 [ - + ]: 2132 : if (!HeapTupleIsValid(cla_ht))
10443 [ # # ]: 0 : elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
10444 : 2132 : cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
10445 : 2132 : amid = cla_tup->opcmethod;
10446 : 2132 : opfamily = cla_tup->opcfamily;
10447 : 2132 : opcintype = cla_tup->opcintype;
10448 : 2132 : ReleaseSysCache(cla_ht);
10449 : :
10450 : : /*
10451 : : * Get strategy number from index AM.
10452 : : *
10453 : : * For a normal foreign-key constraint, this should not fail, since we
10454 : : * already checked that the index is unique and should therefore have
10455 : : * appropriate equal operators. For a period foreign key, this could
10456 : : * fail if we selected a non-matching exclusion constraint earlier.
10457 : : * (XXX Maybe we should do these lookups earlier so we don't end up
10458 : : * doing that.)
10459 : : */
10460 [ + + + + ]: 2132 : for_overlaps = with_period && i == numpks - 1;
10461 [ + + ]: 2132 : cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
10462 : 2132 : eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
10463 [ - + ]: 2132 : if (eqstrategy == InvalidStrategy)
10464 [ # # # # ]: 0 : ereport(ERROR,
10465 : : errcode(ERRCODE_UNDEFINED_OBJECT),
10466 : : for_overlaps
10467 : : ? errmsg("could not identify an overlaps operator for foreign key")
10468 : : : errmsg("could not identify an equality operator for foreign key"),
10469 : : errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
10470 : : cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
10471 : :
10472 : : /*
10473 : : * There had better be a primary equality operator for the index.
10474 : : * We'll use it for PK = PK comparisons.
10475 : : */
10476 : 2132 : ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
10477 : : eqstrategy);
10478 : :
10479 [ - + ]: 2132 : if (!OidIsValid(ppeqop))
10480 [ # # ]: 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
10481 : : eqstrategy, opcintype, opcintype, opfamily);
10482 : :
10483 : : /*
10484 : : * Are there equality operators that take exactly the FK type? Assume
10485 : : * we should look through any domain here.
10486 : : */
10487 : 2132 : fktyped = getBaseType(fktype);
10488 : :
10489 : 2132 : pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
10490 : : eqstrategy);
10491 [ + + ]: 2132 : if (OidIsValid(pfeqop))
10492 : : {
10493 : 1647 : pfeqop_right = fktyped;
10494 : 1647 : ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
10495 : : eqstrategy);
10496 : : }
10497 : : else
10498 : : {
10499 : : /* keep compiler quiet */
10500 : 485 : pfeqop_right = InvalidOid;
10501 : 485 : ffeqop = InvalidOid;
10502 : : }
10503 : :
10504 [ + + - + ]: 2132 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10505 : : {
10506 : : /*
10507 : : * Otherwise, look for an implicit cast from the FK type to the
10508 : : * opcintype, and if found, use the primary equality operator.
10509 : : * This is a bit tricky because opcintype might be a polymorphic
10510 : : * type such as ANYARRAY or ANYENUM; so what we have to test is
10511 : : * whether the two actual column types can be concurrently cast to
10512 : : * that type. (Otherwise, we'd fail to reject combinations such
10513 : : * as int[] and point[].)
10514 : : */
10515 : : Oid input_typeids[2];
10516 : : Oid target_typeids[2];
10517 : :
10518 : 485 : input_typeids[0] = pktype;
10519 : 485 : input_typeids[1] = fktype;
10520 : 485 : target_typeids[0] = opcintype;
10521 : 485 : target_typeids[1] = opcintype;
10522 [ + + ]: 485 : if (can_coerce_type(2, input_typeids, target_typeids,
10523 : : COERCION_IMPLICIT))
10524 : : {
10525 : 333 : pfeqop = ffeqop = ppeqop;
10526 : 333 : pfeqop_right = opcintype;
10527 : : }
10528 : : }
10529 : :
10530 [ + + - + ]: 2132 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10531 [ + - ]: 152 : ereport(ERROR,
10532 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
10533 : : errmsg("foreign key constraint \"%s\" cannot be implemented",
10534 : : fkconstraint->conname),
10535 : : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10536 : : "are of incompatible types: %s and %s.",
10537 : : strVal(list_nth(fkconstraint->fk_attrs, i)),
10538 : : strVal(list_nth(fkconstraint->pk_attrs, i)),
10539 : : format_type_be(fktype),
10540 : : format_type_be(pktype))));
10541 : :
10542 : : /*
10543 : : * This shouldn't be possible, but better check to make sure we have a
10544 : : * consistent state for the check below.
10545 : : */
10546 [ + + + - : 1980 : if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
+ + - + ]
10547 [ # # ]: 0 : elog(ERROR, "key columns are not both collatable");
10548 : :
10549 [ + + + - ]: 1980 : if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
10550 : : {
10551 : : bool pkcolldet;
10552 : : bool fkcolldet;
10553 : :
10554 : 89 : pkcolldet = get_collation_isdeterministic(pkcoll);
10555 : 89 : fkcolldet = get_collation_isdeterministic(fkcoll);
10556 : :
10557 : : /*
10558 : : * SQL requires that both collations are the same. This is
10559 : : * because we need a consistent notion of equality on both
10560 : : * columns. We relax this by allowing different collations if
10561 : : * they are both deterministic. (This is also for backward
10562 : : * compatibility, because PostgreSQL has always allowed this.)
10563 : : */
10564 [ + + + + : 89 : if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
+ + ]
10565 [ + - ]: 8 : ereport(ERROR,
10566 : : (errcode(ERRCODE_COLLATION_MISMATCH),
10567 : : errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
10568 : : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10569 : : "have incompatible collations: \"%s\" and \"%s\". "
10570 : : "If either collation is nondeterministic, then both collations have to be the same.",
10571 : : strVal(list_nth(fkconstraint->fk_attrs, i)),
10572 : : strVal(list_nth(fkconstraint->pk_attrs, i)),
10573 : : get_collation_name(fkcoll),
10574 : : get_collation_name(pkcoll))));
10575 : : }
10576 : :
10577 [ + + ]: 1972 : if (old_check_ok)
10578 : : {
10579 : : /*
10580 : : * When a pfeqop changes, revalidate the constraint. We could
10581 : : * permit intra-opfamily changes, but that adds subtle complexity
10582 : : * without any concrete benefit for core types. We need not
10583 : : * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
10584 : : */
10585 : 4 : old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
10586 : 4 : old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
10587 : : old_pfeqop_item);
10588 : : }
10589 [ + + ]: 1972 : if (old_check_ok)
10590 : : {
10591 : : Oid old_fktype;
10592 : : Oid new_fktype;
10593 : : CoercionPathType old_pathtype;
10594 : : CoercionPathType new_pathtype;
10595 : : Oid old_castfunc;
10596 : : Oid new_castfunc;
10597 : : Oid old_fkcoll;
10598 : : Oid new_fkcoll;
10599 : 4 : Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
10600 : 4 : fkattnum[i] - 1);
10601 : :
10602 : : /*
10603 : : * Identify coercion pathways from each of the old and new FK-side
10604 : : * column types to the right (foreign) operand type of the pfeqop.
10605 : : * We may assume that pg_constraint.conkey is not changing.
10606 : : */
10607 : 4 : old_fktype = attr->atttypid;
10608 : 4 : new_fktype = fktype;
10609 : 4 : old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
10610 : : &old_castfunc);
10611 : 4 : new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
10612 : : &new_castfunc);
10613 : :
10614 : 4 : old_fkcoll = attr->attcollation;
10615 : 4 : new_fkcoll = fkcoll;
10616 : :
10617 : : /*
10618 : : * Upon a change to the cast from the FK column to its pfeqop
10619 : : * operand, revalidate the constraint. For this evaluation, a
10620 : : * binary coercion cast is equivalent to no cast at all. While
10621 : : * type implementors should design implicit casts with an eye
10622 : : * toward consistency of operations like equality, we cannot
10623 : : * assume here that they have done so.
10624 : : *
10625 : : * A function with a polymorphic argument could change behavior
10626 : : * arbitrarily in response to get_fn_expr_argtype(). Therefore,
10627 : : * when the cast destination is polymorphic, we only avoid
10628 : : * revalidation if the input type has not changed at all. Given
10629 : : * just the core data types and operator classes, this requirement
10630 : : * prevents no would-be optimizations.
10631 : : *
10632 : : * If the cast converts from a base type to a domain thereon, then
10633 : : * that domain type must be the opcintype of the unique index.
10634 : : * Necessarily, the primary key column must then be of the domain
10635 : : * type. Since the constraint was previously valid, all values on
10636 : : * the foreign side necessarily exist on the primary side and in
10637 : : * turn conform to the domain. Consequently, we need not treat
10638 : : * domains specially here.
10639 : : *
10640 : : * If the collation changes, revalidation is required, unless both
10641 : : * collations are deterministic, because those share the same
10642 : : * notion of equality (because texteq reduces to bitwise
10643 : : * equality).
10644 : : *
10645 : : * We need not directly consider the PK type. It's necessarily
10646 : : * binary coercible to the opcintype of the unique index column,
10647 : : * and ri_triggers.c will only deal with PK datums in terms of
10648 : : * that opcintype. Changing the opcintype also changes pfeqop.
10649 : : */
10650 : 4 : old_check_ok = (new_pathtype == old_pathtype &&
10651 [ + - + - ]: 4 : new_castfunc == old_castfunc &&
10652 [ + - + - : 4 : (!IsPolymorphicType(pfeqop_right) ||
+ - + - +
- + - + -
+ - + - -
+ - - ]
10653 [ + - - + ]: 8 : new_fktype == old_fktype) &&
10654 [ # # ]: 0 : (new_fkcoll == old_fkcoll ||
10655 [ # # ]: 0 : (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
10656 : : }
10657 : :
10658 : 1972 : pfeqoperators[i] = pfeqop;
10659 : 1972 : ppeqoperators[i] = ppeqop;
10660 : 1972 : ffeqoperators[i] = ffeqop;
10661 : : }
10662 : :
10663 : : /*
10664 : : * For FKs with PERIOD we need additional operators to check whether the
10665 : : * referencing row's range is contained by the aggregated ranges of the
10666 : : * referenced row(s). For rangetypes and multirangetypes this is
10667 : : * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
10668 : : * support for now. FKs will look these up at "runtime", but we should
10669 : : * make sure the lookup works here, even if we don't use the values.
10670 : : */
10671 [ + + ]: 1503 : if (with_period)
10672 : : {
10673 : : Oid periodoperoid;
10674 : : Oid aggedperiodoperoid;
10675 : : Oid intersectoperoid;
10676 : :
10677 : 118 : FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
10678 : : &intersectoperoid);
10679 : : }
10680 : :
10681 : : /* First, create the constraint catalog entry itself. */
10682 : 1503 : address = addFkConstraint(addFkBothSides,
10683 : : fkconstraint->conname, fkconstraint, rel, pkrel,
10684 : : indexOid,
10685 : : InvalidOid, /* no parent constraint */
10686 : : numfks,
10687 : : pkattnum,
10688 : : fkattnum,
10689 : : pfeqoperators,
10690 : : ppeqoperators,
10691 : : ffeqoperators,
10692 : : numfkdelsetcols,
10693 : : fkdelsetcols,
10694 : : false,
10695 : : with_period);
10696 : :
10697 : : /* Next process the action triggers at the referenced side and recurse */
10698 : 1503 : addFkRecurseReferenced(fkconstraint, rel, pkrel,
10699 : : indexOid,
10700 : : address.objectId,
10701 : : numfks,
10702 : : pkattnum,
10703 : : fkattnum,
10704 : : pfeqoperators,
10705 : : ppeqoperators,
10706 : : ffeqoperators,
10707 : : numfkdelsetcols,
10708 : : fkdelsetcols,
10709 : : old_check_ok,
10710 : : InvalidOid, InvalidOid,
10711 : : with_period);
10712 : :
10713 : : /* Lastly create the check triggers at the referencing side and recurse */
10714 : 1503 : addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
10715 : : indexOid,
10716 : : address.objectId,
10717 : : numfks,
10718 : : pkattnum,
10719 : : fkattnum,
10720 : : pfeqoperators,
10721 : : ppeqoperators,
10722 : : ffeqoperators,
10723 : : numfkdelsetcols,
10724 : : fkdelsetcols,
10725 : : old_check_ok,
10726 : : lockmode,
10727 : : InvalidOid, InvalidOid,
10728 : : with_period);
10729 : :
10730 : : /*
10731 : : * Done. Close pk table, but keep lock until we've committed.
10732 : : */
10733 : 1503 : table_close(pkrel, NoLock);
10734 : :
10735 : 1503 : return address;
10736 : : }
10737 : :
10738 : : /*
10739 : : * validateFkOnDeleteSetColumns
10740 : : * Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
10741 : : * column lists are valid.
10742 : : *
10743 : : * If there are duplicates in the fksetcolsattnums[] array, this silently
10744 : : * removes the dups. The new count of numfksetcols is returned.
10745 : : */
10746 : : static int
10747 : 1819 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
10748 : : int numfksetcols, int16 *fksetcolsattnums,
10749 : : List *fksetcols)
10750 : : {
10751 : 1819 : int numcolsout = 0;
10752 : :
10753 [ + + ]: 1839 : for (int i = 0; i < numfksetcols; i++)
10754 : : {
10755 : 24 : int16 setcol_attnum = fksetcolsattnums[i];
10756 : 24 : bool seen = false;
10757 : :
10758 : : /* Make sure it's in fkattnums[] */
10759 [ + + ]: 44 : for (int j = 0; j < numfks; j++)
10760 : : {
10761 [ + + ]: 40 : if (fkattnums[j] == setcol_attnum)
10762 : : {
10763 : 20 : seen = true;
10764 : 20 : break;
10765 : : }
10766 : : }
10767 : :
10768 [ + + ]: 24 : if (!seen)
10769 : : {
10770 : 4 : char *col = strVal(list_nth(fksetcols, i));
10771 : :
10772 [ + - ]: 4 : ereport(ERROR,
10773 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
10774 : : errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
10775 : : }
10776 : :
10777 : : /* Now check for dups */
10778 : 20 : seen = false;
10779 [ + + ]: 20 : for (int j = 0; j < numcolsout; j++)
10780 : : {
10781 [ + - ]: 4 : if (fksetcolsattnums[j] == setcol_attnum)
10782 : : {
10783 : 4 : seen = true;
10784 : 4 : break;
10785 : : }
10786 : : }
10787 [ + + ]: 20 : if (!seen)
10788 : 16 : fksetcolsattnums[numcolsout++] = setcol_attnum;
10789 : : }
10790 : 1815 : return numcolsout;
10791 : : }
10792 : :
10793 : : /*
10794 : : * addFkConstraint
10795 : : * Install pg_constraint entries to implement a foreign key constraint.
10796 : : * Caller must separately invoke addFkRecurseReferenced and
10797 : : * addFkRecurseReferencing, as appropriate, to install pg_trigger entries
10798 : : * and (for partitioned tables) recurse to partitions.
10799 : : *
10800 : : * fkside: the side of the FK (or both) to create. Caller should
10801 : : * call addFkRecurseReferenced if this is addFkReferencedSide,
10802 : : * addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
10803 : : * addFkBothSides.
10804 : : * constraintname: the base name for the constraint being added,
10805 : : * copied to fkconstraint->conname if the latter is not set
10806 : : * fkconstraint: the constraint being added
10807 : : * rel: the root referencing relation
10808 : : * pkrel: the referenced relation; might be a partition, if recursing
10809 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
10810 : : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10811 : : * top-level constraint
10812 : : * numfks: the number of columns in the foreign key
10813 : : * pkattnum: the attnum array of referenced attributes
10814 : : * fkattnum: the attnum array of referencing attributes
10815 : : * pf/pp/ffeqoperators: OID array of operators between columns
10816 : : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
10817 : : * (...) clause
10818 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10819 : : * NULL/DEFAULT clause
10820 : : * with_period: true if this is a temporal FK
10821 : : */
10822 : : static ObjectAddress
10823 : 2770 : addFkConstraint(addFkConstraintSides fkside,
10824 : : char *constraintname, Constraint *fkconstraint,
10825 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
10826 : : int numfks, int16 *pkattnum,
10827 : : int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
10828 : : Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
10829 : : bool is_internal, bool with_period)
10830 : : {
10831 : : ObjectAddress address;
10832 : : Oid constrOid;
10833 : : char *conname;
10834 : : bool conislocal;
10835 : : int16 coninhcount;
10836 : : bool connoinherit;
10837 : :
10838 : : /*
10839 : : * Verify relkind for each referenced partition. At the top level, this
10840 : : * is redundant with a previous check, but we need it when recursing.
10841 : : */
10842 [ + + ]: 2770 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10843 [ - + ]: 559 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10844 [ # # ]: 0 : ereport(ERROR,
10845 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10846 : : errmsg("referenced relation \"%s\" is not a table",
10847 : : RelationGetRelationName(pkrel))));
10848 : :
10849 : : /*
10850 : : * Caller supplies us with a constraint name; however, it may be used in
10851 : : * this partition, so come up with a different one in that case. Unless
10852 : : * truncation to NAMEDATALEN dictates otherwise, the new name will be the
10853 : : * supplied name with an underscore and digit(s) appended.
10854 : : */
10855 [ + + ]: 2770 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
10856 : : RelationGetRelid(rel),
10857 : : constraintname))
10858 : 755 : conname = ChooseConstraintName(constraintname,
10859 : : NULL,
10860 : : "",
10861 : 755 : RelationGetNamespace(rel), NIL);
10862 : : else
10863 : 2015 : conname = constraintname;
10864 : :
10865 [ + + ]: 2770 : if (fkconstraint->conname == NULL)
10866 : 243 : fkconstraint->conname = pstrdup(conname);
10867 : :
10868 [ + + ]: 2770 : if (OidIsValid(parentConstr))
10869 : : {
10870 : 1267 : conislocal = false;
10871 : 1267 : coninhcount = 1;
10872 : 1267 : connoinherit = false;
10873 : : }
10874 : : else
10875 : : {
10876 : 1503 : conislocal = true;
10877 : 1503 : coninhcount = 0;
10878 : :
10879 : : /*
10880 : : * always inherit for partitioned tables, never for legacy inheritance
10881 : : */
10882 : 1503 : connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
10883 : : }
10884 : :
10885 : : /*
10886 : : * Record the FK constraint in pg_constraint.
10887 : : */
10888 : 2770 : constrOid = CreateConstraintEntry(conname,
10889 : 2770 : RelationGetNamespace(rel),
10890 : : CONSTRAINT_FOREIGN,
10891 : 2770 : fkconstraint->deferrable,
10892 : 2770 : fkconstraint->initdeferred,
10893 : 2770 : fkconstraint->is_enforced,
10894 : 2770 : fkconstraint->initially_valid,
10895 : : parentConstr,
10896 : : RelationGetRelid(rel),
10897 : : fkattnum,
10898 : : numfks,
10899 : : numfks,
10900 : : InvalidOid, /* not a domain constraint */
10901 : : indexOid,
10902 : : RelationGetRelid(pkrel),
10903 : : pkattnum,
10904 : : pfeqoperators,
10905 : : ppeqoperators,
10906 : : ffeqoperators,
10907 : : numfks,
10908 : 2770 : fkconstraint->fk_upd_action,
10909 : 2770 : fkconstraint->fk_del_action,
10910 : : fkdelsetcols,
10911 : : numfkdelsetcols,
10912 : 2770 : fkconstraint->fk_matchtype,
10913 : : NULL, /* no exclusion constraint */
10914 : : NULL, /* no check constraint */
10915 : : NULL,
10916 : : conislocal, /* islocal */
10917 : : coninhcount, /* inhcount */
10918 : : connoinherit, /* conNoInherit */
10919 : : with_period, /* conPeriod */
10920 : : is_internal); /* is_internal */
10921 : :
10922 : 2770 : ObjectAddressSet(address, ConstraintRelationId, constrOid);
10923 : :
10924 : : /*
10925 : : * In partitioning cases, create the dependency entries for this
10926 : : * constraint. (For non-partitioned cases, relevant entries were created
10927 : : * by CreateConstraintEntry.)
10928 : : *
10929 : : * On the referenced side, we need the constraint to have an internal
10930 : : * dependency on its parent constraint; this means that this constraint
10931 : : * cannot be dropped on its own -- only through the parent constraint. It
10932 : : * also means the containing partition cannot be dropped on its own, but
10933 : : * it can be detached, at which point this dependency is removed (after
10934 : : * verifying that no rows are referenced via this FK.)
10935 : : *
10936 : : * When processing the referencing side, we link the constraint via the
10937 : : * special partitioning dependencies: the parent constraint is the primary
10938 : : * dependent, and the partition on which the foreign key exists is the
10939 : : * secondary dependency. That way, this constraint is dropped if either
10940 : : * of these objects is.
10941 : : *
10942 : : * Note that this is only necessary for the subsidiary pg_constraint rows
10943 : : * in partitions; the topmost row doesn't need any of this.
10944 : : */
10945 [ + + ]: 2770 : if (OidIsValid(parentConstr))
10946 : : {
10947 : : ObjectAddress referenced;
10948 : :
10949 : 1267 : ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
10950 : :
10951 : : Assert(fkside != addFkBothSides);
10952 [ + + ]: 1267 : if (fkside == addFkReferencedSide)
10953 : 751 : recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
10954 : : else
10955 : : {
10956 : 516 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
10957 : 516 : ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
10958 : 516 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
10959 : : }
10960 : : }
10961 : :
10962 : : /* make new constraint visible, in case we add more */
10963 : 2770 : CommandCounterIncrement();
10964 : :
10965 : 2770 : return address;
10966 : : }
10967 : :
10968 : : /*
10969 : : * addFkRecurseReferenced
10970 : : * Recursive helper for the referenced side of foreign key creation,
10971 : : * which creates the action triggers and recurses
10972 : : *
10973 : : * If the referenced relation is a plain relation, create the necessary action
10974 : : * triggers that implement the constraint. If the referenced relation is a
10975 : : * partitioned table, then we create a pg_constraint row referencing the parent
10976 : : * of the referencing side for it and recurse on this routine for each
10977 : : * partition.
10978 : : *
10979 : : * fkconstraint: the constraint being added
10980 : : * rel: the root referencing relation
10981 : : * pkrel: the referenced relation; might be a partition, if recursing
10982 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
10983 : : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10984 : : * top-level constraint
10985 : : * numfks: the number of columns in the foreign key
10986 : : * pkattnum: the attnum array of referenced attributes
10987 : : * fkattnum: the attnum array of referencing attributes
10988 : : * numfkdelsetcols: the number of columns in the ON DELETE SET
10989 : : * NULL/DEFAULT (...) clause
10990 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10991 : : * NULL/DEFAULT clause
10992 : : * pf/pp/ffeqoperators: OID array of operators between columns
10993 : : * old_check_ok: true if this constraint replaces an existing one that
10994 : : * was already validated (thus this one doesn't need validation)
10995 : : * parentDelTrigger and parentUpdTrigger: when recursively called on a
10996 : : * partition, the OIDs of the parent action triggers for DELETE and
10997 : : * UPDATE respectively.
10998 : : * with_period: true if this is a temporal FK
10999 : : */
11000 : : static void
11001 : 2322 : addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
11002 : : Relation pkrel, Oid indexOid, Oid parentConstr,
11003 : : int numfks,
11004 : : int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
11005 : : Oid *ppeqoperators, Oid *ffeqoperators,
11006 : : int numfkdelsetcols, int16 *fkdelsetcols,
11007 : : bool old_check_ok,
11008 : : Oid parentDelTrigger, Oid parentUpdTrigger,
11009 : : bool with_period)
11010 : : {
11011 : 2322 : Oid deleteTriggerOid = InvalidOid,
11012 : 2322 : updateTriggerOid = InvalidOid;
11013 : :
11014 : : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11015 : : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11016 : :
11017 : : /*
11018 : : * Create action triggers to enforce the constraint, or skip them if the
11019 : : * constraint is NOT ENFORCED.
11020 : : */
11021 [ + + ]: 2322 : if (fkconstraint->is_enforced)
11022 : 2285 : createForeignKeyActionTriggers(RelationGetRelid(rel),
11023 : : RelationGetRelid(pkrel),
11024 : : fkconstraint,
11025 : : parentConstr, indexOid,
11026 : : parentDelTrigger, parentUpdTrigger,
11027 : : &deleteTriggerOid, &updateTriggerOid);
11028 : :
11029 : : /*
11030 : : * If the referenced table is partitioned, recurse on ourselves to handle
11031 : : * each partition. We need one pg_constraint row created for each
11032 : : * partition in addition to the pg_constraint row for the parent table.
11033 : : */
11034 [ + + ]: 2322 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11035 : : {
11036 : 363 : PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
11037 : :
11038 [ + + ]: 1010 : for (int i = 0; i < pd->nparts; i++)
11039 : : {
11040 : : Relation partRel;
11041 : : AttrMap *map;
11042 : : AttrNumber *mapped_pkattnum;
11043 : : Oid partIndexId;
11044 : : ObjectAddress address;
11045 : :
11046 : : /* XXX would it be better to acquire these locks beforehand? */
11047 : 647 : partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
11048 : :
11049 : : /*
11050 : : * Map the attribute numbers in the referenced side of the FK
11051 : : * definition to match the partition's column layout.
11052 : : */
11053 : 647 : map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
11054 : : RelationGetDescr(pkrel),
11055 : : false);
11056 [ + + ]: 647 : if (map)
11057 : : {
11058 : 89 : mapped_pkattnum = palloc_array(AttrNumber, numfks);
11059 [ + + ]: 186 : for (int j = 0; j < numfks; j++)
11060 : 97 : mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
11061 : : }
11062 : : else
11063 : 558 : mapped_pkattnum = pkattnum;
11064 : :
11065 : : /* Determine the index to use at this level */
11066 : 647 : partIndexId = index_get_partition(partRel, indexOid);
11067 [ - + ]: 647 : if (!OidIsValid(partIndexId))
11068 [ # # ]: 0 : elog(ERROR, "index for %u not found in partition %s",
11069 : : indexOid, RelationGetRelationName(partRel));
11070 : :
11071 : : /* Create entry at this level ... */
11072 : 647 : address = addFkConstraint(addFkReferencedSide,
11073 : : fkconstraint->conname, fkconstraint, rel,
11074 : : partRel, partIndexId, parentConstr,
11075 : : numfks, mapped_pkattnum,
11076 : : fkattnum, pfeqoperators, ppeqoperators,
11077 : : ffeqoperators, numfkdelsetcols,
11078 : : fkdelsetcols, true, with_period);
11079 : : /* ... and recurse to our children */
11080 : 647 : addFkRecurseReferenced(fkconstraint, rel, partRel,
11081 : : partIndexId, address.objectId, numfks,
11082 : : mapped_pkattnum, fkattnum,
11083 : : pfeqoperators, ppeqoperators, ffeqoperators,
11084 : : numfkdelsetcols, fkdelsetcols,
11085 : : old_check_ok,
11086 : : deleteTriggerOid, updateTriggerOid,
11087 : : with_period);
11088 : :
11089 : : /* Done -- clean up (but keep the lock) */
11090 : 647 : table_close(partRel, NoLock);
11091 [ + + ]: 647 : if (map)
11092 : : {
11093 : 89 : pfree(mapped_pkattnum);
11094 : 89 : free_attrmap(map);
11095 : : }
11096 : : }
11097 : : }
11098 : 2322 : }
11099 : :
11100 : : /*
11101 : : * addFkRecurseReferencing
11102 : : * Recursive helper for the referencing side of foreign key creation,
11103 : : * which creates the check triggers and recurses
11104 : : *
11105 : : * If the referencing relation is a plain relation, create the necessary check
11106 : : * triggers that implement the constraint, and set up for Phase 3 constraint
11107 : : * verification. If the referencing relation is a partitioned table, then
11108 : : * we create a pg_constraint row for it and recurse on this routine for each
11109 : : * partition.
11110 : : *
11111 : : * We assume that the referenced relation is locked against concurrent
11112 : : * deletions. If it's a partitioned relation, every partition must be so
11113 : : * locked.
11114 : : *
11115 : : * wqueue: the ALTER TABLE work queue; NULL when not running as part
11116 : : * of an ALTER TABLE sequence.
11117 : : * fkconstraint: the constraint being added
11118 : : * rel: the referencing relation; might be a partition, if recursing
11119 : : * pkrel: the root referenced relation
11120 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
11121 : : * parentConstr: the OID of the parent constraint (there is always one)
11122 : : * numfks: the number of columns in the foreign key
11123 : : * pkattnum: the attnum array of referenced attributes
11124 : : * fkattnum: the attnum array of referencing attributes
11125 : : * pf/pp/ffeqoperators: OID array of operators between columns
11126 : : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
11127 : : * (...) clause
11128 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
11129 : : * NULL/DEFAULT clause
11130 : : * old_check_ok: true if this constraint replaces an existing one that
11131 : : * was already validated (thus this one doesn't need validation)
11132 : : * lockmode: the lockmode to acquire on partitions when recursing
11133 : : * parentInsTrigger and parentUpdTrigger: when being recursively called on
11134 : : * a partition, the OIDs of the parent check triggers for INSERT and
11135 : : * UPDATE respectively.
11136 : : * with_period: true if this is a temporal FK
11137 : : */
11138 : : static void
11139 : 2019 : addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
11140 : : Relation pkrel, Oid indexOid, Oid parentConstr,
11141 : : int numfks, int16 *pkattnum, int16 *fkattnum,
11142 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
11143 : : int numfkdelsetcols, int16 *fkdelsetcols,
11144 : : bool old_check_ok, LOCKMODE lockmode,
11145 : : Oid parentInsTrigger, Oid parentUpdTrigger,
11146 : : bool with_period)
11147 : : {
11148 : 2019 : Oid insertTriggerOid = InvalidOid,
11149 : 2019 : updateTriggerOid = InvalidOid;
11150 : :
11151 : : Assert(OidIsValid(parentConstr));
11152 : : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11153 : : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11154 : :
11155 [ - + ]: 2019 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11156 [ # # ]: 0 : ereport(ERROR,
11157 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11158 : : errmsg("foreign key constraints are not supported on foreign tables")));
11159 : :
11160 : : /*
11161 : : * Add check triggers if the constraint is ENFORCED, and if needed,
11162 : : * schedule them to be checked in Phase 3.
11163 : : *
11164 : : * If the relation is partitioned, drill down to do it to its partitions.
11165 : : */
11166 [ + + ]: 2019 : if (fkconstraint->is_enforced)
11167 : 1986 : createForeignKeyCheckTriggers(RelationGetRelid(rel),
11168 : : RelationGetRelid(pkrel),
11169 : : fkconstraint,
11170 : : parentConstr,
11171 : : indexOid,
11172 : : parentInsTrigger, parentUpdTrigger,
11173 : : &insertTriggerOid, &updateTriggerOid);
11174 : :
11175 [ + + ]: 2019 : if (rel->rd_rel->relkind == RELKIND_RELATION)
11176 : : {
11177 : : /*
11178 : : * Tell Phase 3 to check that the constraint is satisfied by existing
11179 : : * rows. We can skip this during table creation, when constraint is
11180 : : * specified as NOT ENFORCED, or when requested explicitly by
11181 : : * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
11182 : : * recreating a constraint following a SET DATA TYPE operation that
11183 : : * did not impugn its validity.
11184 : : */
11185 [ + + + + : 1710 : if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
+ + ]
11186 [ + - ]: 605 : fkconstraint->is_enforced)
11187 : : {
11188 : : NewConstraint *newcon;
11189 : : AlteredTableInfo *tab;
11190 : :
11191 : 605 : tab = ATGetQueueEntry(wqueue, rel);
11192 : :
11193 : 605 : newcon = palloc0_object(NewConstraint);
11194 : 605 : newcon->name = get_constraint_name(parentConstr);
11195 : 605 : newcon->contype = CONSTR_FOREIGN;
11196 : 605 : newcon->refrelid = RelationGetRelid(pkrel);
11197 : 605 : newcon->refindid = indexOid;
11198 : 605 : newcon->conid = parentConstr;
11199 : 605 : newcon->conwithperiod = fkconstraint->fk_with_period;
11200 : 605 : newcon->qual = (Node *) fkconstraint;
11201 : :
11202 : 605 : tab->constraints = lappend(tab->constraints, newcon);
11203 : : }
11204 : : }
11205 [ + - ]: 309 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11206 : : {
11207 : 309 : PartitionDesc pd = RelationGetPartitionDesc(rel, true);
11208 : : Relation trigrel;
11209 : :
11210 : : /*
11211 : : * Triggers of the foreign keys will be manipulated a bunch of times
11212 : : * in the loop below. To avoid repeatedly opening/closing the trigger
11213 : : * catalog relation, we open it here and pass it to the subroutines
11214 : : * called below.
11215 : : */
11216 : 309 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11217 : :
11218 : : /*
11219 : : * Recurse to take appropriate action on each partition; either we
11220 : : * find an existing constraint to reparent to ours, or we create a new
11221 : : * one.
11222 : : */
11223 [ + + ]: 590 : for (int i = 0; i < pd->nparts; i++)
11224 : : {
11225 : 285 : Relation partition = table_open(pd->oids[i], lockmode);
11226 : : List *partFKs;
11227 : : AttrMap *attmap;
11228 : : AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
11229 : : bool attached;
11230 : : ObjectAddress address;
11231 : :
11232 : 285 : CheckAlterTableIsSafe(partition);
11233 : :
11234 : 281 : attmap = build_attrmap_by_name(RelationGetDescr(partition),
11235 : : RelationGetDescr(rel),
11236 : : false);
11237 [ + + ]: 706 : for (int j = 0; j < numfks; j++)
11238 : 425 : mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
11239 : :
11240 : : /* Check whether an existing constraint can be repurposed */
11241 : 281 : partFKs = copyObject(RelationGetFKeyList(partition));
11242 : 281 : attached = false;
11243 [ + + + + : 571 : foreach_node(ForeignKeyCacheInfo, fk, partFKs)
+ + ]
11244 : : {
11245 [ + + ]: 17 : if (tryAttachPartitionForeignKey(wqueue,
11246 : : fk,
11247 : : partition,
11248 : : parentConstr,
11249 : : numfks,
11250 : : mapped_fkattnum,
11251 : : pkattnum,
11252 : : pfeqoperators,
11253 : : insertTriggerOid,
11254 : : updateTriggerOid,
11255 : : trigrel))
11256 : : {
11257 : 8 : attached = true;
11258 : 8 : break;
11259 : : }
11260 : : }
11261 [ + + ]: 281 : if (attached)
11262 : : {
11263 : 8 : table_close(partition, NoLock);
11264 : 8 : continue;
11265 : : }
11266 : :
11267 : : /*
11268 : : * No luck finding a good constraint to reuse; create our own.
11269 : : */
11270 : 273 : address = addFkConstraint(addFkReferencingSide,
11271 : : fkconstraint->conname, fkconstraint,
11272 : : partition, pkrel, indexOid, parentConstr,
11273 : : numfks, pkattnum,
11274 : : mapped_fkattnum, pfeqoperators,
11275 : : ppeqoperators, ffeqoperators,
11276 : : numfkdelsetcols, fkdelsetcols, true,
11277 : : with_period);
11278 : :
11279 : : /* call ourselves to finalize the creation and we're done */
11280 : 273 : addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
11281 : : indexOid,
11282 : : address.objectId,
11283 : : numfks,
11284 : : pkattnum,
11285 : : mapped_fkattnum,
11286 : : pfeqoperators,
11287 : : ppeqoperators,
11288 : : ffeqoperators,
11289 : : numfkdelsetcols,
11290 : : fkdelsetcols,
11291 : : old_check_ok,
11292 : : lockmode,
11293 : : insertTriggerOid,
11294 : : updateTriggerOid,
11295 : : with_period);
11296 : :
11297 : 273 : table_close(partition, NoLock);
11298 : : }
11299 : :
11300 : 305 : table_close(trigrel, RowExclusiveLock);
11301 : : }
11302 : 2015 : }
11303 : :
11304 : : /*
11305 : : * CloneForeignKeyConstraints
11306 : : * Clone foreign keys from a partitioned table to a newly acquired
11307 : : * partition.
11308 : : *
11309 : : * partitionRel is a partition of parentRel, so we can be certain that it has
11310 : : * the same columns with the same datatypes. The columns may be in different
11311 : : * order, though.
11312 : : *
11313 : : * wqueue must be passed to set up phase 3 constraint checking, unless the
11314 : : * referencing-side partition is known to be empty (such as in CREATE TABLE /
11315 : : * PARTITION OF).
11316 : : */
11317 : : static void
11318 : 7049 : CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
11319 : : Relation partitionRel)
11320 : : {
11321 : : /* This only works for declarative partitioning */
11322 : : Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
11323 : :
11324 : : /*
11325 : : * First, clone constraints where the parent is on the referencing side.
11326 : : */
11327 : 7049 : CloneFkReferencing(wqueue, parentRel, partitionRel);
11328 : :
11329 : : /*
11330 : : * Clone constraints for which the parent is on the referenced side.
11331 : : */
11332 : 7037 : CloneFkReferenced(parentRel, partitionRel);
11333 : 7037 : }
11334 : :
11335 : : /*
11336 : : * CloneFkReferenced
11337 : : * Subroutine for CloneForeignKeyConstraints
11338 : : *
11339 : : * Find all the FKs that have the parent relation on the referenced side;
11340 : : * clone those constraints to the given partition. This is to be called
11341 : : * when the partition is being created or attached.
11342 : : *
11343 : : * This recurses to partitions, if the relation being attached is partitioned.
11344 : : * Recursion is done by calling addFkRecurseReferenced.
11345 : : */
11346 : : static void
11347 : 7037 : CloneFkReferenced(Relation parentRel, Relation partitionRel)
11348 : : {
11349 : : Relation pg_constraint;
11350 : : AttrMap *attmap;
11351 : : ListCell *cell;
11352 : : SysScanDesc scan;
11353 : : ScanKeyData key[2];
11354 : : HeapTuple tuple;
11355 : 7037 : List *clone = NIL;
11356 : : Relation trigrel;
11357 : :
11358 : : /*
11359 : : * Search for any constraints where this partition's parent is in the
11360 : : * referenced side. However, we must not clone any constraint whose
11361 : : * parent constraint is also going to be cloned, to avoid duplicates. So
11362 : : * do it in two steps: first construct the list of constraints to clone,
11363 : : * then go over that list cloning those whose parents are not in the list.
11364 : : * (We must not rely on the parent being seen first, since the catalog
11365 : : * scan could return children first.)
11366 : : */
11367 : 7037 : pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11368 : 7037 : ScanKeyInit(&key[0],
11369 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
11370 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
11371 : 7037 : ScanKeyInit(&key[1],
11372 : : Anum_pg_constraint_contype, BTEqualStrategyNumber,
11373 : : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
11374 : : /* This is a seqscan, as we don't have a usable index ... */
11375 : 7037 : scan = systable_beginscan(pg_constraint, InvalidOid, true,
11376 : : NULL, 2, key);
11377 [ + + ]: 7289 : while ((tuple = systable_getnext(scan)) != NULL)
11378 : : {
11379 : 252 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11380 : :
11381 : 252 : clone = lappend_oid(clone, constrForm->oid);
11382 : : }
11383 : 7037 : systable_endscan(scan);
11384 : 7037 : table_close(pg_constraint, RowShareLock);
11385 : :
11386 : : /*
11387 : : * Triggers of the foreign keys will be manipulated a bunch of times in
11388 : : * the loop below. To avoid repeatedly opening/closing the trigger
11389 : : * catalog relation, we open it here and pass it to the subroutines called
11390 : : * below.
11391 : : */
11392 : 7037 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11393 : :
11394 : 7037 : attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
11395 : : RelationGetDescr(parentRel),
11396 : : false);
11397 [ + + + + : 7289 : foreach(cell, clone)
+ + ]
11398 : : {
11399 : 252 : Oid constrOid = lfirst_oid(cell);
11400 : : Form_pg_constraint constrForm;
11401 : : Relation fkRel;
11402 : : Oid indexOid;
11403 : : Oid partIndexId;
11404 : : int numfks;
11405 : : AttrNumber conkey[INDEX_MAX_KEYS];
11406 : : AttrNumber mapped_confkey[INDEX_MAX_KEYS];
11407 : : AttrNumber confkey[INDEX_MAX_KEYS];
11408 : : Oid conpfeqop[INDEX_MAX_KEYS];
11409 : : Oid conppeqop[INDEX_MAX_KEYS];
11410 : : Oid conffeqop[INDEX_MAX_KEYS];
11411 : : int numfkdelsetcols;
11412 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11413 : : Constraint *fkconstraint;
11414 : : ObjectAddress address;
11415 : 252 : Oid deleteTriggerOid = InvalidOid,
11416 : 252 : updateTriggerOid = InvalidOid;
11417 : :
11418 : 252 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
11419 [ - + ]: 252 : if (!HeapTupleIsValid(tuple))
11420 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
11421 : 252 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11422 : :
11423 : : /*
11424 : : * As explained above: don't try to clone a constraint for which we're
11425 : : * going to clone the parent.
11426 : : */
11427 [ + + ]: 252 : if (list_member_oid(clone, constrForm->conparentid))
11428 : : {
11429 : 148 : ReleaseSysCache(tuple);
11430 : 148 : continue;
11431 : : }
11432 : :
11433 : : /* We need the same lock level that CreateTrigger will acquire */
11434 : 104 : fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
11435 : :
11436 : 104 : indexOid = constrForm->conindid;
11437 : 104 : DeconstructFkConstraintRow(tuple,
11438 : : &numfks,
11439 : : conkey,
11440 : : confkey,
11441 : : conpfeqop,
11442 : : conppeqop,
11443 : : conffeqop,
11444 : : &numfkdelsetcols,
11445 : : confdelsetcols);
11446 : :
11447 [ + + ]: 236 : for (int i = 0; i < numfks; i++)
11448 : 132 : mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
11449 : :
11450 : 104 : fkconstraint = makeNode(Constraint);
11451 : 104 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11452 : 104 : fkconstraint->conname = NameStr(constrForm->conname);
11453 : 104 : fkconstraint->deferrable = constrForm->condeferrable;
11454 : 104 : fkconstraint->initdeferred = constrForm->condeferred;
11455 : 104 : fkconstraint->location = -1;
11456 : 104 : fkconstraint->pktable = NULL;
11457 : : /* ->fk_attrs determined below */
11458 : 104 : fkconstraint->pk_attrs = NIL;
11459 : 104 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11460 : 104 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11461 : 104 : fkconstraint->fk_del_action = constrForm->confdeltype;
11462 : 104 : fkconstraint->fk_del_set_cols = NIL;
11463 : 104 : fkconstraint->old_conpfeqop = NIL;
11464 : 104 : fkconstraint->old_pktable_oid = InvalidOid;
11465 : 104 : fkconstraint->is_enforced = constrForm->conenforced;
11466 : 104 : fkconstraint->skip_validation = false;
11467 : 104 : fkconstraint->initially_valid = constrForm->convalidated;
11468 : :
11469 : : /* set up colnames that are used to generate the constraint name */
11470 [ + + ]: 236 : for (int i = 0; i < numfks; i++)
11471 : : {
11472 : : Form_pg_attribute att;
11473 : :
11474 : 132 : att = TupleDescAttr(RelationGetDescr(fkRel),
11475 : 132 : conkey[i] - 1);
11476 : 132 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11477 : 132 : makeString(NameStr(att->attname)));
11478 : : }
11479 : :
11480 : : /*
11481 : : * Add the new foreign key constraint pointing to the new partition.
11482 : : * Because this new partition appears in the referenced side of the
11483 : : * constraint, we don't need to set up for Phase 3 check.
11484 : : */
11485 : 104 : partIndexId = index_get_partition(partitionRel, indexOid);
11486 [ - + ]: 104 : if (!OidIsValid(partIndexId))
11487 [ # # ]: 0 : elog(ERROR, "index for %u not found in partition %s",
11488 : : indexOid, RelationGetRelationName(partitionRel));
11489 : :
11490 : : /*
11491 : : * Get the "action" triggers belonging to the constraint to pass as
11492 : : * parent OIDs for similar triggers that will be created on the
11493 : : * partition in addFkRecurseReferenced().
11494 : : */
11495 [ + - ]: 104 : if (constrForm->conenforced)
11496 : 104 : GetForeignKeyActionTriggers(trigrel, constrOid,
11497 : : constrForm->confrelid, constrForm->conrelid,
11498 : : &deleteTriggerOid, &updateTriggerOid);
11499 : :
11500 : : /* Add this constraint ... */
11501 : 104 : address = addFkConstraint(addFkReferencedSide,
11502 : : fkconstraint->conname, fkconstraint, fkRel,
11503 : : partitionRel, partIndexId, constrOid,
11504 : : numfks, mapped_confkey,
11505 : : conkey, conpfeqop, conppeqop, conffeqop,
11506 : : numfkdelsetcols, confdelsetcols, false,
11507 : 104 : constrForm->conperiod);
11508 : : /* ... and recurse */
11509 : 104 : addFkRecurseReferenced(fkconstraint,
11510 : : fkRel,
11511 : : partitionRel,
11512 : : partIndexId,
11513 : : address.objectId,
11514 : : numfks,
11515 : : mapped_confkey,
11516 : : conkey,
11517 : : conpfeqop,
11518 : : conppeqop,
11519 : : conffeqop,
11520 : : numfkdelsetcols,
11521 : : confdelsetcols,
11522 : : true,
11523 : : deleteTriggerOid,
11524 : : updateTriggerOid,
11525 : 104 : constrForm->conperiod);
11526 : :
11527 : 104 : table_close(fkRel, NoLock);
11528 : 104 : ReleaseSysCache(tuple);
11529 : : }
11530 : :
11531 : 7037 : table_close(trigrel, RowExclusiveLock);
11532 : 7037 : }
11533 : :
11534 : : /*
11535 : : * CloneFkReferencing
11536 : : * Subroutine for CloneForeignKeyConstraints
11537 : : *
11538 : : * For each FK constraint of the parent relation in the given list, find an
11539 : : * equivalent constraint in its partition relation that can be reparented;
11540 : : * if one cannot be found, create a new constraint in the partition as its
11541 : : * child.
11542 : : *
11543 : : * If wqueue is given, it is used to set up phase-3 verification for each
11544 : : * cloned constraint; omit it if such verification is not needed
11545 : : * (example: the partition is being created anew).
11546 : : */
11547 : : static void
11548 : 7049 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
11549 : : {
11550 : : AttrMap *attmap;
11551 : : List *partFKs;
11552 : 7049 : List *clone = NIL;
11553 : : ListCell *cell;
11554 : : Relation trigrel;
11555 : :
11556 : : /* obtain a list of constraints that we need to clone */
11557 [ + + + + : 7836 : foreach(cell, RelationGetFKeyList(parentRel))
+ + ]
11558 : : {
11559 : 791 : ForeignKeyCacheInfo *fk = lfirst(cell);
11560 : :
11561 : : /*
11562 : : * Refuse to attach a table as partition that this partitioned table
11563 : : * already has a foreign key to. This isn't useful schema, which is
11564 : : * proven by the fact that there have been no user complaints that
11565 : : * it's already impossible to achieve this in the opposite direction,
11566 : : * i.e., creating a foreign key that references a partition. This
11567 : : * restriction allows us to dodge some complexities around
11568 : : * pg_constraint and pg_trigger row creations that would be needed
11569 : : * during ATTACH/DETACH for this kind of relationship.
11570 : : */
11571 [ + + ]: 791 : if (fk->confrelid == RelationGetRelid(partRel))
11572 [ + - ]: 4 : ereport(ERROR,
11573 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11574 : : errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
11575 : : RelationGetRelationName(partRel),
11576 : : get_constraint_name(fk->conoid))));
11577 : :
11578 : 787 : clone = lappend_oid(clone, fk->conoid);
11579 : : }
11580 : :
11581 : : /*
11582 : : * Silently do nothing if there's nothing to do. In particular, this
11583 : : * avoids throwing a spurious error for foreign tables.
11584 : : */
11585 [ + + ]: 7045 : if (clone == NIL)
11586 : 6722 : return;
11587 : :
11588 [ - + ]: 323 : if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11589 [ # # ]: 0 : ereport(ERROR,
11590 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11591 : : errmsg("foreign key constraints are not supported on foreign tables")));
11592 : :
11593 : : /*
11594 : : * Triggers of the foreign keys will be manipulated a bunch of times in
11595 : : * the loop below. To avoid repeatedly opening/closing the trigger
11596 : : * catalog relation, we open it here and pass it to the subroutines called
11597 : : * below.
11598 : : */
11599 : 323 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11600 : :
11601 : : /*
11602 : : * The constraint key may differ, if the columns in the partition are
11603 : : * different. This map is used to convert them.
11604 : : */
11605 : 323 : attmap = build_attrmap_by_name(RelationGetDescr(partRel),
11606 : : RelationGetDescr(parentRel),
11607 : : false);
11608 : :
11609 : 323 : partFKs = copyObject(RelationGetFKeyList(partRel));
11610 : :
11611 [ + - + + : 1102 : foreach(cell, clone)
+ + ]
11612 : : {
11613 : 787 : Oid parentConstrOid = lfirst_oid(cell);
11614 : : Form_pg_constraint constrForm;
11615 : : Relation pkrel;
11616 : : HeapTuple tuple;
11617 : : int numfks;
11618 : : AttrNumber conkey[INDEX_MAX_KEYS];
11619 : : AttrNumber mapped_conkey[INDEX_MAX_KEYS];
11620 : : AttrNumber confkey[INDEX_MAX_KEYS];
11621 : : Oid conpfeqop[INDEX_MAX_KEYS];
11622 : : Oid conppeqop[INDEX_MAX_KEYS];
11623 : : Oid conffeqop[INDEX_MAX_KEYS];
11624 : : int numfkdelsetcols;
11625 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11626 : : Constraint *fkconstraint;
11627 : : bool attached;
11628 : : Oid indexOid;
11629 : : ObjectAddress address;
11630 : : ListCell *lc;
11631 : 787 : Oid insertTriggerOid = InvalidOid,
11632 : 787 : updateTriggerOid = InvalidOid;
11633 : : bool with_period;
11634 : :
11635 : 787 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
11636 [ - + ]: 787 : if (!HeapTupleIsValid(tuple))
11637 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
11638 : : parentConstrOid);
11639 : 787 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11640 : :
11641 : : /* Don't clone constraints whose parents are being cloned */
11642 [ + + ]: 787 : if (list_member_oid(clone, constrForm->conparentid))
11643 : : {
11644 : 440 : ReleaseSysCache(tuple);
11645 : 540 : continue;
11646 : : }
11647 : :
11648 : : /*
11649 : : * Need to prevent concurrent deletions. If pkrel is a partitioned
11650 : : * relation, that means to lock all partitions.
11651 : : */
11652 : 347 : pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
11653 [ + + ]: 347 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11654 : 148 : (void) find_all_inheritors(RelationGetRelid(pkrel),
11655 : : ShareRowExclusiveLock, NULL);
11656 : :
11657 : 347 : DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
11658 : : conpfeqop, conppeqop, conffeqop,
11659 : : &numfkdelsetcols, confdelsetcols);
11660 [ + + ]: 850 : for (int i = 0; i < numfks; i++)
11661 : 503 : mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
11662 : :
11663 : : /*
11664 : : * Get the "check" triggers belonging to the constraint, if it is
11665 : : * ENFORCED, to pass as parent OIDs for similar triggers that will be
11666 : : * created on the partition in addFkRecurseReferencing(). They are
11667 : : * also passed to tryAttachPartitionForeignKey() below to simply
11668 : : * assign as parents to the partition's existing "check" triggers,
11669 : : * that is, if the corresponding constraints is deemed attachable to
11670 : : * the parent constraint.
11671 : : */
11672 [ + + ]: 347 : if (constrForm->conenforced)
11673 : 339 : GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
11674 : : constrForm->confrelid, constrForm->conrelid,
11675 : : &insertTriggerOid, &updateTriggerOid);
11676 : :
11677 : : /*
11678 : : * Before creating a new constraint, see whether any existing FKs are
11679 : : * fit for the purpose. If one is, attach the parent constraint to
11680 : : * it, and don't clone anything. This way we avoid the expensive
11681 : : * verification step and don't end up with a duplicate FK, and we
11682 : : * don't need to recurse to partitions for this constraint.
11683 : : */
11684 : 347 : attached = false;
11685 [ + + + + : 407 : foreach(lc, partFKs)
+ + ]
11686 : : {
11687 : 164 : ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
11688 : :
11689 [ + + ]: 164 : if (tryAttachPartitionForeignKey(wqueue,
11690 : : fk,
11691 : : partRel,
11692 : : parentConstrOid,
11693 : : numfks,
11694 : : mapped_conkey,
11695 : : confkey,
11696 : : conpfeqop,
11697 : : insertTriggerOid,
11698 : : updateTriggerOid,
11699 : : trigrel))
11700 : : {
11701 : 100 : attached = true;
11702 : 100 : table_close(pkrel, NoLock);
11703 : 100 : break;
11704 : : }
11705 : : }
11706 [ + + ]: 343 : if (attached)
11707 : : {
11708 : 100 : ReleaseSysCache(tuple);
11709 : 100 : continue;
11710 : : }
11711 : :
11712 : : /* No dice. Set up to create our own constraint */
11713 : 243 : fkconstraint = makeNode(Constraint);
11714 : 243 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11715 : : /* ->conname determined below */
11716 : 243 : fkconstraint->deferrable = constrForm->condeferrable;
11717 : 243 : fkconstraint->initdeferred = constrForm->condeferred;
11718 : 243 : fkconstraint->location = -1;
11719 : 243 : fkconstraint->pktable = NULL;
11720 : : /* ->fk_attrs determined below */
11721 : 243 : fkconstraint->pk_attrs = NIL;
11722 : 243 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11723 : 243 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11724 : 243 : fkconstraint->fk_del_action = constrForm->confdeltype;
11725 : 243 : fkconstraint->fk_del_set_cols = NIL;
11726 : 243 : fkconstraint->old_conpfeqop = NIL;
11727 : 243 : fkconstraint->old_pktable_oid = InvalidOid;
11728 : 243 : fkconstraint->is_enforced = constrForm->conenforced;
11729 : 243 : fkconstraint->skip_validation = false;
11730 : 243 : fkconstraint->initially_valid = constrForm->convalidated;
11731 [ + + ]: 566 : for (int i = 0; i < numfks; i++)
11732 : : {
11733 : : Form_pg_attribute att;
11734 : :
11735 : 323 : att = TupleDescAttr(RelationGetDescr(partRel),
11736 : 323 : mapped_conkey[i] - 1);
11737 : 323 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11738 : 323 : makeString(NameStr(att->attname)));
11739 : : }
11740 : :
11741 : 243 : indexOid = constrForm->conindid;
11742 : 243 : with_period = constrForm->conperiod;
11743 : :
11744 : : /* Create the pg_constraint entry at this level */
11745 : 243 : address = addFkConstraint(addFkReferencingSide,
11746 : 243 : NameStr(constrForm->conname), fkconstraint,
11747 : : partRel, pkrel, indexOid, parentConstrOid,
11748 : : numfks, confkey,
11749 : : mapped_conkey, conpfeqop,
11750 : : conppeqop, conffeqop,
11751 : : numfkdelsetcols, confdelsetcols,
11752 : : false, with_period);
11753 : :
11754 : : /* Done with the cloned constraint's tuple */
11755 : 243 : ReleaseSysCache(tuple);
11756 : :
11757 : : /* Create the check triggers, and recurse to partitions, if any */
11758 : 243 : addFkRecurseReferencing(wqueue,
11759 : : fkconstraint,
11760 : : partRel,
11761 : : pkrel,
11762 : : indexOid,
11763 : : address.objectId,
11764 : : numfks,
11765 : : confkey,
11766 : : mapped_conkey,
11767 : : conpfeqop,
11768 : : conppeqop,
11769 : : conffeqop,
11770 : : numfkdelsetcols,
11771 : : confdelsetcols,
11772 : : false, /* no old check exists */
11773 : : AccessExclusiveLock,
11774 : : insertTriggerOid,
11775 : : updateTriggerOid,
11776 : : with_period);
11777 : 239 : table_close(pkrel, NoLock);
11778 : : }
11779 : :
11780 : 315 : table_close(trigrel, RowExclusiveLock);
11781 : : }
11782 : :
11783 : : /*
11784 : : * When the parent of a partition receives [the referencing side of] a foreign
11785 : : * key, we must propagate that foreign key to the partition. However, the
11786 : : * partition might already have an equivalent foreign key; this routine
11787 : : * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
11788 : : * by the other parameters. If they are equivalent, create the link between
11789 : : * the two constraints and return true.
11790 : : *
11791 : : * If the given FK does not match the one defined by rest of the params,
11792 : : * return false.
11793 : : */
11794 : : static bool
11795 : 181 : tryAttachPartitionForeignKey(List **wqueue,
11796 : : ForeignKeyCacheInfo *fk,
11797 : : Relation partition,
11798 : : Oid parentConstrOid,
11799 : : int numfks,
11800 : : AttrNumber *mapped_conkey,
11801 : : AttrNumber *confkey,
11802 : : Oid *conpfeqop,
11803 : : Oid parentInsTrigger,
11804 : : Oid parentUpdTrigger,
11805 : : Relation trigrel)
11806 : : {
11807 : : HeapTuple parentConstrTup;
11808 : : Form_pg_constraint parentConstr;
11809 : : HeapTuple partcontup;
11810 : : Form_pg_constraint partConstr;
11811 : :
11812 : 181 : parentConstrTup = SearchSysCache1(CONSTROID,
11813 : : ObjectIdGetDatum(parentConstrOid));
11814 [ - + ]: 181 : if (!HeapTupleIsValid(parentConstrTup))
11815 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11816 : 181 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11817 : :
11818 : : /*
11819 : : * Do some quick & easy initial checks. If any of these fail, we cannot
11820 : : * use this constraint.
11821 : : */
11822 [ + - - + ]: 181 : if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
11823 : : {
11824 : 0 : ReleaseSysCache(parentConstrTup);
11825 : 0 : return false;
11826 : : }
11827 [ + + ]: 503 : for (int i = 0; i < numfks; i++)
11828 : : {
11829 [ + - ]: 322 : if (fk->conkey[i] != mapped_conkey[i] ||
11830 [ + - ]: 322 : fk->confkey[i] != confkey[i] ||
11831 [ - + ]: 322 : fk->conpfeqop[i] != conpfeqop[i])
11832 : : {
11833 : 0 : ReleaseSysCache(parentConstrTup);
11834 : 0 : return false;
11835 : : }
11836 : : }
11837 : :
11838 : : /* Looks good so far; perform more extensive checks. */
11839 : 181 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
11840 [ - + ]: 181 : if (!HeapTupleIsValid(partcontup))
11841 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
11842 : 181 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11843 : :
11844 : : /*
11845 : : * An error should be raised if the constraint enforceability is
11846 : : * different. Returning false without raising an error, as we do for other
11847 : : * attributes, could lead to a duplicate constraint with the same
11848 : : * enforceability as the parent. While this may be acceptable, it may not
11849 : : * be ideal. Therefore, it's better to raise an error and allow the user
11850 : : * to correct the enforceability before proceeding.
11851 : : */
11852 [ + + ]: 181 : if (partConstr->conenforced != parentConstr->conenforced)
11853 [ + - ]: 4 : ereport(ERROR,
11854 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
11855 : : errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
11856 : : NameStr(parentConstr->conname),
11857 : : NameStr(partConstr->conname),
11858 : : RelationGetRelationName(partition))));
11859 : :
11860 [ + + ]: 177 : if (OidIsValid(partConstr->conparentid) ||
11861 [ + + ]: 158 : partConstr->condeferrable != parentConstr->condeferrable ||
11862 [ + - ]: 140 : partConstr->condeferred != parentConstr->condeferred ||
11863 [ + + ]: 140 : partConstr->confupdtype != parentConstr->confupdtype ||
11864 [ + - ]: 117 : partConstr->confdeltype != parentConstr->confdeltype ||
11865 [ + + ]: 117 : partConstr->confmatchtype != parentConstr->confmatchtype)
11866 : : {
11867 : 69 : ReleaseSysCache(parentConstrTup);
11868 : 69 : ReleaseSysCache(partcontup);
11869 : 69 : return false;
11870 : : }
11871 : :
11872 : 108 : ReleaseSysCache(parentConstrTup);
11873 : 108 : ReleaseSysCache(partcontup);
11874 : :
11875 : : /* Looks good! Attach this constraint. */
11876 : 108 : AttachPartitionForeignKey(wqueue, partition, fk->conoid,
11877 : : parentConstrOid, parentInsTrigger,
11878 : : parentUpdTrigger, trigrel);
11879 : :
11880 : 108 : return true;
11881 : : }
11882 : :
11883 : : /*
11884 : : * AttachPartitionForeignKey
11885 : : *
11886 : : * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
11887 : : * attaching the constraint, removing redundant triggers and entries from
11888 : : * pg_constraint, and setting the constraint's parent.
11889 : : */
11890 : : static void
11891 : 108 : AttachPartitionForeignKey(List **wqueue,
11892 : : Relation partition,
11893 : : Oid partConstrOid,
11894 : : Oid parentConstrOid,
11895 : : Oid parentInsTrigger,
11896 : : Oid parentUpdTrigger,
11897 : : Relation trigrel)
11898 : : {
11899 : : HeapTuple parentConstrTup;
11900 : : Form_pg_constraint parentConstr;
11901 : : HeapTuple partcontup;
11902 : : Form_pg_constraint partConstr;
11903 : : bool queueValidation;
11904 : : Oid partConstrFrelid;
11905 : : Oid partConstrRelid;
11906 : : bool parentConstrIsEnforced;
11907 : :
11908 : : /* Fetch the parent constraint tuple */
11909 : 108 : parentConstrTup = SearchSysCache1(CONSTROID,
11910 : : ObjectIdGetDatum(parentConstrOid));
11911 [ - + ]: 108 : if (!HeapTupleIsValid(parentConstrTup))
11912 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11913 : 108 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11914 : 108 : parentConstrIsEnforced = parentConstr->conenforced;
11915 : :
11916 : : /* Fetch the child constraint tuple */
11917 : 108 : partcontup = SearchSysCache1(CONSTROID,
11918 : : ObjectIdGetDatum(partConstrOid));
11919 [ - + ]: 108 : if (!HeapTupleIsValid(partcontup))
11920 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11921 : 108 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11922 : 108 : partConstrFrelid = partConstr->confrelid;
11923 : 108 : partConstrRelid = partConstr->conrelid;
11924 : :
11925 : : /*
11926 : : * If the referenced table is partitioned, then the partition we're
11927 : : * attaching now has extra pg_constraint rows and action triggers that are
11928 : : * no longer needed. Remove those.
11929 : : */
11930 [ + + ]: 108 : if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
11931 : : {
11932 : 24 : Relation pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11933 : :
11934 : 24 : RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
11935 : : partConstrRelid);
11936 : :
11937 : 24 : table_close(pg_constraint, RowShareLock);
11938 : : }
11939 : :
11940 : : /*
11941 : : * Will we need to validate this constraint? A valid parent constraint
11942 : : * implies that all child constraints have been validated, so if this one
11943 : : * isn't, we must trigger phase 3 validation.
11944 : : */
11945 [ + + + + ]: 108 : queueValidation = parentConstr->convalidated && !partConstr->convalidated;
11946 : :
11947 : 108 : ReleaseSysCache(partcontup);
11948 : 108 : ReleaseSysCache(parentConstrTup);
11949 : :
11950 : : /*
11951 : : * The action triggers in the new partition become redundant -- the parent
11952 : : * table already has equivalent ones, and those will be able to reach the
11953 : : * partition. Remove the ones in the partition. We identify them because
11954 : : * they have our constraint OID, as well as being on the referenced rel.
11955 : : */
11956 : 108 : DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
11957 : : partConstrRelid);
11958 : :
11959 : 108 : ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
11960 : : RelationGetRelid(partition));
11961 : :
11962 : : /*
11963 : : * Like the constraint, attach partition's "check" triggers to the
11964 : : * corresponding parent triggers if the constraint is ENFORCED. NOT
11965 : : * ENFORCED constraints do not have these triggers.
11966 : : */
11967 [ + + ]: 108 : if (parentConstrIsEnforced)
11968 : : {
11969 : : Oid insertTriggerOid,
11970 : : updateTriggerOid;
11971 : :
11972 : 100 : GetForeignKeyCheckTriggers(trigrel,
11973 : : partConstrOid, partConstrFrelid, partConstrRelid,
11974 : : &insertTriggerOid, &updateTriggerOid);
11975 : : Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
11976 : 100 : TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
11977 : : RelationGetRelid(partition));
11978 : : Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
11979 : 100 : TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
11980 : : RelationGetRelid(partition));
11981 : : }
11982 : :
11983 : : /*
11984 : : * We updated this pg_constraint row above to set its parent; validating
11985 : : * it will cause its convalidated flag to change, so we need CCI here. In
11986 : : * addition, we need it unconditionally for the rare case where the parent
11987 : : * table has *two* identical constraints; when reaching this function for
11988 : : * the second one, we must have made our changes visible, otherwise we
11989 : : * would try to attach both to this one.
11990 : : */
11991 : 108 : CommandCounterIncrement();
11992 : :
11993 : : /* If validation is needed, put it in the queue now. */
11994 [ + + ]: 108 : if (queueValidation)
11995 : : {
11996 : : Relation conrel;
11997 : : Oid confrelid;
11998 : :
11999 : 12 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12000 : :
12001 : 12 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
12002 [ - + ]: 12 : if (!HeapTupleIsValid(partcontup))
12003 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
12004 : :
12005 : 12 : confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
12006 : :
12007 : : /* Use the same lock as for AT_ValidateConstraint */
12008 : 12 : QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
12009 : : partcontup, ShareUpdateExclusiveLock);
12010 : 12 : ReleaseSysCache(partcontup);
12011 : 12 : table_close(conrel, RowExclusiveLock);
12012 : : }
12013 : 108 : }
12014 : :
12015 : : /*
12016 : : * RemoveInheritedConstraint
12017 : : *
12018 : : * Removes the constraint and its associated trigger from the specified
12019 : : * relation, which inherited the given constraint.
12020 : : */
12021 : : static void
12022 : 24 : RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
12023 : : Oid conrelid)
12024 : : {
12025 : : ObjectAddresses *objs;
12026 : : HeapTuple consttup;
12027 : : ScanKeyData key;
12028 : : SysScanDesc scan;
12029 : : HeapTuple trigtup;
12030 : :
12031 : 24 : ScanKeyInit(&key,
12032 : : Anum_pg_constraint_conrelid,
12033 : : BTEqualStrategyNumber, F_OIDEQ,
12034 : : ObjectIdGetDatum(conrelid));
12035 : :
12036 : 24 : scan = systable_beginscan(conrel,
12037 : : ConstraintRelidTypidNameIndexId,
12038 : : true, NULL, 1, &key);
12039 : 24 : objs = new_object_addresses();
12040 [ + + ]: 216 : while ((consttup = systable_getnext(scan)) != NULL)
12041 : : {
12042 : 192 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
12043 : :
12044 [ + + ]: 192 : if (conform->conparentid != conoid)
12045 : 140 : continue;
12046 : : else
12047 : : {
12048 : : ObjectAddress addr;
12049 : : SysScanDesc scan2;
12050 : : ScanKeyData key2;
12051 : : int n PG_USED_FOR_ASSERTS_ONLY;
12052 : :
12053 : 52 : ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
12054 : 52 : add_exact_object_address(&addr, objs);
12055 : :
12056 : : /*
12057 : : * First we must delete the dependency record that binds the
12058 : : * constraint records together.
12059 : : */
12060 : 52 : n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
12061 : : conform->oid,
12062 : : DEPENDENCY_INTERNAL,
12063 : : ConstraintRelationId,
12064 : : conoid);
12065 : : Assert(n == 1); /* actually only one is expected */
12066 : :
12067 : : /*
12068 : : * Now search for the triggers for this constraint and set them up
12069 : : * for deletion too
12070 : : */
12071 : 52 : ScanKeyInit(&key2,
12072 : : Anum_pg_trigger_tgconstraint,
12073 : : BTEqualStrategyNumber, F_OIDEQ,
12074 : : ObjectIdGetDatum(conform->oid));
12075 : 52 : scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
12076 : : true, NULL, 1, &key2);
12077 [ + + ]: 156 : while ((trigtup = systable_getnext(scan2)) != NULL)
12078 : : {
12079 : 104 : ObjectAddressSet(addr, TriggerRelationId,
12080 : : ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
12081 : 104 : add_exact_object_address(&addr, objs);
12082 : : }
12083 : 52 : systable_endscan(scan2);
12084 : : }
12085 : : }
12086 : : /* make the dependency deletions visible */
12087 : 24 : CommandCounterIncrement();
12088 : 24 : performMultipleDeletions(objs, DROP_RESTRICT,
12089 : : PERFORM_DELETION_INTERNAL);
12090 : 24 : systable_endscan(scan);
12091 : 24 : }
12092 : :
12093 : : /*
12094 : : * DropForeignKeyConstraintTriggers
12095 : : *
12096 : : * The subroutine for tryAttachPartitionForeignKey handles the deletion of
12097 : : * action triggers for the foreign key constraint.
12098 : : *
12099 : : * If valid confrelid and conrelid values are not provided, the respective
12100 : : * trigger check will be skipped, and the trigger will be considered for
12101 : : * removal.
12102 : : */
12103 : : static void
12104 : 160 : DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
12105 : : Oid conrelid)
12106 : : {
12107 : : ScanKeyData key;
12108 : : SysScanDesc scan;
12109 : : HeapTuple trigtup;
12110 : :
12111 : 160 : ScanKeyInit(&key,
12112 : : Anum_pg_trigger_tgconstraint,
12113 : : BTEqualStrategyNumber, F_OIDEQ,
12114 : : ObjectIdGetDatum(conoid));
12115 : 160 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12116 : : NULL, 1, &key);
12117 [ + + ]: 696 : while ((trigtup = systable_getnext(scan)) != NULL)
12118 : : {
12119 : 536 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12120 : : ObjectAddress trigger;
12121 : :
12122 : : /* Invalid if trigger is not for a referential integrity constraint */
12123 [ - + ]: 536 : if (!OidIsValid(trgform->tgconstrrelid))
12124 : 200 : continue;
12125 [ + + + + ]: 536 : if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
12126 : 200 : continue;
12127 [ + + - + ]: 336 : if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
12128 : 0 : continue;
12129 : :
12130 : : /* We should be dropping trigger related to foreign key constraint */
12131 : : Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
12132 : : trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
12133 : : trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
12134 : : trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
12135 : : trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
12136 : : trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
12137 : : trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
12138 : : trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
12139 : : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
12140 : : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
12141 : : trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
12142 : : trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
12143 : :
12144 : : /*
12145 : : * The constraint is originally set up to contain this trigger as an
12146 : : * implementation object, so there's a dependency record that links
12147 : : * the two; however, since the trigger is no longer needed, we remove
12148 : : * the dependency link in order to be able to drop the trigger while
12149 : : * keeping the constraint intact.
12150 : : */
12151 : 336 : deleteDependencyRecordsFor(TriggerRelationId,
12152 : : trgform->oid,
12153 : : false);
12154 : : /* make dependency deletion visible to performDeletion */
12155 : 336 : CommandCounterIncrement();
12156 : 336 : ObjectAddressSet(trigger, TriggerRelationId,
12157 : : trgform->oid);
12158 : 336 : performDeletion(&trigger, DROP_RESTRICT, 0);
12159 : : /* make trigger drop visible, in case the loop iterates */
12160 : 336 : CommandCounterIncrement();
12161 : : }
12162 : :
12163 : 160 : systable_endscan(scan);
12164 : 160 : }
12165 : :
12166 : : /*
12167 : : * GetForeignKeyActionTriggers
12168 : : * Returns delete and update "action" triggers of the given relation
12169 : : * belonging to the given constraint
12170 : : */
12171 : : static void
12172 : 104 : GetForeignKeyActionTriggers(Relation trigrel,
12173 : : Oid conoid, Oid confrelid, Oid conrelid,
12174 : : Oid *deleteTriggerOid,
12175 : : Oid *updateTriggerOid)
12176 : : {
12177 : : ScanKeyData key;
12178 : : SysScanDesc scan;
12179 : : HeapTuple trigtup;
12180 : :
12181 : 104 : *deleteTriggerOid = *updateTriggerOid = InvalidOid;
12182 : 104 : ScanKeyInit(&key,
12183 : : Anum_pg_trigger_tgconstraint,
12184 : : BTEqualStrategyNumber, F_OIDEQ,
12185 : : ObjectIdGetDatum(conoid));
12186 : :
12187 : 104 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12188 : : NULL, 1, &key);
12189 [ + - ]: 218 : while ((trigtup = systable_getnext(scan)) != NULL)
12190 : : {
12191 : 218 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12192 : :
12193 [ + + ]: 218 : if (trgform->tgconstrrelid != conrelid)
12194 : 7 : continue;
12195 [ - + ]: 211 : if (trgform->tgrelid != confrelid)
12196 : 0 : continue;
12197 : : /* Only ever look at "action" triggers on the PK side. */
12198 [ + + ]: 211 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
12199 : 3 : continue;
12200 [ + + ]: 208 : if (TRIGGER_FOR_DELETE(trgform->tgtype))
12201 : : {
12202 : : Assert(*deleteTriggerOid == InvalidOid);
12203 : 104 : *deleteTriggerOid = trgform->oid;
12204 : : }
12205 [ + - ]: 104 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12206 : : {
12207 : : Assert(*updateTriggerOid == InvalidOid);
12208 : 104 : *updateTriggerOid = trgform->oid;
12209 : : }
12210 : : #ifndef USE_ASSERT_CHECKING
12211 : : /* In an assert-enabled build, continue looking to find duplicates */
12212 [ + + + + ]: 208 : if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
12213 : 104 : break;
12214 : : #endif
12215 : : }
12216 : :
12217 [ - + ]: 104 : if (!OidIsValid(*deleteTriggerOid))
12218 [ # # ]: 0 : elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
12219 : : conoid);
12220 [ - + ]: 104 : if (!OidIsValid(*updateTriggerOid))
12221 [ # # ]: 0 : elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
12222 : : conoid);
12223 : :
12224 : 104 : systable_endscan(scan);
12225 : 104 : }
12226 : :
12227 : : /*
12228 : : * GetForeignKeyCheckTriggers
12229 : : * Returns insert and update "check" triggers of the given relation
12230 : : * belonging to the given constraint
12231 : : */
12232 : : static void
12233 : 507 : GetForeignKeyCheckTriggers(Relation trigrel,
12234 : : Oid conoid, Oid confrelid, Oid conrelid,
12235 : : Oid *insertTriggerOid,
12236 : : Oid *updateTriggerOid)
12237 : : {
12238 : : ScanKeyData key;
12239 : : SysScanDesc scan;
12240 : : HeapTuple trigtup;
12241 : :
12242 : 507 : *insertTriggerOid = *updateTriggerOid = InvalidOid;
12243 : 507 : ScanKeyInit(&key,
12244 : : Anum_pg_trigger_tgconstraint,
12245 : : BTEqualStrategyNumber, F_OIDEQ,
12246 : : ObjectIdGetDatum(conoid));
12247 : :
12248 : 507 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12249 : : NULL, 1, &key);
12250 [ + - ]: 1605 : while ((trigtup = systable_getnext(scan)) != NULL)
12251 : : {
12252 : 1605 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12253 : :
12254 [ + + ]: 1605 : if (trgform->tgconstrrelid != confrelid)
12255 : 521 : continue;
12256 [ - + ]: 1084 : if (trgform->tgrelid != conrelid)
12257 : 0 : continue;
12258 : : /* Only ever look at "check" triggers on the FK side. */
12259 [ + + ]: 1084 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
12260 : 70 : continue;
12261 [ + + ]: 1014 : if (TRIGGER_FOR_INSERT(trgform->tgtype))
12262 : : {
12263 : : Assert(*insertTriggerOid == InvalidOid);
12264 : 507 : *insertTriggerOid = trgform->oid;
12265 : : }
12266 [ + - ]: 507 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12267 : : {
12268 : : Assert(*updateTriggerOid == InvalidOid);
12269 : 507 : *updateTriggerOid = trgform->oid;
12270 : : }
12271 : : #ifndef USE_ASSERT_CHECKING
12272 : : /* In an assert-enabled build, continue looking to find duplicates. */
12273 [ + + + + ]: 1014 : if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
12274 : 507 : break;
12275 : : #endif
12276 : : }
12277 : :
12278 [ - + ]: 507 : if (!OidIsValid(*insertTriggerOid))
12279 [ # # ]: 0 : elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
12280 : : conoid);
12281 [ - + ]: 507 : if (!OidIsValid(*updateTriggerOid))
12282 [ # # ]: 0 : elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
12283 : : conoid);
12284 : :
12285 : 507 : systable_endscan(scan);
12286 : 507 : }
12287 : :
12288 : : /*
12289 : : * ALTER TABLE ALTER CONSTRAINT
12290 : : *
12291 : : * Update the attributes of a constraint.
12292 : : *
12293 : : * Currently works for Foreign Key, Check, and not null constraints.
12294 : : *
12295 : : * If the constraint is modified, returns its address; otherwise, return
12296 : : * InvalidObjectAddress.
12297 : : */
12298 : : static ObjectAddress
12299 : 344 : ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
12300 : : bool recurse, LOCKMODE lockmode)
12301 : : {
12302 : : Relation conrel;
12303 : : Relation tgrel;
12304 : : SysScanDesc scan;
12305 : : ScanKeyData skey[3];
12306 : : HeapTuple contuple;
12307 : : Form_pg_constraint currcon;
12308 : : ObjectAddress address;
12309 : :
12310 : : /*
12311 : : * Disallow altering ONLY a partitioned table, as it would make no sense.
12312 : : * This is okay for legacy inheritance.
12313 : : */
12314 [ + + - + ]: 344 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
12315 [ # # ]: 0 : ereport(ERROR,
12316 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12317 : : errmsg("constraint must be altered in child tables too"),
12318 : : errhint("Do not specify the ONLY keyword."));
12319 : :
12320 : :
12321 : 344 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12322 : 344 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
12323 : :
12324 : : /*
12325 : : * Find and check the target constraint
12326 : : */
12327 : 344 : ScanKeyInit(&skey[0],
12328 : : Anum_pg_constraint_conrelid,
12329 : : BTEqualStrategyNumber, F_OIDEQ,
12330 : : ObjectIdGetDatum(RelationGetRelid(rel)));
12331 : 344 : ScanKeyInit(&skey[1],
12332 : : Anum_pg_constraint_contypid,
12333 : : BTEqualStrategyNumber, F_OIDEQ,
12334 : : ObjectIdGetDatum(InvalidOid));
12335 : 344 : ScanKeyInit(&skey[2],
12336 : : Anum_pg_constraint_conname,
12337 : : BTEqualStrategyNumber, F_NAMEEQ,
12338 : 344 : CStringGetDatum(cmdcon->conname));
12339 : 344 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12340 : : true, NULL, 3, skey);
12341 : :
12342 : : /* There can be at most one matching row */
12343 [ + + ]: 344 : if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
12344 [ + - ]: 4 : ereport(ERROR,
12345 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
12346 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12347 : : cmdcon->conname, RelationGetRelationName(rel))));
12348 : :
12349 : 340 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12350 [ + + - + ]: 340 : if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
12351 [ # # ]: 0 : ereport(ERROR,
12352 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12353 : : errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
12354 : : cmdcon->conname, RelationGetRelationName(rel))));
12355 [ + + ]: 340 : if (cmdcon->alterEnforceability &&
12356 [ + + + + ]: 204 : (currcon->contype != CONSTRAINT_FOREIGN && currcon->contype != CONSTRAINT_CHECK))
12357 [ + - ]: 8 : ereport(ERROR,
12358 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12359 : : errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
12360 : : cmdcon->conname, RelationGetRelationName(rel)),
12361 : : errhint("Only foreign key and check constraints can change enforceability.")));
12362 [ + + ]: 332 : if (cmdcon->alterInheritability &&
12363 [ + + ]: 64 : currcon->contype != CONSTRAINT_NOTNULL)
12364 [ + - ]: 16 : ereport(ERROR,
12365 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
12366 : : errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
12367 : : cmdcon->conname, RelationGetRelationName(rel)));
12368 [ + + ]: 316 : if (cmdcon->alterInheritability &&
12369 [ + + + + ]: 48 : cmdcon->noinherit && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12370 [ + - ]: 4 : ereport(ERROR,
12371 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12372 : : errmsg("not-null constraint \"%s\" on partitioned table \"%s\" cannot be NO INHERIT",
12373 : : cmdcon->conname, RelationGetRelationName(rel)));
12374 : :
12375 : : /* Refuse to modify inheritability of inherited constraints */
12376 [ + + ]: 312 : if (cmdcon->alterInheritability &&
12377 [ + + + + ]: 44 : cmdcon->noinherit && currcon->coninhcount > 0)
12378 [ + - ]: 4 : ereport(ERROR,
12379 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12380 : : errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
12381 : : NameStr(currcon->conname),
12382 : : RelationGetRelationName(rel)));
12383 : :
12384 : : /*
12385 : : * If it's not the topmost constraint, raise an error.
12386 : : *
12387 : : * Altering a non-topmost constraint leaves some triggers untouched, since
12388 : : * they are not directly connected to this constraint; also, pg_dump would
12389 : : * ignore the deferrability status of the individual constraint, since it
12390 : : * only dumps topmost constraints. Avoid these problems by refusing this
12391 : : * operation and telling the user to alter the parent constraint instead.
12392 : : */
12393 [ + + ]: 308 : if (OidIsValid(currcon->conparentid))
12394 : : {
12395 : : HeapTuple tp;
12396 : 8 : Oid parent = currcon->conparentid;
12397 : 8 : char *ancestorname = NULL;
12398 : 8 : char *ancestortable = NULL;
12399 : :
12400 : : /* Loop to find the topmost constraint */
12401 [ + - ]: 16 : while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
12402 : : {
12403 : 16 : Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
12404 : :
12405 : : /* If no parent, this is the constraint we want */
12406 [ + + ]: 16 : if (!OidIsValid(contup->conparentid))
12407 : : {
12408 : 8 : ancestorname = pstrdup(NameStr(contup->conname));
12409 : 8 : ancestortable = get_rel_name(contup->conrelid);
12410 : 8 : ReleaseSysCache(tp);
12411 : 8 : break;
12412 : : }
12413 : :
12414 : 8 : parent = contup->conparentid;
12415 : 8 : ReleaseSysCache(tp);
12416 : : }
12417 : :
12418 [ + - + - : 8 : ereport(ERROR,
+ - ]
12419 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12420 : : errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
12421 : : cmdcon->conname, RelationGetRelationName(rel)),
12422 : : ancestorname && ancestortable ?
12423 : : errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
12424 : : cmdcon->conname, ancestorname, ancestortable) : 0,
12425 : : errhint("You may alter the constraint it derives from instead.")));
12426 : : }
12427 : :
12428 : 300 : address = InvalidObjectAddress;
12429 : :
12430 : : /*
12431 : : * Do the actual catalog work, and recurse if necessary.
12432 : : */
12433 [ + + ]: 300 : if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
12434 : : contuple, recurse, lockmode))
12435 : 244 : ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
12436 : :
12437 : 260 : systable_endscan(scan);
12438 : :
12439 : 260 : table_close(tgrel, RowExclusiveLock);
12440 : 260 : table_close(conrel, RowExclusiveLock);
12441 : :
12442 : 260 : return address;
12443 : : }
12444 : :
12445 : : /*
12446 : : * A subroutine of ATExecAlterConstraint that calls the respective routines for
12447 : : * altering constraint's enforceability, deferrability or inheritability.
12448 : : */
12449 : : static bool
12450 : 300 : ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
12451 : : Relation conrel, Relation tgrel, Relation rel,
12452 : : HeapTuple contuple, bool recurse,
12453 : : LOCKMODE lockmode)
12454 : : {
12455 : : Form_pg_constraint currcon;
12456 : 300 : bool changed = false;
12457 : 300 : List *otherrelids = NIL;
12458 : :
12459 : 300 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12460 : :
12461 : : /*
12462 : : * Do the catalog work for the enforceability or deferrability change,
12463 : : * recurse if necessary.
12464 : : *
12465 : : * Note that even if deferrability is requested to be altered along with
12466 : : * enforceability, we don't need to explicitly update multiple entries in
12467 : : * pg_trigger related to deferrability.
12468 : : *
12469 : : * Modifying foreign key enforceability involves either creating or
12470 : : * dropping the trigger, during which the deferrability setting will be
12471 : : * adjusted automatically.
12472 : : */
12473 [ + + ]: 300 : if (cmdcon->alterEnforceability)
12474 : : {
12475 [ + + ]: 196 : if (currcon->contype == CONSTRAINT_FOREIGN)
12476 : 56 : changed = ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
12477 : : currcon->conrelid,
12478 : : currcon->confrelid,
12479 : : contuple, lockmode,
12480 : : InvalidOid, InvalidOid,
12481 : : InvalidOid, InvalidOid);
12482 [ + - ]: 140 : else if (currcon->contype == CONSTRAINT_CHECK)
12483 : 140 : changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel,
12484 : : contuple, recurse, false,
12485 : : NIL, lockmode);
12486 : : }
12487 [ + + + - ]: 168 : else if (cmdcon->alterDeferrability &&
12488 : 64 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
12489 : : contuple, recurse, &otherrelids,
12490 : : lockmode))
12491 : : {
12492 : : /*
12493 : : * AlterConstrUpdateConstraintEntry already invalidated relcache for
12494 : : * the relations having the constraint itself; here we also invalidate
12495 : : * for relations that have any triggers that are part of the
12496 : : * constraint.
12497 : : */
12498 [ + + + + : 204 : foreach_oid(relid, otherrelids)
+ + ]
12499 : 76 : CacheInvalidateRelcacheByRelid(relid);
12500 : :
12501 : 64 : changed = true;
12502 : : }
12503 : :
12504 : : /*
12505 : : * Do the catalog work for the inheritability change.
12506 : : */
12507 [ + + + - ]: 300 : if (cmdcon->alterInheritability &&
12508 : 40 : ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
12509 : : lockmode))
12510 : 36 : changed = true;
12511 : :
12512 : 260 : return changed;
12513 : : }
12514 : :
12515 : : /*
12516 : : * Returns true if the foreign key constraint's enforceability is altered.
12517 : : *
12518 : : * Depending on whether the constraint is being set to ENFORCED or NOT
12519 : : * ENFORCED, it creates or drops the trigger accordingly.
12520 : : *
12521 : : * Note that we must recurse even when trying to change a constraint to not
12522 : : * enforced if it is already not enforced, in case descendant constraints
12523 : : * might be enforced and need to be changed to not enforced. Conversely, we
12524 : : * should do nothing if a constraint is being set to enforced and is already
12525 : : * enforced, as descendant constraints cannot be different in that case.
12526 : : */
12527 : : static bool
12528 : 120 : ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12529 : : Relation conrel, Relation tgrel,
12530 : : Oid fkrelid, Oid pkrelid,
12531 : : HeapTuple contuple, LOCKMODE lockmode,
12532 : : Oid ReferencedParentDelTrigger,
12533 : : Oid ReferencedParentUpdTrigger,
12534 : : Oid ReferencingParentInsTrigger,
12535 : : Oid ReferencingParentUpdTrigger)
12536 : : {
12537 : : Form_pg_constraint currcon;
12538 : : Oid conoid;
12539 : : Relation rel;
12540 : 120 : bool changed = false;
12541 : :
12542 : : /* Since this function recurses, it could be driven to stack overflow */
12543 : 120 : check_stack_depth();
12544 : :
12545 : : Assert(cmdcon->alterEnforceability);
12546 : :
12547 : 120 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12548 : 120 : conoid = currcon->oid;
12549 : :
12550 : : /* Should be foreign key constraint */
12551 : : Assert(currcon->contype == CONSTRAINT_FOREIGN);
12552 : :
12553 : 120 : rel = table_open(currcon->conrelid, lockmode);
12554 : :
12555 [ + + ]: 120 : if (currcon->conenforced != cmdcon->is_enforced)
12556 : : {
12557 : 116 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12558 : 116 : changed = true;
12559 : : }
12560 : :
12561 : : /* Drop triggers */
12562 [ + + ]: 120 : if (!cmdcon->is_enforced)
12563 : : {
12564 : : /*
12565 : : * When setting a constraint to NOT ENFORCED, the constraint triggers
12566 : : * need to be dropped. Therefore, we must process the child relations
12567 : : * first, followed by the parent, to account for dependencies.
12568 : : */
12569 [ + + - + ]: 92 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12570 : 40 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12571 : 12 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12572 : : fkrelid, pkrelid, contuple,
12573 : : lockmode, InvalidOid, InvalidOid,
12574 : : InvalidOid, InvalidOid);
12575 : :
12576 : : /* Drop all the triggers */
12577 : 52 : DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
12578 : : }
12579 [ + - ]: 68 : else if (changed) /* Create triggers */
12580 : : {
12581 : 68 : Oid ReferencedDelTriggerOid = InvalidOid,
12582 : 68 : ReferencedUpdTriggerOid = InvalidOid,
12583 : 68 : ReferencingInsTriggerOid = InvalidOid,
12584 : 68 : ReferencingUpdTriggerOid = InvalidOid;
12585 : :
12586 : : /* Prepare the minimal information required for trigger creation. */
12587 : 68 : Constraint *fkconstraint = makeNode(Constraint);
12588 : :
12589 : 68 : fkconstraint->conname = pstrdup(NameStr(currcon->conname));
12590 : 68 : fkconstraint->fk_matchtype = currcon->confmatchtype;
12591 : 68 : fkconstraint->fk_upd_action = currcon->confupdtype;
12592 : 68 : fkconstraint->fk_del_action = currcon->confdeltype;
12593 : 68 : fkconstraint->deferrable = currcon->condeferrable;
12594 : 68 : fkconstraint->initdeferred = currcon->condeferred;
12595 : :
12596 : : /* Create referenced triggers */
12597 [ + + ]: 68 : if (currcon->conrelid == fkrelid)
12598 : 40 : createForeignKeyActionTriggers(currcon->conrelid,
12599 : : currcon->confrelid,
12600 : : fkconstraint,
12601 : : conoid,
12602 : : currcon->conindid,
12603 : : ReferencedParentDelTrigger,
12604 : : ReferencedParentUpdTrigger,
12605 : : &ReferencedDelTriggerOid,
12606 : : &ReferencedUpdTriggerOid);
12607 : :
12608 : : /* Create referencing triggers */
12609 [ + + ]: 68 : if (currcon->confrelid == pkrelid)
12610 : 60 : createForeignKeyCheckTriggers(currcon->conrelid,
12611 : : pkrelid,
12612 : : fkconstraint,
12613 : : conoid,
12614 : : currcon->conindid,
12615 : : ReferencingParentInsTrigger,
12616 : : ReferencingParentUpdTrigger,
12617 : : &ReferencingInsTriggerOid,
12618 : : &ReferencingUpdTriggerOid);
12619 : :
12620 : : /*
12621 : : * Tell Phase 3 to check that the constraint is satisfied by existing
12622 : : * rows. Only applies to leaf partitions, and (for constraints that
12623 : : * reference a partitioned table) only if this is not one of the
12624 : : * pg_constraint rows that exist solely to support action triggers.
12625 : : */
12626 [ + + ]: 68 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12627 [ + + ]: 56 : currcon->confrelid == pkrelid)
12628 : : {
12629 : : AlteredTableInfo *tab;
12630 : : NewConstraint *newcon;
12631 : :
12632 : 48 : newcon = palloc0_object(NewConstraint);
12633 : 48 : newcon->name = fkconstraint->conname;
12634 : 48 : newcon->contype = CONSTR_FOREIGN;
12635 : 48 : newcon->refrelid = currcon->confrelid;
12636 : 48 : newcon->refindid = currcon->conindid;
12637 : 48 : newcon->conid = currcon->oid;
12638 : 48 : newcon->qual = (Node *) fkconstraint;
12639 : :
12640 : : /* Find or create work queue entry for this table */
12641 : 48 : tab = ATGetQueueEntry(wqueue, rel);
12642 : 48 : tab->constraints = lappend(tab->constraints, newcon);
12643 : : }
12644 : :
12645 : : /*
12646 : : * If the table at either end of the constraint is partitioned, we
12647 : : * need to recurse and create triggers for each constraint that is a
12648 : : * child of this one.
12649 : : */
12650 [ + + + + ]: 124 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12651 : 56 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12652 : 16 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12653 : : fkrelid, pkrelid, contuple,
12654 : : lockmode,
12655 : : ReferencedDelTriggerOid,
12656 : : ReferencedUpdTriggerOid,
12657 : : ReferencingInsTriggerOid,
12658 : : ReferencingUpdTriggerOid);
12659 : : }
12660 : :
12661 : 120 : table_close(rel, NoLock);
12662 : :
12663 : 120 : return changed;
12664 : : }
12665 : :
12666 : : /*
12667 : : * Returns true if the CHECK constraint's enforceability is altered.
12668 : : */
12669 : : static bool
12670 : 360 : ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12671 : : Relation conrel, HeapTuple contuple,
12672 : : bool recurse, bool recursing,
12673 : : List *changing_conids,
12674 : : LOCKMODE lockmode)
12675 : : {
12676 : : Form_pg_constraint currcon;
12677 : : Relation rel;
12678 : 360 : bool changed = false;
12679 : 360 : List *children = NIL;
12680 : 360 : bool target_enforced = cmdcon->is_enforced;
12681 : 360 : Oid enforced_parentoid = InvalidOid;
12682 : :
12683 : : /* Since this function recurses, it could be driven to stack overflow */
12684 : 360 : check_stack_depth();
12685 : :
12686 : : Assert(cmdcon->alterEnforceability);
12687 : :
12688 : 360 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12689 : :
12690 : : Assert(currcon->contype == CONSTRAINT_CHECK);
12691 : :
12692 : : /*
12693 : : * Parent relation already locked by caller, children will be locked by
12694 : : * find_all_inheritors. So NoLock is fine here.
12695 : : */
12696 : 360 : rel = table_open(currcon->conrelid, NoLock);
12697 : :
12698 : : /*
12699 : : * When setting a constraint to NOT ENFORCED, check whether any matching
12700 : : * parent constraint remains ENFORCED and is not part of this ALTER.
12701 : : *
12702 : : * For a direct ALTER of an inherited constraint, reject the command,
12703 : : * because the child cannot be weakened while its parent remains enforced.
12704 : : *
12705 : : * During recursion, another parent outside this ALTER may still enforce
12706 : : * the same constraint in a regular inheritance hierarchy. In that case,
12707 : : * keep the child constraint ENFORCED so that its merged enforceability
12708 : : * still reflects the remaining enforced parent. Partitions do not need
12709 : : * this recursive parent check because a partition can have only one
12710 : : * direct parent.
12711 : : */
12712 [ + + ]: 360 : if (!cmdcon->is_enforced &&
12713 [ + + + + : 304 : (!recursing || !rel->rd_rel->relispartition) &&
+ + ]
12714 : 144 : ATCheckCheckConstrHasEnforcedParent(conrel, rel, contuple,
12715 : : changing_conids,
12716 : : &enforced_parentoid))
12717 : : {
12718 [ + + ]: 32 : if (!recursing)
12719 [ + - ]: 20 : ereport(ERROR,
12720 : : errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
12721 : : errmsg("cannot mark inherited constraint \"%s\" as %s",
12722 : : NameStr(currcon->conname),
12723 : : "NOT ENFORCED"),
12724 : : errdetail("The matching constraint on parent table \"%s\" is %s.",
12725 : : get_rel_name(enforced_parentoid), "ENFORCED"));
12726 : :
12727 : 12 : target_enforced = true;
12728 : : }
12729 : :
12730 : : /*
12731 : : * The constraint is about to be marked validated, so a descendant that is
12732 : : * enforced but not yet valid conflicts with it, as in ALTER TABLE ...
12733 : : * INHERIT.
12734 : : */
12735 [ + + + + ]: 340 : if (recursing && cmdcon->is_enforced &&
12736 [ + + + + ]: 128 : currcon->conenforced && !currcon->convalidated)
12737 [ + - ]: 8 : ereport(ERROR,
12738 : : errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
12739 : : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
12740 : : NameStr(currcon->conname), RelationGetRelationName(rel)),
12741 : : errhint("You may need to use %s on table \"%s\" first.",
12742 : : "ALTER TABLE ... VALIDATE CONSTRAINT",
12743 : : RelationGetRelationName(rel)));
12744 : :
12745 : : /*
12746 : : * Update to the merged enforceability if needed. This may differ from the
12747 : : * requested enforceability when another matching parent constraint
12748 : : * remains enforced.
12749 : : */
12750 [ + + ]: 332 : if (currcon->conenforced != target_enforced)
12751 : : {
12752 : 260 : ATAlterConstraint updatecon = *cmdcon;
12753 : :
12754 : 260 : updatecon.is_enforced = target_enforced;
12755 : 260 : AlterConstrUpdateConstraintEntry(&updatecon, conrel, contuple);
12756 : 260 : changed = true;
12757 : : }
12758 : :
12759 : : /*
12760 : : * Note that we must recurse even when trying to change a check constraint
12761 : : * to not enforced if it is already not enforced, in case descendant
12762 : : * constraints might be enforced and need to be changed to not enforced,
12763 : : * unless they still inherit an enforced constraint from another parent.
12764 : : * Conversely, we should do nothing if a constraint is being set to
12765 : : * enforced and is already enforced, as descendant constraints cannot be
12766 : : * different in that case.
12767 : : */
12768 [ + + + + ]: 332 : if (!cmdcon->is_enforced || changed)
12769 : : {
12770 : : /*
12771 : : * If we're recursing, the parent has already done this, so skip it.
12772 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't
12773 : : * try to look for it in the children.
12774 : : */
12775 [ + + + + ]: 312 : if (!recursing && !currcon->connoinherit)
12776 : : {
12777 : : Assert(changing_conids == NIL);
12778 : :
12779 : 116 : children = find_all_inheritors(RelationGetRelid(rel),
12780 : : lockmode, NULL);
12781 : :
12782 : : /*
12783 : : * When setting NOT ENFORCED, build the set of equivalent CHECK
12784 : : * constraints that this command will attempt to change before
12785 : : * visiting descendants. The root itself has already been checked
12786 : : * above.
12787 : : */
12788 [ + + ]: 116 : if (!cmdcon->is_enforced)
12789 : 48 : changing_conids = list_make1_oid(currcon->oid);
12790 : :
12791 [ + - + + : 560 : foreach_oid(childoid, children)
+ + ]
12792 : : {
12793 [ + + ]: 344 : if (childoid == RelationGetRelid(rel))
12794 : 116 : continue;
12795 : :
12796 : : /*
12797 : : * If we are told not to recurse, there had better not be any
12798 : : * child tables, because we can't change constraint
12799 : : * enforceability on the parent unless we have changed
12800 : : * enforceability for all child.
12801 : : */
12802 [ + + ]: 228 : if (!recurse)
12803 [ + - ]: 8 : ereport(ERROR,
12804 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12805 : : errmsg("constraint must be altered on child tables too"),
12806 : : errhint("Do not specify the ONLY keyword."));
12807 : :
12808 : : /*
12809 : : * It is sufficient to look up the constraint by name here.
12810 : : * Supported DDL ensures that inheritable CHECK constraints
12811 : : * with the same name have equivalent definitions when they
12812 : : * are propagated to children or when inheritance is
12813 : : * established. All descendants returned by
12814 : : * find_all_inheritors must have this constraint: inherited
12815 : : * CHECK constraints propagate to all children at
12816 : : * inheritance-link creation time and cannot be dropped
12817 : : * independently on child tables.
12818 : : */
12819 [ + + ]: 220 : if (!cmdcon->is_enforced)
12820 : : changing_conids =
12821 : 92 : list_append_unique_oid(changing_conids,
12822 : : get_relation_constraint_oid(childoid,
12823 : 92 : cmdcon->conname,
12824 : : false));
12825 : : }
12826 : : }
12827 : :
12828 [ + + + + : 920 : foreach_oid(childoid, children)
+ + ]
12829 : : {
12830 [ + + ]: 328 : if (childoid == RelationGetRelid(rel))
12831 : 108 : continue;
12832 : :
12833 : 220 : AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel,
12834 : : childoid, false, true,
12835 : : changing_conids,
12836 : : lockmode);
12837 : : }
12838 : : }
12839 : :
12840 : : /*
12841 : : * Tell Phase 3 to check that the constraint is satisfied by existing
12842 : : * rows. We only need do this when altering the constraint from NOT
12843 : : * ENFORCED to ENFORCED.
12844 : : */
12845 [ + + ]: 316 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12846 [ + + + + ]: 268 : !currcon->conenforced &&
12847 : : target_enforced)
12848 : : {
12849 : : AlteredTableInfo *tab;
12850 : : NewConstraint *newcon;
12851 : : Datum val;
12852 : : char *conbin;
12853 : :
12854 : 120 : newcon = palloc0_object(NewConstraint);
12855 : 120 : newcon->name = pstrdup(NameStr(currcon->conname));
12856 : 120 : newcon->contype = CONSTR_CHECK;
12857 : :
12858 : 120 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
12859 : : Anum_pg_constraint_conbin);
12860 : 120 : conbin = TextDatumGetCString(val);
12861 : 120 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
12862 : :
12863 : : /* Find or create work queue entry for this table */
12864 : 120 : tab = ATGetQueueEntry(wqueue, rel);
12865 : 120 : tab->constraints = lappend(tab->constraints, newcon);
12866 : : }
12867 : :
12868 : 316 : table_close(rel, NoLock);
12869 : :
12870 : 316 : return changed;
12871 : : }
12872 : :
12873 : : /*
12874 : : * Invokes ATExecAlterCheckConstrEnforceability for each CHECK constraint that
12875 : : * is a child of the specified constraint.
12876 : : *
12877 : : * We rely on the parent and child tables having identical CHECK constraint
12878 : : * names to retrieve the child's pg_constraint tuple.
12879 : : *
12880 : : * The arguments to this function have the same meaning as the arguments to
12881 : : * ATExecAlterCheckConstrEnforceability.
12882 : : */
12883 : : static void
12884 : 220 : AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12885 : : Relation conrel, Oid conrelid,
12886 : : bool recurse, bool recursing,
12887 : : List *changing_conids,
12888 : : LOCKMODE lockmode)
12889 : : {
12890 : : SysScanDesc pscan;
12891 : : HeapTuple childtup;
12892 : : ScanKeyData skey[3];
12893 : :
12894 : 220 : ScanKeyInit(&skey[0],
12895 : : Anum_pg_constraint_conrelid,
12896 : : BTEqualStrategyNumber, F_OIDEQ,
12897 : : ObjectIdGetDatum(conrelid));
12898 : 220 : ScanKeyInit(&skey[1],
12899 : : Anum_pg_constraint_contypid,
12900 : : BTEqualStrategyNumber, F_OIDEQ,
12901 : : ObjectIdGetDatum(InvalidOid));
12902 : 220 : ScanKeyInit(&skey[2],
12903 : : Anum_pg_constraint_conname,
12904 : : BTEqualStrategyNumber, F_NAMEEQ,
12905 : 220 : CStringGetDatum(cmdcon->conname));
12906 : :
12907 : 220 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
12908 : : NULL, 3, skey);
12909 : :
12910 [ - + ]: 220 : if (!HeapTupleIsValid(childtup = systable_getnext(pscan)))
12911 [ # # ]: 0 : ereport(ERROR,
12912 : : errcode(ERRCODE_UNDEFINED_OBJECT),
12913 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12914 : : cmdcon->conname, get_rel_name(conrelid)));
12915 : :
12916 : 220 : ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup,
12917 : : recurse, recursing, changing_conids,
12918 : : lockmode);
12919 : :
12920 : 212 : systable_endscan(pscan);
12921 : 212 : }
12922 : :
12923 : : /*
12924 : : * When setting an inherited CHECK constraint to NOT ENFORCED, look for a
12925 : : * matching parent constraint that remains ENFORCED and is not part of the same
12926 : : * ALTER.
12927 : : */
12928 : : static bool
12929 : 268 : ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel,
12930 : : HeapTuple contuple,
12931 : : List *changing_conids,
12932 : : Oid *enforced_parentoid)
12933 : : {
12934 : : Form_pg_constraint currcon;
12935 : : Relation inhrel;
12936 : : SysScanDesc scan;
12937 : : ScanKeyData skey;
12938 : : HeapTuple inheritsTuple;
12939 : :
12940 : : /* Since this function recurses, it could be driven to stack overflow */
12941 : 268 : check_stack_depth();
12942 : :
12943 : 268 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12944 : : Assert(currcon->contype == CONSTRAINT_CHECK);
12945 : :
12946 [ + + ]: 268 : if (currcon->coninhcount <= 0)
12947 : 124 : return false;
12948 : :
12949 : 144 : inhrel = table_open(InheritsRelationId, AccessShareLock);
12950 : :
12951 : 144 : ScanKeyInit(&skey,
12952 : : Anum_pg_inherits_inhrelid,
12953 : : BTEqualStrategyNumber, F_OIDEQ,
12954 : : ObjectIdGetDatum(RelationGetRelid(rel)));
12955 : 144 : scan = systable_beginscan(inhrel, InheritsRelidSeqnoIndexId,
12956 : : true, NULL, 1, &skey);
12957 : :
12958 [ + + ]: 304 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
12959 : : {
12960 : : Oid parentoid;
12961 : 200 : Relation parentrel = NULL;
12962 : : SysScanDesc pscan;
12963 : : ScanKeyData pkey[3];
12964 : : HeapTuple parenttup;
12965 : :
12966 : 200 : parentoid = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
12967 : :
12968 : 200 : ScanKeyInit(&pkey[0],
12969 : : Anum_pg_constraint_conrelid,
12970 : : BTEqualStrategyNumber, F_OIDEQ,
12971 : : ObjectIdGetDatum(parentoid));
12972 : 200 : ScanKeyInit(&pkey[1],
12973 : : Anum_pg_constraint_contypid,
12974 : : BTEqualStrategyNumber, F_OIDEQ,
12975 : : ObjectIdGetDatum(InvalidOid));
12976 : 200 : ScanKeyInit(&pkey[2],
12977 : : Anum_pg_constraint_conname,
12978 : : BTEqualStrategyNumber, F_NAMEEQ,
12979 : 200 : NameGetDatum(&currcon->conname));
12980 : :
12981 : 200 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12982 : : true, NULL, 3, pkey);
12983 : :
12984 : : /*
12985 : : * ConstraintRelidTypidNameIndexId is unique on (conrelid, contypid,
12986 : : * conname), so this loop body executes at most once per parent.
12987 : : */
12988 [ + + ]: 360 : while (HeapTupleIsValid(parenttup = systable_getnext(pscan)))
12989 : : {
12990 : : Form_pg_constraint parentcon;
12991 : :
12992 : 200 : parentcon = (Form_pg_constraint) GETSTRUCT(parenttup);
12993 : :
12994 [ + - ]: 200 : if (parentcon->contype != CONSTRAINT_CHECK ||
12995 [ + - ]: 200 : parentcon->connoinherit ||
12996 [ + + ]: 200 : !parentcon->conenforced)
12997 : 44 : continue;
12998 : :
12999 [ - + ]: 156 : if (!constraints_equivalent(parenttup, contuple,
13000 : : RelationGetDescr(conrel)))
13001 [ # # ]: 0 : elog(ERROR, "child table \"%s\" has different definition for check constraint \"%s\"",
13002 : : RelationGetRelationName(rel),
13003 : : NameStr(parentcon->conname));
13004 : :
13005 : : /*
13006 : : * A parent listed in changing_conids is being changed by the same
13007 : : * ALTER, but it may not have been updated yet. For regular
13008 : : * inheritance, recurse upward to check whether an equivalent
13009 : : * enforced parent outside the ALTER will make it remain enforced.
13010 : : * Partitions cannot have multiple parents, so they do not need
13011 : : * this check.
13012 : : */
13013 [ + + + + ]: 300 : if (!rel->rd_rel->relispartition &&
13014 : 144 : list_member_oid(changing_conids, parentcon->oid))
13015 : : {
13016 : 124 : Oid parent_enforced_parentoid = InvalidOid;
13017 : :
13018 [ + - ]: 124 : if (parentrel == NULL)
13019 : 124 : parentrel = table_open(parentoid, NoLock);
13020 : :
13021 [ + + ]: 124 : if (!ATCheckCheckConstrHasEnforcedParent(conrel,
13022 : : parentrel,
13023 : : parenttup,
13024 : : changing_conids,
13025 : : &parent_enforced_parentoid))
13026 : 116 : continue;
13027 : : }
13028 : :
13029 : 40 : *enforced_parentoid = parentoid;
13030 [ + + ]: 40 : if (parentrel != NULL)
13031 : 8 : table_close(parentrel, NoLock);
13032 : 40 : systable_endscan(pscan);
13033 : 40 : systable_endscan(scan);
13034 : 40 : table_close(inhrel, AccessShareLock);
13035 : 40 : return true;
13036 : : }
13037 : :
13038 [ + + ]: 160 : if (parentrel != NULL)
13039 : 116 : table_close(parentrel, NoLock);
13040 : 160 : systable_endscan(pscan);
13041 : : }
13042 : :
13043 : 104 : systable_endscan(scan);
13044 : 104 : table_close(inhrel, AccessShareLock);
13045 : :
13046 : 104 : return false;
13047 : : }
13048 : :
13049 : : /*
13050 : : * Returns true if the constraint's deferrability is altered.
13051 : : *
13052 : : * *otherrelids is appended OIDs of relations containing affected triggers.
13053 : : *
13054 : : * Note that we must recurse even when the values are correct, in case
13055 : : * indirect descendants have had their constraints altered locally.
13056 : : * (This could be avoided if we forbade altering constraints in partitions
13057 : : * but existing releases don't do that.)
13058 : : */
13059 : : static bool
13060 : 108 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
13061 : : Relation conrel, Relation tgrel, Relation rel,
13062 : : HeapTuple contuple, bool recurse,
13063 : : List **otherrelids, LOCKMODE lockmode)
13064 : : {
13065 : : Form_pg_constraint currcon;
13066 : : Oid refrelid;
13067 : 108 : bool changed = false;
13068 : :
13069 : : /* since this function recurses, it could be driven to stack overflow */
13070 : 108 : check_stack_depth();
13071 : :
13072 : : Assert(cmdcon->alterDeferrability);
13073 : :
13074 : 108 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13075 : 108 : refrelid = currcon->confrelid;
13076 : :
13077 : : /* Should be foreign key constraint */
13078 : : Assert(currcon->contype == CONSTRAINT_FOREIGN);
13079 : :
13080 : : /*
13081 : : * If called to modify a constraint that's already in the desired state,
13082 : : * silently do nothing.
13083 : : */
13084 [ + + ]: 108 : if (currcon->condeferrable != cmdcon->deferrable ||
13085 [ + - ]: 4 : currcon->condeferred != cmdcon->initdeferred)
13086 : : {
13087 : 108 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13088 : 108 : changed = true;
13089 : :
13090 : : /*
13091 : : * Now we need to update the multiple entries in pg_trigger that
13092 : : * implement the constraint.
13093 : : */
13094 : 108 : AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
13095 : 108 : cmdcon->deferrable,
13096 : 108 : cmdcon->initdeferred, otherrelids);
13097 : : }
13098 : :
13099 : : /*
13100 : : * If the table at either end of the constraint is partitioned, we need to
13101 : : * handle every constraint that is a child of this one.
13102 : : */
13103 [ + - + - ]: 108 : if (recurse && changed &&
13104 [ + + + + ]: 200 : (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13105 : 92 : get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
13106 : 28 : AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
13107 : : contuple, recurse, otherrelids,
13108 : : lockmode);
13109 : :
13110 : 108 : return changed;
13111 : : }
13112 : :
13113 : : /*
13114 : : * Returns true if the constraint's inheritability is altered.
13115 : : */
13116 : : static bool
13117 : 40 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
13118 : : Relation conrel, Relation rel,
13119 : : HeapTuple contuple, LOCKMODE lockmode)
13120 : : {
13121 : : Form_pg_constraint currcon;
13122 : : AttrNumber colNum;
13123 : : char *colName;
13124 : : List *children;
13125 : :
13126 : : Assert(cmdcon->alterInheritability);
13127 : :
13128 : 40 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13129 : :
13130 : : /* The current implementation only works for NOT NULL constraints */
13131 : : Assert(currcon->contype == CONSTRAINT_NOTNULL);
13132 : :
13133 : : /*
13134 : : * If called to modify a constraint that's already in the desired state,
13135 : : * silently do nothing.
13136 : : */
13137 [ - + ]: 40 : if (cmdcon->noinherit == currcon->connoinherit)
13138 : 0 : return false;
13139 : :
13140 : 40 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13141 : 40 : CommandCounterIncrement();
13142 : :
13143 : : /* Fetch the column number and name */
13144 : 40 : colNum = extractNotNullColumn(contuple);
13145 : 40 : colName = get_attname(currcon->conrelid, colNum, false);
13146 : :
13147 : : /*
13148 : : * Propagate the change to children. For this subcommand type we don't
13149 : : * recursively affect children, just the immediate level.
13150 : : */
13151 : 40 : children = find_inheritance_children(RelationGetRelid(rel),
13152 : : lockmode);
13153 [ + + + + : 128 : foreach_oid(childoid, children)
+ + ]
13154 : : {
13155 : : ObjectAddress addr;
13156 : :
13157 [ + + ]: 56 : if (cmdcon->noinherit)
13158 : : {
13159 : : HeapTuple childtup;
13160 : : Form_pg_constraint childcon;
13161 : :
13162 : 20 : childtup = findNotNullConstraint(childoid, colName);
13163 [ - + ]: 20 : if (!childtup)
13164 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
13165 : : colName, childoid);
13166 : 20 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13167 : : Assert(childcon->coninhcount > 0);
13168 : 20 : childcon->coninhcount--;
13169 : 20 : childcon->conislocal = true;
13170 : 20 : CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
13171 : 20 : heap_freetuple(childtup);
13172 : : }
13173 : : else
13174 : : {
13175 : 36 : Relation childrel = table_open(childoid, NoLock);
13176 : :
13177 : 36 : addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
13178 : : colName, true, true, lockmode);
13179 [ + - ]: 32 : if (OidIsValid(addr.objectId))
13180 : 32 : CommandCounterIncrement();
13181 : 32 : table_close(childrel, NoLock);
13182 : : }
13183 : : }
13184 : :
13185 : 36 : return true;
13186 : : }
13187 : :
13188 : : /*
13189 : : * A subroutine of ATExecAlterConstrDeferrability that updated constraint
13190 : : * trigger's deferrability.
13191 : : *
13192 : : * The arguments to this function have the same meaning as the arguments to
13193 : : * ATExecAlterConstrDeferrability.
13194 : : */
13195 : : static void
13196 : 108 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
13197 : : bool deferrable, bool initdeferred,
13198 : : List **otherrelids)
13199 : : {
13200 : : HeapTuple tgtuple;
13201 : : ScanKeyData tgkey;
13202 : : SysScanDesc tgscan;
13203 : :
13204 : 108 : ScanKeyInit(&tgkey,
13205 : : Anum_pg_trigger_tgconstraint,
13206 : : BTEqualStrategyNumber, F_OIDEQ,
13207 : : ObjectIdGetDatum(conoid));
13208 : 108 : tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
13209 : : NULL, 1, &tgkey);
13210 [ + + ]: 420 : while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
13211 : : {
13212 : 312 : Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
13213 : : Form_pg_trigger copy_tg;
13214 : : HeapTuple tgCopyTuple;
13215 : :
13216 : : /*
13217 : : * Remember OIDs of other relation(s) involved in FK constraint.
13218 : : * (Note: it's likely that we could skip forcing a relcache inval for
13219 : : * other rels that don't have a trigger whose properties change, but
13220 : : * let's be conservative.)
13221 : : */
13222 [ + + ]: 312 : if (tgform->tgrelid != RelationGetRelid(rel))
13223 : 152 : *otherrelids = list_append_unique_oid(*otherrelids,
13224 : : tgform->tgrelid);
13225 : :
13226 : : /*
13227 : : * Update enable status and deferrability of RI_FKey_noaction_del,
13228 : : * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
13229 : : * triggers, but not others; see createForeignKeyActionTriggers and
13230 : : * CreateFKCheckTrigger.
13231 : : */
13232 [ + + ]: 312 : if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
13233 [ + + ]: 248 : tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
13234 [ + + ]: 172 : tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
13235 [ + + ]: 92 : tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
13236 : 12 : continue;
13237 : :
13238 : 300 : tgCopyTuple = heap_copytuple(tgtuple);
13239 : 300 : copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
13240 : :
13241 : 300 : copy_tg->tgdeferrable = deferrable;
13242 : 300 : copy_tg->tginitdeferred = initdeferred;
13243 : 300 : CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
13244 : :
13245 [ - + ]: 300 : InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
13246 : :
13247 : 300 : heap_freetuple(tgCopyTuple);
13248 : : }
13249 : :
13250 : 108 : systable_endscan(tgscan);
13251 : 108 : }
13252 : :
13253 : : /*
13254 : : * Invokes ATExecAlterFKConstrEnforceability for each foreign key constraint
13255 : : * that is a child of the specified constraint.
13256 : : *
13257 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13258 : : * list of child relations and recursing; instead it uses the conparentid
13259 : : * relationships. This may need to be reconsidered.
13260 : : *
13261 : : * The arguments to this function have the same meaning as the arguments to
13262 : : * ATExecAlterFKConstrEnforceability.
13263 : : */
13264 : : static void
13265 : 28 : AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13266 : : Relation conrel, Relation tgrel,
13267 : : Oid fkrelid, Oid pkrelid,
13268 : : HeapTuple contuple, LOCKMODE lockmode,
13269 : : Oid ReferencedParentDelTrigger,
13270 : : Oid ReferencedParentUpdTrigger,
13271 : : Oid ReferencingParentInsTrigger,
13272 : : Oid ReferencingParentUpdTrigger)
13273 : : {
13274 : : Form_pg_constraint currcon;
13275 : : Oid conoid;
13276 : : ScanKeyData pkey;
13277 : : SysScanDesc pscan;
13278 : : HeapTuple childtup;
13279 : :
13280 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13281 : 28 : conoid = currcon->oid;
13282 : :
13283 : 28 : ScanKeyInit(&pkey,
13284 : : Anum_pg_constraint_conparentid,
13285 : : BTEqualStrategyNumber, F_OIDEQ,
13286 : : ObjectIdGetDatum(conoid));
13287 : :
13288 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13289 : : true, NULL, 1, &pkey);
13290 : :
13291 [ + + ]: 92 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13292 : 64 : ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
13293 : : pkrelid, childtup, lockmode,
13294 : : ReferencedParentDelTrigger,
13295 : : ReferencedParentUpdTrigger,
13296 : : ReferencingParentInsTrigger,
13297 : : ReferencingParentUpdTrigger);
13298 : :
13299 : 28 : systable_endscan(pscan);
13300 : 28 : }
13301 : :
13302 : : /*
13303 : : * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
13304 : : * the specified constraint.
13305 : : *
13306 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13307 : : * list of child relations and recursing; instead it uses the conparentid
13308 : : * relationships. This may need to be reconsidered.
13309 : : *
13310 : : * The arguments to this function have the same meaning as the arguments to
13311 : : * ATExecAlterConstrDeferrability.
13312 : : */
13313 : : static void
13314 : 28 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13315 : : Relation conrel, Relation tgrel, Relation rel,
13316 : : HeapTuple contuple, bool recurse,
13317 : : List **otherrelids, LOCKMODE lockmode)
13318 : : {
13319 : : Form_pg_constraint currcon;
13320 : : Oid conoid;
13321 : : ScanKeyData pkey;
13322 : : SysScanDesc pscan;
13323 : : HeapTuple childtup;
13324 : :
13325 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13326 : 28 : conoid = currcon->oid;
13327 : :
13328 : 28 : ScanKeyInit(&pkey,
13329 : : Anum_pg_constraint_conparentid,
13330 : : BTEqualStrategyNumber, F_OIDEQ,
13331 : : ObjectIdGetDatum(conoid));
13332 : :
13333 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13334 : : true, NULL, 1, &pkey);
13335 : :
13336 [ + + ]: 72 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13337 : : {
13338 : 44 : Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13339 : : Relation childrel;
13340 : :
13341 : 44 : childrel = table_open(childcon->conrelid, lockmode);
13342 : :
13343 : 44 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
13344 : : childtup, recurse, otherrelids, lockmode);
13345 : 44 : table_close(childrel, NoLock);
13346 : : }
13347 : :
13348 : 28 : systable_endscan(pscan);
13349 : 28 : }
13350 : :
13351 : : /*
13352 : : * Update the constraint entry for the given ATAlterConstraint command, and
13353 : : * invoke the appropriate hooks.
13354 : : */
13355 : : static void
13356 : 524 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
13357 : : HeapTuple contuple)
13358 : : {
13359 : : HeapTuple copyTuple;
13360 : : Form_pg_constraint copy_con;
13361 : :
13362 : : Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
13363 : : cmdcon->alterInheritability);
13364 : :
13365 : 524 : copyTuple = heap_copytuple(contuple);
13366 : 524 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13367 : :
13368 [ + + ]: 524 : if (cmdcon->alterEnforceability)
13369 : : {
13370 : 376 : copy_con->conenforced = cmdcon->is_enforced;
13371 : :
13372 : : /*
13373 : : * NB: The convalidated status is irrelevant when the constraint is
13374 : : * set to NOT ENFORCED, but for consistency, it should still be set
13375 : : * appropriately. Similarly, if the constraint is later changed to
13376 : : * ENFORCED, validation will be performed during phase 3, so it makes
13377 : : * sense to mark it as valid in that case.
13378 : : */
13379 : 376 : copy_con->convalidated = cmdcon->is_enforced;
13380 : : }
13381 [ + + ]: 524 : if (cmdcon->alterDeferrability)
13382 : : {
13383 : 112 : copy_con->condeferrable = cmdcon->deferrable;
13384 : 112 : copy_con->condeferred = cmdcon->initdeferred;
13385 : : }
13386 [ + + ]: 524 : if (cmdcon->alterInheritability)
13387 : 40 : copy_con->connoinherit = cmdcon->noinherit;
13388 : :
13389 : 524 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13390 [ - + ]: 524 : InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
13391 : :
13392 : : /* Make new constraint flags visible to others */
13393 : 524 : CacheInvalidateRelcacheByRelid(copy_con->conrelid);
13394 : :
13395 : 524 : heap_freetuple(copyTuple);
13396 : 524 : }
13397 : :
13398 : : /*
13399 : : * ALTER TABLE VALIDATE CONSTRAINT
13400 : : *
13401 : : * XXX The reason we handle recursion here rather than at Phase 1 is because
13402 : : * there's no good way to skip recursing when handling foreign keys: there is
13403 : : * no need to lock children in that case, yet we wouldn't be able to avoid
13404 : : * doing so at that level.
13405 : : *
13406 : : * Return value is the address of the validated constraint. If the constraint
13407 : : * was already validated, InvalidObjectAddress is returned.
13408 : : */
13409 : : static ObjectAddress
13410 : 364 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
13411 : : bool recurse, bool recursing, LOCKMODE lockmode)
13412 : : {
13413 : : Relation conrel;
13414 : : SysScanDesc scan;
13415 : : ScanKeyData skey[3];
13416 : : HeapTuple tuple;
13417 : : Form_pg_constraint con;
13418 : : ObjectAddress address;
13419 : :
13420 : 364 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
13421 : :
13422 : : /*
13423 : : * Find and check the target constraint
13424 : : */
13425 : 364 : ScanKeyInit(&skey[0],
13426 : : Anum_pg_constraint_conrelid,
13427 : : BTEqualStrategyNumber, F_OIDEQ,
13428 : : ObjectIdGetDatum(RelationGetRelid(rel)));
13429 : 364 : ScanKeyInit(&skey[1],
13430 : : Anum_pg_constraint_contypid,
13431 : : BTEqualStrategyNumber, F_OIDEQ,
13432 : : ObjectIdGetDatum(InvalidOid));
13433 : 364 : ScanKeyInit(&skey[2],
13434 : : Anum_pg_constraint_conname,
13435 : : BTEqualStrategyNumber, F_NAMEEQ,
13436 : : CStringGetDatum(constrName));
13437 : 364 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
13438 : : true, NULL, 3, skey);
13439 : :
13440 : : /* There can be at most one matching row */
13441 [ - + ]: 364 : if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
13442 [ # # ]: 0 : ereport(ERROR,
13443 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
13444 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
13445 : : constrName, RelationGetRelationName(rel))));
13446 : :
13447 : 364 : con = (Form_pg_constraint) GETSTRUCT(tuple);
13448 [ + + ]: 364 : if (con->contype != CONSTRAINT_FOREIGN &&
13449 [ + + ]: 178 : con->contype != CONSTRAINT_CHECK &&
13450 [ - + ]: 78 : con->contype != CONSTRAINT_NOTNULL)
13451 [ # # ]: 0 : ereport(ERROR,
13452 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
13453 : : errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
13454 : : constrName, RelationGetRelationName(rel)),
13455 : : errdetail("This operation is not supported for this type of constraint."));
13456 : :
13457 [ + + ]: 364 : if (!con->conenforced)
13458 [ + - ]: 4 : ereport(ERROR,
13459 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13460 : : errmsg("cannot validate NOT ENFORCED constraint")));
13461 : :
13462 [ + + ]: 360 : if (!con->convalidated)
13463 : : {
13464 [ + + ]: 348 : if (con->contype == CONSTRAINT_FOREIGN)
13465 : : {
13466 : 182 : QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
13467 : : tuple, lockmode);
13468 : : }
13469 [ + + ]: 166 : else if (con->contype == CONSTRAINT_CHECK)
13470 : : {
13471 : 88 : QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
13472 : : tuple, recurse, recursing, lockmode);
13473 : : }
13474 [ + - ]: 78 : else if (con->contype == CONSTRAINT_NOTNULL)
13475 : : {
13476 : 78 : QueueNNConstraintValidation(wqueue, conrel, rel,
13477 : : tuple, recurse, recursing, lockmode);
13478 : : }
13479 : :
13480 : 348 : ObjectAddressSet(address, ConstraintRelationId, con->oid);
13481 : : }
13482 : : else
13483 : 12 : address = InvalidObjectAddress; /* already validated */
13484 : :
13485 : 360 : systable_endscan(scan);
13486 : :
13487 : 360 : table_close(conrel, RowExclusiveLock);
13488 : :
13489 : 360 : return address;
13490 : : }
13491 : :
13492 : : /*
13493 : : * QueueFKConstraintValidation
13494 : : *
13495 : : * Add an entry to the wqueue to validate the given foreign key constraint in
13496 : : * Phase 3 and update the convalidated field in the pg_constraint catalog
13497 : : * for the specified relation and all its children.
13498 : : */
13499 : : static void
13500 : 230 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
13501 : : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
13502 : : {
13503 : : Form_pg_constraint con;
13504 : : AlteredTableInfo *tab;
13505 : : HeapTuple copyTuple;
13506 : : Form_pg_constraint copy_con;
13507 : :
13508 : : /* since this function recurses, it could be driven to stack overflow */
13509 : 230 : check_stack_depth();
13510 : :
13511 : 230 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13512 : : Assert(con->contype == CONSTRAINT_FOREIGN);
13513 : : Assert(!con->convalidated);
13514 : :
13515 : : /*
13516 : : * Add the validation to phase 3's queue; not needed for partitioned
13517 : : * tables themselves, only for their partitions.
13518 : : *
13519 : : * When the referenced table (pkrelid) is partitioned, the referencing
13520 : : * table (fkrel) has one pg_constraint row pointing to each partition
13521 : : * thereof. These rows are there only to support action triggers and no
13522 : : * table scan is needed, therefore skip this for them as well.
13523 : : */
13524 [ + + ]: 230 : if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
13525 [ + + ]: 198 : con->confrelid == pkrelid)
13526 : : {
13527 : : NewConstraint *newcon;
13528 : : Constraint *fkconstraint;
13529 : :
13530 : : /* Queue validation for phase 3 */
13531 : 190 : fkconstraint = makeNode(Constraint);
13532 : : /* for now this is all we need */
13533 : 190 : fkconstraint->conname = pstrdup(NameStr(con->conname));
13534 : :
13535 : 190 : newcon = palloc0_object(NewConstraint);
13536 : 190 : newcon->name = fkconstraint->conname;
13537 : 190 : newcon->contype = CONSTR_FOREIGN;
13538 : 190 : newcon->refrelid = con->confrelid;
13539 : 190 : newcon->refindid = con->conindid;
13540 : 190 : newcon->conid = con->oid;
13541 : 190 : newcon->qual = (Node *) fkconstraint;
13542 : :
13543 : : /* Find or create work queue entry for this table */
13544 : 190 : tab = ATGetQueueEntry(wqueue, fkrel);
13545 : 190 : tab->constraints = lappend(tab->constraints, newcon);
13546 : : }
13547 : :
13548 : : /*
13549 : : * If the table at either end of the constraint is partitioned, we need to
13550 : : * recurse and handle every unvalidated constraint that is a child of this
13551 : : * constraint.
13552 : : */
13553 [ + + + + ]: 428 : if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13554 : 198 : get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
13555 : : {
13556 : : ScanKeyData pkey;
13557 : : SysScanDesc pscan;
13558 : : HeapTuple childtup;
13559 : :
13560 : 48 : ScanKeyInit(&pkey,
13561 : : Anum_pg_constraint_conparentid,
13562 : : BTEqualStrategyNumber, F_OIDEQ,
13563 : : ObjectIdGetDatum(con->oid));
13564 : :
13565 : 48 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13566 : : true, NULL, 1, &pkey);
13567 : :
13568 [ + + ]: 96 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13569 : : {
13570 : : Form_pg_constraint childcon;
13571 : : Relation childrel;
13572 : :
13573 : 48 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13574 : :
13575 : : /*
13576 : : * If the child constraint has already been validated, no further
13577 : : * action is required for it or its descendants, as they are all
13578 : : * valid.
13579 : : */
13580 [ + + ]: 48 : if (childcon->convalidated)
13581 : 12 : continue;
13582 : :
13583 : 36 : childrel = table_open(childcon->conrelid, lockmode);
13584 : :
13585 : : /*
13586 : : * NB: Note that pkrelid should be passed as-is during recursion,
13587 : : * as it is required to identify the root referenced table.
13588 : : */
13589 : 36 : QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
13590 : : childtup, lockmode);
13591 : 36 : table_close(childrel, NoLock);
13592 : : }
13593 : :
13594 : 48 : systable_endscan(pscan);
13595 : : }
13596 : :
13597 : : /*
13598 : : * Now mark the pg_constraint row as validated (even if we didn't check,
13599 : : * notably the ones for partitions on the referenced side).
13600 : : *
13601 : : * We rely on transaction abort to roll back this change if phase 3
13602 : : * ultimately finds violating rows. This is a bit ugly.
13603 : : */
13604 : 230 : copyTuple = heap_copytuple(contuple);
13605 : 230 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13606 : 230 : copy_con->convalidated = true;
13607 : 230 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13608 : :
13609 [ - + ]: 230 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13610 : :
13611 : 230 : heap_freetuple(copyTuple);
13612 : 230 : }
13613 : :
13614 : : /*
13615 : : * QueueCheckConstraintValidation
13616 : : *
13617 : : * Add an entry to the wqueue to validate the given check constraint in Phase 3
13618 : : * and update the convalidated field in the pg_constraint catalog for the
13619 : : * specified relation and all its inheriting children.
13620 : : */
13621 : : static void
13622 : 88 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13623 : : char *constrName, HeapTuple contuple,
13624 : : bool recurse, bool recursing, LOCKMODE lockmode)
13625 : : {
13626 : : Form_pg_constraint con;
13627 : : AlteredTableInfo *tab;
13628 : : HeapTuple copyTuple;
13629 : : Form_pg_constraint copy_con;
13630 : :
13631 : 88 : List *children = NIL;
13632 : : ListCell *child;
13633 : : NewConstraint *newcon;
13634 : : Datum val;
13635 : : char *conbin;
13636 : :
13637 : 88 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13638 : : Assert(con->contype == CONSTRAINT_CHECK);
13639 : :
13640 : : /*
13641 : : * If we're recursing, the parent has already done this, so skip it. Also,
13642 : : * if the constraint is a NO INHERIT constraint, we shouldn't try to look
13643 : : * for it in the children.
13644 : : */
13645 [ + + + + ]: 88 : if (!recursing && !con->connoinherit)
13646 : 52 : children = find_all_inheritors(RelationGetRelid(rel),
13647 : : lockmode, NULL);
13648 : :
13649 : : /*
13650 : : * For CHECK constraints, we must ensure that we only mark the constraint
13651 : : * as validated on the parent if it's already validated on the children.
13652 : : *
13653 : : * We recurse before validating on the parent, to reduce risk of
13654 : : * deadlocks.
13655 : : */
13656 [ + + + + : 172 : foreach(child, children)
+ + ]
13657 : : {
13658 : 84 : Oid childoid = lfirst_oid(child);
13659 : : Relation childrel;
13660 : :
13661 [ + + ]: 84 : if (childoid == RelationGetRelid(rel))
13662 : 52 : continue;
13663 : :
13664 : : /*
13665 : : * If we are told not to recurse, there had better not be any child
13666 : : * tables, because we can't mark the constraint on the parent valid
13667 : : * unless it is valid for all child tables.
13668 : : */
13669 [ - + ]: 32 : if (!recurse)
13670 [ # # ]: 0 : ereport(ERROR,
13671 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13672 : : errmsg("constraint must be validated on child tables too")));
13673 : :
13674 : : /* find_all_inheritors already got lock */
13675 : 32 : childrel = table_open(childoid, NoLock);
13676 : :
13677 : 32 : ATExecValidateConstraint(wqueue, childrel, constrName, false,
13678 : : true, lockmode);
13679 : 32 : table_close(childrel, NoLock);
13680 : : }
13681 : :
13682 : : /* Queue validation for phase 3 */
13683 : 88 : newcon = palloc0_object(NewConstraint);
13684 : 88 : newcon->name = constrName;
13685 : 88 : newcon->contype = CONSTR_CHECK;
13686 : 88 : newcon->refrelid = InvalidOid;
13687 : 88 : newcon->refindid = InvalidOid;
13688 : 88 : newcon->conid = con->oid;
13689 : :
13690 : 88 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
13691 : : Anum_pg_constraint_conbin);
13692 : 88 : conbin = TextDatumGetCString(val);
13693 : 88 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
13694 : :
13695 : : /* Find or create work queue entry for this table */
13696 : 88 : tab = ATGetQueueEntry(wqueue, rel);
13697 : 88 : tab->constraints = lappend(tab->constraints, newcon);
13698 : :
13699 : : /*
13700 : : * Invalidate relcache so that others see the new validated constraint.
13701 : : */
13702 : 88 : CacheInvalidateRelcache(rel);
13703 : :
13704 : : /*
13705 : : * Now update the catalog, while we have the door open.
13706 : : */
13707 : 88 : copyTuple = heap_copytuple(contuple);
13708 : 88 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13709 : 88 : copy_con->convalidated = true;
13710 : 88 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13711 : :
13712 [ - + ]: 88 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13713 : :
13714 : 88 : heap_freetuple(copyTuple);
13715 : 88 : }
13716 : :
13717 : : /*
13718 : : * QueueNNConstraintValidation
13719 : : *
13720 : : * Add an entry to the wqueue to validate the given not-null constraint in
13721 : : * Phase 3 and update the convalidated field in the pg_constraint catalog for
13722 : : * the specified relation and all its inheriting children.
13723 : : */
13724 : : static void
13725 : 78 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13726 : : HeapTuple contuple, bool recurse, bool recursing,
13727 : : LOCKMODE lockmode)
13728 : : {
13729 : : Form_pg_constraint con;
13730 : : AlteredTableInfo *tab;
13731 : : HeapTuple copyTuple;
13732 : : Form_pg_constraint copy_con;
13733 : 78 : List *children = NIL;
13734 : : AttrNumber attnum;
13735 : : char *colname;
13736 : :
13737 : 78 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13738 : : Assert(con->contype == CONSTRAINT_NOTNULL);
13739 : :
13740 : 78 : attnum = extractNotNullColumn(contuple);
13741 : :
13742 : : /*
13743 : : * If we're recursing, we've already done this for parent, so skip it.
13744 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
13745 : : * look for it in the children.
13746 : : *
13747 : : * We recurse before validating on the parent, to reduce risk of
13748 : : * deadlocks.
13749 : : */
13750 [ + + + - ]: 78 : if (!recursing && !con->connoinherit)
13751 : 54 : children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
13752 : :
13753 : 78 : colname = get_attname(RelationGetRelid(rel), attnum, false);
13754 [ + + + + : 262 : foreach_oid(childoid, children)
+ + ]
13755 : : {
13756 : : Relation childrel;
13757 : : HeapTuple contup;
13758 : : Form_pg_constraint childcon;
13759 : : char *conname;
13760 : :
13761 [ + + ]: 106 : if (childoid == RelationGetRelid(rel))
13762 : 54 : continue;
13763 : :
13764 : : /*
13765 : : * If we are told not to recurse, there had better not be any child
13766 : : * tables, because we can't mark the constraint on the parent valid
13767 : : * unless it is valid for all child tables.
13768 : : */
13769 [ - + ]: 52 : if (!recurse)
13770 [ # # ]: 0 : ereport(ERROR,
13771 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13772 : : errmsg("constraint must be validated on child tables too"));
13773 : :
13774 : : /*
13775 : : * The column on child might have a different attnum, so search by
13776 : : * column name.
13777 : : */
13778 : 52 : contup = findNotNullConstraint(childoid, colname);
13779 [ - + ]: 52 : if (!contup)
13780 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
13781 : : colname, get_rel_name(childoid));
13782 : 52 : childcon = (Form_pg_constraint) GETSTRUCT(contup);
13783 [ + + ]: 52 : if (childcon->convalidated)
13784 : 28 : continue;
13785 : :
13786 : : /* find_all_inheritors already got lock */
13787 : 24 : childrel = table_open(childoid, NoLock);
13788 : 24 : conname = pstrdup(NameStr(childcon->conname));
13789 : :
13790 : : /* XXX improve ATExecValidateConstraint API to avoid double search */
13791 : 24 : ATExecValidateConstraint(wqueue, childrel, conname,
13792 : : false, true, lockmode);
13793 : 24 : table_close(childrel, NoLock);
13794 : : }
13795 : :
13796 : : /* Set attnotnull appropriately without queueing another validation */
13797 : 78 : set_attnotnull(NULL, rel, attnum, false);
13798 : :
13799 : 78 : tab = ATGetQueueEntry(wqueue, rel);
13800 : 78 : tab->verify_new_notnull = true;
13801 : :
13802 : : /*
13803 : : * Invalidate relcache so that others see the new validated constraint.
13804 : : */
13805 : 78 : CacheInvalidateRelcache(rel);
13806 : :
13807 : : /*
13808 : : * Now update the catalogs, while we have the door open.
13809 : : */
13810 : 78 : copyTuple = heap_copytuple(contuple);
13811 : 78 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13812 : 78 : copy_con->convalidated = true;
13813 : 78 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13814 : :
13815 [ - + ]: 78 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13816 : :
13817 : 78 : heap_freetuple(copyTuple);
13818 : 78 : }
13819 : :
13820 : : /*
13821 : : * transformColumnNameList - transform list of column names
13822 : : *
13823 : : * Lookup each name and return its attnum and, optionally, type and collation
13824 : : * OIDs
13825 : : *
13826 : : * Note: the name of this function suggests that it's general-purpose,
13827 : : * but actually it's only used to look up names appearing in foreign-key
13828 : : * clauses. The error messages would need work to use it in other cases,
13829 : : * and perhaps the validity checks as well.
13830 : : */
13831 : : static int
13832 : 4593 : transformColumnNameList(Oid relId, List *colList,
13833 : : int16 *attnums, Oid *atttypids, Oid *attcollids)
13834 : : {
13835 : : ListCell *l;
13836 : : int attnum;
13837 : :
13838 : 4593 : attnum = 0;
13839 [ + + + + : 8369 : foreach(l, colList)
+ + ]
13840 : : {
13841 : 3820 : char *attname = strVal(lfirst(l));
13842 : : HeapTuple atttuple;
13843 : : Form_pg_attribute attform;
13844 : :
13845 : 3820 : atttuple = SearchSysCacheAttName(relId, attname);
13846 [ + + ]: 3820 : if (!HeapTupleIsValid(atttuple))
13847 [ + - ]: 36 : ereport(ERROR,
13848 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
13849 : : errmsg("column \"%s\" referenced in foreign key constraint does not exist",
13850 : : attname)));
13851 : 3784 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
13852 [ + + ]: 3784 : if (attform->attnum < 0)
13853 [ + - ]: 8 : ereport(ERROR,
13854 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13855 : : errmsg("system columns cannot be used in foreign keys")));
13856 [ - + ]: 3776 : if (attnum >= INDEX_MAX_KEYS)
13857 [ # # ]: 0 : ereport(ERROR,
13858 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
13859 : : errmsg("cannot have more than %d keys in a foreign key",
13860 : : INDEX_MAX_KEYS)));
13861 : 3776 : attnums[attnum] = attform->attnum;
13862 [ + + ]: 3776 : if (atttypids != NULL)
13863 : 3752 : atttypids[attnum] = attform->atttypid;
13864 [ + + ]: 3776 : if (attcollids != NULL)
13865 : 3752 : attcollids[attnum] = attform->attcollation;
13866 : 3776 : ReleaseSysCache(atttuple);
13867 : 3776 : attnum++;
13868 : : }
13869 : :
13870 : 4549 : return attnum;
13871 : : }
13872 : :
13873 : : /*
13874 : : * transformFkeyGetPrimaryKey -
13875 : : *
13876 : : * Look up the names, attnums, types, and collations of the primary key attributes
13877 : : * for the pkrel. Also return the index OID and index opclasses of the
13878 : : * index supporting the primary key. Also return whether the index has
13879 : : * WITHOUT OVERLAPS.
13880 : : *
13881 : : * All parameters except pkrel are output parameters. Also, the function
13882 : : * return value is the number of attributes in the primary key.
13883 : : *
13884 : : * Used when the column list in the REFERENCES specification is omitted.
13885 : : */
13886 : : static int
13887 : 904 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
13888 : : List **attnamelist,
13889 : : int16 *attnums, Oid *atttypids, Oid *attcollids,
13890 : : Oid *opclasses, bool *pk_has_without_overlaps)
13891 : : {
13892 : : List *indexoidlist;
13893 : : ListCell *indexoidscan;
13894 : 904 : HeapTuple indexTuple = NULL;
13895 : 904 : Form_pg_index indexStruct = NULL;
13896 : : Datum indclassDatum;
13897 : : oidvector *indclass;
13898 : : int i;
13899 : :
13900 : : /*
13901 : : * Get the list of index OIDs for the table from the relcache, and look up
13902 : : * each one in the pg_index syscache until we find one marked primary key
13903 : : * (hopefully there isn't more than one such). Insist it's valid, too.
13904 : : */
13905 : 904 : *indexOid = InvalidOid;
13906 : :
13907 : 904 : indexoidlist = RelationGetIndexList(pkrel);
13908 : :
13909 [ + - + - : 908 : foreach(indexoidscan, indexoidlist)
+ - ]
13910 : : {
13911 : 908 : Oid indexoid = lfirst_oid(indexoidscan);
13912 : :
13913 : 908 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13914 [ - + ]: 908 : if (!HeapTupleIsValid(indexTuple))
13915 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
13916 : 908 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13917 [ + + + - ]: 908 : if (indexStruct->indisprimary && indexStruct->indisvalid)
13918 : : {
13919 : : /*
13920 : : * Refuse to use a deferrable primary key. This is per SQL spec,
13921 : : * and there would be a lot of interesting semantic problems if we
13922 : : * tried to allow it.
13923 : : */
13924 [ - + ]: 904 : if (!indexStruct->indimmediate)
13925 [ # # ]: 0 : ereport(ERROR,
13926 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13927 : : errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
13928 : : RelationGetRelationName(pkrel))));
13929 : :
13930 : 904 : *indexOid = indexoid;
13931 : 904 : break;
13932 : : }
13933 : 4 : ReleaseSysCache(indexTuple);
13934 : : }
13935 : :
13936 : 904 : list_free(indexoidlist);
13937 : :
13938 : : /*
13939 : : * Check that we found it
13940 : : */
13941 [ - + ]: 904 : if (!OidIsValid(*indexOid))
13942 [ # # ]: 0 : ereport(ERROR,
13943 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
13944 : : errmsg("there is no primary key for referenced table \"%s\"",
13945 : : RelationGetRelationName(pkrel))));
13946 : :
13947 : : /* Must get indclass the hard way */
13948 : 904 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13949 : : Anum_pg_index_indclass);
13950 : 904 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
13951 : :
13952 : : /*
13953 : : * Now build the list of PK attributes from the indkey definition (we
13954 : : * assume a primary key cannot have expressional elements)
13955 : : */
13956 : 904 : *attnamelist = NIL;
13957 [ + + ]: 2124 : for (i = 0; i < indexStruct->indnkeyatts; i++)
13958 : : {
13959 : 1220 : int pkattno = indexStruct->indkey.values[i];
13960 : :
13961 : 1220 : attnums[i] = pkattno;
13962 : 1220 : atttypids[i] = attnumTypeId(pkrel, pkattno);
13963 : 1220 : attcollids[i] = attnumCollationId(pkrel, pkattno);
13964 : 1220 : opclasses[i] = indclass->values[i];
13965 : 1220 : *attnamelist = lappend(*attnamelist,
13966 : 1220 : makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
13967 : : }
13968 : :
13969 : 904 : *pk_has_without_overlaps = indexStruct->indisexclusion;
13970 : :
13971 : 904 : ReleaseSysCache(indexTuple);
13972 : :
13973 : 904 : return i;
13974 : : }
13975 : :
13976 : : /*
13977 : : * transformFkeyCheckAttrs -
13978 : : *
13979 : : * Validate that the 'attnums' columns in the 'pkrel' relation are valid to
13980 : : * reference as part of a foreign key constraint.
13981 : : *
13982 : : * Returns the OID of the unique index supporting the constraint and
13983 : : * populates the caller-provided 'opclasses' array with the opclasses
13984 : : * associated with the index columns. Also sets whether the index
13985 : : * uses WITHOUT OVERLAPS.
13986 : : *
13987 : : * Raises an ERROR on validation failure.
13988 : : */
13989 : : static Oid
13990 : 875 : transformFkeyCheckAttrs(Relation pkrel,
13991 : : int numattrs, int16 *attnums,
13992 : : bool with_period, Oid *opclasses,
13993 : : bool *pk_has_without_overlaps)
13994 : : {
13995 : 875 : Oid indexoid = InvalidOid;
13996 : 875 : bool found = false;
13997 : 875 : bool found_deferrable = false;
13998 : : List *indexoidlist;
13999 : : ListCell *indexoidscan;
14000 : : int i,
14001 : : j;
14002 : :
14003 : : /*
14004 : : * Reject duplicate appearances of columns in the referenced-columns list.
14005 : : * Such a case is forbidden by the SQL standard, and even if we thought it
14006 : : * useful to allow it, there would be ambiguity about how to match the
14007 : : * list to unique indexes (in particular, it'd be unclear which index
14008 : : * opclass goes with which FK column).
14009 : : */
14010 [ + + ]: 2055 : for (i = 0; i < numattrs; i++)
14011 : : {
14012 [ + + ]: 1567 : for (j = i + 1; j < numattrs; j++)
14013 : : {
14014 [ + + ]: 387 : if (attnums[i] == attnums[j])
14015 [ + - ]: 16 : ereport(ERROR,
14016 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
14017 : : errmsg("foreign key referenced-columns list must not contain duplicates")));
14018 : : }
14019 : : }
14020 : :
14021 : : /*
14022 : : * Get the list of index OIDs for the table from the relcache, and look up
14023 : : * each one in the pg_index syscache, and match unique indexes to the list
14024 : : * of attnums we are given.
14025 : : */
14026 : 859 : indexoidlist = RelationGetIndexList(pkrel);
14027 : :
14028 [ + - + + : 978 : foreach(indexoidscan, indexoidlist)
+ + ]
14029 : : {
14030 : : HeapTuple indexTuple;
14031 : : Form_pg_index indexStruct;
14032 : :
14033 : 970 : indexoid = lfirst_oid(indexoidscan);
14034 : 970 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
14035 [ - + ]: 970 : if (!HeapTupleIsValid(indexTuple))
14036 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
14037 : 970 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
14038 : :
14039 : : /*
14040 : : * Must have the right number of columns; must be unique (or if
14041 : : * temporal then exclusion instead) and not a partial index; forget it
14042 : : * if there are any expressions, too. Invalid indexes are out as well.
14043 : : */
14044 [ + + + + : 970 : if (indexStruct->indnkeyatts == numattrs &&
+ + ]
14045 : 889 : (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
14046 [ + - + - ]: 1778 : indexStruct->indisvalid &&
14047 [ + - ]: 1778 : heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
14048 : 889 : heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
14049 : : {
14050 : : Datum indclassDatum;
14051 : : oidvector *indclass;
14052 : :
14053 : : /* Must get indclass the hard way */
14054 : 889 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
14055 : : Anum_pg_index_indclass);
14056 : 889 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
14057 : :
14058 : : /*
14059 : : * The given attnum list may match the index columns in any order.
14060 : : * Check for a match, and extract the appropriate opclasses while
14061 : : * we're at it.
14062 : : *
14063 : : * We know that attnums[] is duplicate-free per the test at the
14064 : : * start of this function, and we checked above that the number of
14065 : : * index columns agrees, so if we find a match for each attnums[]
14066 : : * entry then we must have a one-to-one match in some order.
14067 : : */
14068 [ + + ]: 2061 : for (i = 0; i < numattrs; i++)
14069 : : {
14070 : 1210 : found = false;
14071 [ + + ]: 1619 : for (j = 0; j < numattrs; j++)
14072 : : {
14073 [ + + ]: 1581 : if (attnums[i] == indexStruct->indkey.values[j])
14074 : : {
14075 : 1172 : opclasses[i] = indclass->values[j];
14076 : 1172 : found = true;
14077 : 1172 : break;
14078 : : }
14079 : : }
14080 [ + + ]: 1210 : if (!found)
14081 : 38 : break;
14082 : : }
14083 : : /* The last attribute in the index must be the PERIOD FK part */
14084 [ + + + + ]: 889 : if (found && with_period)
14085 : : {
14086 : 80 : int16 periodattnum = attnums[numattrs - 1];
14087 : :
14088 : 80 : found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
14089 : : }
14090 : :
14091 : : /*
14092 : : * Refuse to use a deferrable unique/primary key. This is per SQL
14093 : : * spec, and there would be a lot of interesting semantic problems
14094 : : * if we tried to allow it.
14095 : : */
14096 [ + + - + ]: 889 : if (found && !indexStruct->indimmediate)
14097 : : {
14098 : : /*
14099 : : * Remember that we found an otherwise matching index, so that
14100 : : * we can generate a more appropriate error message.
14101 : : */
14102 : 0 : found_deferrable = true;
14103 : 0 : found = false;
14104 : : }
14105 : :
14106 : : /* We need to know whether the index has WITHOUT OVERLAPS */
14107 [ + + ]: 889 : if (found)
14108 : 851 : *pk_has_without_overlaps = indexStruct->indisexclusion;
14109 : : }
14110 : 970 : ReleaseSysCache(indexTuple);
14111 [ + + ]: 970 : if (found)
14112 : 851 : break;
14113 : : }
14114 : :
14115 [ + + ]: 859 : if (!found)
14116 : : {
14117 [ - + ]: 8 : if (found_deferrable)
14118 [ # # ]: 0 : ereport(ERROR,
14119 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14120 : : errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
14121 : : RelationGetRelationName(pkrel))));
14122 : : else
14123 [ + - ]: 8 : ereport(ERROR,
14124 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
14125 : : errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
14126 : : RelationGetRelationName(pkrel))));
14127 : : }
14128 : :
14129 : 851 : list_free(indexoidlist);
14130 : :
14131 : 851 : return indexoid;
14132 : : }
14133 : :
14134 : : /*
14135 : : * findFkeyCast -
14136 : : *
14137 : : * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
14138 : : * Caller has equal regard for binary coercibility and for an exact match.
14139 : : */
14140 : : static CoercionPathType
14141 : 8 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
14142 : : {
14143 : : CoercionPathType ret;
14144 : :
14145 [ + - ]: 8 : if (targetTypeId == sourceTypeId)
14146 : : {
14147 : 8 : ret = COERCION_PATH_RELABELTYPE;
14148 : 8 : *funcid = InvalidOid;
14149 : : }
14150 : : else
14151 : : {
14152 : 0 : ret = find_coercion_pathway(targetTypeId, sourceTypeId,
14153 : : COERCION_IMPLICIT, funcid);
14154 [ # # ]: 0 : if (ret == COERCION_PATH_NONE)
14155 : : /* A previously-relied-upon cast is now gone. */
14156 [ # # ]: 0 : elog(ERROR, "could not find cast from %u to %u",
14157 : : sourceTypeId, targetTypeId);
14158 : : }
14159 : :
14160 : 8 : return ret;
14161 : : }
14162 : :
14163 : : /*
14164 : : * Permissions checks on the referenced table for ADD FOREIGN KEY
14165 : : *
14166 : : * Note: we have already checked that the user owns the referencing table,
14167 : : * else we'd have failed much earlier; no additional checks are needed for it.
14168 : : */
14169 : : static void
14170 : 1731 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
14171 : : {
14172 : 1731 : Oid roleid = GetUserId();
14173 : : AclResult aclresult;
14174 : : int i;
14175 : :
14176 : : /* Okay if we have relation-level REFERENCES permission */
14177 : 1731 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
14178 : : ACL_REFERENCES);
14179 [ + - ]: 1731 : if (aclresult == ACLCHECK_OK)
14180 : 1731 : return;
14181 : : /* Else we must have REFERENCES on each column */
14182 [ # # ]: 0 : for (i = 0; i < natts; i++)
14183 : : {
14184 : 0 : aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
14185 : : roleid, ACL_REFERENCES);
14186 [ # # ]: 0 : if (aclresult != ACLCHECK_OK)
14187 : 0 : aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
14188 : 0 : RelationGetRelationName(rel));
14189 : : }
14190 : : }
14191 : :
14192 : : /*
14193 : : * Scan the existing rows in a table to verify they meet a proposed FK
14194 : : * constraint.
14195 : : *
14196 : : * Caller must have opened and locked both relations appropriately.
14197 : : */
14198 : : static void
14199 : 839 : validateForeignKeyConstraint(char *conname,
14200 : : Relation rel,
14201 : : Relation pkrel,
14202 : : Oid pkindOid,
14203 : : Oid constraintOid,
14204 : : bool hasperiod)
14205 : : {
14206 : : TupleTableSlot *slot;
14207 : : TableScanDesc scan;
14208 : 839 : Trigger trig = {0};
14209 : : Snapshot snapshot;
14210 : : MemoryContext oldcxt;
14211 : : MemoryContext perTupCxt;
14212 : :
14213 [ - + ]: 839 : ereport(DEBUG1,
14214 : : (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
14215 : :
14216 : : /*
14217 : : * Build a trigger call structure; we'll need it either way.
14218 : : */
14219 : 839 : trig.tgoid = InvalidOid;
14220 : 839 : trig.tgname = conname;
14221 : 839 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
14222 : 839 : trig.tgisinternal = true;
14223 : 839 : trig.tgconstrrelid = RelationGetRelid(pkrel);
14224 : 839 : trig.tgconstrindid = pkindOid;
14225 : 839 : trig.tgconstraint = constraintOid;
14226 : 839 : trig.tgdeferrable = false;
14227 : 839 : trig.tginitdeferred = false;
14228 : : /* we needn't fill in remaining fields */
14229 : :
14230 : : /*
14231 : : * See if we can do it with a single LEFT JOIN query. A false result
14232 : : * indicates we must proceed with the fire-the-trigger method. We can't do
14233 : : * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
14234 : : * left joins.
14235 : : */
14236 [ + + + + ]: 839 : if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
14237 : 680 : return;
14238 : :
14239 : : /*
14240 : : * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
14241 : : * if that tuple had just been inserted. If any of those fail, it should
14242 : : * ereport(ERROR) and that's that.
14243 : : */
14244 : 112 : snapshot = RegisterSnapshot(GetLatestSnapshot());
14245 : 112 : slot = table_slot_create(rel, NULL);
14246 : 112 : scan = table_beginscan(rel, snapshot, 0, NULL,
14247 : : SO_NONE);
14248 : 112 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
14249 : : "validateForeignKeyConstraint",
14250 : : ALLOCSET_SMALL_SIZES);
14251 : 112 : oldcxt = MemoryContextSwitchTo(perTupCxt);
14252 : :
14253 [ + + ]: 581 : while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
14254 : : {
14255 : 509 : LOCAL_FCINFO(fcinfo, 0);
14256 : 509 : TriggerData trigdata = {0};
14257 : :
14258 [ - + ]: 509 : CHECK_FOR_INTERRUPTS();
14259 : :
14260 : : /*
14261 : : * Make a call to the trigger function
14262 : : *
14263 : : * No parameters are passed, but we do set a context
14264 : : */
14265 [ + - + - : 2545 : MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
+ - + - +
+ ]
14266 : :
14267 : : /*
14268 : : * We assume RI_FKey_check_ins won't look at flinfo...
14269 : : */
14270 : 509 : trigdata.type = T_TriggerData;
14271 : 509 : trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
14272 : 509 : trigdata.tg_relation = rel;
14273 : 509 : trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
14274 : 509 : trigdata.tg_trigslot = slot;
14275 : 509 : trigdata.tg_trigger = &trig;
14276 : :
14277 : 509 : fcinfo->context = (Node *) &trigdata;
14278 : :
14279 : 509 : RI_FKey_check_ins(fcinfo);
14280 : :
14281 : 469 : MemoryContextReset(perTupCxt);
14282 : : }
14283 : :
14284 : 72 : MemoryContextSwitchTo(oldcxt);
14285 : 72 : MemoryContextDelete(perTupCxt);
14286 : 72 : table_endscan(scan);
14287 : 72 : UnregisterSnapshot(snapshot);
14288 : 72 : ExecDropSingleTupleTableSlot(slot);
14289 : : }
14290 : :
14291 : : /*
14292 : : * CreateFKCheckTrigger
14293 : : * Creates the insert (on_insert=true) or update "check" trigger that
14294 : : * implements a given foreign key
14295 : : *
14296 : : * Returns the OID of the so created trigger.
14297 : : */
14298 : : static Oid
14299 : 4092 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14300 : : Oid constraintOid, Oid indexOid, Oid parentTrigOid,
14301 : : bool on_insert)
14302 : : {
14303 : : ObjectAddress trigAddress;
14304 : : CreateTrigStmt *fk_trigger;
14305 : :
14306 : : /*
14307 : : * Note: for a self-referential FK (referencing and referenced tables are
14308 : : * the same), it is important that the ON UPDATE action fires before the
14309 : : * CHECK action, since both triggers will fire on the same row during an
14310 : : * UPDATE event; otherwise the CHECK trigger will be checking a non-final
14311 : : * state of the row. Triggers fire in name order, so we ensure this by
14312 : : * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
14313 : : * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
14314 : : */
14315 : 4092 : fk_trigger = makeNode(CreateTrigStmt);
14316 : 4092 : fk_trigger->replace = false;
14317 : 4092 : fk_trigger->isconstraint = true;
14318 : 4092 : fk_trigger->trigname = "RI_ConstraintTrigger_c";
14319 : 4092 : fk_trigger->relation = NULL;
14320 : :
14321 : : /* Either ON INSERT or ON UPDATE */
14322 [ + + ]: 4092 : if (on_insert)
14323 : : {
14324 : 2046 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
14325 : 2046 : fk_trigger->events = TRIGGER_TYPE_INSERT;
14326 : : }
14327 : : else
14328 : : {
14329 : 2046 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
14330 : 2046 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14331 : : }
14332 : :
14333 : 4092 : fk_trigger->args = NIL;
14334 : 4092 : fk_trigger->row = true;
14335 : 4092 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14336 : 4092 : fk_trigger->columns = NIL;
14337 : 4092 : fk_trigger->whenClause = NULL;
14338 : 4092 : fk_trigger->transitionRels = NIL;
14339 : 4092 : fk_trigger->deferrable = fkconstraint->deferrable;
14340 : 4092 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14341 : 4092 : fk_trigger->constrrel = NULL;
14342 : :
14343 : 4092 : trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
14344 : : constraintOid, indexOid, InvalidOid,
14345 : : parentTrigOid, NULL, true, false);
14346 : :
14347 : : /* Make changes-so-far visible */
14348 : 4092 : CommandCounterIncrement();
14349 : :
14350 : 4092 : return trigAddress.objectId;
14351 : : }
14352 : :
14353 : : /*
14354 : : * createForeignKeyActionTriggers
14355 : : * Create the referenced-side "action" triggers that implement a foreign
14356 : : * key.
14357 : : *
14358 : : * Returns the OIDs of the so created triggers in *deleteTrigOid and
14359 : : * *updateTrigOid.
14360 : : */
14361 : : static void
14362 : 2325 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14363 : : Oid constraintOid, Oid indexOid,
14364 : : Oid parentDelTrigger, Oid parentUpdTrigger,
14365 : : Oid *deleteTrigOid, Oid *updateTrigOid)
14366 : : {
14367 : : CreateTrigStmt *fk_trigger;
14368 : : ObjectAddress trigAddress;
14369 : :
14370 : : /*
14371 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14372 : : * DELETE action on the referenced table.
14373 : : */
14374 : 2325 : fk_trigger = makeNode(CreateTrigStmt);
14375 : 2325 : fk_trigger->replace = false;
14376 : 2325 : fk_trigger->isconstraint = true;
14377 : 2325 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14378 : 2325 : fk_trigger->relation = NULL;
14379 : 2325 : fk_trigger->args = NIL;
14380 : 2325 : fk_trigger->row = true;
14381 : 2325 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14382 : 2325 : fk_trigger->events = TRIGGER_TYPE_DELETE;
14383 : 2325 : fk_trigger->columns = NIL;
14384 : 2325 : fk_trigger->whenClause = NULL;
14385 : 2325 : fk_trigger->transitionRels = NIL;
14386 : 2325 : fk_trigger->constrrel = NULL;
14387 : :
14388 [ + + + + : 2325 : switch (fkconstraint->fk_del_action)
+ - ]
14389 : : {
14390 : 1892 : case FKCONSTR_ACTION_NOACTION:
14391 : 1892 : fk_trigger->deferrable = fkconstraint->deferrable;
14392 : 1892 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14393 : 1892 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
14394 : 1892 : break;
14395 : 20 : case FKCONSTR_ACTION_RESTRICT:
14396 : 20 : fk_trigger->deferrable = false;
14397 : 20 : fk_trigger->initdeferred = false;
14398 : 20 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
14399 : 20 : break;
14400 : 310 : case FKCONSTR_ACTION_CASCADE:
14401 : 310 : fk_trigger->deferrable = false;
14402 : 310 : fk_trigger->initdeferred = false;
14403 : 310 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
14404 : 310 : break;
14405 : 63 : case FKCONSTR_ACTION_SETNULL:
14406 : 63 : fk_trigger->deferrable = false;
14407 : 63 : fk_trigger->initdeferred = false;
14408 : 63 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
14409 : 63 : break;
14410 : 40 : case FKCONSTR_ACTION_SETDEFAULT:
14411 : 40 : fk_trigger->deferrable = false;
14412 : 40 : fk_trigger->initdeferred = false;
14413 : 40 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
14414 : 40 : break;
14415 : 0 : default:
14416 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
14417 : : (int) fkconstraint->fk_del_action);
14418 : : break;
14419 : : }
14420 : :
14421 : 2325 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14422 : : constraintOid, indexOid, InvalidOid,
14423 : : parentDelTrigger, NULL, true, false);
14424 [ + - ]: 2325 : if (deleteTrigOid)
14425 : 2325 : *deleteTrigOid = trigAddress.objectId;
14426 : :
14427 : : /* Make changes-so-far visible */
14428 : 2325 : CommandCounterIncrement();
14429 : :
14430 : : /*
14431 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14432 : : * UPDATE action on the referenced table.
14433 : : */
14434 : 2325 : fk_trigger = makeNode(CreateTrigStmt);
14435 : 2325 : fk_trigger->replace = false;
14436 : 2325 : fk_trigger->isconstraint = true;
14437 : 2325 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14438 : 2325 : fk_trigger->relation = NULL;
14439 : 2325 : fk_trigger->args = NIL;
14440 : 2325 : fk_trigger->row = true;
14441 : 2325 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14442 : 2325 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14443 : 2325 : fk_trigger->columns = NIL;
14444 : 2325 : fk_trigger->whenClause = NULL;
14445 : 2325 : fk_trigger->transitionRels = NIL;
14446 : 2325 : fk_trigger->constrrel = NULL;
14447 : :
14448 [ + + + + : 2325 : switch (fkconstraint->fk_upd_action)
+ - ]
14449 : : {
14450 : 2021 : case FKCONSTR_ACTION_NOACTION:
14451 : 2021 : fk_trigger->deferrable = fkconstraint->deferrable;
14452 : 2021 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14453 : 2021 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
14454 : 2021 : break;
14455 : 24 : case FKCONSTR_ACTION_RESTRICT:
14456 : 24 : fk_trigger->deferrable = false;
14457 : 24 : fk_trigger->initdeferred = false;
14458 : 24 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
14459 : 24 : break;
14460 : 211 : case FKCONSTR_ACTION_CASCADE:
14461 : 211 : fk_trigger->deferrable = false;
14462 : 211 : fk_trigger->initdeferred = false;
14463 : 211 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
14464 : 211 : break;
14465 : 41 : case FKCONSTR_ACTION_SETNULL:
14466 : 41 : fk_trigger->deferrable = false;
14467 : 41 : fk_trigger->initdeferred = false;
14468 : 41 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
14469 : 41 : break;
14470 : 28 : case FKCONSTR_ACTION_SETDEFAULT:
14471 : 28 : fk_trigger->deferrable = false;
14472 : 28 : fk_trigger->initdeferred = false;
14473 : 28 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
14474 : 28 : break;
14475 : 0 : default:
14476 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
14477 : : (int) fkconstraint->fk_upd_action);
14478 : : break;
14479 : : }
14480 : :
14481 : 2325 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14482 : : constraintOid, indexOid, InvalidOid,
14483 : : parentUpdTrigger, NULL, true, false);
14484 [ + - ]: 2325 : if (updateTrigOid)
14485 : 2325 : *updateTrigOid = trigAddress.objectId;
14486 : 2325 : }
14487 : :
14488 : : /*
14489 : : * createForeignKeyCheckTriggers
14490 : : * Create the referencing-side "check" triggers that implement a foreign
14491 : : * key.
14492 : : *
14493 : : * Returns the OIDs of the so created triggers in *insertTrigOid and
14494 : : * *updateTrigOid.
14495 : : */
14496 : : static void
14497 : 2046 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
14498 : : Constraint *fkconstraint, Oid constraintOid,
14499 : : Oid indexOid,
14500 : : Oid parentInsTrigger, Oid parentUpdTrigger,
14501 : : Oid *insertTrigOid, Oid *updateTrigOid)
14502 : : {
14503 : 2046 : *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14504 : : constraintOid, indexOid,
14505 : : parentInsTrigger, true);
14506 : 2046 : *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14507 : : constraintOid, indexOid,
14508 : : parentUpdTrigger, false);
14509 : 2046 : }
14510 : :
14511 : : /*
14512 : : * ALTER TABLE DROP CONSTRAINT
14513 : : *
14514 : : * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
14515 : : */
14516 : : static void
14517 : 563 : ATExecDropConstraint(Relation rel, const char *constrName,
14518 : : DropBehavior behavior, bool recurse,
14519 : : bool missing_ok, LOCKMODE lockmode)
14520 : : {
14521 : : Relation conrel;
14522 : : SysScanDesc scan;
14523 : : ScanKeyData skey[3];
14524 : : HeapTuple tuple;
14525 : 563 : bool found = false;
14526 : :
14527 : 563 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14528 : :
14529 : : /*
14530 : : * Find and drop the target constraint
14531 : : */
14532 : 563 : ScanKeyInit(&skey[0],
14533 : : Anum_pg_constraint_conrelid,
14534 : : BTEqualStrategyNumber, F_OIDEQ,
14535 : : ObjectIdGetDatum(RelationGetRelid(rel)));
14536 : 563 : ScanKeyInit(&skey[1],
14537 : : Anum_pg_constraint_contypid,
14538 : : BTEqualStrategyNumber, F_OIDEQ,
14539 : : ObjectIdGetDatum(InvalidOid));
14540 : 563 : ScanKeyInit(&skey[2],
14541 : : Anum_pg_constraint_conname,
14542 : : BTEqualStrategyNumber, F_NAMEEQ,
14543 : : CStringGetDatum(constrName));
14544 : 563 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14545 : : true, NULL, 3, skey);
14546 : :
14547 : : /* There can be at most one matching row */
14548 [ + + ]: 563 : if (HeapTupleIsValid(tuple = systable_getnext(scan)))
14549 : : {
14550 : 539 : dropconstraint_internal(rel, tuple, behavior, recurse, false,
14551 : : missing_ok, lockmode);
14552 : 415 : found = true;
14553 : : }
14554 : :
14555 : 439 : systable_endscan(scan);
14556 : :
14557 [ + + ]: 439 : if (!found)
14558 : : {
14559 [ + + ]: 24 : if (!missing_ok)
14560 [ + - ]: 16 : ereport(ERROR,
14561 : : errcode(ERRCODE_UNDEFINED_OBJECT),
14562 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14563 : : constrName, RelationGetRelationName(rel)));
14564 : : else
14565 [ + - ]: 8 : ereport(NOTICE,
14566 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
14567 : : constrName, RelationGetRelationName(rel)));
14568 : : }
14569 : :
14570 : 423 : table_close(conrel, RowExclusiveLock);
14571 : 423 : }
14572 : :
14573 : : /*
14574 : : * Remove a constraint, using its pg_constraint tuple
14575 : : *
14576 : : * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
14577 : : * DROP NOT NULL.
14578 : : *
14579 : : * Returns the address of the constraint being removed.
14580 : : */
14581 : : static ObjectAddress
14582 : 867 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
14583 : : bool recurse, bool recursing, bool missing_ok,
14584 : : LOCKMODE lockmode)
14585 : : {
14586 : : Relation conrel;
14587 : : Form_pg_constraint con;
14588 : : ObjectAddress conobj;
14589 : : List *children;
14590 : 867 : bool is_no_inherit_constraint = false;
14591 : : char *constrName;
14592 : 867 : char *colname = NULL;
14593 : :
14594 : : /* Guard against stack overflow due to overly deep inheritance tree. */
14595 : 867 : check_stack_depth();
14596 : :
14597 : : /* At top level, permission check was done in ATPrepCmd, else do it */
14598 [ + + ]: 867 : if (recursing)
14599 : 163 : ATSimplePermissions(AT_DropConstraint, rel,
14600 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
14601 : :
14602 : 863 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14603 : :
14604 : 863 : con = (Form_pg_constraint) GETSTRUCT(constraintTup);
14605 : 863 : constrName = NameStr(con->conname);
14606 : :
14607 : : /* Don't allow drop of inherited constraints */
14608 [ + + + + ]: 863 : if (con->coninhcount > 0 && !recursing)
14609 [ + - ]: 104 : ereport(ERROR,
14610 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14611 : : errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
14612 : : constrName, RelationGetRelationName(rel))));
14613 : :
14614 : : /*
14615 : : * Reset pg_constraint.attnotnull, if this is a not-null constraint.
14616 : : *
14617 : : * While doing that, we're in a good position to disallow dropping a not-
14618 : : * null constraint underneath a primary key, a replica identity index, or
14619 : : * a generated identity column.
14620 : : */
14621 [ + + ]: 759 : if (con->contype == CONSTRAINT_NOTNULL)
14622 : : {
14623 : 235 : Relation attrel = table_open(AttributeRelationId, RowExclusiveLock);
14624 : 235 : AttrNumber attnum = extractNotNullColumn(constraintTup);
14625 : : Bitmapset *pkattrs;
14626 : : Bitmapset *irattrs;
14627 : : HeapTuple atttup;
14628 : : Form_pg_attribute attForm;
14629 : :
14630 : : /* save column name for recursion step */
14631 : 235 : colname = get_attname(RelationGetRelid(rel), attnum, false);
14632 : :
14633 : : /*
14634 : : * Disallow if it's in the primary key. For partitioned tables we
14635 : : * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
14636 : : * return NULL if the primary key is invalid; but we still need to
14637 : : * protect not-null constraints under such a constraint, so check the
14638 : : * slow way.
14639 : : */
14640 : 235 : pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
14641 : :
14642 [ + + ]: 235 : if (pkattrs == NULL &&
14643 [ + + ]: 215 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14644 : : {
14645 : 16 : Oid pkindex = RelationGetPrimaryKeyIndex(rel, true);
14646 : :
14647 [ - + ]: 16 : if (OidIsValid(pkindex))
14648 : : {
14649 : 0 : Relation pk = relation_open(pkindex, AccessShareLock);
14650 : :
14651 : 0 : pkattrs = NULL;
14652 [ # # ]: 0 : for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
14653 : 0 : pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
14654 : :
14655 : 0 : relation_close(pk, AccessShareLock);
14656 : : }
14657 : : }
14658 : :
14659 [ + + + + ]: 255 : if (pkattrs &&
14660 : 20 : bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
14661 [ + - ]: 16 : ereport(ERROR,
14662 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14663 : : errmsg("column \"%s\" is in a primary key",
14664 : : get_attname(RelationGetRelid(rel), attnum, false)));
14665 : :
14666 : : /* Disallow if it's in the replica identity */
14667 : 219 : irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
14668 [ + + ]: 219 : if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
14669 [ + - ]: 8 : ereport(ERROR,
14670 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14671 : : errmsg("column \"%s\" is in index used as replica identity",
14672 : : get_attname(RelationGetRelid(rel), attnum, false)));
14673 : :
14674 : : /* Disallow if it's a GENERATED AS IDENTITY column */
14675 : 211 : atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
14676 [ - + ]: 211 : if (!HeapTupleIsValid(atttup))
14677 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
14678 : : attnum, RelationGetRelid(rel));
14679 : 211 : attForm = (Form_pg_attribute) GETSTRUCT(atttup);
14680 [ - + ]: 211 : if (attForm->attidentity != '\0')
14681 [ # # ]: 0 : ereport(ERROR,
14682 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14683 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
14684 : : get_attname(RelationGetRelid(rel), attnum,
14685 : : false),
14686 : : RelationGetRelationName(rel)));
14687 : :
14688 : : /* All good -- reset attnotnull if needed */
14689 [ + - ]: 211 : if (attForm->attnotnull)
14690 : : {
14691 : 211 : attForm->attnotnull = false;
14692 : 211 : CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
14693 : : }
14694 : :
14695 : 211 : table_close(attrel, RowExclusiveLock);
14696 : : }
14697 : :
14698 : 735 : is_no_inherit_constraint = con->connoinherit;
14699 : :
14700 : : /*
14701 : : * If it's a foreign-key constraint, we'd better lock the referenced table
14702 : : * and check that that's not in use, just as we've already done for the
14703 : : * constrained table (else we might, eg, be dropping a trigger that has
14704 : : * unfired events). But we can/must skip that in the self-referential
14705 : : * case.
14706 : : */
14707 [ + + ]: 735 : if (con->contype == CONSTRAINT_FOREIGN &&
14708 [ + - ]: 112 : con->confrelid != RelationGetRelid(rel))
14709 : : {
14710 : : Relation frel;
14711 : :
14712 : : /* Must match lock taken by RemoveTriggerById: */
14713 : 112 : frel = table_open(con->confrelid, AccessExclusiveLock);
14714 : 112 : CheckAlterTableIsSafe(frel);
14715 : 108 : table_close(frel, NoLock);
14716 : : }
14717 : :
14718 : : /*
14719 : : * Perform the actual constraint deletion
14720 : : */
14721 : 731 : ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
14722 : 731 : performDeletion(&conobj, behavior, 0);
14723 : :
14724 : : /*
14725 : : * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
14726 : : * are dropped via the dependency mechanism, so we're done here.
14727 : : */
14728 [ + + ]: 707 : if (con->contype != CONSTRAINT_CHECK &&
14729 [ + + ]: 450 : con->contype != CONSTRAINT_NOTNULL &&
14730 [ + + ]: 239 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14731 : : {
14732 : 52 : table_close(conrel, RowExclusiveLock);
14733 : 52 : return conobj;
14734 : : }
14735 : :
14736 : : /*
14737 : : * Propagate to children as appropriate. Unlike most other ALTER
14738 : : * routines, we have to do this one level of recursion at a time; we can't
14739 : : * use find_all_inheritors to do it in one pass.
14740 : : */
14741 [ + + ]: 655 : if (!is_no_inherit_constraint)
14742 : 452 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
14743 : : else
14744 : 203 : children = NIL;
14745 : :
14746 [ + + + + : 1589 : foreach_oid(childrelid, children)
+ + ]
14747 : : {
14748 : : Relation childrel;
14749 : : HeapTuple tuple;
14750 : : Form_pg_constraint childcon;
14751 : :
14752 : : /* find_inheritance_children already got lock */
14753 : 287 : childrel = table_open(childrelid, NoLock);
14754 : 287 : CheckAlterTableIsSafe(childrel);
14755 : :
14756 : : /*
14757 : : * We search for not-null constraints by column name, and others by
14758 : : * constraint name.
14759 : : */
14760 [ + + ]: 287 : if (con->contype == CONSTRAINT_NOTNULL)
14761 : : {
14762 : 102 : tuple = findNotNullConstraint(childrelid, colname);
14763 [ - + ]: 102 : if (!HeapTupleIsValid(tuple))
14764 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
14765 : : colname, RelationGetRelid(childrel));
14766 : : }
14767 : : else
14768 : : {
14769 : : SysScanDesc scan;
14770 : : ScanKeyData skey[3];
14771 : :
14772 : 185 : ScanKeyInit(&skey[0],
14773 : : Anum_pg_constraint_conrelid,
14774 : : BTEqualStrategyNumber, F_OIDEQ,
14775 : : ObjectIdGetDatum(childrelid));
14776 : 185 : ScanKeyInit(&skey[1],
14777 : : Anum_pg_constraint_contypid,
14778 : : BTEqualStrategyNumber, F_OIDEQ,
14779 : : ObjectIdGetDatum(InvalidOid));
14780 : 185 : ScanKeyInit(&skey[2],
14781 : : Anum_pg_constraint_conname,
14782 : : BTEqualStrategyNumber, F_NAMEEQ,
14783 : : CStringGetDatum(constrName));
14784 : 185 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14785 : : true, NULL, 3, skey);
14786 : : /* There can only be one, so no need to loop */
14787 : 185 : tuple = systable_getnext(scan);
14788 [ - + ]: 185 : if (!HeapTupleIsValid(tuple))
14789 [ # # ]: 0 : ereport(ERROR,
14790 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
14791 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14792 : : constrName,
14793 : : RelationGetRelationName(childrel))));
14794 : 185 : tuple = heap_copytuple(tuple);
14795 : 185 : systable_endscan(scan);
14796 : : }
14797 : :
14798 : 287 : childcon = (Form_pg_constraint) GETSTRUCT(tuple);
14799 : :
14800 : : /* Right now only CHECK and not-null constraints can be inherited */
14801 [ + + ]: 287 : if (childcon->contype != CONSTRAINT_CHECK &&
14802 [ - + ]: 102 : childcon->contype != CONSTRAINT_NOTNULL)
14803 [ # # ]: 0 : elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
14804 : :
14805 [ - + ]: 287 : if (childcon->coninhcount <= 0) /* shouldn't happen */
14806 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
14807 : : childrelid, NameStr(childcon->conname));
14808 : :
14809 [ + + ]: 287 : if (recurse)
14810 : : {
14811 : : /*
14812 : : * If the child constraint has other definition sources, just
14813 : : * decrement its inheritance count; if not, recurse to delete it.
14814 : : */
14815 [ + + + + ]: 219 : if (childcon->coninhcount == 1 && !childcon->conislocal)
14816 : : {
14817 : : /* Time to delete this child constraint, too */
14818 : 163 : dropconstraint_internal(childrel, tuple, behavior,
14819 : : recurse, true, missing_ok,
14820 : : lockmode);
14821 : : }
14822 : : else
14823 : : {
14824 : : /* Child constraint must survive my deletion */
14825 : 56 : childcon->coninhcount--;
14826 : 56 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14827 : :
14828 : : /* Make update visible */
14829 : 56 : CommandCounterIncrement();
14830 : : }
14831 : : }
14832 : : else
14833 : : {
14834 : : /*
14835 : : * If we were told to drop ONLY in this table (no recursion) and
14836 : : * there are no further parents for this constraint, we need to
14837 : : * mark the inheritors' constraints as locally defined rather than
14838 : : * inherited.
14839 : : */
14840 : 68 : childcon->coninhcount--;
14841 [ + - ]: 68 : if (childcon->coninhcount == 0)
14842 : 68 : childcon->conislocal = true;
14843 : :
14844 : 68 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14845 : :
14846 : : /* Make update visible */
14847 : 68 : CommandCounterIncrement();
14848 : : }
14849 : :
14850 : 283 : heap_freetuple(tuple);
14851 : :
14852 : 283 : table_close(childrel, NoLock);
14853 : : }
14854 : :
14855 : 651 : table_close(conrel, RowExclusiveLock);
14856 : :
14857 : 651 : return conobj;
14858 : : }
14859 : :
14860 : : /*
14861 : : * ALTER COLUMN TYPE
14862 : : *
14863 : : * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
14864 : : * TYPE during phase 1 --- the AlterTableCmd passed in here is already
14865 : : * transformed (and must be, because we rely on some transformed fields).
14866 : : *
14867 : : * The point of this is that the execution of all ALTER COLUMN TYPEs for a
14868 : : * table will be done "in parallel" during phase 3, so all the USING
14869 : : * expressions should be parsed assuming the original column types. Also,
14870 : : * this allows a USING expression to refer to a field that will be dropped.
14871 : : *
14872 : : * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
14873 : : * the first two execution steps in phase 2; they must not see the effects
14874 : : * of any other subcommand types, since the USING expressions are parsed
14875 : : * against the unmodified table's state.
14876 : : */
14877 : : static void
14878 : 959 : ATPrepAlterColumnType(List **wqueue,
14879 : : AlteredTableInfo *tab, Relation rel,
14880 : : bool recurse, bool recursing,
14881 : : AlterTableCmd *cmd, LOCKMODE lockmode,
14882 : : AlterTableUtilityContext *context)
14883 : : {
14884 : 959 : char *colName = cmd->name;
14885 : 959 : ColumnDef *def = (ColumnDef *) cmd->def;
14886 : 959 : TypeName *typeName = def->typeName;
14887 : 959 : Node *transform = def->cooked_default;
14888 : : HeapTuple tuple;
14889 : : Form_pg_attribute attTup;
14890 : : AttrNumber attnum;
14891 : : Oid targettype;
14892 : : int32 targettypmod;
14893 : : Oid targetcollid;
14894 : : NewColumnValue *newval;
14895 : 959 : ParseState *pstate = make_parsestate(NULL);
14896 : : AclResult aclresult;
14897 : : bool is_expr;
14898 : :
14899 : 959 : pstate->p_sourcetext = context->queryString;
14900 : :
14901 [ + + + + ]: 959 : if (rel->rd_rel->reloftype && !recursing)
14902 [ + - ]: 4 : ereport(ERROR,
14903 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14904 : : errmsg("cannot alter column type of typed table"),
14905 : : parser_errposition(pstate, def->location)));
14906 : :
14907 : : /* lookup the attribute so we can check inheritance status */
14908 : 955 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
14909 [ - + ]: 955 : if (!HeapTupleIsValid(tuple))
14910 [ # # ]: 0 : ereport(ERROR,
14911 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
14912 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
14913 : : colName, RelationGetRelationName(rel)),
14914 : : parser_errposition(pstate, def->location)));
14915 : 955 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
14916 : 955 : attnum = attTup->attnum;
14917 : :
14918 : : /* Can't alter a system attribute */
14919 [ + + ]: 955 : if (attnum <= 0)
14920 [ + - ]: 4 : ereport(ERROR,
14921 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14922 : : errmsg("cannot alter system column \"%s\"", colName),
14923 : : parser_errposition(pstate, def->location)));
14924 : :
14925 : : /*
14926 : : * Cannot specify USING when altering type of a generated column, because
14927 : : * that would violate the generation expression.
14928 : : */
14929 [ + + + + ]: 951 : if (attTup->attgenerated && def->cooked_default)
14930 [ + - ]: 8 : ereport(ERROR,
14931 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
14932 : : errmsg("cannot specify USING when altering type of generated column"),
14933 : : errdetail("Column \"%s\" is a generated column.", colName),
14934 : : parser_errposition(pstate, def->location)));
14935 : :
14936 : : /*
14937 : : * Don't alter inherited columns. At outer level, there had better not be
14938 : : * any inherited definition; when recursing, we assume this was checked at
14939 : : * the parent level (see below).
14940 : : */
14941 [ + + + + ]: 943 : if (attTup->attinhcount > 0 && !recursing)
14942 [ + - ]: 4 : ereport(ERROR,
14943 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14944 : : errmsg("cannot alter inherited column \"%s\"", colName),
14945 : : parser_errposition(pstate, def->location)));
14946 : :
14947 : : /* Don't alter columns used in the partition key */
14948 [ + + ]: 939 : if (has_partition_attrs(rel,
14949 : : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
14950 : : &is_expr))
14951 [ + - ]: 12 : ereport(ERROR,
14952 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14953 : : errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
14954 : : colName, RelationGetRelationName(rel)),
14955 : : parser_errposition(pstate, def->location)));
14956 : :
14957 : : /* Look up the target type */
14958 : 927 : typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
14959 : :
14960 : 923 : aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
14961 [ + + ]: 923 : if (aclresult != ACLCHECK_OK)
14962 : 8 : aclcheck_error_type(aclresult, targettype);
14963 : :
14964 : : /* And the collation */
14965 : 915 : targetcollid = GetColumnDefCollation(pstate, def, targettype);
14966 : :
14967 : : /* make sure datatype is legal for a column */
14968 : 1822 : CheckAttributeType(colName, targettype, targetcollid,
14969 : 911 : list_make1_oid(rel->rd_rel->reltype),
14970 [ + + ]: 911 : (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
14971 : :
14972 [ + + ]: 903 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14973 : : {
14974 : : /* do nothing */
14975 : : }
14976 [ + + ]: 879 : else if (tab->relkind == RELKIND_RELATION ||
14977 [ + + ]: 137 : tab->relkind == RELKIND_PARTITIONED_TABLE)
14978 : : {
14979 : : /*
14980 : : * Set up an expression to transform the old data value to the new
14981 : : * type. If a USING option was given, use the expression as
14982 : : * transformed by transformAlterTableStmt, else just take the old
14983 : : * value and try to coerce it. We do this first so that type
14984 : : * incompatibility can be detected before we waste effort, and because
14985 : : * we need the expression to be parsed against the original table row
14986 : : * type.
14987 : : */
14988 [ + + ]: 786 : if (!transform)
14989 : : {
14990 : 635 : transform = (Node *) makeVar(1, attnum,
14991 : : attTup->atttypid, attTup->atttypmod,
14992 : : attTup->attcollation,
14993 : : 0);
14994 : : }
14995 : :
14996 : 786 : transform = coerce_to_target_type(pstate,
14997 : : transform, exprType(transform),
14998 : : targettype, targettypmod,
14999 : : COERCION_ASSIGNMENT,
15000 : : COERCE_IMPLICIT_CAST,
15001 : : -1);
15002 [ + + ]: 786 : if (transform == NULL)
15003 : : {
15004 : : /* error text depends on whether USING was specified or not */
15005 [ + + ]: 15 : if (def->cooked_default != NULL)
15006 [ + - ]: 4 : ereport(ERROR,
15007 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15008 : : errmsg("result of USING clause for column \"%s\""
15009 : : " cannot be cast automatically to type %s",
15010 : : colName, format_type_be(targettype)),
15011 : : errhint("You might need to add an explicit cast.")));
15012 : : else
15013 [ + - + - ]: 11 : ereport(ERROR,
15014 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15015 : : errmsg("column \"%s\" cannot be cast automatically to type %s",
15016 : : colName, format_type_be(targettype)),
15017 : : !attTup->attgenerated ?
15018 : : /* translator: USING is SQL, don't translate it */
15019 : : errhint("You might need to specify \"USING %s::%s\".",
15020 : : quote_identifier(colName),
15021 : : format_type_with_typemod(targettype,
15022 : : targettypmod)) : 0));
15023 : : }
15024 : :
15025 : : /* Fix collations after all else */
15026 : 771 : assign_expr_collations(pstate, transform);
15027 : :
15028 : : /* Expand virtual generated columns in the expr. */
15029 : 771 : transform = expand_generated_columns_in_expr(transform, rel, 1);
15030 : :
15031 : : /* Plan the expr now so we can accurately assess the need to rewrite. */
15032 : 771 : transform = (Node *) expression_planner((Expr *) transform);
15033 : :
15034 : : /*
15035 : : * Add a work queue item to make ATRewriteTable update the column
15036 : : * contents.
15037 : : */
15038 : 771 : newval = palloc0_object(NewColumnValue);
15039 : 771 : newval->attnum = attnum;
15040 : 771 : newval->expr = (Expr *) transform;
15041 : 771 : newval->is_generated = false;
15042 : :
15043 : 771 : tab->newvals = lappend(tab->newvals, newval);
15044 [ + + ]: 1410 : if (ATColumnChangeRequiresRewrite(transform, attnum))
15045 : 639 : tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
15046 : : }
15047 [ + + ]: 93 : else if (transform)
15048 [ + - ]: 8 : ereport(ERROR,
15049 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15050 : : errmsg("\"%s\" is not a table",
15051 : : RelationGetRelationName(rel))));
15052 : :
15053 [ + + + - : 880 : if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ - + - -
+ + + ]
15054 : : {
15055 : : /*
15056 : : * For relations or columns without storage, do this check now.
15057 : : * Regular tables will check it later when the table is being
15058 : : * rewritten.
15059 : : */
15060 : 153 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
15061 : : }
15062 : :
15063 : 848 : ReleaseSysCache(tuple);
15064 : :
15065 : : /*
15066 : : * Recurse manually by queueing a new command for each child, if
15067 : : * necessary. We cannot apply ATSimpleRecursion here because we need to
15068 : : * remap attribute numbers in the USING expression, if any.
15069 : : *
15070 : : * If we are told not to recurse, there had better not be any child
15071 : : * tables; else the alter would put them out of step.
15072 : : */
15073 [ + + ]: 848 : if (recurse)
15074 : : {
15075 : 673 : Oid relid = RelationGetRelid(rel);
15076 : : List *child_oids,
15077 : : *child_numparents;
15078 : : ListCell *lo,
15079 : : *li;
15080 : :
15081 : 673 : child_oids = find_all_inheritors(relid, lockmode,
15082 : : &child_numparents);
15083 : :
15084 : : /*
15085 : : * find_all_inheritors does the recursive search of the inheritance
15086 : : * hierarchy, so all we have to do is process all of the relids in the
15087 : : * list that it returns.
15088 : : */
15089 [ + - + + : 1484 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
15090 : : {
15091 : 827 : Oid childrelid = lfirst_oid(lo);
15092 : 827 : int numparents = lfirst_int(li);
15093 : : Relation childrel;
15094 : : HeapTuple childtuple;
15095 : : Form_pg_attribute childattTup;
15096 : :
15097 [ + + ]: 827 : if (childrelid == relid)
15098 : 673 : continue;
15099 : :
15100 : : /* find_all_inheritors already got lock */
15101 : 154 : childrel = relation_open(childrelid, NoLock);
15102 : 154 : CheckAlterTableIsSafe(childrel);
15103 : :
15104 : : /*
15105 : : * Verify that the child doesn't have any inherited definitions of
15106 : : * this column that came from outside this inheritance hierarchy.
15107 : : * (renameatt makes a similar test, though in a different way
15108 : : * because of its different recursion mechanism.)
15109 : : */
15110 : 154 : childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
15111 : : colName);
15112 [ - + ]: 154 : if (!HeapTupleIsValid(childtuple))
15113 [ # # ]: 0 : ereport(ERROR,
15114 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15115 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15116 : : colName, RelationGetRelationName(childrel))));
15117 : 154 : childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
15118 : :
15119 [ + + ]: 154 : if (childattTup->attinhcount > numparents)
15120 [ + - ]: 4 : ereport(ERROR,
15121 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15122 : : errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
15123 : : colName, RelationGetRelationName(childrel))));
15124 : :
15125 : 150 : ReleaseSysCache(childtuple);
15126 : :
15127 : : /*
15128 : : * Remap the attribute numbers. If no USING expression was
15129 : : * specified, there is no need for this step.
15130 : : */
15131 [ + + ]: 150 : if (def->cooked_default)
15132 : : {
15133 : : AttrMap *attmap;
15134 : : bool found_whole_row;
15135 : :
15136 : : /* create a copy to scribble on */
15137 : 52 : cmd = copyObject(cmd);
15138 : :
15139 : 52 : attmap = build_attrmap_by_name(RelationGetDescr(childrel),
15140 : : RelationGetDescr(rel),
15141 : : false);
15142 : 104 : ((ColumnDef *) cmd->def)->cooked_default =
15143 : 52 : map_variable_attnos(def->cooked_default,
15144 : : 1, 0,
15145 : : attmap,
15146 : : InvalidOid, &found_whole_row);
15147 [ + + ]: 52 : if (found_whole_row)
15148 [ + - ]: 4 : ereport(ERROR,
15149 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15150 : : errmsg("cannot convert whole-row table reference"),
15151 : : errdetail("USING expression contains a whole-row table reference.")));
15152 : 48 : pfree(attmap);
15153 : : }
15154 : 146 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
15155 : 138 : relation_close(childrel, NoLock);
15156 : : }
15157 : : }
15158 [ + + - + ]: 212 : else if (!recursing &&
15159 : 37 : find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
15160 [ # # ]: 0 : ereport(ERROR,
15161 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15162 : : errmsg("type of inherited column \"%s\" must be changed in child tables too",
15163 : : colName)));
15164 : :
15165 [ + + ]: 832 : if (tab->relkind == RELKIND_COMPOSITE_TYPE)
15166 : 37 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
15167 : 828 : }
15168 : :
15169 : : /*
15170 : : * When the data type of a column is changed, a rewrite might not be required
15171 : : * if the new type is sufficiently identical to the old one, and the USING
15172 : : * clause isn't trying to insert some other value. It's safe to skip the
15173 : : * rewrite in these cases:
15174 : : *
15175 : : * - the old type is binary coercible to the new type
15176 : : * - the new type is an unconstrained domain over the old type
15177 : : * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
15178 : : *
15179 : : * In the case of a constrained domain, we could get by with scanning the
15180 : : * table and checking the constraint rather than actually rewriting it, but we
15181 : : * don't currently try to do that.
15182 : : */
15183 : : static bool
15184 : 771 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
15185 : : {
15186 : : Assert(expr != NULL);
15187 : :
15188 : : for (;;)
15189 : : {
15190 : : /* only one varno, so no need to check that */
15191 [ + + + - ]: 847 : if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
15192 : 132 : return false;
15193 [ + + ]: 715 : else if (IsA(expr, RelabelType))
15194 : 68 : expr = (Node *) ((RelabelType *) expr)->arg;
15195 [ + + ]: 647 : else if (IsA(expr, CoerceToDomain))
15196 : : {
15197 : 4 : CoerceToDomain *d = (CoerceToDomain *) expr;
15198 : :
15199 [ + - ]: 4 : if (DomainHasConstraints(d->resulttype, NULL))
15200 : 4 : return true;
15201 : 0 : expr = (Node *) d->arg;
15202 : : }
15203 [ + + ]: 643 : else if (IsA(expr, FuncExpr))
15204 : : {
15205 : 510 : FuncExpr *f = (FuncExpr *) expr;
15206 : :
15207 [ + + ]: 510 : switch (f->funcid)
15208 : : {
15209 : 12 : case F_TIMESTAMPTZ_TIMESTAMP:
15210 : : case F_TIMESTAMP_TIMESTAMPTZ:
15211 [ + + ]: 12 : if (TimestampTimestampTzRequiresRewrite())
15212 : 4 : return true;
15213 : : else
15214 : 8 : expr = linitial(f->args);
15215 : 8 : break;
15216 : 498 : default:
15217 : 498 : return true;
15218 : : }
15219 : : }
15220 : : else
15221 : 133 : return true;
15222 : : }
15223 : : }
15224 : :
15225 : : /*
15226 : : * ALTER COLUMN .. SET DATA TYPE
15227 : : *
15228 : : * Return the address of the modified column.
15229 : : */
15230 : : static ObjectAddress
15231 : 804 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
15232 : : AlterTableCmd *cmd, LOCKMODE lockmode)
15233 : : {
15234 : 804 : char *colName = cmd->name;
15235 : 804 : ColumnDef *def = (ColumnDef *) cmd->def;
15236 : 804 : TypeName *typeName = def->typeName;
15237 : : HeapTuple heapTup;
15238 : : Form_pg_attribute attTup,
15239 : : attOldTup;
15240 : : AttrNumber attnum;
15241 : : HeapTuple typeTuple;
15242 : : Form_pg_type tform;
15243 : : Oid targettype;
15244 : : int32 targettypmod;
15245 : : Oid targetcollid;
15246 : : Node *defaultexpr;
15247 : : Relation attrelation;
15248 : : Relation depRel;
15249 : : ScanKeyData key[3];
15250 : : SysScanDesc scan;
15251 : : HeapTuple depTup;
15252 : : ObjectAddress address;
15253 : :
15254 : : /*
15255 : : * Clear all the missing values if we're rewriting the table, since this
15256 : : * renders them pointless.
15257 : : */
15258 [ + + ]: 804 : if (tab->rewrite)
15259 : : {
15260 : : Relation newrel;
15261 : :
15262 : 599 : newrel = table_open(RelationGetRelid(rel), NoLock);
15263 : 599 : RelationClearMissing(newrel);
15264 : 599 : relation_close(newrel, NoLock);
15265 : : /* make sure we don't conflict with later attribute modifications */
15266 : 599 : CommandCounterIncrement();
15267 : : }
15268 : :
15269 : 804 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
15270 : :
15271 : : /* Look up the target column */
15272 : 804 : heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
15273 [ - + ]: 804 : if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
15274 [ # # ]: 0 : ereport(ERROR,
15275 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15276 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15277 : : colName, RelationGetRelationName(rel))));
15278 : 804 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15279 : 804 : attnum = attTup->attnum;
15280 : 804 : attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
15281 : :
15282 : : /* Check for multiple ALTER TYPE on same column --- can't cope */
15283 [ + - ]: 804 : if (attTup->atttypid != attOldTup->atttypid ||
15284 [ - + ]: 804 : attTup->atttypmod != attOldTup->atttypmod)
15285 [ # # ]: 0 : ereport(ERROR,
15286 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15287 : : errmsg("cannot alter type of column \"%s\" twice",
15288 : : colName)));
15289 : :
15290 : : /* Look up the target type (should not fail, since prep found it) */
15291 : 804 : typeTuple = typenameType(NULL, typeName, &targettypmod);
15292 : 804 : tform = (Form_pg_type) GETSTRUCT(typeTuple);
15293 : 804 : targettype = tform->oid;
15294 : : /* And the collation */
15295 : 804 : targetcollid = GetColumnDefCollation(NULL, def, targettype);
15296 : :
15297 : : /*
15298 : : * If there is a default expression for the column, get it and ensure we
15299 : : * can coerce it to the new datatype. (We must do this before changing
15300 : : * the column type, because build_column_default itself will try to
15301 : : * coerce, and will not issue the error message we want if it fails.)
15302 : : *
15303 : : * We remove any implicit coercion steps at the top level of the old
15304 : : * default expression; this has been agreed to satisfy the principle of
15305 : : * least surprise. (The conversion to the new column type should act like
15306 : : * it started from what the user sees as the stored expression, and the
15307 : : * implicit coercions aren't going to be shown.)
15308 : : */
15309 [ + + ]: 804 : if (attTup->atthasdef)
15310 : : {
15311 : 68 : defaultexpr = build_column_default(rel, attnum);
15312 : : Assert(defaultexpr);
15313 : 68 : defaultexpr = strip_implicit_coercions(defaultexpr);
15314 : 68 : defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
15315 : : defaultexpr, exprType(defaultexpr),
15316 : : targettype, targettypmod,
15317 : : COERCION_ASSIGNMENT,
15318 : : COERCE_IMPLICIT_CAST,
15319 : : -1);
15320 [ + + ]: 68 : if (defaultexpr == NULL)
15321 : : {
15322 [ - + ]: 4 : if (attTup->attgenerated)
15323 [ # # ]: 0 : ereport(ERROR,
15324 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15325 : : errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
15326 : : colName, format_type_be(targettype))));
15327 : : else
15328 [ + - ]: 4 : ereport(ERROR,
15329 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15330 : : errmsg("default for column \"%s\" cannot be cast automatically to type %s",
15331 : : colName, format_type_be(targettype))));
15332 : : }
15333 : : }
15334 : : else
15335 : 736 : defaultexpr = NULL;
15336 : :
15337 : : /*
15338 : : * Find everything that depends on the column (constraints, indexes, etc),
15339 : : * and record enough information to let us recreate the objects.
15340 : : *
15341 : : * The actual recreation does not happen here, but only after we have
15342 : : * performed all the individual ALTER TYPE operations. We have to save
15343 : : * the info before executing ALTER TYPE, though, else the deparser will
15344 : : * get confused.
15345 : : */
15346 : 800 : RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
15347 : :
15348 : : /*
15349 : : * Now scan for dependencies of this column on other things. The only
15350 : : * things we should find are the dependency on the column datatype and
15351 : : * possibly a collation dependency. Those can be removed.
15352 : : */
15353 : 776 : depRel = table_open(DependRelationId, RowExclusiveLock);
15354 : :
15355 : 776 : ScanKeyInit(&key[0],
15356 : : Anum_pg_depend_classid,
15357 : : BTEqualStrategyNumber, F_OIDEQ,
15358 : : ObjectIdGetDatum(RelationRelationId));
15359 : 776 : ScanKeyInit(&key[1],
15360 : : Anum_pg_depend_objid,
15361 : : BTEqualStrategyNumber, F_OIDEQ,
15362 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15363 : 776 : ScanKeyInit(&key[2],
15364 : : Anum_pg_depend_objsubid,
15365 : : BTEqualStrategyNumber, F_INT4EQ,
15366 : : Int32GetDatum((int32) attnum));
15367 : :
15368 : 776 : scan = systable_beginscan(depRel, DependDependerIndexId, true,
15369 : : NULL, 3, key);
15370 : :
15371 [ + + ]: 778 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15372 : : {
15373 : 2 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15374 : : ObjectAddress foundObject;
15375 : :
15376 : 2 : foundObject.classId = foundDep->refclassid;
15377 : 2 : foundObject.objectId = foundDep->refobjid;
15378 : 2 : foundObject.objectSubId = foundDep->refobjsubid;
15379 : :
15380 [ - + ]: 2 : if (foundDep->deptype != DEPENDENCY_NORMAL)
15381 [ # # ]: 0 : elog(ERROR, "found unexpected dependency type '%c'",
15382 : : foundDep->deptype);
15383 [ + - ]: 2 : if (!(foundDep->refclassid == TypeRelationId &&
15384 [ - + ]: 2 : foundDep->refobjid == attTup->atttypid) &&
15385 [ # # ]: 0 : !(foundDep->refclassid == CollationRelationId &&
15386 [ # # ]: 0 : foundDep->refobjid == attTup->attcollation))
15387 [ # # ]: 0 : elog(ERROR, "found unexpected dependency for column: %s",
15388 : : getObjectDescription(&foundObject, false));
15389 : :
15390 : 2 : CatalogTupleDelete(depRel, &depTup->t_self);
15391 : : }
15392 : :
15393 : 776 : systable_endscan(scan);
15394 : :
15395 : 776 : table_close(depRel, RowExclusiveLock);
15396 : :
15397 : : /*
15398 : : * Here we go --- change the recorded column type and collation. (Note
15399 : : * heapTup is a copy of the syscache entry, so okay to scribble on.) First
15400 : : * fix up the missing value if any.
15401 : : */
15402 [ + + ]: 776 : if (attTup->atthasmissing)
15403 : : {
15404 : : Datum missingval;
15405 : : bool missingNull;
15406 : :
15407 : : /* if rewrite is true the missing value should already be cleared */
15408 : : Assert(tab->rewrite == 0);
15409 : :
15410 : : /* Get the missing value datum */
15411 : 4 : missingval = heap_getattr(heapTup,
15412 : : Anum_pg_attribute_attmissingval,
15413 : : attrelation->rd_att,
15414 : : &missingNull);
15415 : :
15416 : : /* if it's a null array there is nothing to do */
15417 : :
15418 [ + - ]: 4 : if (!missingNull)
15419 : : {
15420 : : /*
15421 : : * Get the datum out of the array and repack it in a new array
15422 : : * built with the new type data. We assume that since the table
15423 : : * doesn't need rewriting, the actual Datum doesn't need to be
15424 : : * changed, only the array metadata.
15425 : : */
15426 : :
15427 : 4 : int one = 1;
15428 : : bool isNull;
15429 : 4 : Datum valuesAtt[Natts_pg_attribute] = {0};
15430 : 4 : bool nullsAtt[Natts_pg_attribute] = {0};
15431 : 4 : bool replacesAtt[Natts_pg_attribute] = {0};
15432 : : HeapTuple newTup;
15433 : :
15434 : 8 : missingval = array_get_element(missingval,
15435 : : 1,
15436 : : &one,
15437 : : 0,
15438 : 4 : attTup->attlen,
15439 : 4 : attTup->attbyval,
15440 : 4 : attTup->attalign,
15441 : : &isNull);
15442 : 4 : missingval = PointerGetDatum(construct_array(&missingval,
15443 : : 1,
15444 : : targettype,
15445 : : tform->typlen,
15446 : : tform->typbyval,
15447 : : tform->typalign));
15448 : :
15449 : 4 : valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
15450 : 4 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
15451 : 4 : nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
15452 : :
15453 : 4 : newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
15454 : : valuesAtt, nullsAtt, replacesAtt);
15455 : 4 : heap_freetuple(heapTup);
15456 : 4 : heapTup = newTup;
15457 : 4 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15458 : : }
15459 : : }
15460 : :
15461 : 776 : attTup->atttypid = targettype;
15462 : 776 : attTup->atttypmod = targettypmod;
15463 : 776 : attTup->attcollation = targetcollid;
15464 [ - + ]: 776 : if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
15465 [ # # ]: 0 : ereport(ERROR,
15466 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
15467 : : errmsg("too many array dimensions"));
15468 : 776 : attTup->attndims = list_length(typeName->arrayBounds);
15469 : 776 : attTup->attlen = tform->typlen;
15470 : 776 : attTup->attbyval = tform->typbyval;
15471 : 776 : attTup->attalign = tform->typalign;
15472 : 776 : attTup->attstorage = tform->typstorage;
15473 : 776 : attTup->attcompression = InvalidCompressionMethod;
15474 : :
15475 : 776 : ReleaseSysCache(typeTuple);
15476 : :
15477 : 776 : CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
15478 : :
15479 : 776 : table_close(attrelation, RowExclusiveLock);
15480 : :
15481 : : /* Install dependencies on new datatype and collation */
15482 : 776 : add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
15483 : 776 : add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
15484 : :
15485 : : /*
15486 : : * Drop any pg_statistic entry for the column, since it's now wrong type
15487 : : */
15488 : 776 : RemoveStatistics(RelationGetRelid(rel), attnum);
15489 : :
15490 [ - + ]: 776 : InvokeObjectPostAlterHook(RelationRelationId,
15491 : : RelationGetRelid(rel), attnum);
15492 : :
15493 : : /*
15494 : : * Update the default, if present, by brute force --- remove and re-add
15495 : : * the default. Probably unsafe to take shortcuts, since the new version
15496 : : * may well have additional dependencies. (It's okay to do this now,
15497 : : * rather than after other ALTER TYPE commands, since the default won't
15498 : : * depend on other column types.)
15499 : : */
15500 [ + + ]: 776 : if (defaultexpr)
15501 : : {
15502 : : /*
15503 : : * If it's a GENERATED default, drop its dependency records, in
15504 : : * particular its INTERNAL dependency on the column, which would
15505 : : * otherwise cause dependency.c to refuse to perform the deletion.
15506 : : */
15507 [ + + ]: 64 : if (attTup->attgenerated)
15508 : : {
15509 : 28 : Oid attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
15510 : :
15511 [ - + ]: 28 : if (!OidIsValid(attrdefoid))
15512 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
15513 : : RelationGetRelid(rel), attnum);
15514 : 28 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
15515 : : }
15516 : :
15517 : : /*
15518 : : * Make updates-so-far visible, particularly the new pg_attribute row
15519 : : * which will be updated again.
15520 : : */
15521 : 64 : CommandCounterIncrement();
15522 : :
15523 : : /*
15524 : : * We use RESTRICT here for safety, but at present we do not expect
15525 : : * anything to depend on the default.
15526 : : */
15527 : 64 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
15528 : : true);
15529 : :
15530 : 64 : (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
15531 : : }
15532 : :
15533 : 776 : ObjectAddressSubSet(address, RelationRelationId,
15534 : : RelationGetRelid(rel), attnum);
15535 : :
15536 : : /* Cleanup */
15537 : 776 : heap_freetuple(heapTup);
15538 : :
15539 : 776 : return address;
15540 : : }
15541 : :
15542 : : /*
15543 : : * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
15544 : : * that depends on the column (constraints, indexes, etc), and record enough
15545 : : * information to let us recreate the objects.
15546 : : */
15547 : : static void
15548 : 981 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
15549 : : Relation rel, AttrNumber attnum, const char *colName)
15550 : : {
15551 : : Relation depRel;
15552 : : ScanKeyData key[3];
15553 : : SysScanDesc scan;
15554 : : HeapTuple depTup;
15555 : :
15556 : : Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
15557 : :
15558 : 981 : depRel = table_open(DependRelationId, RowExclusiveLock);
15559 : :
15560 : 981 : ScanKeyInit(&key[0],
15561 : : Anum_pg_depend_refclassid,
15562 : : BTEqualStrategyNumber, F_OIDEQ,
15563 : : ObjectIdGetDatum(RelationRelationId));
15564 : 981 : ScanKeyInit(&key[1],
15565 : : Anum_pg_depend_refobjid,
15566 : : BTEqualStrategyNumber, F_OIDEQ,
15567 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15568 : 981 : ScanKeyInit(&key[2],
15569 : : Anum_pg_depend_refobjsubid,
15570 : : BTEqualStrategyNumber, F_INT4EQ,
15571 : : Int32GetDatum((int32) attnum));
15572 : :
15573 : 981 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15574 : : NULL, 3, key);
15575 : :
15576 [ + + ]: 2003 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15577 : : {
15578 : 1046 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15579 : : ObjectAddress foundObject;
15580 : :
15581 : 1046 : foundObject.classId = foundDep->classid;
15582 : 1046 : foundObject.objectId = foundDep->objid;
15583 : 1046 : foundObject.objectSubId = foundDep->objsubid;
15584 : :
15585 [ + + - + : 1046 : switch (foundObject.classId)
- - + + -
- ]
15586 : : {
15587 : 192 : case RelationRelationId:
15588 : : {
15589 : 192 : char relKind = get_rel_relkind(foundObject.objectId);
15590 : :
15591 [ + + + + ]: 192 : if (relKind == RELKIND_INDEX ||
15592 : : relKind == RELKIND_PARTITIONED_INDEX)
15593 : : {
15594 : : Assert(foundObject.objectSubId == 0);
15595 : 167 : RememberIndexForRebuilding(foundObject.objectId, tab);
15596 : : }
15597 [ - + ]: 25 : else if (relKind == RELKIND_SEQUENCE)
15598 : : {
15599 : : /*
15600 : : * This must be a SERIAL column's sequence. We need
15601 : : * not do anything to it.
15602 : : */
15603 : : Assert(foundObject.objectSubId == 0);
15604 : : }
15605 : : else
15606 : : {
15607 : : /* Not expecting any other direct dependencies... */
15608 [ # # ]: 0 : elog(ERROR, "unexpected object depending on column: %s",
15609 : : getObjectDescription(&foundObject, false));
15610 : : }
15611 : 192 : break;
15612 : : }
15613 : :
15614 : 528 : case ConstraintRelationId:
15615 : : Assert(foundObject.objectSubId == 0);
15616 : 528 : RememberConstraintForRebuilding(foundObject.objectId, tab);
15617 : 528 : break;
15618 : :
15619 : 0 : case ProcedureRelationId:
15620 : :
15621 : : /*
15622 : : * A new-style SQL function can depend on a column, if that
15623 : : * column is referenced in the parsed function body. Ideally
15624 : : * we'd automatically update the function by deparsing and
15625 : : * reparsing it, but that's risky and might well fail anyhow.
15626 : : * FIXME someday.
15627 : : *
15628 : : * This is only a problem for AT_AlterColumnType, not
15629 : : * AT_SetExpression.
15630 : : */
15631 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15632 [ # # ]: 0 : ereport(ERROR,
15633 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15634 : : errmsg("cannot alter type of a column used by a function or procedure"),
15635 : : errdetail("%s depends on column \"%s\".",
15636 : : getObjectDescription(&foundObject, false),
15637 : : colName)));
15638 : 0 : break;
15639 : :
15640 : 8 : case RewriteRelationId:
15641 : :
15642 : : /*
15643 : : * View/rule bodies have pretty much the same issues as
15644 : : * function bodies. FIXME someday.
15645 : : */
15646 [ + - ]: 8 : if (subtype == AT_AlterColumnType)
15647 [ + - ]: 8 : ereport(ERROR,
15648 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15649 : : errmsg("cannot alter type of a column used by a view or rule"),
15650 : : errdetail("%s depends on column \"%s\".",
15651 : : getObjectDescription(&foundObject, false),
15652 : : colName)));
15653 : 0 : break;
15654 : :
15655 : 0 : case TriggerRelationId:
15656 : :
15657 : : /*
15658 : : * A trigger can depend on a column because the column is
15659 : : * specified as an update target, or because the column is
15660 : : * used in the trigger's WHEN condition. The first case would
15661 : : * not require any extra work, but the second case would
15662 : : * require updating the WHEN expression, which has the same
15663 : : * issues as above. Since we can't easily tell which case
15664 : : * applies, we punt for both. FIXME someday.
15665 : : */
15666 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15667 [ # # ]: 0 : ereport(ERROR,
15668 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15669 : : errmsg("cannot alter type of a column used in a trigger definition"),
15670 : : errdetail("%s depends on column \"%s\".",
15671 : : getObjectDescription(&foundObject, false),
15672 : : colName)));
15673 : 0 : break;
15674 : :
15675 : 0 : case PolicyRelationId:
15676 : :
15677 : : /*
15678 : : * A policy can depend on a column because the column is
15679 : : * specified in the policy's USING or WITH CHECK qual
15680 : : * expressions. It might be possible to rewrite and recheck
15681 : : * the policy expression, but punt for now. It's certainly
15682 : : * easy enough to remove and recreate the policy; still, FIXME
15683 : : * someday.
15684 : : */
15685 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15686 [ # # ]: 0 : ereport(ERROR,
15687 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15688 : : errmsg("cannot alter type of a column used in a policy definition"),
15689 : : errdetail("%s depends on column \"%s\".",
15690 : : getObjectDescription(&foundObject, false),
15691 : : colName)));
15692 : 0 : break;
15693 : :
15694 : 261 : case AttrDefaultRelationId:
15695 : : {
15696 : 261 : ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
15697 : :
15698 [ + - ]: 506 : if (col.objectId == RelationGetRelid(rel) &&
15699 [ + + ]: 261 : col.objectSubId == attnum)
15700 : : {
15701 : : /*
15702 : : * Ignore the column's own default expression. The
15703 : : * caller deals with it.
15704 : : */
15705 : : }
15706 : : else
15707 : : {
15708 : : /*
15709 : : * This must be a reference from the expression of a
15710 : : * generated column elsewhere in the same table.
15711 : : * Changing the type/generated expression of a column
15712 : : * that is used by a generated column is not allowed
15713 : : * by SQL standard, so just punt for now. It might be
15714 : : * doable with some thinking and effort.
15715 : : */
15716 [ + - ]: 16 : if (subtype == AT_AlterColumnType)
15717 [ + - ]: 16 : ereport(ERROR,
15718 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15719 : : errmsg("cannot alter type of a column used by a generated column"),
15720 : : errdetail("Column \"%s\" is used by generated column \"%s\".",
15721 : : colName,
15722 : : get_attname(col.objectId,
15723 : : col.objectSubId,
15724 : : false))));
15725 : : }
15726 : 245 : break;
15727 : : }
15728 : :
15729 : 57 : case StatisticExtRelationId:
15730 : :
15731 : : /*
15732 : : * Give the extended-stats machinery a chance to fix anything
15733 : : * that this column type change would break.
15734 : : */
15735 : 57 : RememberStatisticsForRebuilding(foundObject.objectId, tab);
15736 : 57 : break;
15737 : :
15738 : 0 : case PublicationRelRelationId:
15739 : :
15740 : : /*
15741 : : * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
15742 : : * clause. Same issues as above. FIXME someday.
15743 : : */
15744 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15745 [ # # ]: 0 : ereport(ERROR,
15746 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15747 : : errmsg("cannot alter type of a column used by a publication WHERE clause"),
15748 : : errdetail("%s depends on column \"%s\".",
15749 : : getObjectDescription(&foundObject, false),
15750 : : colName)));
15751 : 0 : break;
15752 : :
15753 : 0 : default:
15754 : :
15755 : : /*
15756 : : * We don't expect any other sorts of objects to depend on a
15757 : : * column.
15758 : : */
15759 [ # # ]: 0 : elog(ERROR, "unexpected object depending on column: %s",
15760 : : getObjectDescription(&foundObject, false));
15761 : : break;
15762 : : }
15763 : : }
15764 : :
15765 : 957 : systable_endscan(scan);
15766 : 957 : table_close(depRel, NoLock);
15767 : 957 : }
15768 : :
15769 : : /*
15770 : : * Record information about dependencies between objects with whole-row Var
15771 : : * references (indexes, check constraints, etc.) and the relation.
15772 : : *
15773 : : * See also RememberAllDependentForRebuilding, which handles non-whole-row Var
15774 : : * references.
15775 : : *
15776 : : * This function currently applies only to ALTER COLUMN SET EXPRESSION.
15777 : : */
15778 : : static void
15779 : 181 : RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, Relation rel)
15780 : : {
15781 : : ScanKeyData skey;
15782 : : Relation pg_constraint;
15783 : : Relation pg_index;
15784 : : SysScanDesc conscan;
15785 : : SysScanDesc indscan;
15786 : : HeapTuple constrTuple;
15787 : : HeapTuple indexTuple;
15788 : : bool isnull;
15789 : :
15790 : : Assert(subtype == AT_SetExpression);
15791 : :
15792 : : /*
15793 : : * Check CHECK constraints with whole-row references first.
15794 : : */
15795 [ + - ]: 181 : if (RelationGetDescr(rel)->constr &&
15796 [ + + ]: 181 : RelationGetDescr(rel)->constr->num_check > 0)
15797 : : {
15798 : 28 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
15799 : :
15800 : 28 : ScanKeyInit(&skey,
15801 : : Anum_pg_constraint_conrelid,
15802 : : BTEqualStrategyNumber, F_OIDEQ,
15803 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15804 : :
15805 : 28 : conscan = systable_beginscan(pg_constraint,
15806 : : ConstraintRelidTypidNameIndexId,
15807 : : true,
15808 : : NULL,
15809 : : 1,
15810 : : &skey);
15811 : :
15812 [ + + ]: 96 : while (HeapTupleIsValid(constrTuple = systable_getnext(conscan)))
15813 : : {
15814 : 68 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(constrTuple);
15815 : : Datum exprDatum;
15816 : :
15817 [ + + ]: 68 : if (conform->contype != CONSTRAINT_CHECK)
15818 : 40 : continue;
15819 : :
15820 : 28 : exprDatum = heap_getattr(constrTuple,
15821 : : Anum_pg_constraint_conbin,
15822 : : RelationGetDescr(pg_constraint),
15823 : : &isnull);
15824 [ - + ]: 28 : if (isnull)
15825 [ # # ]: 0 : elog(ERROR, "null conbin for relation \"%s\"",
15826 : : RelationGetRelationName(rel));
15827 : : else
15828 : : {
15829 : : char *exprString;
15830 : : Node *expr;
15831 : 28 : Bitmapset *expr_attrs = NULL;
15832 : :
15833 : 28 : exprString = TextDatumGetCString(exprDatum);
15834 : 28 : expr = stringToNode(exprString);
15835 : 28 : pfree(exprString);
15836 : :
15837 : : /* Find all attributes referenced */
15838 : 28 : pull_varattnos(expr, 1, &expr_attrs);
15839 : :
15840 : : /*
15841 : : * If the CHECK constraint contains whole-row reference then
15842 : : * remember it.
15843 : : */
15844 [ + + ]: 28 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15845 : : {
15846 : 8 : RememberConstraintForRebuilding(conform->oid, tab);
15847 : : }
15848 : : }
15849 : : }
15850 : 28 : systable_endscan(conscan);
15851 : 28 : table_close(pg_constraint, AccessShareLock);
15852 : : }
15853 : :
15854 : : /*
15855 : : * Now check indexes with whole-row references. Prepare to scan pg_index
15856 : : * for entries having indrelid matching this relation.
15857 : : */
15858 : 181 : ScanKeyInit(&skey,
15859 : : Anum_pg_index_indrelid,
15860 : : BTEqualStrategyNumber, F_OIDEQ,
15861 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15862 : :
15863 : 181 : pg_index = table_open(IndexRelationId, AccessShareLock);
15864 : :
15865 : 181 : indscan = systable_beginscan(pg_index,
15866 : : IndexIndrelidIndexId,
15867 : : true,
15868 : : NULL,
15869 : : 1,
15870 : : &skey);
15871 : :
15872 [ + + ]: 261 : while (HeapTupleIsValid(indexTuple = systable_getnext(indscan)))
15873 : : {
15874 : 80 : Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
15875 : : Datum exprDatum;
15876 : :
15877 : 80 : exprDatum = heap_getattr(indexTuple,
15878 : : Anum_pg_index_indexprs,
15879 : : RelationGetDescr(pg_index),
15880 : : &isnull);
15881 [ + + ]: 80 : if (!isnull)
15882 : : {
15883 : : char *exprString;
15884 : : Node *expr;
15885 : 12 : Bitmapset *expr_attrs = NULL;
15886 : :
15887 : 12 : exprString = TextDatumGetCString(exprDatum);
15888 : 12 : expr = stringToNode(exprString);
15889 : 12 : pfree(exprString);
15890 : :
15891 : : /* Find all attributes referenced */
15892 : 12 : pull_varattnos(expr, 1, &expr_attrs);
15893 : :
15894 : : /*
15895 : : * If the index expression contains a whole-row reference then
15896 : : * remember it.
15897 : : */
15898 [ + + ]: 12 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15899 : : {
15900 : 8 : RememberIndexForRebuilding(index->indexrelid, tab);
15901 : 8 : continue;
15902 : : }
15903 : : }
15904 : :
15905 : 72 : exprDatum = heap_getattr(indexTuple,
15906 : : Anum_pg_index_indpred,
15907 : : RelationGetDescr(pg_index),
15908 : : &isnull);
15909 [ + + ]: 72 : if (!isnull)
15910 : : {
15911 : : char *exprString;
15912 : : Node *expr;
15913 : 20 : Bitmapset *expr_attrs = NULL;
15914 : :
15915 : 20 : exprString = TextDatumGetCString(exprDatum);
15916 : 20 : expr = stringToNode(exprString);
15917 : 20 : pfree(exprString);
15918 : :
15919 : : /* Find all attributes referenced */
15920 : 20 : pull_varattnos(expr, 1, &expr_attrs);
15921 : :
15922 : : /*
15923 : : * If the index predicate expression contains a whole-row
15924 : : * reference then remember it.
15925 : : */
15926 [ + + ]: 20 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15927 : : {
15928 : 16 : RememberIndexForRebuilding(index->indexrelid, tab);
15929 : : }
15930 : : }
15931 : : }
15932 : :
15933 : 181 : systable_endscan(indscan);
15934 : 181 : table_close(pg_index, AccessShareLock);
15935 : 181 : }
15936 : :
15937 : : /*
15938 : : * Subroutine for ATExecAlterColumnType: remember that a replica identity
15939 : : * needs to be reset.
15940 : : */
15941 : : static void
15942 : 330 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
15943 : : {
15944 [ + + ]: 330 : if (!get_index_isreplident(indoid))
15945 : 318 : return;
15946 : :
15947 [ - + ]: 12 : if (tab->replicaIdentityIndex)
15948 [ # # ]: 0 : elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
15949 : :
15950 : 12 : tab->replicaIdentityIndex = get_rel_name(indoid);
15951 : : }
15952 : :
15953 : : /*
15954 : : * Subroutine for ATExecAlterColumnType: remember any clustered index.
15955 : : */
15956 : : static void
15957 : 330 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
15958 : : {
15959 [ + + ]: 330 : if (!get_index_isclustered(indoid))
15960 : 318 : return;
15961 : :
15962 [ - + ]: 12 : if (tab->clusterOnIndex)
15963 [ # # ]: 0 : elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
15964 : :
15965 : 12 : tab->clusterOnIndex = get_rel_name(indoid);
15966 : : }
15967 : :
15968 : : /*
15969 : : * Subroutine for ATExecAlterColumnType: remember that a constraint needs
15970 : : * to be rebuilt (which we might already know).
15971 : : */
15972 : : static void
15973 : 544 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
15974 : : {
15975 : : /*
15976 : : * This de-duplication check is critical for two independent reasons: we
15977 : : * mustn't try to recreate the same constraint twice, and if a constraint
15978 : : * depends on more than one column whose type is to be altered, we must
15979 : : * capture its definition string before applying any of the column type
15980 : : * changes. ruleutils.c will get confused if we ask again later.
15981 : : */
15982 [ + + ]: 544 : if (!list_member_oid(tab->changedConstraintOids, conoid))
15983 : : {
15984 : : /* OK, capture the constraint's existing definition string */
15985 : 468 : char *defstring = pg_get_constraintdef_command(conoid);
15986 : : Oid indoid;
15987 : :
15988 : : /*
15989 : : * It is critical to create not-null constraints ahead of primary key
15990 : : * indexes; otherwise, the not-null constraint would be created by the
15991 : : * primary key, and the constraint name would be wrong.
15992 : : */
15993 [ + + ]: 468 : if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
15994 : : {
15995 : 163 : tab->changedConstraintOids = lcons_oid(conoid,
15996 : : tab->changedConstraintOids);
15997 : 163 : tab->changedConstraintDefs = lcons(defstring,
15998 : : tab->changedConstraintDefs);
15999 : : }
16000 : : else
16001 : : {
16002 : :
16003 : 305 : tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
16004 : : conoid);
16005 : 305 : tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
16006 : : defstring);
16007 : : }
16008 : :
16009 : : /*
16010 : : * For the index of a constraint, if any, remember if it is used for
16011 : : * the table's replica identity or if it is a clustered index, so that
16012 : : * ATPostAlterTypeCleanup() can queue up commands necessary to restore
16013 : : * those properties.
16014 : : */
16015 : 468 : indoid = get_constraint_index(conoid);
16016 [ + + ]: 468 : if (OidIsValid(indoid))
16017 : : {
16018 : 152 : RememberReplicaIdentityForRebuilding(indoid, tab);
16019 : 152 : RememberClusterOnForRebuilding(indoid, tab);
16020 : : }
16021 : : }
16022 : 544 : }
16023 : :
16024 : : /*
16025 : : * Subroutine for ATExecAlterColumnType: remember that an index needs
16026 : : * to be rebuilt (which we might already know).
16027 : : */
16028 : : static void
16029 : 191 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
16030 : : {
16031 : : /*
16032 : : * This de-duplication check is critical for two independent reasons: we
16033 : : * mustn't try to recreate the same index twice, and if an index depends
16034 : : * on more than one column whose type is to be altered, we must capture
16035 : : * its definition string before applying any of the column type changes.
16036 : : * ruleutils.c will get confused if we ask again later.
16037 : : */
16038 [ + + ]: 191 : if (!list_member_oid(tab->changedIndexOids, indoid))
16039 : : {
16040 : : /*
16041 : : * Before adding it as an index-to-rebuild, we'd better see if it
16042 : : * belongs to a constraint, and if so rebuild the constraint instead.
16043 : : * Typically this check fails, because constraint indexes normally
16044 : : * have only dependencies on their constraint. But it's possible for
16045 : : * such an index to also have direct dependencies on table columns,
16046 : : * for example with a partial exclusion constraint.
16047 : : */
16048 : 186 : Oid conoid = get_index_constraint(indoid);
16049 : :
16050 [ + + ]: 186 : if (OidIsValid(conoid))
16051 : : {
16052 : 8 : RememberConstraintForRebuilding(conoid, tab);
16053 : : }
16054 : : else
16055 : : {
16056 : : /* OK, capture the index's existing definition string */
16057 : 178 : char *defstring = pg_get_indexdef_string(indoid);
16058 : :
16059 : 178 : tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
16060 : : indoid);
16061 : 178 : tab->changedIndexDefs = lappend(tab->changedIndexDefs,
16062 : : defstring);
16063 : :
16064 : : /*
16065 : : * Remember if this index is used for the table's replica identity
16066 : : * or if it is a clustered index, so that ATPostAlterTypeCleanup()
16067 : : * can queue up commands necessary to restore those properties.
16068 : : */
16069 : 178 : RememberReplicaIdentityForRebuilding(indoid, tab);
16070 : 178 : RememberClusterOnForRebuilding(indoid, tab);
16071 : : }
16072 : : }
16073 : 191 : }
16074 : :
16075 : : /*
16076 : : * Subroutine for ATExecAlterColumnType: remember that a statistics object
16077 : : * needs to be rebuilt (which we might already know).
16078 : : */
16079 : : static void
16080 : 57 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
16081 : : {
16082 : : /*
16083 : : * This de-duplication check is critical for two independent reasons: we
16084 : : * mustn't try to recreate the same statistics object twice, and if the
16085 : : * statistics object depends on more than one column whose type is to be
16086 : : * altered, we must capture its definition string before applying any of
16087 : : * the type changes. ruleutils.c will get confused if we ask again later.
16088 : : */
16089 [ + - ]: 57 : if (!list_member_oid(tab->changedStatisticsOids, stxoid))
16090 : : {
16091 : : /* OK, capture the statistics object's existing definition string */
16092 : 57 : char *defstring = pg_get_statisticsobjdef_string(stxoid);
16093 : : HeapTuple tup;
16094 : : Form_pg_statistic_ext statext;
16095 : :
16096 : 57 : tup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
16097 : :
16098 [ - + ]: 57 : if (!HeapTupleIsValid(tup)) /* should not happen */
16099 [ # # ]: 0 : elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
16100 : :
16101 : 57 : statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
16102 : :
16103 : 57 : tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
16104 : : stxoid);
16105 : 57 : tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
16106 : : defstring);
16107 : :
16108 : 57 : tab->changedStatisticsOwners = lappend_oid(tab->changedStatisticsOwners,
16109 : : statext->stxowner);
16110 : :
16111 : 57 : ReleaseSysCache(tup);
16112 : : }
16113 : 57 : }
16114 : :
16115 : : /*
16116 : : * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
16117 : : * operations for a particular relation. We have to drop and recreate all the
16118 : : * indexes and constraints that depend on the altered columns. We do the
16119 : : * actual dropping here, but re-creation is managed by adding work queue
16120 : : * entries to do those steps later.
16121 : : */
16122 : : static void
16123 : 925 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
16124 : : {
16125 : : ObjectAddress obj;
16126 : : ObjectAddresses *objects;
16127 : : ListCell *def_item;
16128 : : ListCell *oid_item;
16129 : : ListCell *owner_item;
16130 : :
16131 : : /*
16132 : : * Collect all the constraints and indexes to drop so we can process them
16133 : : * in a single call. That way we don't have to worry about dependencies
16134 : : * among them.
16135 : : */
16136 : 925 : objects = new_object_addresses();
16137 : :
16138 : : /*
16139 : : * Re-parse the index and constraint definitions, and attach them to the
16140 : : * appropriate work queue entries. We do this before dropping because in
16141 : : * the case of a constraint on another table, we might not yet have
16142 : : * exclusive lock on the table the constraint is attached to, and we need
16143 : : * to get that before reparsing/dropping. (That's possible at least for
16144 : : * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
16145 : : * requires a dependency on the target table's composite type in the other
16146 : : * table's constraint expressions.)
16147 : : *
16148 : : * We can't rely on the output of deparsing to tell us which relation to
16149 : : * operate on, because concurrent activity might have made the name
16150 : : * resolve differently. Instead, we've got to use the OID of the
16151 : : * constraint or index we're processing to figure out which relation to
16152 : : * operate on.
16153 : : */
16154 [ + + + + : 1393 : forboth(oid_item, tab->changedConstraintOids,
+ + + + +
+ + - +
+ ]
16155 : : def_item, tab->changedConstraintDefs)
16156 : : {
16157 : 468 : Oid oldId = lfirst_oid(oid_item);
16158 : : HeapTuple tup;
16159 : : Form_pg_constraint con;
16160 : : Oid relid;
16161 : : Oid confrelid;
16162 : : bool conislocal;
16163 : :
16164 : 468 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16165 [ - + ]: 468 : if (!HeapTupleIsValid(tup)) /* should not happen */
16166 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16167 : 468 : con = (Form_pg_constraint) GETSTRUCT(tup);
16168 [ + + ]: 468 : if (OidIsValid(con->conrelid))
16169 : 455 : relid = con->conrelid;
16170 : : else
16171 : : {
16172 : : /* must be a domain constraint */
16173 : 13 : relid = get_typ_typrelid(getBaseType(con->contypid));
16174 [ - + ]: 13 : if (!OidIsValid(relid))
16175 [ # # ]: 0 : elog(ERROR, "could not identify relation associated with constraint %u", oldId);
16176 : : }
16177 : 468 : confrelid = con->confrelid;
16178 : 468 : conislocal = con->conislocal;
16179 : 468 : ReleaseSysCache(tup);
16180 : :
16181 : 468 : ObjectAddressSet(obj, ConstraintRelationId, oldId);
16182 : 468 : add_exact_object_address(&obj, objects);
16183 : :
16184 : : /*
16185 : : * If the constraint is inherited (only), we don't want to inject a
16186 : : * new definition here; it'll get recreated when
16187 : : * ATAddCheckNNConstraint recurses from adding the parent table's
16188 : : * constraint. But we had to carry the info this far so that we can
16189 : : * drop the constraint below.
16190 : : */
16191 [ + + ]: 468 : if (!conislocal)
16192 : 34 : continue;
16193 : :
16194 : : /*
16195 : : * When rebuilding another table's constraint that references the
16196 : : * table we're modifying, we might not yet have any lock on the other
16197 : : * table, so get one now. We'll need AccessExclusiveLock for the DROP
16198 : : * CONSTRAINT step, so there's no value in asking for anything weaker.
16199 : : */
16200 [ + + ]: 434 : if (relid != tab->relid)
16201 : 36 : LockRelationOid(relid, AccessExclusiveLock);
16202 : :
16203 : 434 : ATPostAlterTypeParse(oldId, relid, confrelid, InvalidOid,
16204 : 434 : (char *) lfirst(def_item),
16205 : 434 : wqueue, lockmode, tab->rewrite);
16206 : : }
16207 [ + + + + : 1103 : forboth(oid_item, tab->changedIndexOids,
+ + + + +
+ + - +
+ ]
16208 : : def_item, tab->changedIndexDefs)
16209 : : {
16210 : 178 : Oid oldId = lfirst_oid(oid_item);
16211 : : Oid relid;
16212 : :
16213 : 178 : relid = IndexGetRelation(oldId, false);
16214 : :
16215 : : /*
16216 : : * As above, make sure we have lock on the index's table if it's not
16217 : : * the same table.
16218 : : */
16219 [ + + ]: 178 : if (relid != tab->relid)
16220 : 12 : LockRelationOid(relid, AccessExclusiveLock);
16221 : :
16222 : 178 : ATPostAlterTypeParse(oldId, relid, InvalidOid, InvalidOid,
16223 : 178 : (char *) lfirst(def_item),
16224 : 178 : wqueue, lockmode, tab->rewrite);
16225 : :
16226 : 178 : ObjectAddressSet(obj, RelationRelationId, oldId);
16227 : 178 : add_exact_object_address(&obj, objects);
16228 : : }
16229 : :
16230 : : /* add dependencies for new statistics */
16231 [ + + + + : 982 : forthree(oid_item, tab->changedStatisticsOids,
+ + + + +
+ + + + +
+ - + - +
+ ]
16232 : : def_item, tab->changedStatisticsDefs,
16233 : : owner_item, tab->changedStatisticsOwners)
16234 : : {
16235 : 57 : Oid oldId = lfirst_oid(oid_item);
16236 : : Oid relid;
16237 : :
16238 : 57 : relid = StatisticsGetRelation(oldId, false);
16239 : :
16240 : : /*
16241 : : * As above, make sure we have lock on the statistics object's table
16242 : : * if it's not the same table. However, we take
16243 : : * ShareUpdateExclusiveLock here, aligning with the lock level used in
16244 : : * CreateStatistics and RemoveStatisticsById.
16245 : : *
16246 : : * CAUTION: this should be done after all cases that grab
16247 : : * AccessExclusiveLock, else we risk causing deadlock due to needing
16248 : : * to promote our table lock.
16249 : : */
16250 [ + + ]: 57 : if (relid != tab->relid)
16251 : 12 : LockRelationOid(relid, ShareUpdateExclusiveLock);
16252 : :
16253 : 57 : ATPostAlterTypeParse(oldId, relid, InvalidOid, lfirst_oid(owner_item),
16254 : 57 : (char *) lfirst(def_item),
16255 : 57 : wqueue, lockmode, tab->rewrite);
16256 : :
16257 : 57 : ObjectAddressSet(obj, StatisticExtRelationId, oldId);
16258 : 57 : add_exact_object_address(&obj, objects);
16259 : : }
16260 : :
16261 : : /*
16262 : : * Queue up command to restore replica identity index marking
16263 : : */
16264 [ + + ]: 925 : if (tab->replicaIdentityIndex)
16265 : : {
16266 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16267 : 12 : ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
16268 : :
16269 : 12 : subcmd->identity_type = REPLICA_IDENTITY_INDEX;
16270 : 12 : subcmd->name = tab->replicaIdentityIndex;
16271 : 12 : cmd->subtype = AT_ReplicaIdentity;
16272 : 12 : cmd->def = (Node *) subcmd;
16273 : :
16274 : : /* do it after indexes and constraints */
16275 : 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16276 : 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16277 : : }
16278 : :
16279 : : /*
16280 : : * Queue up command to restore marking of index used for cluster.
16281 : : */
16282 [ + + ]: 925 : if (tab->clusterOnIndex)
16283 : : {
16284 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16285 : :
16286 : 12 : cmd->subtype = AT_ClusterOn;
16287 : 12 : cmd->name = tab->clusterOnIndex;
16288 : :
16289 : : /* do it after indexes and constraints */
16290 : 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16291 : 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16292 : : }
16293 : :
16294 : : /*
16295 : : * It should be okay to use DROP_RESTRICT here, since nothing else should
16296 : : * be depending on these objects.
16297 : : */
16298 : 925 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
16299 : :
16300 : 925 : free_object_addresses(objects);
16301 : :
16302 : : /*
16303 : : * The objects will get recreated during subsequent passes over the work
16304 : : * queue.
16305 : : */
16306 : 925 : }
16307 : :
16308 : : /*
16309 : : * Parse the previously-saved definition string for a constraint, index or
16310 : : * statistics object against the newly-established column data type(s), and
16311 : : * queue up the resulting command parsetrees for execution.
16312 : : *
16313 : : * This might fail if, for example, you have a WHERE clause that uses an
16314 : : * operator that's not available for the new column type.
16315 : : */
16316 : : static void
16317 : 669 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
16318 : : const char *cmdstring, List **wqueue, LOCKMODE lockmode,
16319 : : bool rewrite)
16320 : : {
16321 : : List *raw_parsetree_list;
16322 : : List *querytree_list;
16323 : : ListCell *list_item;
16324 : : Relation rel;
16325 : :
16326 : : /*
16327 : : * We expect that we will get only ALTER TABLE and CREATE INDEX
16328 : : * statements. Hence, there is no need to pass them through
16329 : : * parse_analyze_*() or the rewriter, but instead we need to pass them
16330 : : * through parse_utilcmd.c to make them ready for execution.
16331 : : */
16332 : 669 : raw_parsetree_list = raw_parser(cmdstring, RAW_PARSE_DEFAULT);
16333 : 669 : querytree_list = NIL;
16334 [ + - + + : 1338 : foreach(list_item, raw_parsetree_list)
+ + ]
16335 : : {
16336 : 669 : RawStmt *rs = lfirst_node(RawStmt, list_item);
16337 : 669 : Node *stmt = rs->stmt;
16338 : :
16339 [ + + ]: 669 : if (IsA(stmt, IndexStmt))
16340 : 178 : querytree_list = lappend(querytree_list,
16341 : 178 : transformIndexStmt(oldRelId,
16342 : : (IndexStmt *) stmt,
16343 : : cmdstring));
16344 [ + + ]: 491 : else if (IsA(stmt, AlterTableStmt))
16345 : : {
16346 : : List *beforeStmts;
16347 : : List *afterStmts;
16348 : :
16349 : 421 : stmt = (Node *) transformAlterTableStmt(oldRelId,
16350 : : (AlterTableStmt *) stmt,
16351 : : cmdstring,
16352 : : &beforeStmts,
16353 : : &afterStmts);
16354 : 421 : querytree_list = list_concat(querytree_list, beforeStmts);
16355 : 421 : querytree_list = lappend(querytree_list, stmt);
16356 : 421 : querytree_list = list_concat(querytree_list, afterStmts);
16357 : : }
16358 [ + + ]: 70 : else if (IsA(stmt, CreateStatsStmt))
16359 : : {
16360 : : CreateStatsStmt *csstmt;
16361 : :
16362 : 57 : csstmt = transformStatsStmt(oldRelId, (CreateStatsStmt *) stmt, cmdstring);
16363 : 57 : csstmt->owner = ownerId;
16364 : :
16365 : 57 : querytree_list = lappend(querytree_list, csstmt);
16366 : : }
16367 : : else
16368 : 13 : querytree_list = lappend(querytree_list, stmt);
16369 : : }
16370 : :
16371 : : /* Caller should already have acquired whatever lock we need. */
16372 : 669 : rel = relation_open(oldRelId, NoLock);
16373 : :
16374 : : /*
16375 : : * Attach each generated command to the proper place in the work queue.
16376 : : * Note this could result in creation of entirely new work-queue entries.
16377 : : *
16378 : : * Also note that we have to tweak the command subtypes, because it turns
16379 : : * out that re-creation of indexes and constraints has to act a bit
16380 : : * differently from initial creation.
16381 : : */
16382 [ + - + + : 1338 : foreach(list_item, querytree_list)
+ + ]
16383 : : {
16384 : 669 : Node *stm = (Node *) lfirst(list_item);
16385 : : AlteredTableInfo *tab;
16386 : :
16387 : 669 : tab = ATGetQueueEntry(wqueue, rel);
16388 : :
16389 [ + + ]: 669 : if (IsA(stm, IndexStmt))
16390 : : {
16391 : 178 : IndexStmt *stmt = (IndexStmt *) stm;
16392 : : AlterTableCmd *newcmd;
16393 : :
16394 [ + + ]: 178 : if (!rewrite)
16395 : 53 : TryReuseIndex(oldId, stmt);
16396 : 178 : stmt->reset_default_tblspc = true;
16397 : : /* keep the index's comment */
16398 : 178 : stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
16399 : :
16400 : 178 : newcmd = makeNode(AlterTableCmd);
16401 : 178 : newcmd->subtype = AT_ReAddIndex;
16402 : 178 : newcmd->def = (Node *) stmt;
16403 : 178 : tab->subcmds[AT_PASS_OLD_INDEX] =
16404 : 178 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
16405 : : }
16406 [ + + ]: 491 : else if (IsA(stm, AlterTableStmt))
16407 : : {
16408 : 421 : AlterTableStmt *stmt = (AlterTableStmt *) stm;
16409 : : ListCell *lcmd;
16410 : :
16411 [ + - + + : 842 : foreach(lcmd, stmt->cmds)
+ + ]
16412 : : {
16413 : 421 : AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
16414 : :
16415 [ + + ]: 421 : if (cmd->subtype == AT_AddIndex)
16416 : : {
16417 : : IndexStmt *indstmt;
16418 : : Oid indoid;
16419 : :
16420 : 152 : indstmt = castNode(IndexStmt, cmd->def);
16421 : 152 : indoid = get_constraint_index(oldId);
16422 : :
16423 [ + + ]: 152 : if (!rewrite)
16424 : 32 : TryReuseIndex(indoid, indstmt);
16425 : : /* keep any comment on the index */
16426 : 152 : indstmt->idxcomment = GetComment(indoid,
16427 : : RelationRelationId, 0);
16428 : 152 : indstmt->reset_default_tblspc = true;
16429 : :
16430 : 152 : cmd->subtype = AT_ReAddIndex;
16431 : 152 : tab->subcmds[AT_PASS_OLD_INDEX] =
16432 : 152 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
16433 : :
16434 : : /* recreate any comment on the constraint */
16435 : 152 : RebuildConstraintComment(tab,
16436 : : AT_PASS_OLD_INDEX,
16437 : : oldId,
16438 : : rel,
16439 : : NIL,
16440 : 152 : indstmt->idxname);
16441 : : }
16442 [ + - ]: 269 : else if (cmd->subtype == AT_AddConstraint)
16443 : : {
16444 : 269 : Constraint *con = castNode(Constraint, cmd->def);
16445 : :
16446 : 269 : con->old_pktable_oid = refRelId;
16447 : : /* rewriting neither side of a FK */
16448 [ + + ]: 269 : if (con->contype == CONSTR_FOREIGN &&
16449 [ + + + - ]: 48 : !rewrite && tab->rewrite == 0)
16450 : 4 : TryReuseForeignKey(oldId, con);
16451 : 269 : con->reset_default_tblspc = true;
16452 : 269 : cmd->subtype = AT_ReAddConstraint;
16453 : 269 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16454 : 269 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16455 : :
16456 : : /*
16457 : : * Recreate any comment on the constraint. If we have
16458 : : * recreated a primary key, then transformTableConstraint
16459 : : * has added an unnamed not-null constraint here; skip
16460 : : * this in that case.
16461 : : */
16462 [ + - ]: 269 : if (con->conname)
16463 : 269 : RebuildConstraintComment(tab,
16464 : : AT_PASS_OLD_CONSTR,
16465 : : oldId,
16466 : : rel,
16467 : : NIL,
16468 : 269 : con->conname);
16469 : : else
16470 : : Assert(con->contype == CONSTR_NOTNULL);
16471 : : }
16472 : : else
16473 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
16474 : : (int) cmd->subtype);
16475 : : }
16476 : : }
16477 [ + + ]: 70 : else if (IsA(stm, AlterDomainStmt))
16478 : : {
16479 : 13 : AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
16480 : :
16481 [ + - ]: 13 : if (stmt->subtype == AD_AddConstraint)
16482 : : {
16483 : 13 : Constraint *con = castNode(Constraint, stmt->def);
16484 : 13 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16485 : :
16486 : 13 : cmd->subtype = AT_ReAddDomainConstraint;
16487 : 13 : cmd->def = (Node *) stmt;
16488 : 13 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16489 : 13 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16490 : :
16491 : : /* recreate any comment on the constraint */
16492 : 13 : RebuildConstraintComment(tab,
16493 : : AT_PASS_OLD_CONSTR,
16494 : : oldId,
16495 : : NULL,
16496 : : stmt->typeName,
16497 : 13 : con->conname);
16498 : : }
16499 : : else
16500 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
16501 : : (int) stmt->subtype);
16502 : : }
16503 [ + - ]: 57 : else if (IsA(stm, CreateStatsStmt))
16504 : : {
16505 : 57 : CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
16506 : : AlterTableCmd *newcmd;
16507 : :
16508 : : /* keep the statistics object's comment */
16509 : 57 : stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
16510 : :
16511 : 57 : newcmd = makeNode(AlterTableCmd);
16512 : 57 : newcmd->subtype = AT_ReAddStatistics;
16513 : 57 : newcmd->def = (Node *) stmt;
16514 : 57 : tab->subcmds[AT_PASS_MISC] =
16515 : 57 : lappend(tab->subcmds[AT_PASS_MISC], newcmd);
16516 : : }
16517 : : else
16518 [ # # ]: 0 : elog(ERROR, "unexpected statement type: %d",
16519 : : (int) nodeTag(stm));
16520 : : }
16521 : :
16522 : 669 : relation_close(rel, NoLock);
16523 : 669 : }
16524 : :
16525 : : /*
16526 : : * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
16527 : : * for a table or domain constraint that is being rebuilt.
16528 : : *
16529 : : * objid is the OID of the constraint.
16530 : : * Pass "rel" for a table constraint, or "domname" (domain's qualified name
16531 : : * as a string list) for a domain constraint.
16532 : : * (We could dig that info, as well as the conname, out of the pg_constraint
16533 : : * entry; but callers already have them so might as well pass them.)
16534 : : */
16535 : : static void
16536 : 434 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
16537 : : Relation rel, List *domname,
16538 : : const char *conname)
16539 : : {
16540 : : CommentStmt *cmd;
16541 : : char *comment_str;
16542 : : AlterTableCmd *newcmd;
16543 : :
16544 : : /* Look for comment for object wanted, and leave if none */
16545 : 434 : comment_str = GetComment(objid, ConstraintRelationId, 0);
16546 [ + + ]: 434 : if (comment_str == NULL)
16547 : 374 : return;
16548 : :
16549 : : /* Build CommentStmt node, copying all input data for safety */
16550 : 60 : cmd = makeNode(CommentStmt);
16551 [ + + ]: 60 : if (rel)
16552 : : {
16553 : 52 : cmd->objtype = OBJECT_TABCONSTRAINT;
16554 : 52 : cmd->object = (Node *)
16555 : 52 : list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
16556 : : makeString(pstrdup(RelationGetRelationName(rel))),
16557 : : makeString(pstrdup(conname)));
16558 : : }
16559 : : else
16560 : : {
16561 : 8 : cmd->objtype = OBJECT_DOMCONSTRAINT;
16562 : 8 : cmd->object = (Node *)
16563 : 8 : list_make2(makeTypeNameFromNameList(copyObject(domname)),
16564 : : makeString(pstrdup(conname)));
16565 : : }
16566 : 60 : cmd->comment = comment_str;
16567 : :
16568 : : /* Append it to list of commands */
16569 : 60 : newcmd = makeNode(AlterTableCmd);
16570 : 60 : newcmd->subtype = AT_ReAddComment;
16571 : 60 : newcmd->def = (Node *) cmd;
16572 : 60 : tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
16573 : : }
16574 : :
16575 : : /*
16576 : : * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
16577 : : * for the real analysis, then mutates the IndexStmt based on that verdict.
16578 : : */
16579 : : static void
16580 : 85 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
16581 : : {
16582 [ + + ]: 85 : if (CheckIndexCompatible(oldId,
16583 : 85 : stmt->accessMethod,
16584 : 85 : stmt->indexParams,
16585 : 85 : stmt->excludeOpNames,
16586 : 85 : stmt->iswithoutoverlaps))
16587 : : {
16588 : 69 : Relation irel = index_open(oldId, NoLock);
16589 : :
16590 : : /* If it's a partitioned index, there is no storage to share. */
16591 [ + + ]: 69 : if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
16592 : : {
16593 : 49 : stmt->oldNumber = irel->rd_locator.relNumber;
16594 : 49 : stmt->oldCreateSubid = irel->rd_createSubid;
16595 : 49 : stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
16596 : : }
16597 : 69 : index_close(irel, NoLock);
16598 : : }
16599 : 85 : }
16600 : :
16601 : : /*
16602 : : * Subroutine for ATPostAlterTypeParse().
16603 : : *
16604 : : * Stash the old P-F equality operator into the Constraint node, for possible
16605 : : * use by ATAddForeignKeyConstraint() in determining whether revalidation of
16606 : : * this constraint can be skipped.
16607 : : */
16608 : : static void
16609 : 4 : TryReuseForeignKey(Oid oldId, Constraint *con)
16610 : : {
16611 : : HeapTuple tup;
16612 : : Datum adatum;
16613 : : ArrayType *arr;
16614 : : Oid *rawarr;
16615 : : int numkeys;
16616 : : int i;
16617 : :
16618 : : Assert(con->contype == CONSTR_FOREIGN);
16619 : : Assert(con->old_conpfeqop == NIL); /* already prepared this node */
16620 : :
16621 : 4 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16622 [ - + ]: 4 : if (!HeapTupleIsValid(tup)) /* should not happen */
16623 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16624 : :
16625 : 4 : adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
16626 : : Anum_pg_constraint_conpfeqop);
16627 : 4 : arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
16628 : 4 : numkeys = ARR_DIMS(arr)[0];
16629 : : /* test follows the one in ri_FetchConstraintInfo() */
16630 [ + - ]: 4 : if (ARR_NDIM(arr) != 1 ||
16631 [ + - ]: 4 : ARR_HASNULL(arr) ||
16632 [ - + ]: 4 : ARR_ELEMTYPE(arr) != OIDOID)
16633 [ # # ]: 0 : elog(ERROR, "conpfeqop is not a 1-D Oid array");
16634 [ - + ]: 4 : rawarr = (Oid *) ARR_DATA_PTR(arr);
16635 : :
16636 : : /* stash a List of the operator Oids in our Constraint node */
16637 [ + + ]: 8 : for (i = 0; i < numkeys; i++)
16638 : 4 : con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
16639 : :
16640 : 4 : ReleaseSysCache(tup);
16641 : 4 : }
16642 : :
16643 : : /*
16644 : : * ALTER COLUMN .. OPTIONS ( ... )
16645 : : *
16646 : : * Returns the address of the modified column
16647 : : */
16648 : : static ObjectAddress
16649 : 94 : ATExecAlterColumnGenericOptions(Relation rel,
16650 : : const char *colName,
16651 : : List *options,
16652 : : LOCKMODE lockmode)
16653 : : {
16654 : : Relation ftrel;
16655 : : Relation attrel;
16656 : : ForeignServer *server;
16657 : : ForeignDataWrapper *fdw;
16658 : : HeapTuple tuple;
16659 : : HeapTuple newtuple;
16660 : : bool isnull;
16661 : : Datum repl_val[Natts_pg_attribute];
16662 : : bool repl_null[Natts_pg_attribute];
16663 : : bool repl_repl[Natts_pg_attribute];
16664 : : Datum datum;
16665 : : Form_pg_foreign_table fttableform;
16666 : : Form_pg_attribute atttableform;
16667 : : AttrNumber attnum;
16668 : : ObjectAddress address;
16669 : :
16670 [ - + ]: 94 : if (options == NIL)
16671 : 0 : return InvalidObjectAddress;
16672 : :
16673 : : /* First, determine FDW validator associated to the foreign table. */
16674 : 94 : ftrel = table_open(ForeignTableRelationId, AccessShareLock);
16675 : 94 : tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
16676 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
16677 [ # # ]: 0 : ereport(ERROR,
16678 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
16679 : : errmsg("foreign table \"%s\" does not exist",
16680 : : RelationGetRelationName(rel))));
16681 : 94 : fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
16682 : 94 : server = GetForeignServer(fttableform->ftserver);
16683 : 94 : fdw = GetForeignDataWrapper(server->fdwid);
16684 : :
16685 : 94 : table_close(ftrel, AccessShareLock);
16686 : 94 : ReleaseSysCache(tuple);
16687 : :
16688 : 94 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
16689 : 94 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
16690 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
16691 [ # # ]: 0 : ereport(ERROR,
16692 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
16693 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
16694 : : colName, RelationGetRelationName(rel))));
16695 : :
16696 : : /* Prevent them from altering a system attribute */
16697 : 94 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
16698 : 94 : attnum = atttableform->attnum;
16699 [ + + ]: 94 : if (attnum <= 0)
16700 [ + - ]: 4 : ereport(ERROR,
16701 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16702 : : errmsg("cannot alter system column \"%s\"", colName)));
16703 : :
16704 : :
16705 : : /* Initialize buffers for new tuple values */
16706 : 90 : memset(repl_val, 0, sizeof(repl_val));
16707 : 90 : memset(repl_null, false, sizeof(repl_null));
16708 : 90 : memset(repl_repl, false, sizeof(repl_repl));
16709 : :
16710 : : /* Extract the current options */
16711 : 90 : datum = SysCacheGetAttr(ATTNAME,
16712 : : tuple,
16713 : : Anum_pg_attribute_attfdwoptions,
16714 : : &isnull);
16715 [ + + ]: 90 : if (isnull)
16716 : 84 : datum = PointerGetDatum(NULL);
16717 : :
16718 : : /* Transform the options */
16719 : 90 : datum = transformGenericOptions(AttributeRelationId,
16720 : : datum,
16721 : : options,
16722 : : fdw->fdwvalidator);
16723 : :
16724 [ + - ]: 90 : if (DatumGetPointer(datum) != NULL)
16725 : 90 : repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
16726 : : else
16727 : 0 : repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
16728 : :
16729 : 90 : repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
16730 : :
16731 : : /* Everything looks good - update the tuple */
16732 : :
16733 : 90 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
16734 : : repl_val, repl_null, repl_repl);
16735 : :
16736 : 90 : CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
16737 : :
16738 [ - + ]: 90 : InvokeObjectPostAlterHook(RelationRelationId,
16739 : : RelationGetRelid(rel),
16740 : : atttableform->attnum);
16741 : 90 : ObjectAddressSubSet(address, RelationRelationId,
16742 : : RelationGetRelid(rel), attnum);
16743 : :
16744 : 90 : ReleaseSysCache(tuple);
16745 : :
16746 : 90 : table_close(attrel, RowExclusiveLock);
16747 : :
16748 : 90 : heap_freetuple(newtuple);
16749 : :
16750 : 90 : return address;
16751 : : }
16752 : :
16753 : : /*
16754 : : * ALTER TABLE OWNER
16755 : : *
16756 : : * recursing is true if we are recursing from a table to its indexes,
16757 : : * sequences, or toast table. We don't allow the ownership of those things to
16758 : : * be changed separately from the parent table. Also, we can skip permission
16759 : : * checks (this is necessary not just an optimization, else we'd fail to
16760 : : * handle toast tables properly).
16761 : : *
16762 : : * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
16763 : : * free-standing composite type.
16764 : : */
16765 : : void
16766 : 1371 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
16767 : : {
16768 : : Relation target_rel;
16769 : : Relation class_rel;
16770 : : HeapTuple tuple;
16771 : : Form_pg_class tuple_class;
16772 : :
16773 : : /*
16774 : : * Get exclusive lock till end of transaction on the target table. Use
16775 : : * relation_open so that we can work on indexes and sequences.
16776 : : */
16777 : 1371 : target_rel = relation_open(relationOid, lockmode);
16778 : :
16779 : : /* Get its pg_class tuple, too */
16780 : 1371 : class_rel = table_open(RelationRelationId, RowExclusiveLock);
16781 : :
16782 : 1371 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16783 [ - + ]: 1371 : if (!HeapTupleIsValid(tuple))
16784 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationOid);
16785 : 1371 : tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16786 : :
16787 : : /* Can we change the ownership of this tuple? */
16788 [ + + + + : 1371 : switch (tuple_class->relkind)
+ + - ]
16789 : : {
16790 : 1109 : case RELKIND_RELATION:
16791 : : case RELKIND_VIEW:
16792 : : case RELKIND_MATVIEW:
16793 : : case RELKIND_FOREIGN_TABLE:
16794 : : case RELKIND_PARTITIONED_TABLE:
16795 : : /* ok to change owner */
16796 : 1109 : break;
16797 : 111 : case RELKIND_INDEX:
16798 [ - + ]: 111 : if (!recursing)
16799 : : {
16800 : : /*
16801 : : * Because ALTER INDEX OWNER used to be allowed, and in fact
16802 : : * is generated by old versions of pg_dump, we give a warning
16803 : : * and do nothing rather than erroring out. Also, to avoid
16804 : : * unnecessary chatter while restoring those old dumps, say
16805 : : * nothing at all if the command would be a no-op anyway.
16806 : : */
16807 [ # # ]: 0 : if (tuple_class->relowner != newOwnerId)
16808 [ # # ]: 0 : ereport(WARNING,
16809 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16810 : : errmsg("cannot change owner of index \"%s\"",
16811 : : NameStr(tuple_class->relname)),
16812 : : errhint("Change the ownership of the index's table instead.")));
16813 : : /* quick hack to exit via the no-op path */
16814 : 0 : newOwnerId = tuple_class->relowner;
16815 : : }
16816 : 111 : break;
16817 : 26 : case RELKIND_PARTITIONED_INDEX:
16818 [ + - ]: 26 : if (recursing)
16819 : 26 : break;
16820 [ # # ]: 0 : ereport(ERROR,
16821 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16822 : : errmsg("cannot change owner of index \"%s\"",
16823 : : NameStr(tuple_class->relname)),
16824 : : errhint("Change the ownership of the index's table instead.")));
16825 : : break;
16826 : 69 : case RELKIND_SEQUENCE:
16827 [ + + ]: 69 : if (!recursing &&
16828 [ + + ]: 39 : tuple_class->relowner != newOwnerId)
16829 : : {
16830 : : /* if it's an owned sequence, disallow changing it by itself */
16831 : : Oid tableId;
16832 : : int32 colId;
16833 : :
16834 [ + - - + ]: 8 : if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16835 : 4 : sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16836 [ # # ]: 0 : ereport(ERROR,
16837 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16838 : : errmsg("cannot change owner of sequence \"%s\"",
16839 : : NameStr(tuple_class->relname)),
16840 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
16841 : : NameStr(tuple_class->relname),
16842 : : get_rel_name(tableId))));
16843 : : }
16844 : 69 : break;
16845 : 5 : case RELKIND_COMPOSITE_TYPE:
16846 [ + - ]: 5 : if (recursing)
16847 : 5 : break;
16848 [ # # ]: 0 : ereport(ERROR,
16849 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16850 : : errmsg("\"%s\" is a composite type",
16851 : : NameStr(tuple_class->relname)),
16852 : : /* translator: %s is an SQL ALTER command */
16853 : : errhint("Use %s instead.",
16854 : : "ALTER TYPE")));
16855 : : break;
16856 : 51 : case RELKIND_TOASTVALUE:
16857 [ + - ]: 51 : if (recursing)
16858 : 51 : break;
16859 : : pg_fallthrough;
16860 : : default:
16861 [ # # ]: 0 : ereport(ERROR,
16862 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16863 : : errmsg("cannot change owner of relation \"%s\"",
16864 : : NameStr(tuple_class->relname)),
16865 : : errdetail_relkind_not_supported(tuple_class->relkind)));
16866 : : }
16867 : :
16868 : : /*
16869 : : * If the new owner is the same as the existing owner, consider the
16870 : : * command to have succeeded. This is for dump restoration purposes.
16871 : : */
16872 [ + + ]: 1371 : if (tuple_class->relowner != newOwnerId)
16873 : : {
16874 : : Datum repl_val[Natts_pg_class];
16875 : : bool repl_null[Natts_pg_class];
16876 : : bool repl_repl[Natts_pg_class];
16877 : : Acl *newAcl;
16878 : : Datum aclDatum;
16879 : : bool isNull;
16880 : : HeapTuple newtuple;
16881 : :
16882 : : /* skip permission checks when recursing to index or toast table */
16883 [ + + ]: 481 : if (!recursing)
16884 : : {
16885 : : /* Superusers can always do it */
16886 [ + + ]: 248 : if (!superuser())
16887 : : {
16888 : 28 : Oid namespaceOid = tuple_class->relnamespace;
16889 : : AclResult aclresult;
16890 : :
16891 : : /* Otherwise, must be owner of the existing object */
16892 [ - + ]: 28 : if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16893 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
16894 : 0 : RelationGetRelationName(target_rel));
16895 : :
16896 : : /* Must be able to become new owner */
16897 : 28 : check_can_set_role(GetUserId(), newOwnerId);
16898 : :
16899 : : /* New owner must have CREATE privilege on namespace */
16900 : 20 : aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16901 : : ACL_CREATE);
16902 [ - + ]: 20 : if (aclresult != ACLCHECK_OK)
16903 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
16904 : 0 : get_namespace_name(namespaceOid));
16905 : : }
16906 : : }
16907 : :
16908 : 473 : memset(repl_null, false, sizeof(repl_null));
16909 : 473 : memset(repl_repl, false, sizeof(repl_repl));
16910 : :
16911 : 473 : repl_repl[Anum_pg_class_relowner - 1] = true;
16912 : 473 : repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16913 : :
16914 : : /*
16915 : : * Determine the modified ACL for the new owner. This is only
16916 : : * necessary when the ACL is non-null.
16917 : : */
16918 : 473 : aclDatum = SysCacheGetAttr(RELOID, tuple,
16919 : : Anum_pg_class_relacl,
16920 : : &isNull);
16921 [ + + ]: 473 : if (!isNull)
16922 : : {
16923 : 36 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
16924 : : tuple_class->relowner, newOwnerId);
16925 : 36 : repl_repl[Anum_pg_class_relacl - 1] = true;
16926 : 36 : repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16927 : : }
16928 : :
16929 : 473 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16930 : :
16931 : 473 : CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16932 : :
16933 : 473 : heap_freetuple(newtuple);
16934 : :
16935 : : /*
16936 : : * We must similarly update any per-column ACLs to reflect the new
16937 : : * owner; for neatness reasons that's split out as a subroutine.
16938 : : */
16939 : 473 : change_owner_fix_column_acls(relationOid,
16940 : : tuple_class->relowner,
16941 : : newOwnerId);
16942 : :
16943 : : /*
16944 : : * Update owner dependency reference, if any. A composite type has
16945 : : * none, because it's tracked for the pg_type entry instead of here;
16946 : : * indexes and TOAST tables don't have their own entries either.
16947 : : */
16948 [ + + ]: 473 : if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16949 [ + + ]: 468 : tuple_class->relkind != RELKIND_INDEX &&
16950 [ + + ]: 357 : tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16951 [ + + ]: 331 : tuple_class->relkind != RELKIND_TOASTVALUE)
16952 : 280 : changeDependencyOnOwner(RelationRelationId, relationOid,
16953 : : newOwnerId);
16954 : :
16955 : : /*
16956 : : * Also change the ownership of the table's row type, if it has one
16957 : : */
16958 [ + + ]: 473 : if (OidIsValid(tuple_class->reltype))
16959 : 260 : AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16960 : :
16961 : : /*
16962 : : * If we are operating on a table or materialized view, also change
16963 : : * the ownership of any indexes and sequences that belong to the
16964 : : * relation, as well as its toast table (if it has one).
16965 : : */
16966 [ + + ]: 473 : if (tuple_class->relkind == RELKIND_RELATION ||
16967 [ + + ]: 269 : tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16968 [ + - ]: 232 : tuple_class->relkind == RELKIND_MATVIEW ||
16969 [ + + ]: 232 : tuple_class->relkind == RELKIND_TOASTVALUE)
16970 : : {
16971 : : List *index_oid_list;
16972 : : ListCell *i;
16973 : :
16974 : : /* Find all the indexes belonging to this relation */
16975 : 292 : index_oid_list = RelationGetIndexList(target_rel);
16976 : :
16977 : : /* For each index, recursively change its ownership */
16978 [ + + + + : 429 : foreach(i, index_oid_list)
+ + ]
16979 : 137 : ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16980 : :
16981 : 292 : list_free(index_oid_list);
16982 : : }
16983 : :
16984 : : /* If it has a toast table, recurse to change its ownership */
16985 [ + + ]: 473 : if (tuple_class->reltoastrelid != InvalidOid)
16986 : 51 : ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16987 : : true, lockmode);
16988 : :
16989 : : /* If it has dependent sequences, recurse to change them too */
16990 : 473 : change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16991 : : }
16992 : :
16993 [ - + ]: 1363 : InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16994 : :
16995 : 1363 : ReleaseSysCache(tuple);
16996 : 1363 : table_close(class_rel, RowExclusiveLock);
16997 : 1363 : relation_close(target_rel, NoLock);
16998 : 1363 : }
16999 : :
17000 : : /*
17001 : : * change_owner_fix_column_acls
17002 : : *
17003 : : * Helper function for ATExecChangeOwner. Scan the columns of the table
17004 : : * and fix any non-null column ACLs to reflect the new owner.
17005 : : */
17006 : : static void
17007 : 473 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
17008 : : {
17009 : : Relation attRelation;
17010 : : SysScanDesc scan;
17011 : : ScanKeyData key[1];
17012 : : HeapTuple attributeTuple;
17013 : :
17014 : 473 : attRelation = table_open(AttributeRelationId, RowExclusiveLock);
17015 : 473 : ScanKeyInit(&key[0],
17016 : : Anum_pg_attribute_attrelid,
17017 : : BTEqualStrategyNumber, F_OIDEQ,
17018 : : ObjectIdGetDatum(relationOid));
17019 : 473 : scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
17020 : : true, NULL, 1, key);
17021 [ + + ]: 3297 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
17022 : : {
17023 : 2824 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
17024 : : Datum repl_val[Natts_pg_attribute];
17025 : : bool repl_null[Natts_pg_attribute];
17026 : : bool repl_repl[Natts_pg_attribute];
17027 : : Acl *newAcl;
17028 : : Datum aclDatum;
17029 : : bool isNull;
17030 : : HeapTuple newtuple;
17031 : :
17032 : : /* Ignore dropped columns */
17033 [ - + ]: 2824 : if (att->attisdropped)
17034 : 2823 : continue;
17035 : :
17036 : 2824 : aclDatum = heap_getattr(attributeTuple,
17037 : : Anum_pg_attribute_attacl,
17038 : : RelationGetDescr(attRelation),
17039 : : &isNull);
17040 : : /* Null ACLs do not require changes */
17041 [ + + ]: 2824 : if (isNull)
17042 : 2823 : continue;
17043 : :
17044 : 1 : memset(repl_null, false, sizeof(repl_null));
17045 : 1 : memset(repl_repl, false, sizeof(repl_repl));
17046 : :
17047 : 1 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
17048 : : oldOwnerId, newOwnerId);
17049 : 1 : repl_repl[Anum_pg_attribute_attacl - 1] = true;
17050 : 1 : repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
17051 : :
17052 : 1 : newtuple = heap_modify_tuple(attributeTuple,
17053 : : RelationGetDescr(attRelation),
17054 : : repl_val, repl_null, repl_repl);
17055 : :
17056 : 1 : CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
17057 : :
17058 : 1 : heap_freetuple(newtuple);
17059 : : }
17060 : 473 : systable_endscan(scan);
17061 : 473 : table_close(attRelation, RowExclusiveLock);
17062 : 473 : }
17063 : :
17064 : : /*
17065 : : * change_owner_recurse_to_sequences
17066 : : *
17067 : : * Helper function for ATExecChangeOwner. Examines pg_depend searching
17068 : : * for sequences that are dependent on serial columns, and changes their
17069 : : * ownership.
17070 : : */
17071 : : static void
17072 : 473 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
17073 : : {
17074 : : Relation depRel;
17075 : : SysScanDesc scan;
17076 : : ScanKeyData key[2];
17077 : : HeapTuple tup;
17078 : :
17079 : : /*
17080 : : * SERIAL sequences are those having an auto dependency on one of the
17081 : : * table's columns (we don't care *which* column, exactly).
17082 : : */
17083 : 473 : depRel = table_open(DependRelationId, AccessShareLock);
17084 : :
17085 : 473 : ScanKeyInit(&key[0],
17086 : : Anum_pg_depend_refclassid,
17087 : : BTEqualStrategyNumber, F_OIDEQ,
17088 : : ObjectIdGetDatum(RelationRelationId));
17089 : 473 : ScanKeyInit(&key[1],
17090 : : Anum_pg_depend_refobjid,
17091 : : BTEqualStrategyNumber, F_OIDEQ,
17092 : : ObjectIdGetDatum(relationOid));
17093 : : /* we leave refobjsubid unspecified */
17094 : :
17095 : 473 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
17096 : : NULL, 2, key);
17097 : :
17098 [ + + ]: 1359 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
17099 : : {
17100 : 886 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
17101 : : Relation seqRel;
17102 : :
17103 : : /* skip dependencies other than auto dependencies on columns */
17104 [ + + ]: 886 : if (depForm->refobjsubid == 0 ||
17105 [ + + ]: 388 : depForm->classid != RelationRelationId ||
17106 [ + - ]: 155 : depForm->objsubid != 0 ||
17107 [ + + - + ]: 155 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
17108 : 731 : continue;
17109 : :
17110 : : /* Use relation_open just in case it's an index */
17111 : 155 : seqRel = relation_open(depForm->objid, lockmode);
17112 : :
17113 : : /* skip non-sequence relations */
17114 [ + + ]: 155 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
17115 : : {
17116 : : /* No need to keep the lock */
17117 : 138 : relation_close(seqRel, lockmode);
17118 : 138 : continue;
17119 : : }
17120 : :
17121 : : /* We don't need to close the sequence while we alter it. */
17122 : 17 : ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
17123 : :
17124 : : /* Now we can close it. Keep the lock till end of transaction. */
17125 : 17 : relation_close(seqRel, NoLock);
17126 : : }
17127 : :
17128 : 473 : systable_endscan(scan);
17129 : :
17130 : 473 : relation_close(depRel, AccessShareLock);
17131 : 473 : }
17132 : :
17133 : : /*
17134 : : * ALTER TABLE CLUSTER ON
17135 : : *
17136 : : * The only thing we have to do is to change the indisclustered bits.
17137 : : *
17138 : : * Return the address of the new clustering index.
17139 : : */
17140 : : static ObjectAddress
17141 : 39 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
17142 : : {
17143 : : Oid indexOid;
17144 : : ObjectAddress address;
17145 : :
17146 : 39 : indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
17147 : :
17148 [ - + ]: 39 : if (!OidIsValid(indexOid))
17149 [ # # ]: 0 : ereport(ERROR,
17150 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
17151 : : errmsg("index \"%s\" for table \"%s\" does not exist",
17152 : : indexName, RelationGetRelationName(rel))));
17153 : :
17154 : : /* Check index is valid to cluster on */
17155 : 39 : check_index_is_clusterable(rel, indexOid, lockmode);
17156 : :
17157 : : /* And do the work */
17158 : 39 : mark_index_clustered(rel, indexOid, false);
17159 : :
17160 : 39 : ObjectAddressSet(address,
17161 : : RelationRelationId, indexOid);
17162 : :
17163 : 39 : return address;
17164 : : }
17165 : :
17166 : : /*
17167 : : * ALTER TABLE SET WITHOUT CLUSTER
17168 : : *
17169 : : * We have to find any indexes on the table that have indisclustered bit
17170 : : * set and turn it off.
17171 : : */
17172 : : static void
17173 : 8 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
17174 : : {
17175 : 8 : mark_index_clustered(rel, InvalidOid, false);
17176 : 8 : }
17177 : :
17178 : : /*
17179 : : * Preparation phase for SET ACCESS METHOD
17180 : : *
17181 : : * Check that the access method exists and determine whether a change is
17182 : : * actually needed.
17183 : : */
17184 : : static void
17185 : 73 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
17186 : : {
17187 : : Oid amoid;
17188 : :
17189 : : /*
17190 : : * Look up the access method name and check that it differs from the
17191 : : * table's current AM. If DEFAULT was specified for a partitioned table
17192 : : * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
17193 : : */
17194 [ + + ]: 73 : if (amname != NULL)
17195 : 49 : amoid = get_table_am_oid(amname, false);
17196 [ + + ]: 24 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17197 : 12 : amoid = InvalidOid;
17198 : : else
17199 : 12 : amoid = get_table_am_oid(default_table_access_method, false);
17200 : :
17201 : : /* if it's a match, phase 3 doesn't need to do anything */
17202 [ + + ]: 73 : if (rel->rd_rel->relam == amoid)
17203 : 8 : return;
17204 : :
17205 : : /* Save info for Phase 3 to do the real work */
17206 : 65 : tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
17207 : 65 : tab->newAccessMethod = amoid;
17208 : 65 : tab->chgAccessMethod = true;
17209 : : }
17210 : :
17211 : : /*
17212 : : * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
17213 : : * storage that have an interest in preserving AM.
17214 : : *
17215 : : * Since these have no storage, setting the access method is a catalog only
17216 : : * operation.
17217 : : */
17218 : : static void
17219 : 29 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
17220 : : {
17221 : : Relation pg_class;
17222 : : Oid oldAccessMethodId;
17223 : : HeapTuple tuple;
17224 : : Form_pg_class rd_rel;
17225 : 29 : Oid reloid = RelationGetRelid(rel);
17226 : :
17227 : : /*
17228 : : * Shouldn't be called on relations having storage; these are processed in
17229 : : * phase 3.
17230 : : */
17231 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17232 : :
17233 : : /* Get a modifiable copy of the relation's pg_class row. */
17234 : 29 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
17235 : :
17236 : 29 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
17237 [ - + ]: 29 : if (!HeapTupleIsValid(tuple))
17238 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
17239 : 29 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
17240 : :
17241 : : /* Update the pg_class row. */
17242 : 29 : oldAccessMethodId = rd_rel->relam;
17243 : 29 : rd_rel->relam = newAccessMethodId;
17244 : :
17245 : : /* Leave if no update required */
17246 [ - + ]: 29 : if (rd_rel->relam == oldAccessMethodId)
17247 : : {
17248 : 0 : heap_freetuple(tuple);
17249 : 0 : table_close(pg_class, RowExclusiveLock);
17250 : 0 : return;
17251 : : }
17252 : :
17253 : 29 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
17254 : :
17255 : : /*
17256 : : * Update the dependency on the new access method. No dependency is added
17257 : : * if the new access method is InvalidOid (default case). Be very careful
17258 : : * that this has to compare the previous value stored in pg_class with the
17259 : : * new one.
17260 : : */
17261 [ + + + - ]: 29 : if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
17262 : 13 : {
17263 : : ObjectAddress relobj,
17264 : : referenced;
17265 : :
17266 : : /*
17267 : : * New access method is defined and there was no dependency
17268 : : * previously, so record a new one.
17269 : : */
17270 : 13 : ObjectAddressSet(relobj, RelationRelationId, reloid);
17271 : 13 : ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
17272 : 13 : recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
17273 : : }
17274 [ + - ]: 16 : else if (OidIsValid(oldAccessMethodId) &&
17275 [ + + ]: 16 : !OidIsValid(rd_rel->relam))
17276 : : {
17277 : : /*
17278 : : * There was an access method defined, and no new one, so just remove
17279 : : * the existing dependency.
17280 : : */
17281 : 8 : deleteDependencyRecordsForClass(RelationRelationId, reloid,
17282 : : AccessMethodRelationId,
17283 : : DEPENDENCY_NORMAL);
17284 : : }
17285 : : else
17286 : : {
17287 : : Assert(OidIsValid(oldAccessMethodId) &&
17288 : : OidIsValid(rd_rel->relam));
17289 : :
17290 : : /* Both are valid, so update the dependency */
17291 : 8 : changeDependencyFor(RelationRelationId, reloid,
17292 : : AccessMethodRelationId,
17293 : : oldAccessMethodId, rd_rel->relam);
17294 : : }
17295 : :
17296 : : /* make the relam and dependency changes visible */
17297 : 29 : CommandCounterIncrement();
17298 : :
17299 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17300 : :
17301 : 29 : heap_freetuple(tuple);
17302 : 29 : table_close(pg_class, RowExclusiveLock);
17303 : : }
17304 : :
17305 : : /*
17306 : : * ALTER TABLE SET TABLESPACE
17307 : : */
17308 : : static void
17309 : 103 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
17310 : : {
17311 : : Oid tablespaceId;
17312 : :
17313 : : /* Check that the tablespace exists */
17314 : 103 : tablespaceId = get_tablespace_oid(tablespacename, false);
17315 : :
17316 : : /* Check permissions except when moving to database's default */
17317 [ + - + + ]: 103 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
17318 : : {
17319 : : AclResult aclresult;
17320 : :
17321 : 48 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
17322 [ - + ]: 48 : if (aclresult != ACLCHECK_OK)
17323 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
17324 : : }
17325 : :
17326 : : /* Save info for Phase 3 to do the real work */
17327 [ - + ]: 103 : if (OidIsValid(tab->newTableSpace))
17328 [ # # ]: 0 : ereport(ERROR,
17329 : : (errcode(ERRCODE_SYNTAX_ERROR),
17330 : : errmsg("cannot have multiple SET TABLESPACE subcommands")));
17331 : :
17332 : 103 : tab->newTableSpace = tablespaceId;
17333 : 103 : }
17334 : :
17335 : : /*
17336 : : * Set, reset, or replace reloptions.
17337 : : */
17338 : : static void
17339 : 675 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
17340 : : LOCKMODE lockmode)
17341 : : {
17342 : : Oid relid;
17343 : : Relation pgclass;
17344 : : HeapTuple tuple;
17345 : : HeapTuple newtuple;
17346 : : Datum datum;
17347 : : Datum newOptions;
17348 : : Datum repl_val[Natts_pg_class];
17349 : : bool repl_null[Natts_pg_class];
17350 : : bool repl_repl[Natts_pg_class];
17351 : 675 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
17352 : :
17353 [ + + - + ]: 675 : if (defList == NIL && operation != AT_ReplaceRelOptions)
17354 : 0 : return; /* nothing to do */
17355 : :
17356 : 675 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
17357 : :
17358 : : /* Fetch heap tuple */
17359 : 675 : relid = RelationGetRelid(rel);
17360 : 675 : tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
17361 [ - + ]: 675 : if (!HeapTupleIsValid(tuple))
17362 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
17363 : :
17364 [ + + ]: 675 : if (operation == AT_ReplaceRelOptions)
17365 : : {
17366 : : /*
17367 : : * If we're supposed to replace the reloptions list, we just pretend
17368 : : * there were none before.
17369 : : */
17370 : 137 : datum = (Datum) 0;
17371 : : }
17372 : : else
17373 : : {
17374 : : bool isnull;
17375 : :
17376 : : /* Get the old reloptions */
17377 : 538 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
17378 : : &isnull);
17379 [ + + ]: 538 : if (isnull)
17380 : 302 : datum = (Datum) 0;
17381 : : }
17382 : :
17383 : : /* Generate new proposed reloptions (text array) */
17384 : 675 : newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
17385 : : operation == AT_ResetRelOptions);
17386 : :
17387 : : /* Validate */
17388 [ + + + + : 671 : switch (rel->rd_rel->relkind)
- ]
17389 : : {
17390 : 391 : case RELKIND_RELATION:
17391 : : case RELKIND_MATVIEW:
17392 : 391 : (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
17393 : 391 : break;
17394 : 4 : case RELKIND_PARTITIONED_TABLE:
17395 : 4 : (void) partitioned_table_reloptions(newOptions, true);
17396 : 0 : break;
17397 : 205 : case RELKIND_VIEW:
17398 : 205 : (void) view_reloptions(newOptions, true);
17399 : 193 : break;
17400 : 71 : case RELKIND_INDEX:
17401 : : case RELKIND_PARTITIONED_INDEX:
17402 : 71 : (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
17403 : 57 : break;
17404 : 0 : case RELKIND_TOASTVALUE:
17405 : : /* fall through to error -- shouldn't ever get here */
17406 : : default:
17407 [ # # ]: 0 : ereport(ERROR,
17408 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17409 : : errmsg("cannot set options for relation \"%s\"",
17410 : : RelationGetRelationName(rel)),
17411 : : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
17412 : : break;
17413 : : }
17414 : :
17415 : : /* Special-case validation of view options */
17416 [ + + ]: 641 : if (rel->rd_rel->relkind == RELKIND_VIEW)
17417 : : {
17418 : 193 : Query *view_query = get_view_query(rel);
17419 : 193 : List *view_options = untransformRelOptions(newOptions);
17420 : : ListCell *cell;
17421 : 193 : bool check_option = false;
17422 : :
17423 [ + + + + : 261 : foreach(cell, view_options)
+ + ]
17424 : : {
17425 : 68 : DefElem *defel = (DefElem *) lfirst(cell);
17426 : :
17427 [ + + ]: 68 : if (strcmp(defel->defname, "check_option") == 0)
17428 : 16 : check_option = true;
17429 : : }
17430 : :
17431 : : /*
17432 : : * If the check option is specified, look to see if the view is
17433 : : * actually auto-updatable or not.
17434 : : */
17435 [ + + ]: 193 : if (check_option)
17436 : : {
17437 : : const char *view_updatable_error =
17438 : 16 : view_query_is_auto_updatable(view_query, true);
17439 : :
17440 [ - + ]: 16 : if (view_updatable_error)
17441 [ # # ]: 0 : ereport(ERROR,
17442 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17443 : : errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
17444 : : errhint("%s", _(view_updatable_error))));
17445 : : }
17446 : : }
17447 : :
17448 : : /*
17449 : : * All we need do here is update the pg_class row; the new options will be
17450 : : * propagated into relcaches during post-commit cache inval.
17451 : : */
17452 : 641 : memset(repl_val, 0, sizeof(repl_val));
17453 : 641 : memset(repl_null, false, sizeof(repl_null));
17454 : 641 : memset(repl_repl, false, sizeof(repl_repl));
17455 : :
17456 [ + + ]: 641 : if (newOptions != (Datum) 0)
17457 : 427 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17458 : : else
17459 : 214 : repl_null[Anum_pg_class_reloptions - 1] = true;
17460 : :
17461 : 641 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17462 : :
17463 : 641 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17464 : : repl_val, repl_null, repl_repl);
17465 : :
17466 : 641 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17467 : 641 : UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
17468 : :
17469 [ - + ]: 641 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17470 : :
17471 : 641 : heap_freetuple(newtuple);
17472 : :
17473 : 641 : ReleaseSysCache(tuple);
17474 : :
17475 : : /* repeat the whole exercise for the toast table, if there's one */
17476 [ + + ]: 641 : if (OidIsValid(rel->rd_rel->reltoastrelid))
17477 : : {
17478 : : Relation toastrel;
17479 : 222 : Oid toastid = rel->rd_rel->reltoastrelid;
17480 : :
17481 : 222 : toastrel = table_open(toastid, lockmode);
17482 : :
17483 : : /* Fetch heap tuple */
17484 : 222 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
17485 [ - + ]: 222 : if (!HeapTupleIsValid(tuple))
17486 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", toastid);
17487 : :
17488 [ - + ]: 222 : if (operation == AT_ReplaceRelOptions)
17489 : : {
17490 : : /*
17491 : : * If we're supposed to replace the reloptions list, we just
17492 : : * pretend there were none before.
17493 : : */
17494 : 0 : datum = (Datum) 0;
17495 : : }
17496 : : else
17497 : : {
17498 : : bool isnull;
17499 : :
17500 : : /* Get the old reloptions */
17501 : 222 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
17502 : : &isnull);
17503 [ + + ]: 222 : if (isnull)
17504 : 198 : datum = (Datum) 0;
17505 : : }
17506 : :
17507 : 222 : newOptions = transformRelOptions(datum, defList, "toast", validnsps,
17508 : : false, operation == AT_ResetRelOptions);
17509 : :
17510 : 222 : (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
17511 : :
17512 : 222 : memset(repl_val, 0, sizeof(repl_val));
17513 : 222 : memset(repl_null, false, sizeof(repl_null));
17514 : 222 : memset(repl_repl, false, sizeof(repl_repl));
17515 : :
17516 [ + + ]: 222 : if (newOptions != (Datum) 0)
17517 : 28 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17518 : : else
17519 : 194 : repl_null[Anum_pg_class_reloptions - 1] = true;
17520 : :
17521 : 222 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17522 : :
17523 : 222 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17524 : : repl_val, repl_null, repl_repl);
17525 : :
17526 : 222 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17527 : :
17528 [ - + ]: 222 : InvokeObjectPostAlterHookArg(RelationRelationId,
17529 : : RelationGetRelid(toastrel), 0,
17530 : : InvalidOid, true);
17531 : :
17532 : 222 : heap_freetuple(newtuple);
17533 : :
17534 : 222 : ReleaseSysCache(tuple);
17535 : :
17536 : 222 : table_close(toastrel, NoLock);
17537 : : }
17538 : :
17539 : 641 : table_close(pgclass, RowExclusiveLock);
17540 : : }
17541 : :
17542 : : /*
17543 : : * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
17544 : : * rewriting to be done, so we just want to copy the data as fast as possible.
17545 : : */
17546 : : static void
17547 : 113 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
17548 : : {
17549 : : Relation rel;
17550 : : Oid reltoastrelid;
17551 : : RelFileNumber newrelfilenumber;
17552 : : RelFileLocator newrlocator;
17553 : 113 : List *reltoastidxids = NIL;
17554 : : ListCell *lc;
17555 : :
17556 : : /*
17557 : : * Need lock here in case we are recursing to toast table or index
17558 : : */
17559 : 113 : rel = relation_open(tableOid, lockmode);
17560 : :
17561 : : /* Check first if relation can be moved to new tablespace */
17562 [ + + ]: 113 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17563 : : {
17564 [ - + ]: 5 : InvokeObjectPostAlterHook(RelationRelationId,
17565 : : RelationGetRelid(rel), 0);
17566 : 5 : relation_close(rel, NoLock);
17567 : 5 : return;
17568 : : }
17569 : :
17570 : 108 : reltoastrelid = rel->rd_rel->reltoastrelid;
17571 : : /* Fetch the list of indexes on toast relation if necessary */
17572 [ + + ]: 108 : if (OidIsValid(reltoastrelid))
17573 : : {
17574 : 17 : Relation toastRel = relation_open(reltoastrelid, lockmode);
17575 : :
17576 : 17 : reltoastidxids = RelationGetIndexList(toastRel);
17577 : 17 : relation_close(toastRel, lockmode);
17578 : : }
17579 : :
17580 : : /*
17581 : : * Relfilenumbers are not unique in databases across tablespaces, so we
17582 : : * need to allocate a new one in the new tablespace.
17583 : : */
17584 : 108 : newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
17585 : 108 : rel->rd_rel->relpersistence);
17586 : :
17587 : : /* Open old and new relation */
17588 : 108 : newrlocator = rel->rd_locator;
17589 : 108 : newrlocator.relNumber = newrelfilenumber;
17590 : 108 : newrlocator.spcOid = newTableSpace;
17591 : :
17592 : : /* hand off to AM to actually create new rel storage and copy the data */
17593 [ + + ]: 108 : if (rel->rd_rel->relkind == RELKIND_INDEX)
17594 : : {
17595 : 40 : index_copy_data(rel, newrlocator);
17596 : : }
17597 : : else
17598 : : {
17599 : : Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
17600 : 68 : table_relation_copy_data(rel, &newrlocator);
17601 : : }
17602 : :
17603 : : /*
17604 : : * Update the pg_class row.
17605 : : *
17606 : : * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
17607 : : * executed on pg_class or its indexes (the above copy wouldn't contain
17608 : : * the updated pg_class entry), but that's forbidden with
17609 : : * CheckRelationTableSpaceMove().
17610 : : */
17611 : 108 : SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
17612 : :
17613 [ - + ]: 108 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17614 : :
17615 : 108 : RelationAssumeNewRelfilelocator(rel);
17616 : :
17617 : 108 : relation_close(rel, NoLock);
17618 : :
17619 : : /* Make sure the reltablespace change is visible */
17620 : 108 : CommandCounterIncrement();
17621 : :
17622 : : /* Move associated toast relation and/or indexes, too */
17623 [ + + ]: 108 : if (OidIsValid(reltoastrelid))
17624 : 17 : ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
17625 [ + + + + : 125 : foreach(lc, reltoastidxids)
+ + ]
17626 : 17 : ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
17627 : :
17628 : : /* Clean up */
17629 : 108 : list_free(reltoastidxids);
17630 : : }
17631 : :
17632 : : /*
17633 : : * Special handling of ALTER TABLE SET TABLESPACE for relations with no
17634 : : * storage that have an interest in preserving tablespace.
17635 : : *
17636 : : * Since these have no storage the tablespace can be updated with a simple
17637 : : * metadata only operation to update the tablespace.
17638 : : */
17639 : : static void
17640 : 24 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
17641 : : {
17642 : : /*
17643 : : * Shouldn't be called on relations having storage; these are processed in
17644 : : * phase 3.
17645 : : */
17646 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17647 : :
17648 : : /* check if relation can be moved to its new tablespace */
17649 [ - + ]: 24 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17650 : : {
17651 [ # # ]: 0 : InvokeObjectPostAlterHook(RelationRelationId,
17652 : : RelationGetRelid(rel),
17653 : : 0);
17654 : 0 : return;
17655 : : }
17656 : :
17657 : : /* Update can be done, so change reltablespace */
17658 : 20 : SetRelationTableSpace(rel, newTableSpace, InvalidOid);
17659 : :
17660 [ - + ]: 20 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17661 : :
17662 : : /* Make sure the reltablespace change is visible */
17663 : 20 : CommandCounterIncrement();
17664 : : }
17665 : :
17666 : : /*
17667 : : * Alter Table ALL ... SET TABLESPACE
17668 : : *
17669 : : * Allows a user to move all objects of some type in a given tablespace in the
17670 : : * current database to another tablespace. Objects can be chosen based on the
17671 : : * owner of the object also, to allow users to move only their objects.
17672 : : * The user must have CREATE rights on the new tablespace, as usual. The main
17673 : : * permissions handling is done by the lower-level table move function.
17674 : : *
17675 : : * All to-be-moved objects are locked first. If NOWAIT is specified and the
17676 : : * lock can't be acquired then we ereport(ERROR).
17677 : : */
17678 : : Oid
17679 : 16 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
17680 : : {
17681 : 16 : List *relations = NIL;
17682 : : ListCell *l;
17683 : : ScanKeyData key[1];
17684 : : Relation rel;
17685 : : TableScanDesc scan;
17686 : : HeapTuple tuple;
17687 : : Oid orig_tablespaceoid;
17688 : : Oid new_tablespaceoid;
17689 : 16 : List *role_oids = roleSpecsToIds(stmt->roles);
17690 : :
17691 : : /* Ensure we were not asked to move something we can't */
17692 [ + + + + ]: 16 : if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17693 [ - + ]: 6 : stmt->objtype != OBJECT_MATVIEW)
17694 [ # # ]: 0 : ereport(ERROR,
17695 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17696 : : errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17697 : :
17698 : : /* Get the orig and new tablespace OIDs */
17699 : 16 : orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17700 : 16 : new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17701 : :
17702 : : /* Can't move shared relations in to or out of pg_global */
17703 : : /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17704 [ + - - + ]: 16 : if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
17705 : : new_tablespaceoid == GLOBALTABLESPACE_OID)
17706 [ # # ]: 0 : ereport(ERROR,
17707 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17708 : : errmsg("cannot move relations in to or out of pg_global tablespace")));
17709 : :
17710 : : /*
17711 : : * Must have CREATE rights on the new tablespace, unless it is the
17712 : : * database default tablespace (which all users implicitly have CREATE
17713 : : * rights on).
17714 : : */
17715 [ + - + + ]: 16 : if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
17716 : : {
17717 : : AclResult aclresult;
17718 : :
17719 : 1 : aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
17720 : : ACL_CREATE);
17721 [ - + ]: 1 : if (aclresult != ACLCHECK_OK)
17722 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
17723 : 0 : get_tablespace_name(new_tablespaceoid));
17724 : : }
17725 : :
17726 : : /*
17727 : : * Now that the checks are done, check if we should set either to
17728 : : * InvalidOid because it is our database's default tablespace.
17729 : : */
17730 [ + + ]: 16 : if (orig_tablespaceoid == MyDatabaseTableSpace)
17731 : 1 : orig_tablespaceoid = InvalidOid;
17732 : :
17733 [ + + ]: 16 : if (new_tablespaceoid == MyDatabaseTableSpace)
17734 : 15 : new_tablespaceoid = InvalidOid;
17735 : :
17736 : : /* no-op */
17737 [ - + ]: 16 : if (orig_tablespaceoid == new_tablespaceoid)
17738 : 0 : return new_tablespaceoid;
17739 : :
17740 : : /*
17741 : : * Walk the list of objects in the tablespace and move them. This will
17742 : : * only find objects in our database, of course.
17743 : : */
17744 : 16 : ScanKeyInit(&key[0],
17745 : : Anum_pg_class_reltablespace,
17746 : : BTEqualStrategyNumber, F_OIDEQ,
17747 : : ObjectIdGetDatum(orig_tablespaceoid));
17748 : :
17749 : 16 : rel = table_open(RelationRelationId, AccessShareLock);
17750 : 16 : scan = table_beginscan_catalog(rel, 1, key);
17751 [ + + ]: 448 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17752 : : {
17753 : 432 : Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
17754 : 432 : Oid relOid = relForm->oid;
17755 : :
17756 : : /*
17757 : : * Do not move objects in pg_catalog as part of this, if an admin
17758 : : * really wishes to do so, they can issue the individual ALTER
17759 : : * commands directly.
17760 : : *
17761 : : * Also, explicitly avoid any shared tables, temp tables, TOAST (TOAST
17762 : : * will be moved with the main table).
17763 : : *
17764 : : * Conflict log tables are system-managed for logical replication and
17765 : : * cannot be altered directly, so skip them as well; otherwise a
17766 : : * single such table in the source tablespace would abort the whole
17767 : : * bulk move.
17768 : : */
17769 [ + + ]: 432 : if (IsCatalogNamespace(relForm->relnamespace) ||
17770 [ + - + - ]: 376 : relForm->relisshared ||
17771 [ + + ]: 376 : isAnyTempNamespace(relForm->relnamespace) ||
17772 [ + + ]: 310 : IsToastNamespace(relForm->relnamespace) ||
17773 : 122 : IsConflictLogTableNamespace(relForm->relnamespace))
17774 : 311 : continue;
17775 : :
17776 : : /* Only move the object type requested */
17777 [ + + ]: 121 : if ((stmt->objtype == OBJECT_TABLE &&
17778 [ + + ]: 100 : relForm->relkind != RELKIND_RELATION &&
17779 [ - + ]: 83 : relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17780 [ + + ]: 38 : (stmt->objtype == OBJECT_INDEX &&
17781 [ + + ]: 18 : relForm->relkind != RELKIND_INDEX &&
17782 [ - + ]: 3 : relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17783 [ + + ]: 35 : (stmt->objtype == OBJECT_MATVIEW &&
17784 [ - + ]: 3 : relForm->relkind != RELKIND_MATVIEW))
17785 : 86 : continue;
17786 : :
17787 : : /* Check if we are only moving objects owned by certain roles */
17788 [ - + - - ]: 35 : if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17789 : 0 : continue;
17790 : :
17791 : : /*
17792 : : * Handle permissions-checking here since we are locking the tables
17793 : : * and also to avoid doing a bunch of work only to fail part-way. Note
17794 : : * that permissions will also be checked by AlterTableInternal().
17795 : : *
17796 : : * Caller must be considered an owner on the table to move it.
17797 : : */
17798 [ - + ]: 35 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17799 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
17800 : 0 : NameStr(relForm->relname));
17801 : :
17802 [ - + ]: 35 : if (stmt->nowait &&
17803 [ # # ]: 0 : !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
17804 [ # # ]: 0 : ereport(ERROR,
17805 : : (errcode(ERRCODE_OBJECT_IN_USE),
17806 : : errmsg("aborting because lock on relation \"%s.%s\" is not available",
17807 : : get_namespace_name(relForm->relnamespace),
17808 : : NameStr(relForm->relname))));
17809 : : else
17810 : 35 : LockRelationOid(relOid, AccessExclusiveLock);
17811 : :
17812 : : /* Add to our list of objects to move */
17813 : 35 : relations = lappend_oid(relations, relOid);
17814 : : }
17815 : :
17816 : 16 : table_endscan(scan);
17817 : 16 : table_close(rel, AccessShareLock);
17818 : :
17819 [ + + ]: 16 : if (relations == NIL)
17820 [ + - + - ]: 6 : ereport(NOTICE,
17821 : : (errcode(ERRCODE_NO_DATA_FOUND),
17822 : : errmsg("no matching relations in tablespace \"%s\" found",
17823 : : orig_tablespaceoid == InvalidOid ? "(database default)" :
17824 : : get_tablespace_name(orig_tablespaceoid))));
17825 : :
17826 : : /* Everything is locked, loop through and move all of the relations. */
17827 [ + + + + : 51 : foreach(l, relations)
+ + ]
17828 : : {
17829 : 35 : List *cmds = NIL;
17830 : 35 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
17831 : :
17832 : 35 : cmd->subtype = AT_SetTableSpace;
17833 : 35 : cmd->name = stmt->new_tablespacename;
17834 : :
17835 : 35 : cmds = lappend(cmds, cmd);
17836 : :
17837 : 35 : EventTriggerAlterTableStart((Node *) stmt);
17838 : : /* OID is set by AlterTableInternal */
17839 : 35 : AlterTableInternal(lfirst_oid(l), cmds, false);
17840 : 35 : EventTriggerAlterTableEnd();
17841 : : }
17842 : :
17843 : 16 : return new_tablespaceoid;
17844 : : }
17845 : :
17846 : : static void
17847 : 40 : index_copy_data(Relation rel, RelFileLocator newrlocator)
17848 : : {
17849 : : SMgrRelation dstrel;
17850 : :
17851 : : /*
17852 : : * Since we copy the file directly without looking at the shared buffers,
17853 : : * we'd better first flush out any pages of the source relation that are
17854 : : * in shared buffers. We assume no new changes will be made while we are
17855 : : * holding exclusive lock on the rel.
17856 : : */
17857 : 40 : FlushRelationBuffers(rel);
17858 : :
17859 : : /*
17860 : : * Create and copy all forks of the relation, and schedule unlinking of
17861 : : * old physical files.
17862 : : *
17863 : : * NOTE: any conflict in relfilenumber value will be caught in
17864 : : * RelationCreateStorage().
17865 : : */
17866 : 40 : dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
17867 : :
17868 : : /* copy main fork */
17869 : 40 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
17870 : 40 : rel->rd_rel->relpersistence);
17871 : :
17872 : : /* copy those extra forks that exist */
17873 : 40 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
17874 [ + + ]: 160 : forkNum <= MAX_FORKNUM; forkNum++)
17875 : : {
17876 [ - + ]: 120 : if (smgrexists(RelationGetSmgr(rel), forkNum))
17877 : : {
17878 : 0 : smgrcreate(dstrel, forkNum, false);
17879 : :
17880 : : /*
17881 : : * WAL log creation if the relation is persistent, or this is the
17882 : : * init fork of an unlogged relation.
17883 : : */
17884 [ # # ]: 0 : if (RelationIsPermanent(rel) ||
17885 [ # # # # ]: 0 : (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
17886 : : forkNum == INIT_FORKNUM))
17887 : 0 : log_smgrcreate(&newrlocator, forkNum);
17888 : 0 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
17889 : 0 : rel->rd_rel->relpersistence);
17890 : : }
17891 : : }
17892 : :
17893 : : /* drop old relation, and close new one */
17894 : 40 : RelationDropStorage(rel);
17895 : 40 : smgrclose(dstrel);
17896 : 40 : }
17897 : :
17898 : : /*
17899 : : * ALTER TABLE ENABLE/DISABLE TRIGGER
17900 : : *
17901 : : * We just pass this off to trigger.c.
17902 : : */
17903 : : static void
17904 : 191 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
17905 : : char fires_when, bool skip_system, bool recurse,
17906 : : LOCKMODE lockmode)
17907 : : {
17908 : 191 : EnableDisableTrigger(rel, trigname, InvalidOid,
17909 : : fires_when, skip_system, recurse,
17910 : : lockmode);
17911 : :
17912 [ + + ]: 191 : InvokeObjectPostAlterHook(RelationRelationId,
17913 : : RelationGetRelid(rel), 0);
17914 : 191 : }
17915 : :
17916 : : /*
17917 : : * ALTER TABLE ENABLE/DISABLE RULE
17918 : : *
17919 : : * We just pass this off to rewriteDefine.c.
17920 : : */
17921 : : static void
17922 : 29 : ATExecEnableDisableRule(Relation rel, const char *rulename,
17923 : : char fires_when, LOCKMODE lockmode)
17924 : : {
17925 : 29 : EnableDisableRule(rel, rulename, fires_when);
17926 : :
17927 [ + + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
17928 : : RelationGetRelid(rel), 0);
17929 : 29 : }
17930 : :
17931 : : /*
17932 : : * Preparation phase of [NO] INHERIT
17933 : : *
17934 : : * Check the relation defined as a child.
17935 : : */
17936 : : static void
17937 : 370 : ATPrepChangeInherit(Relation child_rel)
17938 : : {
17939 [ + + ]: 370 : if (child_rel->rd_rel->reloftype)
17940 [ + - ]: 8 : ereport(ERROR,
17941 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17942 : : errmsg("cannot change inheritance of typed table")));
17943 : :
17944 [ + + ]: 362 : if (child_rel->rd_rel->relispartition)
17945 [ + - ]: 12 : ereport(ERROR,
17946 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17947 : : errmsg("cannot change inheritance of a partition")));
17948 : 350 : }
17949 : :
17950 : : /*
17951 : : * ALTER TABLE INHERIT
17952 : : *
17953 : : * Return the address of the new parent relation.
17954 : : */
17955 : : static ObjectAddress
17956 : 289 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
17957 : : {
17958 : : Relation parent_rel;
17959 : : List *children;
17960 : : ObjectAddress address;
17961 : : const char *trigger_name;
17962 : :
17963 : : /*
17964 : : * A self-exclusive lock is needed here. See the similar case in
17965 : : * MergeAttributes() for a full explanation.
17966 : : */
17967 : 289 : parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
17968 : :
17969 : : /*
17970 : : * Must be owner of both parent and child -- child was checked by
17971 : : * ATSimplePermissions call in ATPrepCmd
17972 : : */
17973 : 289 : ATSimplePermissions(AT_AddInherit, parent_rel,
17974 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
17975 : :
17976 : : /* Permanent rels cannot inherit from temporary ones */
17977 [ + + ]: 289 : if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17978 [ - + ]: 4 : child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
17979 [ # # ]: 0 : ereport(ERROR,
17980 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17981 : : errmsg("cannot inherit from temporary relation \"%s\"",
17982 : : RelationGetRelationName(parent_rel))));
17983 : :
17984 : : /* If parent rel is temp, it must belong to this session */
17985 [ + + - + ]: 289 : if (RELATION_IS_OTHER_TEMP(parent_rel))
17986 [ # # ]: 0 : ereport(ERROR,
17987 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17988 : : errmsg("cannot inherit from temporary relation of another session")));
17989 : :
17990 : : /* Ditto for the child */
17991 [ + + - + ]: 289 : if (RELATION_IS_OTHER_TEMP(child_rel))
17992 [ # # ]: 0 : ereport(ERROR,
17993 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17994 : : errmsg("cannot inherit to temporary relation of another session")));
17995 : :
17996 : : /* Prevent partitioned tables from becoming inheritance parents */
17997 [ + + ]: 289 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17998 [ + - ]: 4 : ereport(ERROR,
17999 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18000 : : errmsg("cannot inherit from partitioned table \"%s\"",
18001 : : parent->relname)));
18002 : :
18003 : : /* Likewise for partitions */
18004 [ + + ]: 285 : if (parent_rel->rd_rel->relispartition)
18005 [ + - ]: 4 : ereport(ERROR,
18006 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18007 : : errmsg("cannot inherit from a partition")));
18008 : :
18009 : : /*
18010 : : * Prevent circularity by seeing if proposed parent inherits from child.
18011 : : * (In particular, this disallows making a rel inherit from itself.)
18012 : : *
18013 : : * This is not completely bulletproof because of race conditions: in
18014 : : * multi-level inheritance trees, someone else could concurrently be
18015 : : * making another inheritance link that closes the loop but does not join
18016 : : * either of the rels we have locked. Preventing that seems to require
18017 : : * exclusive locks on the entire inheritance tree, which is a cure worse
18018 : : * than the disease. find_all_inheritors() will cope with circularity
18019 : : * anyway, so don't sweat it too much.
18020 : : *
18021 : : * We use weakest lock we can on child's children, namely AccessShareLock.
18022 : : */
18023 : 281 : children = find_all_inheritors(RelationGetRelid(child_rel),
18024 : : AccessShareLock, NULL);
18025 : :
18026 [ + + ]: 281 : if (list_member_oid(children, RelationGetRelid(parent_rel)))
18027 [ + - ]: 8 : ereport(ERROR,
18028 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18029 : : errmsg("circular inheritance not allowed"),
18030 : : errdetail("\"%s\" is already a child of \"%s\".",
18031 : : parent->relname,
18032 : : RelationGetRelationName(child_rel))));
18033 : :
18034 : : /*
18035 : : * If child_rel has row-level triggers with transition tables, we
18036 : : * currently don't allow it to become an inheritance child. See also
18037 : : * prohibitions in ATExecAttachPartition() and CreateTrigger().
18038 : : */
18039 : 273 : trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
18040 [ + + ]: 273 : if (trigger_name != NULL)
18041 [ + - ]: 4 : ereport(ERROR,
18042 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18043 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
18044 : : trigger_name, RelationGetRelationName(child_rel)),
18045 : : errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
18046 : :
18047 : : /* OK to create inheritance */
18048 : 269 : CreateInheritance(child_rel, parent_rel, false);
18049 : :
18050 : 209 : ObjectAddressSet(address, RelationRelationId,
18051 : : RelationGetRelid(parent_rel));
18052 : :
18053 : : /* keep our lock on the parent relation until commit */
18054 : 209 : table_close(parent_rel, NoLock);
18055 : :
18056 : 209 : return address;
18057 : : }
18058 : :
18059 : : /*
18060 : : * CreateInheritance
18061 : : * Catalog manipulation portion of creating inheritance between a child
18062 : : * table and a parent table.
18063 : : *
18064 : : * This verifies that all the columns and check constraints of the parent
18065 : : * appear in the child and that they have the same data types and expressions.
18066 : : *
18067 : : * Common to ATExecAddInherit() and ATExecAttachPartition().
18068 : : */
18069 : : static void
18070 : 1698 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
18071 : : {
18072 : : Relation catalogRelation;
18073 : : SysScanDesc scan;
18074 : : ScanKeyData key;
18075 : : HeapTuple inheritsTuple;
18076 : : int32 inhseqno;
18077 : :
18078 : : /* Note: get RowExclusiveLock because we will write pg_inherits below. */
18079 : 1698 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18080 : :
18081 : : /*
18082 : : * Check for duplicates in the list of parents, and determine the highest
18083 : : * inhseqno already present; we'll use the next one for the new parent.
18084 : : * Also, if proposed child is a partition, it cannot already be
18085 : : * inheriting.
18086 : : *
18087 : : * Note: we do not reject the case where the child already inherits from
18088 : : * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
18089 : : */
18090 : 1698 : ScanKeyInit(&key,
18091 : : Anum_pg_inherits_inhrelid,
18092 : : BTEqualStrategyNumber, F_OIDEQ,
18093 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18094 : 1698 : scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
18095 : : true, NULL, 1, &key);
18096 : :
18097 : : /* inhseqno sequences start at 1 */
18098 : 1698 : inhseqno = 0;
18099 [ + + ]: 1749 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18100 : : {
18101 : 55 : Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18102 : :
18103 [ + + ]: 55 : if (inh->inhparent == RelationGetRelid(parent_rel))
18104 [ + - ]: 4 : ereport(ERROR,
18105 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18106 : : errmsg("relation \"%s\" would be inherited from more than once",
18107 : : RelationGetRelationName(parent_rel))));
18108 : :
18109 [ + - ]: 51 : if (inh->inhseqno > inhseqno)
18110 : 51 : inhseqno = inh->inhseqno;
18111 : : }
18112 : 1694 : systable_endscan(scan);
18113 : :
18114 : : /* Match up the columns and bump attinhcount as needed */
18115 : 1694 : MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
18116 : :
18117 : : /* Match up the constraints and bump coninhcount as needed */
18118 : 1606 : MergeConstraintsIntoExisting(child_rel, parent_rel);
18119 : :
18120 : : /*
18121 : : * OK, it looks valid. Make the catalog entries that show inheritance.
18122 : : */
18123 : 1566 : StoreCatalogInheritance1(RelationGetRelid(child_rel),
18124 : : RelationGetRelid(parent_rel),
18125 : : inhseqno + 1,
18126 : : catalogRelation,
18127 : 1566 : parent_rel->rd_rel->relkind ==
18128 : : RELKIND_PARTITIONED_TABLE);
18129 : :
18130 : : /* Now we're done with pg_inherits */
18131 : 1566 : table_close(catalogRelation, RowExclusiveLock);
18132 : 1566 : }
18133 : :
18134 : : /*
18135 : : * Obtain the source-text form of the constraint expression for a check
18136 : : * constraint, given its pg_constraint tuple
18137 : : */
18138 : : static char *
18139 : 480 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
18140 : : {
18141 : : Form_pg_constraint con;
18142 : : bool isnull;
18143 : : Datum attr;
18144 : : Datum expr;
18145 : :
18146 : 480 : con = (Form_pg_constraint) GETSTRUCT(contup);
18147 : 480 : attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
18148 [ - + ]: 480 : if (isnull)
18149 [ # # ]: 0 : elog(ERROR, "null conbin for constraint %u", con->oid);
18150 : :
18151 : 480 : expr = DirectFunctionCall2(pg_get_expr, attr,
18152 : : ObjectIdGetDatum(con->conrelid));
18153 : 480 : return TextDatumGetCString(expr);
18154 : : }
18155 : :
18156 : : /*
18157 : : * Determine whether two check constraints are functionally equivalent
18158 : : *
18159 : : * The test we apply is to see whether they reverse-compile to the same
18160 : : * source string. This insulates us from issues like whether attributes
18161 : : * have the same physical column numbers in parent and child relations.
18162 : : *
18163 : : * Note that we ignore enforceability as there are cases where constraints
18164 : : * with differing enforceability are allowed.
18165 : : */
18166 : : static bool
18167 : 240 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
18168 : : {
18169 : 240 : Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
18170 : 240 : Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
18171 : :
18172 [ + - ]: 240 : if (acon->condeferrable != bcon->condeferrable ||
18173 [ + - ]: 240 : acon->condeferred != bcon->condeferred ||
18174 [ + + ]: 240 : strcmp(decompile_conbin(a, tupleDesc),
18175 : 240 : decompile_conbin(b, tupleDesc)) != 0)
18176 : 4 : return false;
18177 : : else
18178 : 236 : return true;
18179 : : }
18180 : :
18181 : : /*
18182 : : * Check columns in child table match up with columns in parent, and increment
18183 : : * their attinhcount.
18184 : : *
18185 : : * Called by CreateInheritance
18186 : : *
18187 : : * Currently all parent columns must be found in child. Missing columns are an
18188 : : * error. One day we might consider creating new columns like CREATE TABLE
18189 : : * does. However, that is widely unpopular --- in the common use case of
18190 : : * partitioned tables it's a foot-gun.
18191 : : *
18192 : : * The data type must match exactly. If the parent column is NOT NULL then
18193 : : * the child must be as well. Defaults are not compared, however.
18194 : : */
18195 : : static void
18196 : 1694 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
18197 : : {
18198 : : Relation attrrel;
18199 : : TupleDesc parent_desc;
18200 : :
18201 : 1694 : attrrel = table_open(AttributeRelationId, RowExclusiveLock);
18202 : 1694 : parent_desc = RelationGetDescr(parent_rel);
18203 : :
18204 [ + + ]: 5373 : for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
18205 : : {
18206 : 3767 : Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
18207 : 3767 : char *parent_attname = NameStr(parent_att->attname);
18208 : : HeapTuple tuple;
18209 : :
18210 : : /* Ignore dropped columns in the parent. */
18211 [ + + ]: 3767 : if (parent_att->attisdropped)
18212 : 180 : continue;
18213 : :
18214 : : /* Find same column in child (matching on column name). */
18215 : 3587 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
18216 [ + + ]: 3587 : if (HeapTupleIsValid(tuple))
18217 : : {
18218 : 3579 : Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
18219 : :
18220 [ + + ]: 3579 : if (parent_att->atttypid != child_att->atttypid ||
18221 [ + + ]: 3575 : parent_att->atttypmod != child_att->atttypmod)
18222 [ + - ]: 8 : ereport(ERROR,
18223 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18224 : : errmsg("child table \"%s\" has different type for column \"%s\"",
18225 : : RelationGetRelationName(child_rel), parent_attname)));
18226 : :
18227 [ + + ]: 3571 : if (parent_att->attcollation != child_att->attcollation)
18228 [ + - ]: 4 : ereport(ERROR,
18229 : : (errcode(ERRCODE_COLLATION_MISMATCH),
18230 : : errmsg("child table \"%s\" has different collation for column \"%s\"",
18231 : : RelationGetRelationName(child_rel), parent_attname)));
18232 : :
18233 : : /*
18234 : : * If the parent has a not-null constraint that's not NO INHERIT,
18235 : : * make sure the child has one too.
18236 : : *
18237 : : * Other constraints are checked elsewhere.
18238 : : */
18239 [ + + + + ]: 3567 : if (parent_att->attnotnull && !child_att->attnotnull)
18240 : : {
18241 : : HeapTuple contup;
18242 : :
18243 : 32 : contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
18244 : 32 : parent_att->attnum);
18245 [ + - ]: 32 : if (HeapTupleIsValid(contup) &&
18246 [ + + ]: 32 : !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
18247 [ + - ]: 20 : ereport(ERROR,
18248 : : errcode(ERRCODE_DATATYPE_MISMATCH),
18249 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18250 : : parent_attname, RelationGetRelationName(child_rel)));
18251 : : }
18252 : :
18253 : : /*
18254 : : * Child column must be generated if and only if parent column is.
18255 : : */
18256 [ + + + + ]: 3547 : if (parent_att->attgenerated && !child_att->attgenerated)
18257 [ + - ]: 24 : ereport(ERROR,
18258 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18259 : : errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
18260 [ + + + + ]: 3523 : if (child_att->attgenerated && !parent_att->attgenerated)
18261 [ + - ]: 16 : ereport(ERROR,
18262 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18263 : : errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
18264 : :
18265 [ + + + - : 3507 : if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
+ + ]
18266 [ + - + + : 8 : ereport(ERROR,
+ + ]
18267 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18268 : : errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
18269 : : errdetail("Parent column is %s, child column is %s.",
18270 : : parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
18271 : : child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
18272 : :
18273 : : /*
18274 : : * Regular inheritance children are independent enough not to
18275 : : * inherit identity columns. But partitions are integral part of
18276 : : * a partitioned table and inherit identity column.
18277 : : */
18278 [ + + ]: 3499 : if (ispartition)
18279 : 3046 : child_att->attidentity = parent_att->attidentity;
18280 : :
18281 : : /*
18282 : : * OK, bump the child column's inheritance count. (If we fail
18283 : : * later on, this change will just roll back.)
18284 : : */
18285 [ - + ]: 3499 : if (pg_add_s16_overflow(child_att->attinhcount, 1,
18286 : : &child_att->attinhcount))
18287 [ # # ]: 0 : ereport(ERROR,
18288 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18289 : : errmsg("too many inheritance parents"));
18290 : :
18291 : : /*
18292 : : * In case of partitions, we must enforce that value of attislocal
18293 : : * is same in all partitions. (Note: there are only inherited
18294 : : * attributes in partitions)
18295 : : */
18296 [ + + ]: 3499 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18297 : : {
18298 : : Assert(child_att->attinhcount == 1);
18299 : 3046 : child_att->attislocal = false;
18300 : : }
18301 : :
18302 : 3499 : CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
18303 : 3499 : heap_freetuple(tuple);
18304 : : }
18305 : : else
18306 : : {
18307 [ + - ]: 8 : ereport(ERROR,
18308 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18309 : : errmsg("child table is missing column \"%s\"", parent_attname)));
18310 : : }
18311 : : }
18312 : :
18313 : 1606 : table_close(attrrel, RowExclusiveLock);
18314 : 1606 : }
18315 : :
18316 : : /*
18317 : : * Check constraints in child table match up with constraints in parent,
18318 : : * and increment their coninhcount.
18319 : : *
18320 : : * Constraints that are marked ONLY in the parent are ignored.
18321 : : *
18322 : : * Called by CreateInheritance
18323 : : *
18324 : : * Currently all constraints in parent must be present in the child. One day we
18325 : : * may consider adding new constraints like CREATE TABLE does.
18326 : : *
18327 : : * XXX This is O(N^2) which may be an issue with tables with hundreds of
18328 : : * constraints. As long as tables have more like 10 constraints it shouldn't be
18329 : : * a problem though. Even 100 constraints ought not be the end of the world.
18330 : : *
18331 : : * XXX See MergeWithExistingConstraint too if you change this code.
18332 : : */
18333 : : static void
18334 : 1606 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
18335 : : {
18336 : : Relation constraintrel;
18337 : : SysScanDesc parent_scan;
18338 : : ScanKeyData parent_key;
18339 : : HeapTuple parent_tuple;
18340 : 1606 : Oid parent_relid = RelationGetRelid(parent_rel);
18341 : : AttrMap *attmap;
18342 : :
18343 : 1606 : constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
18344 : :
18345 : : /* Outer loop scans through the parent's constraint definitions */
18346 : 1606 : ScanKeyInit(&parent_key,
18347 : : Anum_pg_constraint_conrelid,
18348 : : BTEqualStrategyNumber, F_OIDEQ,
18349 : : ObjectIdGetDatum(parent_relid));
18350 : 1606 : parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
18351 : : true, NULL, 1, &parent_key);
18352 : :
18353 : 1606 : attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
18354 : : RelationGetDescr(child_rel),
18355 : : true);
18356 : :
18357 [ + + ]: 2889 : while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
18358 : : {
18359 : 1323 : Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
18360 : : SysScanDesc child_scan;
18361 : : ScanKeyData child_key;
18362 : : HeapTuple child_tuple;
18363 : : AttrNumber parent_attno;
18364 : 1323 : bool found = false;
18365 : :
18366 [ + + ]: 1323 : if (parent_con->contype != CONSTRAINT_CHECK &&
18367 [ + + ]: 1207 : parent_con->contype != CONSTRAINT_NOTNULL)
18368 : 650 : continue;
18369 : :
18370 : : /* if the parent's constraint is marked NO INHERIT, it's not inherited */
18371 [ + + ]: 705 : if (parent_con->connoinherit)
18372 : 32 : continue;
18373 : :
18374 [ + + ]: 673 : if (parent_con->contype == CONSTRAINT_NOTNULL)
18375 : 573 : parent_attno = extractNotNullColumn(parent_tuple);
18376 : : else
18377 : 100 : parent_attno = InvalidAttrNumber;
18378 : :
18379 : : /* Search for a child constraint matching this one */
18380 : 673 : ScanKeyInit(&child_key,
18381 : : Anum_pg_constraint_conrelid,
18382 : : BTEqualStrategyNumber, F_OIDEQ,
18383 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18384 : 673 : child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
18385 : : true, NULL, 1, &child_key);
18386 : :
18387 [ + + ]: 1060 : while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
18388 : : {
18389 : 1044 : Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
18390 : : HeapTuple child_copy;
18391 : :
18392 [ + + ]: 1044 : if (child_con->contype != parent_con->contype)
18393 : 186 : continue;
18394 : :
18395 : : /*
18396 : : * CHECK constraint are matched by constraint name, NOT NULL ones
18397 : : * by attribute number.
18398 : : */
18399 [ + + ]: 858 : if (child_con->contype == CONSTRAINT_CHECK)
18400 : : {
18401 : 130 : if (strcmp(NameStr(parent_con->conname),
18402 [ + + ]: 107 : NameStr(child_con->conname)) != 0)
18403 : 23 : continue;
18404 : : }
18405 [ + - ]: 751 : else if (child_con->contype == CONSTRAINT_NOTNULL)
18406 : : {
18407 : : Form_pg_attribute parent_attr;
18408 : : Form_pg_attribute child_attr;
18409 : : AttrNumber child_attno;
18410 : :
18411 : 751 : parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
18412 : 751 : child_attno = extractNotNullColumn(child_tuple);
18413 [ + + ]: 751 : if (parent_attno != attmap->attnums[child_attno - 1])
18414 : 178 : continue;
18415 : :
18416 : 573 : child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
18417 : : /* there shouldn't be constraints on dropped columns */
18418 [ + - - + ]: 573 : if (parent_attr->attisdropped || child_attr->attisdropped)
18419 [ # # ]: 0 : elog(ERROR, "found not-null constraint on dropped columns");
18420 : : }
18421 : :
18422 [ + + ]: 657 : if (child_con->contype == CONSTRAINT_CHECK &&
18423 [ + + ]: 84 : !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
18424 [ + - ]: 4 : ereport(ERROR,
18425 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18426 : : errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
18427 : : RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
18428 : :
18429 : : /*
18430 : : * If the child constraint is "no inherit" then cannot merge
18431 : : */
18432 [ + + ]: 653 : if (child_con->connoinherit)
18433 [ + - ]: 8 : ereport(ERROR,
18434 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18435 : : errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
18436 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18437 : :
18438 : : /*
18439 : : * If the child constraint is "not valid" then cannot merge with a
18440 : : * valid parent constraint
18441 : : */
18442 [ + + + + ]: 645 : if (parent_con->convalidated && child_con->conenforced &&
18443 [ + + ]: 593 : !child_con->convalidated)
18444 [ + - ]: 8 : ereport(ERROR,
18445 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18446 : : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
18447 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18448 : :
18449 : : /*
18450 : : * A NOT ENFORCED child constraint cannot be merged with an
18451 : : * ENFORCED parent constraint. However, the reverse is allowed,
18452 : : * where the child constraint is ENFORCED.
18453 : : */
18454 [ + + + + ]: 637 : if (parent_con->conenforced && !child_con->conenforced)
18455 [ + - ]: 4 : ereport(ERROR,
18456 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18457 : : errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
18458 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18459 : :
18460 : : /*
18461 : : * OK, bump the child constraint's inheritance count. (If we fail
18462 : : * later on, this change will just roll back.)
18463 : : */
18464 : 633 : child_copy = heap_copytuple(child_tuple);
18465 : 633 : child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
18466 : :
18467 [ - + ]: 633 : if (pg_add_s16_overflow(child_con->coninhcount, 1,
18468 : : &child_con->coninhcount))
18469 [ # # ]: 0 : ereport(ERROR,
18470 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18471 : : errmsg("too many inheritance parents"));
18472 : :
18473 : : /*
18474 : : * In case of partitions, an inherited constraint must be
18475 : : * inherited only once since it cannot have multiple parents and
18476 : : * it is never considered local.
18477 : : */
18478 [ + + ]: 633 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18479 : : {
18480 : : Assert(child_con->coninhcount == 1);
18481 : 530 : child_con->conislocal = false;
18482 : : }
18483 : :
18484 : 633 : CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
18485 : 633 : heap_freetuple(child_copy);
18486 : :
18487 : 633 : found = true;
18488 : 633 : break;
18489 : : }
18490 : :
18491 : 649 : systable_endscan(child_scan);
18492 : :
18493 [ + + ]: 649 : if (!found)
18494 : : {
18495 [ - + ]: 16 : if (parent_con->contype == CONSTRAINT_NOTNULL)
18496 [ # # ]: 0 : ereport(ERROR,
18497 : : errcode(ERRCODE_DATATYPE_MISMATCH),
18498 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18499 : : get_attname(parent_relid,
18500 : : extractNotNullColumn(parent_tuple),
18501 : : false),
18502 : : RelationGetRelationName(child_rel)));
18503 : :
18504 [ + - ]: 16 : ereport(ERROR,
18505 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18506 : : errmsg("child table is missing constraint \"%s\"",
18507 : : NameStr(parent_con->conname))));
18508 : : }
18509 : : }
18510 : :
18511 : 1566 : systable_endscan(parent_scan);
18512 : 1566 : table_close(constraintrel, RowExclusiveLock);
18513 : 1566 : }
18514 : :
18515 : : /*
18516 : : * ALTER TABLE NO INHERIT
18517 : : *
18518 : : * Return value is the address of the relation that is no longer parent.
18519 : : */
18520 : : static ObjectAddress
18521 : 61 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
18522 : : {
18523 : : ObjectAddress address;
18524 : : Relation parent_rel;
18525 : :
18526 : : /*
18527 : : * AccessShareLock on the parent is probably enough, seeing that DROP
18528 : : * TABLE doesn't lock parent tables at all. We need some lock since we'll
18529 : : * be inspecting the parent's schema.
18530 : : */
18531 : 61 : parent_rel = table_openrv(parent, AccessShareLock);
18532 : :
18533 : : /*
18534 : : * We don't bother to check ownership of the parent table --- ownership of
18535 : : * the child is presumed enough rights.
18536 : : */
18537 : :
18538 : : /* Off to RemoveInheritance() where most of the work happens */
18539 : 61 : RemoveInheritance(rel, parent_rel, false);
18540 : :
18541 : 57 : ObjectAddressSet(address, RelationRelationId,
18542 : : RelationGetRelid(parent_rel));
18543 : :
18544 : : /* keep our lock on the parent relation until commit */
18545 : 57 : table_close(parent_rel, NoLock);
18546 : :
18547 : 57 : return address;
18548 : : }
18549 : :
18550 : : /*
18551 : : * MarkInheritDetached
18552 : : *
18553 : : * Set inhdetachpending for a partition, for ATExecDetachPartition
18554 : : * in concurrent mode. While at it, verify that no other partition is
18555 : : * already pending detach.
18556 : : */
18557 : : static void
18558 : 76 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
18559 : : {
18560 : : Relation catalogRelation;
18561 : : SysScanDesc scan;
18562 : : ScanKeyData key;
18563 : : HeapTuple inheritsTuple;
18564 : 76 : bool found = false;
18565 : :
18566 : : Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18567 : :
18568 : : /*
18569 : : * Find pg_inherits entries by inhparent. (We need to scan them all in
18570 : : * order to verify that no other partition is pending detach.)
18571 : : */
18572 : 76 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18573 : 76 : ScanKeyInit(&key,
18574 : : Anum_pg_inherits_inhparent,
18575 : : BTEqualStrategyNumber, F_OIDEQ,
18576 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18577 : 76 : scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
18578 : : true, NULL, 1, &key);
18579 : :
18580 [ + + ]: 298 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18581 : : {
18582 : : Form_pg_inherits inhForm;
18583 : :
18584 : 147 : inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18585 [ + + ]: 147 : if (inhForm->inhdetachpending)
18586 [ + - ]: 1 : ereport(ERROR,
18587 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
18588 : : errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
18589 : : get_rel_name(inhForm->inhrelid),
18590 : : get_namespace_name(parent_rel->rd_rel->relnamespace),
18591 : : RelationGetRelationName(parent_rel)),
18592 : : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
18593 : :
18594 [ + + ]: 146 : if (inhForm->inhrelid == RelationGetRelid(child_rel))
18595 : : {
18596 : : HeapTuple newtup;
18597 : :
18598 : 75 : newtup = heap_copytuple(inheritsTuple);
18599 : 75 : ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
18600 : :
18601 : 75 : CatalogTupleUpdate(catalogRelation,
18602 : 75 : &inheritsTuple->t_self,
18603 : : newtup);
18604 : 75 : found = true;
18605 : 75 : heap_freetuple(newtup);
18606 : : /* keep looking, to ensure we catch others pending detach */
18607 : : }
18608 : : }
18609 : :
18610 : : /* Done */
18611 : 75 : systable_endscan(scan);
18612 : 75 : table_close(catalogRelation, RowExclusiveLock);
18613 : :
18614 [ - + ]: 75 : if (!found)
18615 [ # # ]: 0 : ereport(ERROR,
18616 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18617 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18618 : : RelationGetRelationName(child_rel),
18619 : : RelationGetRelationName(parent_rel))));
18620 : 75 : }
18621 : :
18622 : : /*
18623 : : * RemoveInheritance
18624 : : *
18625 : : * Drop a parent from the child's parents. This just adjusts the attinhcount
18626 : : * and attislocal of the columns and removes the pg_inherit and pg_depend
18627 : : * entries. expect_detached is passed down to DeleteInheritsTuple, q.v..
18628 : : *
18629 : : * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
18630 : : * up attislocal stays true, which means if a child is ever removed from a
18631 : : * parent then its columns will never be automatically dropped which may
18632 : : * surprise. But at least we'll never surprise by dropping columns someone
18633 : : * isn't expecting to be dropped which would actually mean data loss.
18634 : : *
18635 : : * coninhcount and conislocal for inherited constraints are adjusted in
18636 : : * exactly the same way.
18637 : : *
18638 : : * Common to ATExecDropInherit() and ATExecDetachPartition().
18639 : : */
18640 : : static void
18641 : 385 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
18642 : : {
18643 : : Relation catalogRelation;
18644 : : SysScanDesc scan;
18645 : : ScanKeyData key[3];
18646 : : HeapTuple attributeTuple,
18647 : : constraintTuple;
18648 : : AttrMap *attmap;
18649 : : List *connames;
18650 : : List *nncolumns;
18651 : : bool found;
18652 : : bool is_partitioning;
18653 : :
18654 : 385 : is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18655 : :
18656 : 385 : found = DeleteInheritsTuple(RelationGetRelid(child_rel),
18657 : : RelationGetRelid(parent_rel),
18658 : : expect_detached,
18659 : 385 : RelationGetRelationName(child_rel));
18660 [ + + ]: 385 : if (!found)
18661 : : {
18662 [ + + ]: 16 : if (is_partitioning)
18663 [ + - ]: 12 : ereport(ERROR,
18664 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18665 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18666 : : RelationGetRelationName(child_rel),
18667 : : RelationGetRelationName(parent_rel))));
18668 : : else
18669 [ + - ]: 4 : ereport(ERROR,
18670 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18671 : : errmsg("relation \"%s\" is not a parent of relation \"%s\"",
18672 : : RelationGetRelationName(parent_rel),
18673 : : RelationGetRelationName(child_rel))));
18674 : : }
18675 : :
18676 : : /*
18677 : : * Search through child columns looking for ones matching parent rel
18678 : : */
18679 : 369 : catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
18680 : 369 : ScanKeyInit(&key[0],
18681 : : Anum_pg_attribute_attrelid,
18682 : : BTEqualStrategyNumber, F_OIDEQ,
18683 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18684 : 369 : scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
18685 : : true, NULL, 1, key);
18686 [ + + ]: 3308 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
18687 : : {
18688 : 2939 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
18689 : :
18690 : : /* Ignore if dropped or not inherited */
18691 [ + + ]: 2939 : if (att->attisdropped)
18692 : 4 : continue;
18693 [ + + ]: 2935 : if (att->attinhcount <= 0)
18694 : 2234 : continue;
18695 : :
18696 [ + + ]: 701 : if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
18697 : 701 : NameStr(att->attname)))
18698 : : {
18699 : : /* Decrement inhcount and possibly set islocal to true */
18700 : 665 : HeapTuple copyTuple = heap_copytuple(attributeTuple);
18701 : 665 : Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
18702 : :
18703 : 665 : copy_att->attinhcount--;
18704 [ + + ]: 665 : if (copy_att->attinhcount == 0)
18705 : 645 : copy_att->attislocal = true;
18706 : :
18707 : 665 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18708 : 665 : heap_freetuple(copyTuple);
18709 : : }
18710 : : }
18711 : 369 : systable_endscan(scan);
18712 : 369 : table_close(catalogRelation, RowExclusiveLock);
18713 : :
18714 : : /*
18715 : : * Likewise, find inherited check and not-null constraints and disinherit
18716 : : * them. To do this, we first need a list of the names of the parent's
18717 : : * check constraints. (We cheat a bit by only checking for name matches,
18718 : : * assuming that the expressions will match.)
18719 : : *
18720 : : * For NOT NULL columns, we store column numbers to match, mapping them in
18721 : : * to the child rel's attribute numbers.
18722 : : */
18723 : 369 : attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
18724 : : RelationGetDescr(parent_rel),
18725 : : false);
18726 : :
18727 : 369 : catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
18728 : 369 : ScanKeyInit(&key[0],
18729 : : Anum_pg_constraint_conrelid,
18730 : : BTEqualStrategyNumber, F_OIDEQ,
18731 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18732 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18733 : : true, NULL, 1, key);
18734 : :
18735 : 369 : connames = NIL;
18736 : 369 : nncolumns = NIL;
18737 : :
18738 [ + + ]: 794 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18739 : : {
18740 : 425 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18741 : :
18742 [ + + ]: 425 : if (con->connoinherit)
18743 : 68 : continue;
18744 : :
18745 [ + + ]: 357 : if (con->contype == CONSTRAINT_CHECK)
18746 : 8 : connames = lappend(connames, pstrdup(NameStr(con->conname)));
18747 [ + + ]: 357 : if (con->contype == CONSTRAINT_NOTNULL)
18748 : : {
18749 : 133 : AttrNumber parent_attno = extractNotNullColumn(constraintTuple);
18750 : :
18751 : 133 : nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
18752 : : }
18753 : : }
18754 : :
18755 : 369 : systable_endscan(scan);
18756 : :
18757 : : /* Now scan the child's constraints to find matches */
18758 : 369 : ScanKeyInit(&key[0],
18759 : : Anum_pg_constraint_conrelid,
18760 : : BTEqualStrategyNumber, F_OIDEQ,
18761 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18762 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18763 : : true, NULL, 1, key);
18764 : :
18765 [ + + ]: 790 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18766 : : {
18767 : 421 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18768 : 421 : bool match = false;
18769 : :
18770 : : /*
18771 : : * Match CHECK constraints by name, not-null constraints by column
18772 : : * number, and ignore all others.
18773 : : */
18774 [ + + ]: 421 : if (con->contype == CONSTRAINT_CHECK)
18775 : : {
18776 [ + + + + : 92 : foreach_ptr(char, chkname, connames)
+ + ]
18777 : : {
18778 [ + - ]: 12 : if (con->contype == CONSTRAINT_CHECK &&
18779 [ + + ]: 12 : strcmp(NameStr(con->conname), chkname) == 0)
18780 : : {
18781 : 8 : match = true;
18782 : 8 : connames = foreach_delete_current(connames, chkname);
18783 : 8 : break;
18784 : : }
18785 : : }
18786 : : }
18787 [ + + ]: 377 : else if (con->contype == CONSTRAINT_NOTNULL)
18788 : : {
18789 : 173 : AttrNumber child_attno = extractNotNullColumn(constraintTuple);
18790 : :
18791 [ + + + + : 350 : foreach_int(prevattno, nncolumns)
+ + ]
18792 : : {
18793 [ + + ]: 137 : if (prevattno == child_attno)
18794 : : {
18795 : 133 : match = true;
18796 : 133 : nncolumns = foreach_delete_current(nncolumns, prevattno);
18797 : 133 : break;
18798 : : }
18799 : : }
18800 : : }
18801 : : else
18802 : 204 : continue;
18803 : :
18804 [ + + ]: 217 : if (match)
18805 : : {
18806 : : /* Decrement inhcount and possibly set islocal to true */
18807 : 141 : HeapTuple copyTuple = heap_copytuple(constraintTuple);
18808 : 141 : Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
18809 : :
18810 [ - + ]: 141 : if (copy_con->coninhcount <= 0) /* shouldn't happen */
18811 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
18812 : : RelationGetRelid(child_rel), NameStr(copy_con->conname));
18813 : :
18814 : 141 : copy_con->coninhcount--;
18815 [ + + ]: 141 : if (copy_con->coninhcount == 0)
18816 : 129 : copy_con->conislocal = true;
18817 : :
18818 : 141 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18819 : 141 : heap_freetuple(copyTuple);
18820 : : }
18821 : : }
18822 : :
18823 : : /* We should have matched all constraints */
18824 [ + - - + ]: 369 : if (connames != NIL || nncolumns != NIL)
18825 [ # # ]: 0 : elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
18826 : : list_length(connames) + list_length(nncolumns),
18827 : : RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
18828 : :
18829 : 369 : systable_endscan(scan);
18830 : 369 : table_close(catalogRelation, RowExclusiveLock);
18831 : :
18832 [ + + ]: 369 : drop_parent_dependency(RelationGetRelid(child_rel),
18833 : : RelationRelationId,
18834 : : RelationGetRelid(parent_rel),
18835 : : child_dependency_type(is_partitioning));
18836 : :
18837 : : /*
18838 : : * Post alter hook of this inherits. Since object_access_hook doesn't take
18839 : : * multiple object identifiers, we relay oid of parent relation using
18840 : : * auxiliary_id argument.
18841 : : */
18842 [ - + ]: 369 : InvokeObjectPostAlterHookArg(InheritsRelationId,
18843 : : RelationGetRelid(child_rel), 0,
18844 : : RelationGetRelid(parent_rel), false);
18845 : 369 : }
18846 : :
18847 : : /*
18848 : : * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
18849 : : * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
18850 : : * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
18851 : : * be TypeRelationId). There's no convenient way to do this, so go trawling
18852 : : * through pg_depend.
18853 : : */
18854 : : static void
18855 : 377 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
18856 : : DependencyType deptype)
18857 : : {
18858 : : Relation catalogRelation;
18859 : : SysScanDesc scan;
18860 : : ScanKeyData key[3];
18861 : : HeapTuple depTuple;
18862 : :
18863 : 377 : catalogRelation = table_open(DependRelationId, RowExclusiveLock);
18864 : :
18865 : 377 : ScanKeyInit(&key[0],
18866 : : Anum_pg_depend_classid,
18867 : : BTEqualStrategyNumber, F_OIDEQ,
18868 : : ObjectIdGetDatum(RelationRelationId));
18869 : 377 : ScanKeyInit(&key[1],
18870 : : Anum_pg_depend_objid,
18871 : : BTEqualStrategyNumber, F_OIDEQ,
18872 : : ObjectIdGetDatum(relid));
18873 : 377 : ScanKeyInit(&key[2],
18874 : : Anum_pg_depend_objsubid,
18875 : : BTEqualStrategyNumber, F_INT4EQ,
18876 : : Int32GetDatum(0));
18877 : :
18878 : 377 : scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
18879 : : NULL, 3, key);
18880 : :
18881 [ + + ]: 1172 : while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
18882 : : {
18883 : 795 : Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
18884 : :
18885 [ + + ]: 795 : if (dep->refclassid == refclassid &&
18886 [ + + ]: 405 : dep->refobjid == refobjid &&
18887 [ + - ]: 377 : dep->refobjsubid == 0 &&
18888 [ + - ]: 377 : dep->deptype == deptype)
18889 : 377 : CatalogTupleDelete(catalogRelation, &depTuple->t_self);
18890 : : }
18891 : :
18892 : 377 : systable_endscan(scan);
18893 : 377 : table_close(catalogRelation, RowExclusiveLock);
18894 : 377 : }
18895 : :
18896 : : /*
18897 : : * ALTER TABLE OF
18898 : : *
18899 : : * Attach a table to a composite type, as though it had been created with CREATE
18900 : : * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
18901 : : * subject table must not have inheritance parents. These restrictions ensure
18902 : : * that you cannot create a configuration impossible with CREATE TABLE OF alone.
18903 : : *
18904 : : * The address of the type is returned.
18905 : : */
18906 : : static ObjectAddress
18907 : 50 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
18908 : : {
18909 : 50 : Oid relid = RelationGetRelid(rel);
18910 : : Type typetuple;
18911 : : Form_pg_type typeform;
18912 : : Oid typeid;
18913 : : Relation inheritsRelation,
18914 : : relationRelation;
18915 : : SysScanDesc scan;
18916 : : ScanKeyData key;
18917 : : AttrNumber table_attno,
18918 : : type_attno;
18919 : : TupleDesc typeTupleDesc,
18920 : : tableTupleDesc;
18921 : : ObjectAddress tableobj,
18922 : : typeobj;
18923 : : HeapTuple classtuple;
18924 : : AclResult aclresult;
18925 : :
18926 : : /* Validate the type. */
18927 : 50 : typetuple = typenameType(NULL, ofTypename, NULL);
18928 : 50 : check_of_type(typetuple);
18929 : 50 : typeform = (Form_pg_type) GETSTRUCT(typetuple);
18930 : 50 : typeid = typeform->oid;
18931 : :
18932 : 50 : aclresult = object_aclcheck(TypeRelationId, typeid, GetUserId(), ACL_USAGE);
18933 [ + + ]: 50 : if (aclresult != ACLCHECK_OK)
18934 : 4 : aclcheck_error_type(aclresult, typeid);
18935 : :
18936 : : /* Fail if the table has any inheritance parents. */
18937 : 46 : inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
18938 : 46 : ScanKeyInit(&key,
18939 : : Anum_pg_inherits_inhrelid,
18940 : : BTEqualStrategyNumber, F_OIDEQ,
18941 : : ObjectIdGetDatum(relid));
18942 : 46 : scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
18943 : : true, NULL, 1, &key);
18944 [ + + ]: 46 : if (HeapTupleIsValid(systable_getnext(scan)))
18945 [ + - ]: 4 : ereport(ERROR,
18946 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18947 : : errmsg("typed tables cannot inherit")));
18948 : 42 : systable_endscan(scan);
18949 : 42 : table_close(inheritsRelation, AccessShareLock);
18950 : :
18951 : : /*
18952 : : * Check the tuple descriptors for compatibility. Unlike inheritance, we
18953 : : * require that the order also match. However, attnotnull need not match.
18954 : : */
18955 : 42 : typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
18956 : 42 : tableTupleDesc = RelationGetDescr(rel);
18957 : 42 : table_attno = 1;
18958 [ + + ]: 133 : for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
18959 : : {
18960 : : Form_pg_attribute type_attr,
18961 : : table_attr;
18962 : : const char *type_attname,
18963 : : *table_attname;
18964 : :
18965 : : /* Get the next non-dropped type attribute. */
18966 : 107 : type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
18967 [ + + ]: 107 : if (type_attr->attisdropped)
18968 : 29 : continue;
18969 : 78 : type_attname = NameStr(type_attr->attname);
18970 : :
18971 : : /* Get the next non-dropped table attribute. */
18972 : : do
18973 : : {
18974 [ + + ]: 86 : if (table_attno > tableTupleDesc->natts)
18975 [ + - ]: 4 : ereport(ERROR,
18976 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18977 : : errmsg("table is missing column \"%s\"",
18978 : : type_attname)));
18979 : 82 : table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
18980 : 82 : table_attno++;
18981 [ + + ]: 82 : } while (table_attr->attisdropped);
18982 : 74 : table_attname = NameStr(table_attr->attname);
18983 : :
18984 : : /* Compare name. */
18985 [ + + ]: 74 : if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
18986 [ + - ]: 4 : ereport(ERROR,
18987 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18988 : : errmsg("table has column \"%s\" where type requires \"%s\"",
18989 : : table_attname, type_attname)));
18990 : :
18991 : : /* Compare type. */
18992 [ + + ]: 70 : if (table_attr->atttypid != type_attr->atttypid ||
18993 [ + + ]: 66 : table_attr->atttypmod != type_attr->atttypmod ||
18994 [ - + ]: 62 : table_attr->attcollation != type_attr->attcollation)
18995 [ + - ]: 8 : ereport(ERROR,
18996 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18997 : : errmsg("table \"%s\" has different type for column \"%s\"",
18998 : : RelationGetRelationName(rel), type_attname)));
18999 : : }
19000 [ + - ]: 26 : ReleaseTupleDesc(typeTupleDesc);
19001 : :
19002 : : /* Any remaining columns at the end of the table had better be dropped. */
19003 [ + + ]: 26 : for (; table_attno <= tableTupleDesc->natts; table_attno++)
19004 : : {
19005 : 4 : Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
19006 : : table_attno - 1);
19007 : :
19008 [ + - ]: 4 : if (!table_attr->attisdropped)
19009 [ + - ]: 4 : ereport(ERROR,
19010 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
19011 : : errmsg("table has extra column \"%s\"",
19012 : : NameStr(table_attr->attname))));
19013 : : }
19014 : :
19015 : : /* If the table was already typed, drop the existing dependency. */
19016 [ + + ]: 22 : if (rel->rd_rel->reloftype)
19017 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
19018 : : DEPENDENCY_NORMAL);
19019 : :
19020 : : /* Record a dependency on the new type. */
19021 : 22 : tableobj.classId = RelationRelationId;
19022 : 22 : tableobj.objectId = relid;
19023 : 22 : tableobj.objectSubId = 0;
19024 : 22 : typeobj.classId = TypeRelationId;
19025 : 22 : typeobj.objectId = typeid;
19026 : 22 : typeobj.objectSubId = 0;
19027 : 22 : recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
19028 : :
19029 : : /* Update pg_class.reloftype */
19030 : 22 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19031 : 22 : classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19032 [ - + ]: 22 : if (!HeapTupleIsValid(classtuple))
19033 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19034 : 22 : ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
19035 : 22 : CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
19036 : :
19037 [ - + ]: 22 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19038 : :
19039 : 22 : heap_freetuple(classtuple);
19040 : 22 : table_close(relationRelation, RowExclusiveLock);
19041 : :
19042 : 22 : ReleaseSysCache(typetuple);
19043 : :
19044 : 22 : return typeobj;
19045 : : }
19046 : :
19047 : : /*
19048 : : * ALTER TABLE NOT OF
19049 : : *
19050 : : * Detach a typed table from its originating type. Just clear reloftype and
19051 : : * remove the dependency.
19052 : : */
19053 : : static void
19054 : 4 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
19055 : : {
19056 : 4 : Oid relid = RelationGetRelid(rel);
19057 : : Relation relationRelation;
19058 : : HeapTuple tuple;
19059 : :
19060 [ - + ]: 4 : if (!OidIsValid(rel->rd_rel->reloftype))
19061 [ # # ]: 0 : ereport(ERROR,
19062 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19063 : : errmsg("\"%s\" is not a typed table",
19064 : : RelationGetRelationName(rel))));
19065 : :
19066 : : /*
19067 : : * We don't bother to check ownership of the type --- ownership of the
19068 : : * table is presumed enough rights. No lock required on the type, either.
19069 : : */
19070 : :
19071 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
19072 : : DEPENDENCY_NORMAL);
19073 : :
19074 : : /* Clear pg_class.reloftype */
19075 : 4 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19076 : 4 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19077 [ - + ]: 4 : if (!HeapTupleIsValid(tuple))
19078 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19079 : 4 : ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
19080 : 4 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
19081 : :
19082 [ - + ]: 4 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19083 : :
19084 : 4 : heap_freetuple(tuple);
19085 : 4 : table_close(relationRelation, RowExclusiveLock);
19086 : 4 : }
19087 : :
19088 : : /*
19089 : : * relation_mark_replica_identity: Update a table's replica identity
19090 : : *
19091 : : * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
19092 : : * index. Otherwise, it must be InvalidOid.
19093 : : *
19094 : : * Caller had better hold an exclusive lock on the relation, as the results
19095 : : * of running two of these concurrently wouldn't be pretty.
19096 : : */
19097 : : static void
19098 : 298 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
19099 : : bool is_internal)
19100 : : {
19101 : : Relation pg_index;
19102 : : Relation pg_class;
19103 : : HeapTuple pg_class_tuple;
19104 : : HeapTuple pg_index_tuple;
19105 : : Form_pg_class pg_class_form;
19106 : : Form_pg_index pg_index_form;
19107 : : ListCell *index;
19108 : :
19109 : : /*
19110 : : * Check whether relreplident has changed, and update it if so.
19111 : : */
19112 : 298 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19113 : 298 : pg_class_tuple = SearchSysCacheCopy1(RELOID,
19114 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19115 [ - + ]: 298 : if (!HeapTupleIsValid(pg_class_tuple))
19116 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation \"%s\"",
19117 : : RelationGetRelationName(rel));
19118 : 298 : pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
19119 [ + + ]: 298 : if (pg_class_form->relreplident != ri_type)
19120 : : {
19121 : 264 : pg_class_form->relreplident = ri_type;
19122 : 264 : CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
19123 : : }
19124 : 298 : table_close(pg_class, RowExclusiveLock);
19125 : 298 : heap_freetuple(pg_class_tuple);
19126 : :
19127 : : /*
19128 : : * Update the per-index indisreplident flags correctly.
19129 : : */
19130 : 298 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
19131 [ + + + + : 780 : foreach(index, RelationGetIndexList(rel))
+ + ]
19132 : : {
19133 : 482 : Oid thisIndexOid = lfirst_oid(index);
19134 : 482 : bool dirty = false;
19135 : :
19136 : 482 : pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
19137 : : ObjectIdGetDatum(thisIndexOid));
19138 [ - + ]: 482 : if (!HeapTupleIsValid(pg_index_tuple))
19139 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
19140 : 482 : pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
19141 : :
19142 [ + + ]: 482 : if (thisIndexOid == indexOid)
19143 : : {
19144 : : /* Set the bit if not already set. */
19145 [ + + ]: 162 : if (!pg_index_form->indisreplident)
19146 : : {
19147 : 150 : dirty = true;
19148 : 150 : pg_index_form->indisreplident = true;
19149 : : }
19150 : : }
19151 : : else
19152 : : {
19153 : : /* Unset the bit if set. */
19154 [ + + ]: 320 : if (pg_index_form->indisreplident)
19155 : : {
19156 : 34 : dirty = true;
19157 : 34 : pg_index_form->indisreplident = false;
19158 : : }
19159 : : }
19160 : :
19161 [ + + ]: 482 : if (dirty)
19162 : : {
19163 : 184 : CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
19164 [ - + ]: 184 : InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
19165 : : InvalidOid, is_internal);
19166 : :
19167 : : /*
19168 : : * Invalidate the relcache for the table, so that after we commit
19169 : : * all sessions will refresh the table's replica identity index
19170 : : * before attempting any UPDATE or DELETE on the table. (If we
19171 : : * changed the table's pg_class row above, then a relcache inval
19172 : : * is already queued due to that; but we might not have.)
19173 : : */
19174 : 184 : CacheInvalidateRelcache(rel);
19175 : : }
19176 : 482 : heap_freetuple(pg_index_tuple);
19177 : : }
19178 : :
19179 : 298 : table_close(pg_index, RowExclusiveLock);
19180 : 298 : }
19181 : :
19182 : : /*
19183 : : * ALTER TABLE <name> REPLICA IDENTITY ...
19184 : : */
19185 : : static void
19186 : 334 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
19187 : : {
19188 : : Oid indexOid;
19189 : : Relation indexRel;
19190 : : int key;
19191 : :
19192 [ + + ]: 334 : if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
19193 : : {
19194 : 5 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19195 : 5 : return;
19196 : : }
19197 [ + + ]: 329 : else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
19198 : : {
19199 : 101 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19200 : 101 : return;
19201 : : }
19202 [ + + ]: 228 : else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
19203 : : {
19204 : 30 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19205 : 30 : return;
19206 : : }
19207 [ - + ]: 198 : else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
19208 : : {
19209 : : /* fallthrough */ ;
19210 : : }
19211 : : else
19212 [ # # ]: 0 : elog(ERROR, "unexpected identity type %u", stmt->identity_type);
19213 : :
19214 : : /* Check that the index exists */
19215 : 198 : indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
19216 [ - + ]: 198 : if (!OidIsValid(indexOid))
19217 [ # # ]: 0 : ereport(ERROR,
19218 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
19219 : : errmsg("index \"%s\" for table \"%s\" does not exist",
19220 : : stmt->name, RelationGetRelationName(rel))));
19221 : :
19222 : 198 : indexRel = index_open(indexOid, ShareLock);
19223 : :
19224 : : /* Check that the index is on the relation we're altering. */
19225 [ + - ]: 198 : if (indexRel->rd_index == NULL ||
19226 [ + + ]: 198 : indexRel->rd_index->indrelid != RelationGetRelid(rel))
19227 [ + - ]: 4 : ereport(ERROR,
19228 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19229 : : errmsg("\"%s\" is not an index for table \"%s\"",
19230 : : RelationGetRelationName(indexRel),
19231 : : RelationGetRelationName(rel))));
19232 : :
19233 : : /*
19234 : : * The AM must support uniqueness, and the index must in fact be unique.
19235 : : * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
19236 : : * exclusion), we can use that too.
19237 : : */
19238 [ + + ]: 194 : if ((!indexRel->rd_indam->amcanunique ||
19239 [ + + ]: 180 : !indexRel->rd_index->indisunique) &&
19240 [ + + - + ]: 18 : !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
19241 [ + - ]: 8 : ereport(ERROR,
19242 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19243 : : errmsg("cannot use non-unique index \"%s\" as replica identity",
19244 : : RelationGetRelationName(indexRel))));
19245 : : /* Deferred indexes are not guaranteed to be always unique. */
19246 [ + + ]: 186 : if (!indexRel->rd_index->indimmediate)
19247 [ + - ]: 8 : ereport(ERROR,
19248 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19249 : : errmsg("cannot use non-immediate index \"%s\" as replica identity",
19250 : : RelationGetRelationName(indexRel))));
19251 : : /* Expression indexes aren't supported. */
19252 [ + + ]: 178 : if (RelationGetIndexExpressions(indexRel) != NIL)
19253 [ + - ]: 4 : ereport(ERROR,
19254 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19255 : : errmsg("cannot use expression index \"%s\" as replica identity",
19256 : : RelationGetRelationName(indexRel))));
19257 : : /* Predicate indexes aren't supported. */
19258 [ + + ]: 174 : if (RelationGetIndexPredicate(indexRel) != NIL)
19259 [ + - ]: 4 : ereport(ERROR,
19260 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19261 : : errmsg("cannot use partial index \"%s\" as replica identity",
19262 : : RelationGetRelationName(indexRel))));
19263 : :
19264 : : /* Check index for nullable columns. */
19265 [ + + ]: 377 : for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
19266 : : {
19267 : 215 : int16 attno = indexRel->rd_index->indkey.values[key];
19268 : : Form_pg_attribute attr;
19269 : : HeapTuple contup;
19270 : : Form_pg_constraint conForm;
19271 : :
19272 : : /*
19273 : : * Reject any other system columns. (Going forward, we'll disallow
19274 : : * indexes containing such columns in the first place, but they might
19275 : : * exist in older branches.)
19276 : : */
19277 [ - + ]: 215 : if (attno <= 0)
19278 [ # # ]: 0 : ereport(ERROR,
19279 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
19280 : : errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
19281 : : RelationGetRelationName(indexRel), attno)));
19282 : :
19283 : 215 : attr = TupleDescAttr(rel->rd_att, attno - 1);
19284 [ + + ]: 215 : if (!attr->attnotnull)
19285 [ + - ]: 4 : ereport(ERROR,
19286 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19287 : : errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
19288 : : RelationGetRelationName(indexRel),
19289 : : NameStr(attr->attname))));
19290 : :
19291 : : /*
19292 : : * Verify that the not-null constraint for the column is valid.
19293 : : */
19294 : 211 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel), attno);
19295 [ - + ]: 211 : if (!HeapTupleIsValid(contup))
19296 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
19297 : : NameStr(attr->attname), RelationGetRelationName(rel));
19298 : 211 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
19299 [ + + ]: 211 : if (!conForm->convalidated)
19300 [ + - ]: 4 : ereport(ERROR,
19301 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19302 : : errmsg("cannot use index \"%s\" as replica identity",
19303 : : RelationGetRelationName(indexRel)),
19304 : : /*- translator: third %s is a constraint characteristic such as NOT VALID */
19305 : : errdetail("The constraint \"%s\" on column \"%s\" is marked %s.",
19306 : : NameStr(conForm->conname), NameStr(attr->attname), "NOT VALID"),
19307 : : errhint("You might need to validate it using %s.",
19308 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
19309 : 207 : heap_freetuple(contup);
19310 : : }
19311 : :
19312 : : /* This index is suitable for use as a replica identity. Mark it. */
19313 : 162 : relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
19314 : :
19315 : 162 : index_close(indexRel, NoLock);
19316 : : }
19317 : :
19318 : : /*
19319 : : * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
19320 : : */
19321 : : static void
19322 : 256 : ATExecSetRowSecurity(Relation rel, bool rls)
19323 : : {
19324 : : Relation pg_class;
19325 : : Oid relid;
19326 : : HeapTuple tuple;
19327 : :
19328 : 256 : relid = RelationGetRelid(rel);
19329 : :
19330 : : /* Pull the record for this relation and update it */
19331 : 256 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19332 : :
19333 : 256 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19334 : :
19335 [ - + ]: 256 : if (!HeapTupleIsValid(tuple))
19336 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19337 : :
19338 : 256 : ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
19339 : 256 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
19340 : :
19341 [ + + ]: 256 : InvokeObjectPostAlterHook(RelationRelationId,
19342 : : RelationGetRelid(rel), 0);
19343 : :
19344 : 256 : table_close(pg_class, RowExclusiveLock);
19345 : 256 : heap_freetuple(tuple);
19346 : 256 : }
19347 : :
19348 : : /*
19349 : : * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
19350 : : */
19351 : : static void
19352 : 85 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
19353 : : {
19354 : : Relation pg_class;
19355 : : Oid relid;
19356 : : HeapTuple tuple;
19357 : :
19358 : 85 : relid = RelationGetRelid(rel);
19359 : :
19360 : 85 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19361 : :
19362 : 85 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19363 : :
19364 [ - + ]: 85 : if (!HeapTupleIsValid(tuple))
19365 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19366 : :
19367 : 85 : ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
19368 : 85 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
19369 : :
19370 [ + + ]: 85 : InvokeObjectPostAlterHook(RelationRelationId,
19371 : : RelationGetRelid(rel), 0);
19372 : :
19373 : 85 : table_close(pg_class, RowExclusiveLock);
19374 : 85 : heap_freetuple(tuple);
19375 : 85 : }
19376 : :
19377 : : /*
19378 : : * ALTER FOREIGN TABLE <name> OPTIONS (...)
19379 : : */
19380 : : static void
19381 : 34 : ATExecGenericOptions(Relation rel, List *options)
19382 : : {
19383 : : Relation ftrel;
19384 : : ForeignServer *server;
19385 : : ForeignDataWrapper *fdw;
19386 : : HeapTuple tuple;
19387 : : bool isnull;
19388 : : Datum repl_val[Natts_pg_foreign_table];
19389 : : bool repl_null[Natts_pg_foreign_table];
19390 : : bool repl_repl[Natts_pg_foreign_table];
19391 : : Datum datum;
19392 : : Form_pg_foreign_table tableform;
19393 : :
19394 [ - + ]: 34 : if (options == NIL)
19395 : 0 : return;
19396 : :
19397 : 34 : ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
19398 : :
19399 : 34 : tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
19400 : : ObjectIdGetDatum(rel->rd_id));
19401 [ - + ]: 34 : if (!HeapTupleIsValid(tuple))
19402 [ # # ]: 0 : ereport(ERROR,
19403 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
19404 : : errmsg("foreign table \"%s\" does not exist",
19405 : : RelationGetRelationName(rel))));
19406 : 34 : tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
19407 : 34 : server = GetForeignServer(tableform->ftserver);
19408 : 34 : fdw = GetForeignDataWrapper(server->fdwid);
19409 : :
19410 : 34 : memset(repl_val, 0, sizeof(repl_val));
19411 : 34 : memset(repl_null, false, sizeof(repl_null));
19412 : 34 : memset(repl_repl, false, sizeof(repl_repl));
19413 : :
19414 : : /* Extract the current options */
19415 : 34 : datum = SysCacheGetAttr(FOREIGNTABLEREL,
19416 : : tuple,
19417 : : Anum_pg_foreign_table_ftoptions,
19418 : : &isnull);
19419 [ + + ]: 34 : if (isnull)
19420 : 2 : datum = PointerGetDatum(NULL);
19421 : :
19422 : : /* Transform the options */
19423 : 34 : datum = transformGenericOptions(ForeignTableRelationId,
19424 : : datum,
19425 : : options,
19426 : : fdw->fdwvalidator);
19427 : :
19428 [ + - ]: 33 : if (DatumGetPointer(datum) != NULL)
19429 : 33 : repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
19430 : : else
19431 : 0 : repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
19432 : :
19433 : 33 : repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
19434 : :
19435 : : /* Everything looks good - update the tuple */
19436 : :
19437 : 33 : tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
19438 : : repl_val, repl_null, repl_repl);
19439 : :
19440 : 33 : CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
19441 : :
19442 : : /*
19443 : : * Invalidate relcache so that all sessions will refresh any cached plans
19444 : : * that might depend on the old options.
19445 : : */
19446 : 33 : CacheInvalidateRelcache(rel);
19447 : :
19448 [ - + ]: 33 : InvokeObjectPostAlterHook(ForeignTableRelationId,
19449 : : RelationGetRelid(rel), 0);
19450 : :
19451 : 33 : table_close(ftrel, RowExclusiveLock);
19452 : :
19453 : 33 : heap_freetuple(tuple);
19454 : : }
19455 : :
19456 : : /*
19457 : : * ALTER TABLE ALTER COLUMN SET COMPRESSION
19458 : : *
19459 : : * Return value is the address of the modified column
19460 : : */
19461 : : static ObjectAddress
19462 : 49 : ATExecSetCompression(Relation rel,
19463 : : const char *column,
19464 : : Node *newValue,
19465 : : LOCKMODE lockmode)
19466 : : {
19467 : : Relation attrel;
19468 : : HeapTuple tuple;
19469 : : Form_pg_attribute atttableform;
19470 : : AttrNumber attnum;
19471 : : char *compression;
19472 : : char cmethod;
19473 : : ObjectAddress address;
19474 : :
19475 : 49 : compression = strVal(newValue);
19476 : :
19477 : 49 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
19478 : :
19479 : : /* copy the cache entry so we can scribble on it below */
19480 : 49 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
19481 [ - + ]: 49 : if (!HeapTupleIsValid(tuple))
19482 [ # # ]: 0 : ereport(ERROR,
19483 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
19484 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
19485 : : column, RelationGetRelationName(rel))));
19486 : :
19487 : : /* prevent them from altering a system attribute */
19488 : 49 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
19489 : 49 : attnum = atttableform->attnum;
19490 [ - + ]: 49 : if (attnum <= 0)
19491 [ # # ]: 0 : ereport(ERROR,
19492 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19493 : : errmsg("cannot alter system column \"%s\"", column)));
19494 : :
19495 : : /*
19496 : : * Check that column type is compressible, then get the attribute
19497 : : * compression method code
19498 : : */
19499 : 49 : cmethod = GetAttributeCompression(atttableform->atttypid, compression);
19500 : :
19501 : : /* update pg_attribute entry */
19502 : 45 : atttableform->attcompression = cmethod;
19503 : 45 : CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
19504 : :
19505 [ - + ]: 45 : InvokeObjectPostAlterHook(RelationRelationId,
19506 : : RelationGetRelid(rel),
19507 : : attnum);
19508 : :
19509 : : /*
19510 : : * Apply the change to indexes as well (only for simple index columns,
19511 : : * matching behavior of index.c ConstructTupleDescriptor()).
19512 : : */
19513 : 45 : SetIndexStorageProperties(rel, attrel, attnum,
19514 : : false, 0,
19515 : : true, cmethod,
19516 : : lockmode);
19517 : :
19518 : 45 : heap_freetuple(tuple);
19519 : :
19520 : 45 : table_close(attrel, RowExclusiveLock);
19521 : :
19522 : : /* make changes visible */
19523 : 45 : CommandCounterIncrement();
19524 : :
19525 : 45 : ObjectAddressSubSet(address, RelationRelationId,
19526 : : RelationGetRelid(rel), attnum);
19527 : 45 : return address;
19528 : : }
19529 : :
19530 : :
19531 : : /*
19532 : : * Preparation phase for SET LOGGED/UNLOGGED
19533 : : *
19534 : : * This verifies that we're not trying to change a temp table. Also,
19535 : : * existing foreign key constraints are checked to avoid ending up with
19536 : : * permanent tables referencing unlogged tables.
19537 : : */
19538 : : static void
19539 : 71 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
19540 : : {
19541 : : Relation pg_constraint;
19542 : : HeapTuple tuple;
19543 : : SysScanDesc scan;
19544 : : ScanKeyData skey[1];
19545 : :
19546 : : /*
19547 : : * Disallow changing status for a temp table. Also verify whether we can
19548 : : * get away with doing nothing; in such cases we don't need to run the
19549 : : * checks below, either.
19550 : : */
19551 [ - + + - ]: 71 : switch (rel->rd_rel->relpersistence)
19552 : : {
19553 : 0 : case RELPERSISTENCE_TEMP:
19554 [ # # ]: 0 : ereport(ERROR,
19555 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19556 : : errmsg("cannot change logged status of table \"%s\" because it is temporary",
19557 : : RelationGetRelationName(rel)),
19558 : : errtable(rel)));
19559 : : break;
19560 : 41 : case RELPERSISTENCE_PERMANENT:
19561 [ + + ]: 41 : if (toLogged)
19562 : : /* nothing to do */
19563 : 8 : return;
19564 : 37 : break;
19565 : 30 : case RELPERSISTENCE_UNLOGGED:
19566 [ + + ]: 30 : if (!toLogged)
19567 : : /* nothing to do */
19568 : 4 : return;
19569 : 26 : break;
19570 : : }
19571 : :
19572 : : /*
19573 : : * UNLOGGED tables can neither be published nor be named in a
19574 : : * publication's EXCEPT clause, so reject the change if the table is
19575 : : * referenced by any publication.
19576 : : */
19577 [ + + + + ]: 63 : if (!toLogged && RelationHasPublication(RelationGetRelid(rel)))
19578 [ + - ]: 4 : ereport(ERROR,
19579 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19580 : : errmsg("cannot change table \"%s\" to unlogged because it is referenced by a publication",
19581 : : RelationGetRelationName(rel)),
19582 : : errdetail("Unlogged relations cannot be published or excluded via an EXCEPT clause."),
19583 : : errhint("Drop the table from the publication, or remove it from the publication's EXCEPT clause, first.")));
19584 : :
19585 : : /*
19586 : : * Check existing foreign key constraints to preserve the invariant that
19587 : : * permanent tables cannot reference unlogged ones. Self-referencing
19588 : : * foreign keys can safely be ignored.
19589 : : */
19590 : 59 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
19591 : :
19592 : : /*
19593 : : * Scan conrelid if changing to permanent, else confrelid. This also
19594 : : * determines whether a useful index exists.
19595 : : */
19596 [ + + ]: 59 : ScanKeyInit(&skey[0],
19597 : : toLogged ? Anum_pg_constraint_conrelid :
19598 : : Anum_pg_constraint_confrelid,
19599 : : BTEqualStrategyNumber, F_OIDEQ,
19600 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19601 [ + + ]: 59 : scan = systable_beginscan(pg_constraint,
19602 : : toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
19603 : : true, NULL, 1, skey);
19604 : :
19605 [ + + ]: 95 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
19606 : : {
19607 : 44 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
19608 : :
19609 [ + + ]: 44 : if (con->contype == CONSTRAINT_FOREIGN)
19610 : : {
19611 : : Oid foreignrelid;
19612 : : Relation foreignrel;
19613 : :
19614 : : /* the opposite end of what we used as scankey */
19615 [ + + ]: 20 : foreignrelid = toLogged ? con->confrelid : con->conrelid;
19616 : :
19617 : : /* ignore if self-referencing */
19618 [ + + ]: 20 : if (RelationGetRelid(rel) == foreignrelid)
19619 : 8 : continue;
19620 : :
19621 : 12 : foreignrel = relation_open(foreignrelid, AccessShareLock);
19622 : :
19623 [ + + ]: 12 : if (toLogged)
19624 : : {
19625 [ + - ]: 4 : if (!RelationIsPermanent(foreignrel))
19626 [ + - ]: 4 : ereport(ERROR,
19627 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19628 : : errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
19629 : : RelationGetRelationName(rel),
19630 : : RelationGetRelationName(foreignrel)),
19631 : : errtableconstraint(rel, NameStr(con->conname))));
19632 : : }
19633 : : else
19634 : : {
19635 [ + + ]: 8 : if (RelationIsPermanent(foreignrel))
19636 [ + - ]: 4 : ereport(ERROR,
19637 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19638 : : errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
19639 : : RelationGetRelationName(rel),
19640 : : RelationGetRelationName(foreignrel)),
19641 : : errtableconstraint(rel, NameStr(con->conname))));
19642 : : }
19643 : :
19644 : 4 : relation_close(foreignrel, AccessShareLock);
19645 : : }
19646 : : }
19647 : :
19648 : 51 : systable_endscan(scan);
19649 : :
19650 : 51 : table_close(pg_constraint, AccessShareLock);
19651 : :
19652 : : /* force rewrite if necessary; see comment in ATRewriteTables */
19653 : 51 : tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
19654 [ + + ]: 51 : if (toLogged)
19655 : 22 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
19656 : : else
19657 : 29 : tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
19658 : 51 : tab->chgPersistence = true;
19659 : : }
19660 : :
19661 : : /*
19662 : : * Execute ALTER TABLE SET SCHEMA
19663 : : */
19664 : : ObjectAddress
19665 : 76 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
19666 : : {
19667 : : Relation rel;
19668 : : Oid relid;
19669 : : Oid oldNspOid;
19670 : : Oid nspOid;
19671 : : RangeVar *newrv;
19672 : : ObjectAddresses *objsMoved;
19673 : : ObjectAddress myself;
19674 : :
19675 : 76 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
19676 : 76 : stmt->missing_ok ? RVR_MISSING_OK : 0,
19677 : : RangeVarCallbackForAlterRelation,
19678 : : stmt);
19679 : :
19680 [ + + ]: 71 : if (!OidIsValid(relid))
19681 : : {
19682 [ + - ]: 8 : ereport(NOTICE,
19683 : : (errmsg("relation \"%s\" does not exist, skipping",
19684 : : stmt->relation->relname)));
19685 : 8 : return InvalidObjectAddress;
19686 : : }
19687 : :
19688 : 63 : rel = relation_open(relid, NoLock);
19689 : :
19690 : 63 : oldNspOid = RelationGetNamespace(rel);
19691 : :
19692 : : /* If it's an owned sequence, disallow moving it by itself. */
19693 [ + + ]: 63 : if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19694 : : {
19695 : : Oid tableId;
19696 : : int32 colId;
19697 : :
19698 [ + + - + ]: 6 : if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19699 : 1 : sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
19700 [ + - ]: 4 : ereport(ERROR,
19701 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19702 : : errmsg("cannot move an owned sequence into another schema"),
19703 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
19704 : : RelationGetRelationName(rel),
19705 : : get_rel_name(tableId))));
19706 : : }
19707 : :
19708 : : /* Get and lock schema OID and check its permissions. */
19709 : 59 : newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19710 : 59 : nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
19711 : :
19712 : : /* common checks on switching namespaces */
19713 : 55 : CheckSetNamespace(oldNspOid, nspOid);
19714 : :
19715 : 55 : objsMoved = new_object_addresses();
19716 : 55 : AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
19717 : 55 : free_object_addresses(objsMoved);
19718 : :
19719 : 55 : ObjectAddressSet(myself, RelationRelationId, relid);
19720 : :
19721 [ + - ]: 55 : if (oldschema)
19722 : 55 : *oldschema = oldNspOid;
19723 : :
19724 : : /* close rel, but keep lock until commit */
19725 : 55 : relation_close(rel, NoLock);
19726 : :
19727 : 55 : return myself;
19728 : : }
19729 : :
19730 : : /*
19731 : : * The guts of relocating a table or materialized view to another namespace:
19732 : : * besides moving the relation itself, its dependent objects are relocated to
19733 : : * the new schema.
19734 : : */
19735 : : void
19736 : 56 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
19737 : : ObjectAddresses *objsMoved)
19738 : : {
19739 : : Relation classRel;
19740 : :
19741 : : Assert(objsMoved != NULL);
19742 : :
19743 : : /* OK, modify the pg_class row and pg_depend entry */
19744 : 56 : classRel = table_open(RelationRelationId, RowExclusiveLock);
19745 : :
19746 : 56 : AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
19747 : : nspOid, true, objsMoved);
19748 : :
19749 : : /* Fix the table's row type too, if it has one */
19750 [ + + ]: 56 : if (OidIsValid(rel->rd_rel->reltype))
19751 : 55 : AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
19752 : : false, /* isImplicitArray */
19753 : : false, /* ignoreDependent */
19754 : : false, /* errorOnTableType */
19755 : : objsMoved);
19756 : :
19757 : : /* Fix other dependent stuff */
19758 : 56 : AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
19759 : 56 : AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
19760 : : objsMoved, AccessExclusiveLock);
19761 : 56 : AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
19762 : : false, objsMoved);
19763 : :
19764 : 56 : table_close(classRel, RowExclusiveLock);
19765 : 56 : }
19766 : :
19767 : : /*
19768 : : * The guts of relocating a relation to another namespace: fix the pg_class
19769 : : * entry, and the pg_depend entry if any. Caller must already have
19770 : : * opened and write-locked pg_class.
19771 : : */
19772 : : void
19773 : 123 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
19774 : : Oid oldNspOid, Oid newNspOid,
19775 : : bool hasDependEntry,
19776 : : ObjectAddresses *objsMoved)
19777 : : {
19778 : : HeapTuple classTup;
19779 : : Form_pg_class classForm;
19780 : : ObjectAddress thisobj;
19781 : 123 : bool already_done = false;
19782 : :
19783 : : /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19784 : 123 : classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
19785 [ - + ]: 123 : if (!HeapTupleIsValid(classTup))
19786 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
19787 : 123 : classForm = (Form_pg_class) GETSTRUCT(classTup);
19788 : :
19789 : : Assert(classForm->relnamespace == oldNspOid);
19790 : :
19791 : 123 : thisobj.classId = RelationRelationId;
19792 : 123 : thisobj.objectId = relOid;
19793 : 123 : thisobj.objectSubId = 0;
19794 : :
19795 : : /*
19796 : : * If the object has already been moved, don't move it again. If it's
19797 : : * already in the right place, don't move it, but still fire the object
19798 : : * access hook.
19799 : : */
19800 : 123 : already_done = object_address_present(&thisobj, objsMoved);
19801 [ + - + + ]: 123 : if (!already_done && oldNspOid != newNspOid)
19802 : 95 : {
19803 : 95 : ItemPointerData otid = classTup->t_self;
19804 : :
19805 : : /* check for duplicate name (more friendly than unique-index failure) */
19806 [ - + ]: 95 : if (get_relname_relid(NameStr(classForm->relname),
19807 : : newNspOid) != InvalidOid)
19808 [ # # ]: 0 : ereport(ERROR,
19809 : : (errcode(ERRCODE_DUPLICATE_TABLE),
19810 : : errmsg("relation \"%s\" already exists in schema \"%s\"",
19811 : : NameStr(classForm->relname),
19812 : : get_namespace_name(newNspOid))));
19813 : :
19814 : : /* classTup is a copy, so OK to scribble on */
19815 : 95 : classForm->relnamespace = newNspOid;
19816 : :
19817 : 95 : CatalogTupleUpdate(classRel, &otid, classTup);
19818 : 95 : UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19819 : :
19820 : :
19821 : : /* Update dependency on schema if caller said so */
19822 [ + + - + ]: 163 : if (hasDependEntry &&
19823 : 68 : changeDependencyFor(RelationRelationId,
19824 : : relOid,
19825 : : NamespaceRelationId,
19826 : : oldNspOid,
19827 : : newNspOid) != 1)
19828 [ # # ]: 0 : elog(ERROR, "could not change schema dependency for relation \"%s\"",
19829 : : NameStr(classForm->relname));
19830 : : }
19831 : : else
19832 : 28 : UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19833 [ + - ]: 123 : if (!already_done)
19834 : : {
19835 : 123 : add_exact_object_address(&thisobj, objsMoved);
19836 : :
19837 [ - + ]: 123 : InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19838 : : }
19839 : :
19840 : 123 : heap_freetuple(classTup);
19841 : 123 : }
19842 : :
19843 : : /*
19844 : : * Move all indexes for the specified relation to another namespace.
19845 : : *
19846 : : * Note: we assume adequate permission checking was done by the caller,
19847 : : * and that the caller has a suitable lock on the owning relation.
19848 : : */
19849 : : static void
19850 : 56 : AlterIndexNamespaces(Relation classRel, Relation rel,
19851 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
19852 : : {
19853 : : List *indexList;
19854 : : ListCell *l;
19855 : :
19856 : 56 : indexList = RelationGetIndexList(rel);
19857 : :
19858 [ + + + + : 86 : foreach(l, indexList)
+ + ]
19859 : : {
19860 : 30 : Oid indexOid = lfirst_oid(l);
19861 : : ObjectAddress thisobj;
19862 : :
19863 : 30 : thisobj.classId = RelationRelationId;
19864 : 30 : thisobj.objectId = indexOid;
19865 : 30 : thisobj.objectSubId = 0;
19866 : :
19867 : : /*
19868 : : * Note: currently, the index will not have its own dependency on the
19869 : : * namespace, so we don't need to do changeDependencyFor(). There's no
19870 : : * row type in pg_type, either.
19871 : : *
19872 : : * XXX this objsMoved test may be pointless -- surely we have a single
19873 : : * dependency link from a relation to each index?
19874 : : */
19875 [ + - ]: 30 : if (!object_address_present(&thisobj, objsMoved))
19876 : : {
19877 : 30 : AlterRelationNamespaceInternal(classRel, indexOid,
19878 : : oldNspOid, newNspOid,
19879 : : false, objsMoved);
19880 : 30 : add_exact_object_address(&thisobj, objsMoved);
19881 : : }
19882 : : }
19883 : :
19884 : 56 : list_free(indexList);
19885 : 56 : }
19886 : :
19887 : : /*
19888 : : * Move all identity and SERIAL-column sequences of the specified relation to another
19889 : : * namespace.
19890 : : *
19891 : : * Note: we assume adequate permission checking was done by the caller,
19892 : : * and that the caller has a suitable lock on the owning relation.
19893 : : */
19894 : : static void
19895 : 56 : AlterSeqNamespaces(Relation classRel, Relation rel,
19896 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
19897 : : LOCKMODE lockmode)
19898 : : {
19899 : : Relation depRel;
19900 : : SysScanDesc scan;
19901 : : ScanKeyData key[2];
19902 : : HeapTuple tup;
19903 : :
19904 : : /*
19905 : : * SERIAL sequences are those having an auto dependency on one of the
19906 : : * table's columns (we don't care *which* column, exactly).
19907 : : */
19908 : 56 : depRel = table_open(DependRelationId, AccessShareLock);
19909 : :
19910 : 56 : ScanKeyInit(&key[0],
19911 : : Anum_pg_depend_refclassid,
19912 : : BTEqualStrategyNumber, F_OIDEQ,
19913 : : ObjectIdGetDatum(RelationRelationId));
19914 : 56 : ScanKeyInit(&key[1],
19915 : : Anum_pg_depend_refobjid,
19916 : : BTEqualStrategyNumber, F_OIDEQ,
19917 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19918 : : /* we leave refobjsubid unspecified */
19919 : :
19920 : 56 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
19921 : : NULL, 2, key);
19922 : :
19923 [ + + ]: 405 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
19924 : : {
19925 : 349 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
19926 : : Relation seqRel;
19927 : :
19928 : : /* skip dependencies other than auto dependencies on columns */
19929 [ + + ]: 349 : if (depForm->refobjsubid == 0 ||
19930 [ + + ]: 252 : depForm->classid != RelationRelationId ||
19931 [ + - ]: 28 : depForm->objsubid != 0 ||
19932 [ - + - - ]: 28 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
19933 : 321 : continue;
19934 : :
19935 : : /* Use relation_open just in case it's an index */
19936 : 28 : seqRel = relation_open(depForm->objid, lockmode);
19937 : :
19938 : : /* skip non-sequence relations */
19939 [ - + ]: 28 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
19940 : : {
19941 : : /* No need to keep the lock */
19942 : 0 : relation_close(seqRel, lockmode);
19943 : 0 : continue;
19944 : : }
19945 : :
19946 : : /* Fix the pg_class and pg_depend entries */
19947 : 28 : AlterRelationNamespaceInternal(classRel, depForm->objid,
19948 : : oldNspOid, newNspOid,
19949 : : true, objsMoved);
19950 : :
19951 : : /*
19952 : : * Sequences used to have entries in pg_type, but no longer do. If we
19953 : : * ever re-instate that, we'll need to move the pg_type entry to the
19954 : : * new namespace, too (using AlterTypeNamespaceInternal).
19955 : : */
19956 : : Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
19957 : :
19958 : : /* Now we can close it. Keep the lock till end of transaction. */
19959 : 28 : relation_close(seqRel, NoLock);
19960 : : }
19961 : :
19962 : 56 : systable_endscan(scan);
19963 : :
19964 : 56 : relation_close(depRel, AccessShareLock);
19965 : 56 : }
19966 : :
19967 : :
19968 : : /*
19969 : : * This code supports
19970 : : * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
19971 : : *
19972 : : * Because we only support this for TEMP tables, it's sufficient to remember
19973 : : * the state in a backend-local data structure.
19974 : : */
19975 : :
19976 : : /*
19977 : : * Register a newly-created relation's ON COMMIT action.
19978 : : */
19979 : : void
19980 : 116 : register_on_commit_action(Oid relid, OnCommitAction action)
19981 : : {
19982 : : OnCommitItem *oc;
19983 : : MemoryContext oldcxt;
19984 : :
19985 : : /*
19986 : : * We needn't bother registering the relation unless there is an ON COMMIT
19987 : : * action we need to take.
19988 : : */
19989 [ + - + + ]: 116 : if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19990 : 16 : return;
19991 : :
19992 : 100 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
19993 : :
19994 : 100 : oc = palloc_object(OnCommitItem);
19995 : 100 : oc->relid = relid;
19996 : 100 : oc->oncommit = action;
19997 : 100 : oc->creating_subid = GetCurrentSubTransactionId();
19998 : 100 : oc->deleting_subid = InvalidSubTransactionId;
19999 : :
20000 : : /*
20001 : : * We use lcons() here so that ON COMMIT actions are processed in reverse
20002 : : * order of registration. That might not be essential but it seems
20003 : : * reasonable.
20004 : : */
20005 : 100 : on_commits = lcons(oc, on_commits);
20006 : :
20007 : 100 : MemoryContextSwitchTo(oldcxt);
20008 : : }
20009 : :
20010 : : /*
20011 : : * Unregister any ON COMMIT action when a relation is deleted.
20012 : : *
20013 : : * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
20014 : : */
20015 : : void
20016 : 32580 : remove_on_commit_action(Oid relid)
20017 : : {
20018 : : ListCell *l;
20019 : :
20020 [ + + + + : 32677 : foreach(l, on_commits)
+ + ]
20021 : : {
20022 : 189 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20023 : :
20024 [ + + ]: 189 : if (oc->relid == relid)
20025 : : {
20026 : 92 : oc->deleting_subid = GetCurrentSubTransactionId();
20027 : 92 : break;
20028 : : }
20029 : : }
20030 : 32580 : }
20031 : :
20032 : : /*
20033 : : * Perform ON COMMIT actions.
20034 : : *
20035 : : * This is invoked just before actually committing, since it's possible
20036 : : * to encounter errors.
20037 : : */
20038 : : void
20039 : 613232 : PreCommit_on_commit_actions(void)
20040 : : {
20041 : : ListCell *l;
20042 : 613232 : List *oids_to_truncate = NIL;
20043 : 613232 : List *oids_to_drop = NIL;
20044 : :
20045 [ + + + + : 613778 : foreach(l, on_commits)
+ + ]
20046 : : {
20047 : 546 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20048 : :
20049 : : /* Ignore entry if already dropped in this xact */
20050 [ + + ]: 546 : if (oc->deleting_subid != InvalidSubTransactionId)
20051 : 49 : continue;
20052 : :
20053 [ - + + - ]: 497 : switch (oc->oncommit)
20054 : : {
20055 : 0 : case ONCOMMIT_NOOP:
20056 : : case ONCOMMIT_PRESERVE_ROWS:
20057 : : /* Do nothing (there shouldn't be such entries, actually) */
20058 : 0 : break;
20059 : 462 : case ONCOMMIT_DELETE_ROWS:
20060 : :
20061 : : /*
20062 : : * If this transaction hasn't accessed any temporary
20063 : : * relations, we can skip truncating ON COMMIT DELETE ROWS
20064 : : * tables, as they must still be empty.
20065 : : */
20066 [ + + ]: 462 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
20067 : 298 : oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
20068 : 462 : break;
20069 : 35 : case ONCOMMIT_DROP:
20070 : 35 : oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
20071 : 35 : break;
20072 : : }
20073 : : }
20074 : :
20075 : : /*
20076 : : * Truncate relations before dropping so that all dependencies between
20077 : : * relations are removed after they are worked on. Doing it like this
20078 : : * might be a waste as it is possible that a relation being truncated will
20079 : : * be dropped anyway due to its parent being dropped, but this makes the
20080 : : * code more robust because of not having to re-check that the relation
20081 : : * exists at truncation time.
20082 : : */
20083 [ + + ]: 613232 : if (oids_to_truncate != NIL)
20084 : 254 : heap_truncate(oids_to_truncate);
20085 : :
20086 [ + + ]: 613228 : if (oids_to_drop != NIL)
20087 : : {
20088 : 31 : ObjectAddresses *targetObjects = new_object_addresses();
20089 : :
20090 [ + - + + : 66 : foreach(l, oids_to_drop)
+ + ]
20091 : : {
20092 : : ObjectAddress object;
20093 : :
20094 : 35 : object.classId = RelationRelationId;
20095 : 35 : object.objectId = lfirst_oid(l);
20096 : 35 : object.objectSubId = 0;
20097 : :
20098 : : Assert(!object_address_present(&object, targetObjects));
20099 : :
20100 : 35 : add_exact_object_address(&object, targetObjects);
20101 : : }
20102 : :
20103 : : /*
20104 : : * Object deletion might involve toast table access (to clean up
20105 : : * toasted catalog entries), so ensure we have a valid snapshot.
20106 : : */
20107 : 31 : PushActiveSnapshot(GetTransactionSnapshot());
20108 : :
20109 : : /*
20110 : : * Since this is an automatic drop, rather than one directly initiated
20111 : : * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
20112 : : */
20113 : 31 : performMultipleDeletions(targetObjects, DROP_CASCADE,
20114 : : PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
20115 : :
20116 : 31 : PopActiveSnapshot();
20117 : :
20118 : : #ifdef USE_ASSERT_CHECKING
20119 : :
20120 : : /*
20121 : : * Note that table deletion will call remove_on_commit_action, so the
20122 : : * entry should get marked as deleted.
20123 : : */
20124 : : foreach(l, on_commits)
20125 : : {
20126 : : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20127 : :
20128 : : if (oc->oncommit != ONCOMMIT_DROP)
20129 : : continue;
20130 : :
20131 : : Assert(oc->deleting_subid != InvalidSubTransactionId);
20132 : : }
20133 : : #endif
20134 : : }
20135 : 613228 : }
20136 : :
20137 : : /*
20138 : : * Post-commit or post-abort cleanup for ON COMMIT management.
20139 : : *
20140 : : * All we do here is remove no-longer-needed OnCommitItem entries.
20141 : : *
20142 : : * During commit, remove entries that were deleted during this transaction;
20143 : : * during abort, remove those created during this transaction.
20144 : : */
20145 : : void
20146 : 649082 : AtEOXact_on_commit_actions(bool isCommit)
20147 : : {
20148 : : ListCell *cur_item;
20149 : :
20150 [ + + + + : 649648 : foreach(cur_item, on_commits)
+ + ]
20151 : : {
20152 : 566 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20153 : :
20154 [ + + + + ]: 634 : if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
20155 : 68 : oc->creating_subid != InvalidSubTransactionId)
20156 : : {
20157 : : /* cur_item must be removed */
20158 : 100 : on_commits = foreach_delete_current(on_commits, cur_item);
20159 : 100 : pfree(oc);
20160 : : }
20161 : : else
20162 : : {
20163 : : /* cur_item must be preserved */
20164 : 466 : oc->creating_subid = InvalidSubTransactionId;
20165 : 466 : oc->deleting_subid = InvalidSubTransactionId;
20166 : : }
20167 : : }
20168 : 649082 : }
20169 : :
20170 : : /*
20171 : : * Post-subcommit or post-subabort cleanup for ON COMMIT management.
20172 : : *
20173 : : * During subabort, we can immediately remove entries created during this
20174 : : * subtransaction. During subcommit, just relabel entries marked during
20175 : : * this subtransaction as being the parent's responsibility.
20176 : : */
20177 : : void
20178 : 23004 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
20179 : : SubTransactionId parentSubid)
20180 : : {
20181 : : ListCell *cur_item;
20182 : :
20183 [ - + - - : 23004 : foreach(cur_item, on_commits)
- + ]
20184 : : {
20185 : 0 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20186 : :
20187 [ # # # # ]: 0 : if (!isCommit && oc->creating_subid == mySubid)
20188 : : {
20189 : : /* cur_item must be removed */
20190 : 0 : on_commits = foreach_delete_current(on_commits, cur_item);
20191 : 0 : pfree(oc);
20192 : : }
20193 : : else
20194 : : {
20195 : : /* cur_item must be preserved */
20196 [ # # ]: 0 : if (oc->creating_subid == mySubid)
20197 : 0 : oc->creating_subid = parentSubid;
20198 [ # # ]: 0 : if (oc->deleting_subid == mySubid)
20199 [ # # ]: 0 : oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
20200 : : }
20201 : : }
20202 : 23004 : }
20203 : :
20204 : : /*
20205 : : * This is intended as a callback for RangeVarGetRelidExtended(). It allows
20206 : : * the relation to be locked only if (1) it's a plain or partitioned table,
20207 : : * materialized view, or TOAST table and (2) the current user is the owner (or
20208 : : * the superuser) or has been granted MAINTAIN. This meets the
20209 : : * permission-checking needs of CLUSTER, REPACK, REINDEX TABLE, and REFRESH
20210 : : * MATERIALIZED VIEW; we expose it here so that it can be used by all.
20211 : : */
20212 : : void
20213 : 773 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
20214 : : Oid relId, Oid oldRelId, void *arg)
20215 : : {
20216 : : char relkind;
20217 : : AclResult aclresult;
20218 : :
20219 : : /* Nothing to do if the relation was not found. */
20220 [ + + ]: 773 : if (!OidIsValid(relId))
20221 : 3 : return;
20222 : :
20223 : : /*
20224 : : * If the relation does exist, check whether it's an index. But note that
20225 : : * the relation might have been dropped between the time we did the name
20226 : : * lookup and now. In that case, there's nothing to do.
20227 : : */
20228 : 770 : relkind = get_rel_relkind(relId);
20229 [ - + ]: 770 : if (!relkind)
20230 : 0 : return;
20231 [ + + + + : 770 : if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
+ + ]
20232 [ + + ]: 126 : relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
20233 [ + - ]: 22 : ereport(ERROR,
20234 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20235 : : errmsg("\"%s\" is not a table or materialized view", relation->relname)));
20236 : :
20237 : : /* Check permissions */
20238 : 748 : aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
20239 [ + + ]: 748 : if (aclresult != ACLCHECK_OK)
20240 : 20 : aclcheck_error(aclresult,
20241 : 20 : get_relkind_objtype(get_rel_relkind(relId)),
20242 : 20 : relation->relname);
20243 : : }
20244 : :
20245 : : /*
20246 : : * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
20247 : : */
20248 : : static void
20249 : 1424 : RangeVarCallbackForTruncate(const RangeVar *relation,
20250 : : Oid relId, Oid oldRelId, void *arg)
20251 : : {
20252 : : HeapTuple tuple;
20253 : :
20254 : : /* Nothing to do if the relation was not found. */
20255 [ - + ]: 1424 : if (!OidIsValid(relId))
20256 : 0 : return;
20257 : :
20258 : 1424 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20259 [ - + ]: 1424 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20260 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20261 : :
20262 : 1424 : truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
20263 : 1421 : truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
20264 : :
20265 : 1401 : ReleaseSysCache(tuple);
20266 : : }
20267 : :
20268 : : /*
20269 : : * Callback for RangeVarGetRelidExtended(). Checks that the current user is
20270 : : * the owner of the relation, or superuser.
20271 : : */
20272 : : void
20273 : 10499 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
20274 : : Oid relId, Oid oldRelId, void *arg)
20275 : : {
20276 : : HeapTuple tuple;
20277 : :
20278 : : /* Nothing to do if the relation was not found. */
20279 [ + + ]: 10499 : if (!OidIsValid(relId))
20280 : 4 : return;
20281 : :
20282 : 10495 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20283 [ - + ]: 10495 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20284 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20285 : :
20286 [ + + ]: 10495 : if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
20287 : 4 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
20288 : 4 : relation->relname);
20289 : :
20290 : : /*
20291 : : * Conflict log tables are used internally for logical replication
20292 : : * conflict logging and should not be modified directly, as it could
20293 : : * disrupt conflict logging.
20294 : : */
20295 [ + + ]: 10491 : if (IsConflictLogTableClass((Form_pg_class) GETSTRUCT(tuple)))
20296 [ + - ]: 4 : ereport(ERROR,
20297 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20298 : : errmsg("cannot change conflict log table \"%s\"",
20299 : : relation->relname),
20300 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
20301 : :
20302 [ + + + + ]: 20914 : if (!allowSystemTableMods &&
20303 : 10427 : IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
20304 [ + - ]: 1 : ereport(ERROR,
20305 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
20306 : : errmsg("permission denied: \"%s\" is a system catalog",
20307 : : relation->relname)));
20308 : :
20309 : 10486 : ReleaseSysCache(tuple);
20310 : : }
20311 : :
20312 : : /*
20313 : : * Common RangeVarGetRelid callback for rename, set schema, and alter table
20314 : : * processing.
20315 : : */
20316 : : static void
20317 : 22086 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
20318 : : void *arg)
20319 : : {
20320 : 22086 : Node *stmt = (Node *) arg;
20321 : : ObjectType reltype;
20322 : : HeapTuple tuple;
20323 : : Form_pg_class classform;
20324 : : AclResult aclresult;
20325 : : char relkind;
20326 : :
20327 : 22086 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
20328 [ + + ]: 22086 : if (!HeapTupleIsValid(tuple))
20329 : 158 : return; /* concurrently dropped */
20330 : 21928 : classform = (Form_pg_class) GETSTRUCT(tuple);
20331 : 21928 : relkind = classform->relkind;
20332 : :
20333 : : /* Must own relation. */
20334 [ + + ]: 21928 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
20335 : 40 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
20336 : :
20337 : : /*
20338 : : * Conflict log tables are used internally for logical replication
20339 : : * conflict logging and should not be altered directly, as it could
20340 : : * disrupt conflict logging.
20341 : : */
20342 [ + + ]: 21888 : if (IsConflictLogTableClass(classform))
20343 [ + - ]: 13 : ereport(ERROR,
20344 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20345 : : errmsg("cannot alter conflict log table \"%s\"",
20346 : : rv->relname),
20347 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
20348 : :
20349 : : /* No system table modifications unless explicitly allowed. */
20350 [ + + + + ]: 21875 : if (!allowSystemTableMods && IsSystemClass(relid, classform))
20351 [ + - ]: 18 : ereport(ERROR,
20352 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
20353 : : errmsg("permission denied: \"%s\" is a system catalog",
20354 : : rv->relname)));
20355 : :
20356 : : /*
20357 : : * Extract the specified relation type from the statement parse tree.
20358 : : *
20359 : : * Also, for ALTER .. RENAME, check permissions: the user must (still)
20360 : : * have CREATE rights on the containing namespace.
20361 : : */
20362 [ + + ]: 21857 : if (IsA(stmt, RenameStmt))
20363 : : {
20364 : 295 : aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
20365 : : GetUserId(), ACL_CREATE);
20366 [ - + ]: 295 : if (aclresult != ACLCHECK_OK)
20367 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
20368 : 0 : get_namespace_name(classform->relnamespace));
20369 : 295 : reltype = ((RenameStmt *) stmt)->renameType;
20370 : : }
20371 [ + + ]: 21562 : else if (IsA(stmt, AlterObjectSchemaStmt))
20372 : 64 : reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
20373 : :
20374 [ + - ]: 21498 : else if (IsA(stmt, AlterTableStmt))
20375 : 21498 : reltype = ((AlterTableStmt *) stmt)->objtype;
20376 : : else
20377 : : {
20378 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
20379 : : reltype = OBJECT_TABLE; /* placate compiler */
20380 : : }
20381 : :
20382 : : /*
20383 : : * For compatibility with prior releases, we allow ALTER TABLE to be used
20384 : : * with most other types of relations (but not composite types). We allow
20385 : : * similar flexibility for ALTER INDEX in the case of RENAME, but not
20386 : : * otherwise. Otherwise, the user must select the correct form of the
20387 : : * command for the relation at issue.
20388 : : */
20389 [ + + - + ]: 21857 : if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
20390 [ # # ]: 0 : ereport(ERROR,
20391 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20392 : : errmsg("\"%s\" is not a sequence", rv->relname)));
20393 : :
20394 [ + + - + ]: 21857 : if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
20395 [ # # ]: 0 : ereport(ERROR,
20396 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20397 : : errmsg("\"%s\" is not a view", rv->relname)));
20398 : :
20399 [ + + - + ]: 21857 : if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
20400 [ # # ]: 0 : ereport(ERROR,
20401 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20402 : : errmsg("\"%s\" is not a materialized view", rv->relname)));
20403 : :
20404 [ + + - + ]: 21857 : if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
20405 [ # # ]: 0 : ereport(ERROR,
20406 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20407 : : errmsg("\"%s\" is not a foreign table", rv->relname)));
20408 : :
20409 [ + + - + ]: 21857 : if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
20410 [ # # ]: 0 : ereport(ERROR,
20411 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20412 : : errmsg("\"%s\" is not a composite type", rv->relname)));
20413 : :
20414 [ + + + + : 21857 : if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
+ + ]
20415 : : relkind != RELKIND_PARTITIONED_INDEX
20416 [ + + ]: 28 : && !IsA(stmt, RenameStmt))
20417 [ + - ]: 4 : ereport(ERROR,
20418 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20419 : : errmsg("\"%s\" is not an index", rv->relname)));
20420 : :
20421 : : /*
20422 : : * Don't allow ALTER TABLE on composite types. We want people to use ALTER
20423 : : * TYPE for that.
20424 : : */
20425 [ + + - + ]: 21853 : if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
20426 [ # # ]: 0 : ereport(ERROR,
20427 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20428 : : errmsg("\"%s\" is a composite type", rv->relname),
20429 : : /* translator: %s is an SQL ALTER command */
20430 : : errhint("Use %s instead.",
20431 : : "ALTER TYPE")));
20432 : :
20433 : : /*
20434 : : * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
20435 : : * to a different schema, such as indexes and TOAST tables.
20436 : : */
20437 [ + + ]: 21853 : if (IsA(stmt, AlterObjectSchemaStmt))
20438 : : {
20439 [ + - - + ]: 64 : if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
20440 [ # # ]: 0 : ereport(ERROR,
20441 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20442 : : errmsg("cannot change schema of index \"%s\"",
20443 : : rv->relname),
20444 : : errhint("Change the schema of the table instead.")));
20445 [ - + ]: 64 : else if (relkind == RELKIND_COMPOSITE_TYPE)
20446 [ # # ]: 0 : ereport(ERROR,
20447 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20448 : : errmsg("cannot change schema of composite type \"%s\"",
20449 : : rv->relname),
20450 : : /* translator: %s is an SQL ALTER command */
20451 : : errhint("Use %s instead.",
20452 : : "ALTER TYPE")));
20453 [ - + ]: 64 : else if (relkind == RELKIND_TOASTVALUE)
20454 [ # # ]: 0 : ereport(ERROR,
20455 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20456 : : errmsg("cannot change schema of TOAST table \"%s\"",
20457 : : rv->relname),
20458 : : errhint("Change the schema of the table instead.")));
20459 : : }
20460 : :
20461 : 21853 : ReleaseSysCache(tuple);
20462 : : }
20463 : :
20464 : : /*
20465 : : * Transform any expressions present in the partition key
20466 : : *
20467 : : * Returns a transformed PartitionSpec.
20468 : : */
20469 : : static PartitionSpec *
20470 : 3418 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
20471 : : {
20472 : : PartitionSpec *newspec;
20473 : : ParseState *pstate;
20474 : : ParseNamespaceItem *nsitem;
20475 : : ListCell *l;
20476 : :
20477 : 3418 : newspec = makeNode(PartitionSpec);
20478 : :
20479 : 3418 : newspec->strategy = partspec->strategy;
20480 : 3418 : newspec->partParams = NIL;
20481 : 3418 : newspec->location = partspec->location;
20482 : :
20483 : : /* Check valid number of columns for strategy */
20484 [ + + + + ]: 5035 : if (partspec->strategy == PARTITION_STRATEGY_LIST &&
20485 : 1617 : list_length(partspec->partParams) != 1)
20486 [ + - ]: 4 : ereport(ERROR,
20487 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20488 : : errmsg("cannot use \"list\" partition strategy with more than one column")));
20489 : :
20490 : : /*
20491 : : * Create a dummy ParseState and insert the target relation as its sole
20492 : : * rangetable entry. We need a ParseState for transformExpr.
20493 : : */
20494 : 3414 : pstate = make_parsestate(NULL);
20495 : 3414 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
20496 : : NULL, false, true);
20497 : 3414 : addNSItemToQuery(pstate, nsitem, true, true, true);
20498 : :
20499 : : /* take care of any partition expressions */
20500 [ + - + + : 7130 : foreach(l, partspec->partParams)
+ + ]
20501 : : {
20502 : 3732 : PartitionElem *pelem = lfirst_node(PartitionElem, l);
20503 : :
20504 [ + + ]: 3732 : if (pelem->expr)
20505 : : {
20506 : : /* Copy, to avoid scribbling on the input */
20507 : 232 : pelem = copyObject(pelem);
20508 : :
20509 : : /* Now do parse transformation of the expression */
20510 : 232 : pelem->expr = transformExpr(pstate, pelem->expr,
20511 : : EXPR_KIND_PARTITION_EXPRESSION);
20512 : :
20513 : : /* we have to fix its collations too */
20514 : 216 : assign_expr_collations(pstate, pelem->expr);
20515 : : }
20516 : :
20517 : 3716 : newspec->partParams = lappend(newspec->partParams, pelem);
20518 : : }
20519 : :
20520 : 3398 : return newspec;
20521 : : }
20522 : :
20523 : : /*
20524 : : * Compute per-partition-column information from a list of PartitionElems.
20525 : : * Expressions in the PartitionElems must be parse-analyzed already.
20526 : : */
20527 : : static void
20528 : 3398 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
20529 : : List **partexprs, Oid *partopclass, Oid *partcollation,
20530 : : PartitionStrategy strategy)
20531 : : {
20532 : : int attn;
20533 : : ListCell *lc;
20534 : : Oid am_oid;
20535 : :
20536 : 3398 : attn = 0;
20537 [ + - + + : 7026 : foreach(lc, partParams)
+ + ]
20538 : : {
20539 : 3716 : PartitionElem *pelem = lfirst_node(PartitionElem, lc);
20540 : : Oid atttype;
20541 : : Oid attcollation;
20542 : :
20543 [ + + ]: 3716 : if (pelem->name != NULL)
20544 : : {
20545 : : /* Simple attribute reference */
20546 : : HeapTuple atttuple;
20547 : : Form_pg_attribute attform;
20548 : :
20549 : 3500 : atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
20550 : 3500 : pelem->name);
20551 [ + + ]: 3500 : if (!HeapTupleIsValid(atttuple))
20552 [ + - ]: 8 : ereport(ERROR,
20553 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
20554 : : errmsg("column \"%s\" named in partition key does not exist",
20555 : : pelem->name),
20556 : : parser_errposition(pstate, pelem->location)));
20557 : 3492 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
20558 : :
20559 [ + + ]: 3492 : if (attform->attnum <= 0)
20560 [ + - ]: 4 : ereport(ERROR,
20561 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20562 : : errmsg("cannot use system column \"%s\" in partition key",
20563 : : pelem->name),
20564 : : parser_errposition(pstate, pelem->location)));
20565 : :
20566 : : /*
20567 : : * Stored generated columns cannot work: They are computed after
20568 : : * BEFORE triggers, but partition routing is done before all
20569 : : * triggers. Maybe virtual generated columns could be made to
20570 : : * work, but then they would need to be handled as an expression
20571 : : * below.
20572 : : */
20573 [ + + ]: 3488 : if (attform->attgenerated)
20574 [ + - ]: 8 : ereport(ERROR,
20575 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20576 : : errmsg("cannot use generated column in partition key"),
20577 : : errdetail("Column \"%s\" is a generated column.",
20578 : : pelem->name),
20579 : : parser_errposition(pstate, pelem->location)));
20580 : :
20581 : 3480 : partattrs[attn] = attform->attnum;
20582 : 3480 : atttype = attform->atttypid;
20583 : 3480 : attcollation = attform->attcollation;
20584 : 3480 : ReleaseSysCache(atttuple);
20585 : : }
20586 : : else
20587 : : {
20588 : : /* Expression */
20589 : 216 : Node *expr = pelem->expr;
20590 : : char partattname[16];
20591 : 216 : Bitmapset *expr_attrs = NULL;
20592 : : int i;
20593 : :
20594 : : Assert(expr != NULL);
20595 : 216 : atttype = exprType(expr);
20596 : 216 : attcollation = exprCollation(expr);
20597 : :
20598 : : /*
20599 : : * The expression must be of a storable type (e.g., not RECORD).
20600 : : * The test is the same as for whether a table column is of a safe
20601 : : * type (which is why we needn't check for the non-expression
20602 : : * case).
20603 : : */
20604 : 216 : snprintf(partattname, sizeof(partattname), "%d", attn + 1);
20605 : 216 : CheckAttributeType(partattname,
20606 : : atttype, attcollation,
20607 : : NIL, CHKATYPE_IS_PARTKEY);
20608 : :
20609 : : /*
20610 : : * Strip any top-level COLLATE clause. This ensures that we treat
20611 : : * "x COLLATE y" and "(x COLLATE y)" alike.
20612 : : */
20613 [ - + ]: 208 : while (IsA(expr, CollateExpr))
20614 : 0 : expr = (Node *) ((CollateExpr *) expr)->arg;
20615 : :
20616 : : /*
20617 : : * Examine all the columns in the partition key expression. When
20618 : : * the whole-row reference is present, examine all the columns of
20619 : : * the partitioned table.
20620 : : */
20621 : 208 : pull_varattnos(expr, 1, &expr_attrs);
20622 [ + + ]: 208 : if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, expr_attrs))
20623 : : {
20624 : 40 : expr_attrs = bms_add_range(expr_attrs,
20625 : : 1 - FirstLowInvalidHeapAttributeNumber,
20626 : 20 : RelationGetNumberOfAttributes(rel) - FirstLowInvalidHeapAttributeNumber);
20627 : 20 : expr_attrs = bms_del_member(expr_attrs, 0 - FirstLowInvalidHeapAttributeNumber);
20628 : : }
20629 : :
20630 : 208 : i = -1;
20631 [ + + ]: 457 : while ((i = bms_next_member(expr_attrs, i)) >= 0)
20632 : : {
20633 : 281 : AttrNumber attno = i + FirstLowInvalidHeapAttributeNumber;
20634 : :
20635 : : Assert(attno != 0);
20636 : :
20637 : : /*
20638 : : * Cannot allow system column references, since that would
20639 : : * make partition routing impossible: their values won't be
20640 : : * known yet when we need to do that.
20641 : : */
20642 [ - + ]: 281 : if (attno < 0)
20643 [ # # ]: 0 : ereport(ERROR,
20644 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20645 : : errmsg("partition key expressions cannot contain system column references")));
20646 : :
20647 : : /*
20648 : : * Stored generated columns cannot work: They are computed
20649 : : * after BEFORE triggers, but partition routing is done before
20650 : : * all triggers. Virtual generated columns could probably
20651 : : * work, but it would require more work elsewhere (for example
20652 : : * SET EXPRESSION would need to check whether the column is
20653 : : * used in partition keys). Seems safer to prohibit for now.
20654 : : */
20655 [ + + ]: 281 : if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
20656 [ + - ]: 32 : ereport(ERROR,
20657 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20658 : : errmsg("cannot use generated column in partition key"),
20659 : : errdetail("Column \"%s\" is a generated column.",
20660 : : get_attname(RelationGetRelid(rel), attno, false)),
20661 : : parser_errposition(pstate, pelem->location)));
20662 : : }
20663 : :
20664 [ + + ]: 176 : if (IsA(expr, Var) &&
20665 [ + + ]: 8 : ((Var *) expr)->varattno > 0)
20666 : : {
20667 : :
20668 : : /*
20669 : : * User wrote "(column)" or "(column COLLATE something)".
20670 : : * Treat it like simple attribute anyway.
20671 : : */
20672 : 4 : partattrs[attn] = ((Var *) expr)->varattno;
20673 : : }
20674 : : else
20675 : : {
20676 : 172 : partattrs[attn] = 0; /* marks the column as expression */
20677 : 172 : *partexprs = lappend(*partexprs, expr);
20678 : :
20679 : : /*
20680 : : * transformPartitionSpec() should have already rejected
20681 : : * subqueries, aggregates, window functions, and SRFs, based
20682 : : * on the EXPR_KIND_ for partition expressions.
20683 : : */
20684 : :
20685 : : /*
20686 : : * Preprocess the expression before checking for mutability.
20687 : : * This is essential for the reasons described in
20688 : : * contain_mutable_functions_after_planning. However, we call
20689 : : * expression_planner for ourselves rather than using that
20690 : : * function, because if constant-folding reduces the
20691 : : * expression to a constant, we'd like to know that so we can
20692 : : * complain below.
20693 : : *
20694 : : * Like contain_mutable_functions_after_planning, assume that
20695 : : * expression_planner won't scribble on its input, so this
20696 : : * won't affect the partexprs entry we saved above.
20697 : : */
20698 : 172 : expr = (Node *) expression_planner((Expr *) expr);
20699 : :
20700 : : /*
20701 : : * Partition expressions cannot contain mutable functions,
20702 : : * because a given row must always map to the same partition
20703 : : * as long as there is no change in the partition boundary
20704 : : * structure.
20705 : : */
20706 [ + + ]: 172 : if (contain_mutable_functions(expr))
20707 [ + - ]: 4 : ereport(ERROR,
20708 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20709 : : errmsg("functions in partition key expression must be marked IMMUTABLE")));
20710 : :
20711 : : /*
20712 : : * While it is not exactly *wrong* for a partition expression
20713 : : * to be a constant, it seems better to reject such keys.
20714 : : */
20715 [ + + ]: 168 : if (IsA(expr, Const))
20716 [ + - ]: 8 : ereport(ERROR,
20717 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20718 : : errmsg("cannot use constant expression as partition key")));
20719 : : }
20720 : : }
20721 : :
20722 : : /*
20723 : : * Apply collation override if any
20724 : : */
20725 [ + + ]: 3644 : if (pelem->collation)
20726 : 36 : attcollation = get_collation_oid(pelem->collation, false);
20727 : :
20728 : : /*
20729 : : * Check we have a collation iff it's a collatable type. The only
20730 : : * expected failures here are (1) COLLATE applied to a noncollatable
20731 : : * type, or (2) partition expression had an unresolved collation. But
20732 : : * we might as well code this to be a complete consistency check.
20733 : : */
20734 [ + + ]: 3644 : if (type_is_collatable(atttype))
20735 : : {
20736 [ - + ]: 397 : if (!OidIsValid(attcollation))
20737 [ # # ]: 0 : ereport(ERROR,
20738 : : (errcode(ERRCODE_INDETERMINATE_COLLATION),
20739 : : errmsg("could not determine which collation to use for partition expression"),
20740 : : errhint("Use the COLLATE clause to set the collation explicitly.")));
20741 : : }
20742 : : else
20743 : : {
20744 [ - + ]: 3247 : if (OidIsValid(attcollation))
20745 [ # # ]: 0 : ereport(ERROR,
20746 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
20747 : : errmsg("collations are not supported by type %s",
20748 : : format_type_be(atttype))));
20749 : : }
20750 : :
20751 : 3644 : partcollation[attn] = attcollation;
20752 : :
20753 : : /*
20754 : : * Identify the appropriate operator class. For list and range
20755 : : * partitioning, we use a btree operator class; hash partitioning uses
20756 : : * a hash operator class.
20757 : : */
20758 [ + + ]: 3644 : if (strategy == PARTITION_STRATEGY_HASH)
20759 : 207 : am_oid = HASH_AM_OID;
20760 : : else
20761 : 3437 : am_oid = BTREE_AM_OID;
20762 : :
20763 [ + + ]: 3644 : if (!pelem->opclass)
20764 : : {
20765 : 3544 : partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
20766 : :
20767 [ + + ]: 3544 : if (!OidIsValid(partopclass[attn]))
20768 : : {
20769 [ - + ]: 8 : if (strategy == PARTITION_STRATEGY_HASH)
20770 [ # # ]: 0 : ereport(ERROR,
20771 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
20772 : : errmsg("data type %s has no default operator class for access method \"%s\"",
20773 : : format_type_be(atttype), "hash"),
20774 : : errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
20775 : : else
20776 [ + - ]: 8 : ereport(ERROR,
20777 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
20778 : : errmsg("data type %s has no default operator class for access method \"%s\"",
20779 : : format_type_be(atttype), "btree"),
20780 : : errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
20781 : : }
20782 : : }
20783 : : else
20784 [ + + ]: 100 : partopclass[attn] = ResolveOpClass(pelem->opclass,
20785 : : atttype,
20786 : : am_oid == HASH_AM_OID ? "hash" : "btree",
20787 : : am_oid);
20788 : :
20789 : 3628 : attn++;
20790 : : }
20791 : 3310 : }
20792 : :
20793 : : /*
20794 : : * PartConstraintImpliedByRelConstraint
20795 : : * Do scanrel's existing constraints imply the partition constraint?
20796 : : *
20797 : : * "Existing constraints" include its check constraints and column-level
20798 : : * not-null constraints. partConstraint describes the partition constraint,
20799 : : * in implicit-AND form.
20800 : : */
20801 : : bool
20802 : 1991 : PartConstraintImpliedByRelConstraint(Relation scanrel,
20803 : : List *partConstraint)
20804 : : {
20805 : 1991 : List *existConstraint = NIL;
20806 : 1991 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20807 : : int i;
20808 : :
20809 [ + + + + ]: 1991 : if (constr && constr->has_not_null)
20810 : : {
20811 : 500 : int natts = scanrel->rd_att->natts;
20812 : :
20813 [ + + ]: 1662 : for (i = 1; i <= natts; i++)
20814 : : {
20815 : 1162 : CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20816 : :
20817 : : /* invalid not-null constraint must be ignored here */
20818 [ + + + - ]: 1162 : if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20819 : : {
20820 : 695 : Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
20821 : 695 : NullTest *ntest = makeNode(NullTest);
20822 : :
20823 : 695 : ntest->arg = (Expr *) makeVar(1,
20824 : : i,
20825 : : wholeatt->atttypid,
20826 : : wholeatt->atttypmod,
20827 : : wholeatt->attcollation,
20828 : : 0);
20829 : 695 : ntest->nulltesttype = IS_NOT_NULL;
20830 : :
20831 : : /*
20832 : : * argisrow=false is correct even for a composite column,
20833 : : * because attnotnull does not represent a SQL-spec IS NOT
20834 : : * NULL test in such a case, just IS DISTINCT FROM NULL.
20835 : : */
20836 : 695 : ntest->argisrow = false;
20837 : 695 : ntest->location = -1;
20838 : 695 : existConstraint = lappend(existConstraint, ntest);
20839 : : }
20840 : : }
20841 : : }
20842 : :
20843 : 1991 : return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20844 : : }
20845 : :
20846 : : /*
20847 : : * ConstraintImpliedByRelConstraint
20848 : : * Do scanrel's existing constraints imply the given constraint?
20849 : : *
20850 : : * testConstraint is the constraint to validate. provenConstraint is a
20851 : : * caller-provided list of conditions which this function may assume
20852 : : * to be true. Both provenConstraint and testConstraint must be in
20853 : : * implicit-AND form, must only contain immutable clauses, and must
20854 : : * contain only Vars with varno = 1.
20855 : : */
20856 : : bool
20857 : 2835 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
20858 : : {
20859 : 2835 : List *existConstraint = list_copy(provenConstraint);
20860 : 2835 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20861 : : int num_check,
20862 : : i;
20863 : :
20864 [ + + ]: 2835 : num_check = (constr != NULL) ? constr->num_check : 0;
20865 [ + + ]: 3175 : for (i = 0; i < num_check; i++)
20866 : : {
20867 : : Node *cexpr;
20868 : :
20869 : : /*
20870 : : * If this constraint hasn't been fully validated yet, we must ignore
20871 : : * it here.
20872 : : */
20873 [ + + ]: 340 : if (!constr->check[i].ccvalid)
20874 : 16 : continue;
20875 : :
20876 : : /*
20877 : : * NOT ENFORCED constraints are always marked as invalid, which should
20878 : : * have been ignored.
20879 : : */
20880 : : Assert(constr->check[i].ccenforced);
20881 : :
20882 : 324 : cexpr = stringToNode(constr->check[i].ccbin);
20883 : :
20884 : : /*
20885 : : * Run each expression through const-simplification and
20886 : : * canonicalization. It is necessary, because we will be comparing it
20887 : : * to similarly-processed partition constraint expressions, and may
20888 : : * fail to detect valid matches without this.
20889 : : */
20890 : 324 : cexpr = eval_const_expressions(NULL, cexpr);
20891 : 324 : cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
20892 : :
20893 : 324 : existConstraint = list_concat(existConstraint,
20894 : 324 : make_ands_implicit((Expr *) cexpr));
20895 : : }
20896 : :
20897 : : /*
20898 : : * Try to make the proof. Since we are comparing CHECK constraints, we
20899 : : * need to use weak implication, i.e., we assume existConstraint is
20900 : : * not-false and try to prove the same for testConstraint.
20901 : : *
20902 : : * Note that predicate_implied_by assumes its first argument is known
20903 : : * immutable. That should always be true for both NOT NULL and partition
20904 : : * constraints, so we don't test it here.
20905 : : */
20906 : 2835 : return predicate_implied_by(testConstraint, existConstraint, true);
20907 : : }
20908 : :
20909 : : /*
20910 : : * QueuePartitionConstraintValidation
20911 : : *
20912 : : * Add an entry to wqueue to have the given partition constraint validated by
20913 : : * Phase 3, for the given relation, and all its children.
20914 : : *
20915 : : * We first verify whether the given constraint is implied by pre-existing
20916 : : * relation constraints; if it is, there's no need to scan the table to
20917 : : * validate, so don't queue in that case.
20918 : : */
20919 : : static void
20920 : 1642 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
20921 : : List *partConstraint,
20922 : : bool validate_default)
20923 : : {
20924 : : /*
20925 : : * Based on the table's existing constraints, determine whether or not we
20926 : : * may skip scanning the table.
20927 : : */
20928 [ + + ]: 1642 : if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
20929 : : {
20930 [ + + ]: 55 : if (!validate_default)
20931 [ + + ]: 41 : ereport(DEBUG1,
20932 : : (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
20933 : : RelationGetRelationName(scanrel))));
20934 : : else
20935 [ + + ]: 14 : ereport(DEBUG1,
20936 : : (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
20937 : : RelationGetRelationName(scanrel))));
20938 : 55 : return;
20939 : : }
20940 : :
20941 : : /*
20942 : : * Constraints proved insufficient. For plain relations, queue a
20943 : : * validation item now; for partitioned tables, recurse to process each
20944 : : * partition.
20945 : : */
20946 [ + + ]: 1587 : if (scanrel->rd_rel->relkind == RELKIND_RELATION)
20947 : : {
20948 : : AlteredTableInfo *tab;
20949 : :
20950 : : /* Grab a work queue entry. */
20951 : 1324 : tab = ATGetQueueEntry(wqueue, scanrel);
20952 : : Assert(tab->partition_constraint == NULL);
20953 : 1324 : tab->partition_constraint = (Expr *) linitial(partConstraint);
20954 : 1324 : tab->validate_default = validate_default;
20955 : : }
20956 [ + + ]: 263 : else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20957 : : {
20958 : 232 : PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
20959 : : int i;
20960 : :
20961 [ + + ]: 488 : for (i = 0; i < partdesc->nparts; i++)
20962 : : {
20963 : : Relation part_rel;
20964 : : List *thisPartConstraint;
20965 : :
20966 : : /*
20967 : : * This is the minimum lock we need to prevent deadlocks.
20968 : : */
20969 : 256 : part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
20970 : :
20971 : : /*
20972 : : * Adjust the constraint for scanrel so that it matches this
20973 : : * partition's attribute numbers.
20974 : : */
20975 : : thisPartConstraint =
20976 : 256 : map_partition_varattnos(partConstraint, 1,
20977 : : part_rel, scanrel);
20978 : :
20979 : 256 : QueuePartitionConstraintValidation(wqueue, part_rel,
20980 : : thisPartConstraint,
20981 : : validate_default);
20982 : 256 : table_close(part_rel, NoLock); /* keep lock till commit */
20983 : : }
20984 : : }
20985 : : }
20986 : :
20987 : : /*
20988 : : * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
20989 : : *
20990 : : * Return the address of the newly attached partition.
20991 : : */
20992 : : static ObjectAddress
20993 : 1537 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
20994 : : AlterTableUtilityContext *context)
20995 : : {
20996 : : Relation attachrel,
20997 : : catalog;
20998 : : List *attachrel_children;
20999 : : List *partConstraint;
21000 : : SysScanDesc scan;
21001 : : ScanKeyData skey;
21002 : : AttrNumber attno;
21003 : : int natts;
21004 : : TupleDesc tupleDesc;
21005 : : ObjectAddress address;
21006 : : const char *trigger_name;
21007 : : Oid defaultPartOid;
21008 : : List *partBoundConstraint;
21009 : 1537 : List *exceptpuboids = NIL;
21010 : 1537 : ParseState *pstate = make_parsestate(NULL);
21011 : :
21012 : 1537 : pstate->p_sourcetext = context->queryString;
21013 : :
21014 : : /*
21015 : : * We must lock the default partition if one exists, because attaching a
21016 : : * new partition will change its partition constraint.
21017 : : */
21018 : : defaultPartOid =
21019 : 1537 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
21020 [ + + ]: 1537 : if (OidIsValid(defaultPartOid))
21021 : 117 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
21022 : :
21023 : 1537 : attachrel = table_openrv(cmd->name, AccessExclusiveLock);
21024 : :
21025 : : /*
21026 : : * XXX I think it'd be a good idea to grab locks on all tables referenced
21027 : : * by FKs at this point also.
21028 : : */
21029 : :
21030 : : /*
21031 : : * Must be owner of both parent and source table -- parent was checked by
21032 : : * ATSimplePermissions call in ATPrepCmd
21033 : : */
21034 : 1533 : ATSimplePermissions(AT_AttachPartition, attachrel,
21035 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
21036 : :
21037 : : /* A partition can only have one parent */
21038 [ + + ]: 1529 : if (attachrel->rd_rel->relispartition)
21039 [ + - ]: 4 : ereport(ERROR,
21040 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21041 : : errmsg("\"%s\" is already a partition",
21042 : : RelationGetRelationName(attachrel))));
21043 : :
21044 [ + + ]: 1525 : if (OidIsValid(attachrel->rd_rel->reloftype))
21045 [ + - ]: 4 : ereport(ERROR,
21046 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21047 : : errmsg("cannot attach a typed table as partition")));
21048 : :
21049 : : /*
21050 : : * Disallow attaching a partition if the table is referenced in a
21051 : : * publication EXCEPT clause. Changing the partition hierarchy could alter
21052 : : * the effective publication membership.
21053 : : */
21054 : 1521 : exceptpuboids = GetRelationExcludedPublications(RelationGetRelid(attachrel));
21055 [ + + ]: 1521 : if (exceptpuboids != NIL)
21056 : : {
21057 : 4 : bool first = true;
21058 : : StringInfoData pubnames;
21059 : :
21060 : 4 : initStringInfo(&pubnames);
21061 : :
21062 [ + - + + : 12 : foreach_oid(pubid, exceptpuboids)
+ + ]
21063 : : {
21064 : 4 : char *pubname = get_publication_name(pubid, false);
21065 : :
21066 [ + - ]: 4 : if (first)
21067 : 4 : appendStringInfo(&pubnames, _("\"%s\""), pubname);
21068 : : else
21069 : 0 : appendStringInfo(&pubnames, _(", \"%s\""), pubname);
21070 : 4 : first = false;
21071 : : }
21072 : :
21073 [ + - ]: 4 : ereport(ERROR,
21074 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21075 : : errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause",
21076 : : "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause",
21077 : : list_length(exceptpuboids),
21078 : : RelationGetRelationName(attachrel),
21079 : : pubnames.data),
21080 : : errdetail("The publication EXCEPT clause cannot contain tables that are partitions."),
21081 : : errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES."));
21082 : : }
21083 : :
21084 : 1517 : list_free(exceptpuboids);
21085 : :
21086 : : /*
21087 : : * Table being attached should not already be part of inheritance; either
21088 : : * as a child table...
21089 : : */
21090 : 1517 : catalog = table_open(InheritsRelationId, AccessShareLock);
21091 : 1517 : ScanKeyInit(&skey,
21092 : : Anum_pg_inherits_inhrelid,
21093 : : BTEqualStrategyNumber, F_OIDEQ,
21094 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21095 : 1517 : scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
21096 : : NULL, 1, &skey);
21097 [ + + ]: 1517 : if (HeapTupleIsValid(systable_getnext(scan)))
21098 [ + - ]: 4 : ereport(ERROR,
21099 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21100 : : errmsg("cannot attach inheritance child as partition")));
21101 : 1513 : systable_endscan(scan);
21102 : :
21103 : : /* ...or as a parent table (except the case when it is partitioned) */
21104 : 1513 : ScanKeyInit(&skey,
21105 : : Anum_pg_inherits_inhparent,
21106 : : BTEqualStrategyNumber, F_OIDEQ,
21107 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21108 : 1513 : scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
21109 : : 1, &skey);
21110 [ + + ]: 1513 : if (HeapTupleIsValid(systable_getnext(scan)) &&
21111 [ + + ]: 172 : attachrel->rd_rel->relkind == RELKIND_RELATION)
21112 [ + - ]: 4 : ereport(ERROR,
21113 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21114 : : errmsg("cannot attach inheritance parent as partition")));
21115 : 1509 : systable_endscan(scan);
21116 : 1509 : table_close(catalog, AccessShareLock);
21117 : :
21118 : : /*
21119 : : * Prevent circularity by seeing if rel is a partition of attachrel. (In
21120 : : * particular, this disallows making a rel a partition of itself.)
21121 : : *
21122 : : * We do that by checking if rel is a member of the list of attachrel's
21123 : : * partitions provided the latter is partitioned at all. We want to avoid
21124 : : * having to construct this list again, so we request the strongest lock
21125 : : * on all partitions. We need the strongest lock, because we may decide
21126 : : * to scan them if we find out that the table being attached (or its leaf
21127 : : * partitions) may contain rows that violate the partition constraint. If
21128 : : * the table has a constraint that would prevent such rows, which by
21129 : : * definition is present in all the partitions, we need not scan the
21130 : : * table, nor its partitions. But we cannot risk a deadlock by taking a
21131 : : * weaker lock now and the stronger one only when needed.
21132 : : */
21133 : 1509 : attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
21134 : : AccessExclusiveLock, NULL);
21135 [ + + ]: 1509 : if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
21136 [ + - ]: 8 : ereport(ERROR,
21137 : : (errcode(ERRCODE_DUPLICATE_TABLE),
21138 : : errmsg("circular inheritance not allowed"),
21139 : : errdetail("\"%s\" is already a child of \"%s\".",
21140 : : RelationGetRelationName(rel),
21141 : : RelationGetRelationName(attachrel))));
21142 : :
21143 : : /* If the parent is permanent, so must be all of its partitions. */
21144 [ + + ]: 1501 : if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
21145 [ + + ]: 1473 : attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
21146 [ + - ]: 4 : ereport(ERROR,
21147 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21148 : : errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
21149 : : RelationGetRelationName(rel))));
21150 : :
21151 : : /* Temp parent cannot have a partition that is itself not a temp */
21152 [ + + ]: 1497 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
21153 [ + + ]: 28 : attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
21154 [ + - ]: 12 : ereport(ERROR,
21155 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21156 : : errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
21157 : : RelationGetRelationName(rel))));
21158 : :
21159 : : /* If the parent is temp, it must belong to this session */
21160 [ + + - + ]: 1485 : if (RELATION_IS_OTHER_TEMP(rel))
21161 [ # # ]: 0 : ereport(ERROR,
21162 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21163 : : errmsg("cannot attach as partition of temporary relation of another session")));
21164 : :
21165 : : /* Ditto for the partition */
21166 [ + + - + ]: 1485 : if (RELATION_IS_OTHER_TEMP(attachrel))
21167 [ # # ]: 0 : ereport(ERROR,
21168 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21169 : : errmsg("cannot attach temporary relation of another session as partition")));
21170 : :
21171 : : /*
21172 : : * Check if attachrel has any identity columns or any columns that aren't
21173 : : * in the parent.
21174 : : */
21175 : 1485 : tupleDesc = RelationGetDescr(attachrel);
21176 : 1485 : natts = tupleDesc->natts;
21177 [ + + ]: 5063 : for (attno = 1; attno <= natts; attno++)
21178 : : {
21179 : 3606 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
21180 : 3606 : char *attributeName = NameStr(attribute->attname);
21181 : :
21182 : : /* Ignore dropped */
21183 [ + + ]: 3606 : if (attribute->attisdropped)
21184 : 368 : continue;
21185 : :
21186 [ + + ]: 3238 : if (attribute->attidentity)
21187 [ + - ]: 16 : ereport(ERROR,
21188 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21189 : : errmsg("table \"%s\" being attached contains an identity column \"%s\"",
21190 : : RelationGetRelationName(attachrel), attributeName),
21191 : : errdetail("The new partition may not contain an identity column."));
21192 : :
21193 : : /* Try to find the column in parent (matching on column name) */
21194 [ + + ]: 3222 : if (!SearchSysCacheExists2(ATTNAME,
21195 : : ObjectIdGetDatum(RelationGetRelid(rel)),
21196 : : CStringGetDatum(attributeName)))
21197 [ + - ]: 12 : ereport(ERROR,
21198 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
21199 : : errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
21200 : : RelationGetRelationName(attachrel), attributeName,
21201 : : RelationGetRelationName(rel)),
21202 : : errdetail("The new partition may contain only the columns present in parent.")));
21203 : : }
21204 : :
21205 : : /*
21206 : : * If child_rel has row-level triggers with transition tables, we
21207 : : * currently don't allow it to become a partition. See also prohibitions
21208 : : * in ATExecAddInherit() and CreateTrigger().
21209 : : */
21210 : 1457 : trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
21211 [ + + ]: 1457 : if (trigger_name != NULL)
21212 [ + - ]: 4 : ereport(ERROR,
21213 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
21214 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
21215 : : trigger_name, RelationGetRelationName(attachrel)),
21216 : : errdetail("ROW triggers with transition tables are not supported on partitions.")));
21217 : :
21218 : : /*
21219 : : * Check that the new partition's bound is valid and does not overlap any
21220 : : * of existing partitions of the parent - note that it does not return on
21221 : : * error.
21222 : : */
21223 : 1453 : check_new_partition_bound(RelationGetRelationName(attachrel), rel,
21224 : : cmd->bound, pstate);
21225 : :
21226 : : /* OK to create inheritance. Rest of the checks performed there */
21227 : 1429 : CreateInheritance(attachrel, rel, true);
21228 : :
21229 : : /* Update the pg_class entry. */
21230 : 1357 : StorePartitionBound(attachrel, rel, cmd->bound);
21231 : :
21232 : : /* Ensure there exists a correct set of indexes in the partition. */
21233 : 1357 : AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
21234 : :
21235 : : /* and triggers */
21236 : 1337 : CloneRowTriggersToPartition(rel, attachrel);
21237 : :
21238 : : /*
21239 : : * Clone foreign key constraints. Callee is responsible for setting up
21240 : : * for phase 3 constraint verification.
21241 : : */
21242 : 1333 : CloneForeignKeyConstraints(wqueue, rel, attachrel);
21243 : :
21244 : : /*
21245 : : * Generate partition constraint from the partition bound specification.
21246 : : * If the parent itself is a partition, make sure to include its
21247 : : * constraint as well.
21248 : : */
21249 : 1321 : partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
21250 : :
21251 : : /*
21252 : : * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
21253 : : * since it's needed later to construct the constraint expression for
21254 : : * validating against the default partition, if any.
21255 : : */
21256 : 1321 : partConstraint = list_concat_copy(partBoundConstraint,
21257 : 1321 : RelationGetPartitionQual(rel));
21258 : :
21259 : : /* Skip validation if there are no constraints to validate. */
21260 [ + + ]: 1321 : if (partConstraint)
21261 : : {
21262 : : /*
21263 : : * Run the partition quals through const-simplification similar to
21264 : : * check constraints. We skip canonicalize_qual, though, because
21265 : : * partition quals should be in canonical form already.
21266 : : */
21267 : : partConstraint =
21268 : 1293 : (List *) eval_const_expressions(NULL,
21269 : : (Node *) partConstraint);
21270 : :
21271 : : /* XXX this sure looks wrong */
21272 : 1293 : partConstraint = list_make1(make_ands_explicit(partConstraint));
21273 : :
21274 : : /*
21275 : : * Adjust the generated constraint to match this partition's attribute
21276 : : * numbers.
21277 : : */
21278 : 1293 : partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
21279 : : rel);
21280 : :
21281 : : /* Validate partition constraints against the table being attached. */
21282 : 1293 : QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
21283 : : false);
21284 : : }
21285 : :
21286 : : /*
21287 : : * If we're attaching a partition other than the default partition and a
21288 : : * default one exists, then that partition's partition constraint changes,
21289 : : * so add an entry to the work queue to validate it, too. (We must not do
21290 : : * this when the partition being attached is the default one; we already
21291 : : * did it above!)
21292 : : */
21293 [ + + ]: 1321 : if (OidIsValid(defaultPartOid))
21294 : : {
21295 : : Relation defaultrel;
21296 : : List *defPartConstraint;
21297 : :
21298 : : Assert(!cmd->bound->is_default);
21299 : :
21300 : : /* we already hold a lock on the default partition */
21301 : 93 : defaultrel = table_open(defaultPartOid, NoLock);
21302 : : defPartConstraint =
21303 : 93 : get_proposed_default_constraint(partBoundConstraint);
21304 : :
21305 : : /*
21306 : : * Map the Vars in the constraint expression from rel's attnos to
21307 : : * defaultrel's.
21308 : : */
21309 : : defPartConstraint =
21310 : 93 : map_partition_varattnos(defPartConstraint,
21311 : : 1, defaultrel, rel);
21312 : 93 : QueuePartitionConstraintValidation(wqueue, defaultrel,
21313 : : defPartConstraint, true);
21314 : :
21315 : : /* keep our lock until commit. */
21316 : 93 : table_close(defaultrel, NoLock);
21317 : : }
21318 : :
21319 : 1321 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
21320 : :
21321 : : /*
21322 : : * If the partition we just attached is partitioned itself, invalidate
21323 : : * relcache for all descendent partitions too to ensure that their
21324 : : * rd_partcheck expression trees are rebuilt; partitions already locked at
21325 : : * the beginning of this function.
21326 : : */
21327 [ + + ]: 1321 : if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21328 : : {
21329 : : ListCell *l;
21330 : :
21331 [ + - + + : 663 : foreach(l, attachrel_children)
+ + ]
21332 : : {
21333 : 446 : CacheInvalidateRelcacheByRelid(lfirst_oid(l));
21334 : : }
21335 : : }
21336 : :
21337 : : /* keep our lock until commit */
21338 : 1321 : table_close(attachrel, NoLock);
21339 : :
21340 : 1321 : return address;
21341 : : }
21342 : :
21343 : : /*
21344 : : * AttachPartitionEnsureIndexes
21345 : : * subroutine for ATExecAttachPartition to create/match indexes
21346 : : *
21347 : : * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
21348 : : * PARTITION: every partition must have an index attached to each index on the
21349 : : * partitioned table.
21350 : : */
21351 : : static void
21352 : 1357 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
21353 : : {
21354 : : List *idxes;
21355 : : List *attachRelIdxs;
21356 : : Relation *attachrelIdxRels;
21357 : : IndexInfo **attachInfos;
21358 : : ListCell *cell;
21359 : : MemoryContext cxt;
21360 : : MemoryContext oldcxt;
21361 : :
21362 : 1357 : cxt = AllocSetContextCreate(CurrentMemoryContext,
21363 : : "AttachPartitionEnsureIndexes",
21364 : : ALLOCSET_DEFAULT_SIZES);
21365 : 1357 : oldcxt = MemoryContextSwitchTo(cxt);
21366 : :
21367 : 1357 : idxes = RelationGetIndexList(rel);
21368 : 1357 : attachRelIdxs = RelationGetIndexList(attachrel);
21369 : 1357 : attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
21370 : 1357 : attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
21371 : :
21372 : : /* Build arrays of all existing indexes and their IndexInfos */
21373 [ + + + + : 2967 : foreach_oid(cldIdxId, attachRelIdxs)
+ + ]
21374 : : {
21375 : 253 : int i = foreach_current_index(cldIdxId);
21376 : :
21377 : 253 : attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
21378 : 253 : attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
21379 : : }
21380 : :
21381 : : /*
21382 : : * If we're attaching a foreign table, we must fail if any of the indexes
21383 : : * is a constraint index; otherwise, there's nothing to do here. Do this
21384 : : * before starting work, to avoid wasting the effort of building a few
21385 : : * non-unique indexes before coming across a unique one.
21386 : : */
21387 [ + + ]: 1357 : if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
21388 : : {
21389 [ + + + + : 55 : foreach(cell, idxes)
+ + ]
21390 : : {
21391 : 24 : Oid idx = lfirst_oid(cell);
21392 : 24 : Relation idxRel = index_open(idx, AccessShareLock);
21393 : :
21394 [ + + ]: 24 : if (idxRel->rd_index->indisunique ||
21395 [ - + ]: 16 : idxRel->rd_index->indisprimary)
21396 [ + - ]: 8 : ereport(ERROR,
21397 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21398 : : errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
21399 : : RelationGetRelationName(attachrel),
21400 : : RelationGetRelationName(rel)),
21401 : : errdetail("Partitioned table \"%s\" contains unique indexes.",
21402 : : RelationGetRelationName(rel))));
21403 : 16 : index_close(idxRel, AccessShareLock);
21404 : : }
21405 : :
21406 : 31 : goto out;
21407 : : }
21408 : :
21409 : : /*
21410 : : * For each index on the partitioned table, find a matching one in the
21411 : : * partition-to-be; if one is not found, create one.
21412 : : */
21413 [ + + + + : 1599 : foreach(cell, idxes)
+ + ]
21414 : : {
21415 : 293 : Oid idx = lfirst_oid(cell);
21416 : 293 : Relation idxRel = index_open(idx, AccessShareLock);
21417 : : IndexInfo *info;
21418 : : AttrMap *attmap;
21419 : 293 : bool found = false;
21420 : : Oid constraintOid;
21421 : :
21422 : : /*
21423 : : * Ignore indexes in the partitioned table other than partitioned
21424 : : * indexes.
21425 : : */
21426 [ - + ]: 293 : if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
21427 : : {
21428 : 0 : index_close(idxRel, AccessShareLock);
21429 : 0 : continue;
21430 : : }
21431 : :
21432 : : /* construct an indexinfo to compare existing indexes against */
21433 : 293 : info = BuildIndexInfo(idxRel);
21434 : 293 : attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
21435 : : RelationGetDescr(rel),
21436 : : false);
21437 : 293 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
21438 : :
21439 : : /*
21440 : : * Scan the list of existing indexes in the partition-to-be, and mark
21441 : : * the first matching, valid, unattached one we find, if any, as
21442 : : * partition of the parent index. If we find one, we're done.
21443 : : */
21444 [ + + ]: 333 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21445 : : {
21446 : 181 : Oid cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
21447 : 181 : Oid cldConstrOid = InvalidOid;
21448 : :
21449 : : /* does this index have a parent? if so, can't use it */
21450 [ + + ]: 181 : if (attachrelIdxRels[i]->rd_rel->relispartition)
21451 : 8 : continue;
21452 : :
21453 : : /* If this index is invalid, can't use it */
21454 [ + + ]: 173 : if (!attachrelIdxRels[i]->rd_index->indisvalid)
21455 : 4 : continue;
21456 : :
21457 [ + + ]: 169 : if (CompareIndexInfo(attachInfos[i], info,
21458 : 169 : attachrelIdxRels[i]->rd_indcollation,
21459 : 169 : idxRel->rd_indcollation,
21460 : 169 : attachrelIdxRels[i]->rd_opfamily,
21461 : 169 : idxRel->rd_opfamily,
21462 : : attmap))
21463 : : {
21464 : : /*
21465 : : * If this index is being created in the parent because of a
21466 : : * constraint, then the child needs to have a constraint also,
21467 : : * so look for one. If there is no such constraint, this
21468 : : * index is no good, so keep looking.
21469 : : */
21470 [ + + ]: 145 : if (OidIsValid(constraintOid))
21471 : : {
21472 : : cldConstrOid =
21473 : 80 : get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
21474 : : cldIdxId);
21475 : : /* no dice */
21476 [ + + ]: 80 : if (!OidIsValid(cldConstrOid))
21477 : 4 : continue;
21478 : :
21479 : : /* Ensure they're both the same type of constraint */
21480 [ - + ]: 152 : if (get_constraint_type(constraintOid) !=
21481 : 76 : get_constraint_type(cldConstrOid))
21482 : 0 : continue;
21483 : : }
21484 : :
21485 : : /* bingo. */
21486 : 141 : IndexSetParentIndex(attachrelIdxRels[i], idx);
21487 [ + + ]: 141 : if (OidIsValid(constraintOid))
21488 : 76 : ConstraintSetParentConstraint(cldConstrOid, constraintOid,
21489 : : RelationGetRelid(attachrel));
21490 : 141 : found = true;
21491 : :
21492 : 141 : CommandCounterIncrement();
21493 : 141 : break;
21494 : : }
21495 : : }
21496 : :
21497 : : /*
21498 : : * If no suitable index was found in the partition-to-be, create one
21499 : : * now. Note that if this is a PK, not-null constraints must already
21500 : : * exist.
21501 : : */
21502 [ + + ]: 293 : if (!found)
21503 : : {
21504 : : IndexStmt *stmt;
21505 : : Oid conOid;
21506 : :
21507 : 152 : stmt = generateClonedIndexStmt(NULL,
21508 : : idxRel, attmap,
21509 : : &conOid);
21510 : 152 : DefineIndex(NULL,
21511 : : RelationGetRelid(attachrel), stmt, InvalidOid,
21512 : : RelationGetRelid(idxRel),
21513 : : conOid,
21514 : : -1,
21515 : : true, false, false, false, false);
21516 : : }
21517 : :
21518 : 281 : index_close(idxRel, AccessShareLock);
21519 : : }
21520 : :
21521 : 1337 : out:
21522 : : /* Clean up. */
21523 [ + + ]: 1582 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21524 : 245 : index_close(attachrelIdxRels[i], AccessShareLock);
21525 : 1337 : MemoryContextSwitchTo(oldcxt);
21526 : 1337 : MemoryContextDelete(cxt);
21527 : 1337 : }
21528 : :
21529 : : /*
21530 : : * CloneRowTriggersToPartition
21531 : : * subroutine for ATExecAttachPartition/DefineRelation to create row
21532 : : * triggers on partitions
21533 : : */
21534 : : static void
21535 : 1569 : CloneRowTriggersToPartition(Relation parent, Relation partition)
21536 : : {
21537 : : Relation pg_trigger;
21538 : : ScanKeyData key;
21539 : : SysScanDesc scan;
21540 : : HeapTuple tuple;
21541 : : MemoryContext perTupCxt;
21542 : :
21543 : 1569 : ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
21544 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
21545 : 1569 : pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
21546 : 1569 : scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
21547 : : true, NULL, 1, &key);
21548 : :
21549 : 1569 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
21550 : : "clone trig", ALLOCSET_SMALL_SIZES);
21551 : :
21552 [ + + ]: 2626 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
21553 : : {
21554 : 1061 : Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
21555 : : CreateTrigStmt *trigStmt;
21556 : 1061 : Node *qual = NULL;
21557 : : Datum value;
21558 : : bool isnull;
21559 : 1061 : List *cols = NIL;
21560 : 1061 : List *trigargs = NIL;
21561 : : MemoryContext oldcxt;
21562 : :
21563 : : /*
21564 : : * Ignore statement-level triggers; those are not cloned.
21565 : : */
21566 [ + + ]: 1061 : if (!TRIGGER_FOR_ROW(trigForm->tgtype))
21567 : 958 : continue;
21568 : :
21569 : : /*
21570 : : * Don't clone internal triggers, because the constraint cloning code
21571 : : * will.
21572 : : */
21573 [ + + ]: 1049 : if (trigForm->tgisinternal)
21574 : 946 : continue;
21575 : :
21576 : : /*
21577 : : * Complain if we find an unexpected trigger type.
21578 : : */
21579 [ + + ]: 103 : if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
21580 [ - + ]: 91 : !TRIGGER_FOR_AFTER(trigForm->tgtype))
21581 [ # # ]: 0 : elog(ERROR, "unexpected trigger \"%s\" found",
21582 : : NameStr(trigForm->tgname));
21583 : :
21584 : : /* Use short-lived context for CREATE TRIGGER */
21585 : 103 : oldcxt = MemoryContextSwitchTo(perTupCxt);
21586 : :
21587 : : /*
21588 : : * If there is a WHEN clause, generate a 'cooked' version of it that's
21589 : : * appropriate for the partition.
21590 : : */
21591 : 103 : value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
21592 : : RelationGetDescr(pg_trigger), &isnull);
21593 [ + + ]: 103 : if (!isnull)
21594 : : {
21595 : 4 : qual = stringToNode(TextDatumGetCString(value));
21596 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
21597 : : partition, parent);
21598 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
21599 : : partition, parent);
21600 : : }
21601 : :
21602 : : /*
21603 : : * If there is a column list, transform it to a list of column names.
21604 : : * Note we don't need to map this list in any way ...
21605 : : */
21606 [ + + ]: 103 : if (trigForm->tgattr.dim1 > 0)
21607 : : {
21608 : : int i;
21609 : :
21610 [ + + ]: 8 : for (i = 0; i < trigForm->tgattr.dim1; i++)
21611 : : {
21612 : : Form_pg_attribute col;
21613 : :
21614 : 4 : col = TupleDescAttr(parent->rd_att,
21615 : 4 : trigForm->tgattr.values[i] - 1);
21616 : 4 : cols = lappend(cols,
21617 : 4 : makeString(pstrdup(NameStr(col->attname))));
21618 : : }
21619 : : }
21620 : :
21621 : : /* Reconstruct trigger arguments list. */
21622 [ + + ]: 103 : if (trigForm->tgnargs > 0)
21623 : : {
21624 : : char *p;
21625 : :
21626 : 8 : value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
21627 : : RelationGetDescr(pg_trigger), &isnull);
21628 [ - + ]: 8 : if (isnull)
21629 [ # # ]: 0 : elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
21630 : : NameStr(trigForm->tgname), RelationGetRelationName(partition));
21631 : :
21632 : 8 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
21633 : :
21634 [ + + ]: 24 : for (int i = 0; i < trigForm->tgnargs; i++)
21635 : : {
21636 : 16 : trigargs = lappend(trigargs, makeString(pstrdup(p)));
21637 : 16 : p += strlen(p) + 1;
21638 : : }
21639 : : }
21640 : :
21641 : 103 : trigStmt = makeNode(CreateTrigStmt);
21642 : 103 : trigStmt->replace = false;
21643 : 103 : trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
21644 : 103 : trigStmt->trigname = NameStr(trigForm->tgname);
21645 : 103 : trigStmt->relation = NULL;
21646 : 103 : trigStmt->funcname = NULL; /* passed separately */
21647 : 103 : trigStmt->args = trigargs;
21648 : 103 : trigStmt->row = true;
21649 : 103 : trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
21650 : 103 : trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
21651 : 103 : trigStmt->columns = cols;
21652 : 103 : trigStmt->whenClause = NULL; /* passed separately */
21653 : 103 : trigStmt->transitionRels = NIL; /* not supported at present */
21654 : 103 : trigStmt->deferrable = trigForm->tgdeferrable;
21655 : 103 : trigStmt->initdeferred = trigForm->tginitdeferred;
21656 : 103 : trigStmt->constrrel = NULL; /* passed separately */
21657 : :
21658 : 103 : CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
21659 : : trigForm->tgconstrrelid, InvalidOid, InvalidOid,
21660 : : trigForm->tgfoid, trigForm->oid, qual,
21661 : 103 : false, true, trigForm->tgenabled);
21662 : :
21663 : 99 : MemoryContextSwitchTo(oldcxt);
21664 : 99 : MemoryContextReset(perTupCxt);
21665 : : }
21666 : :
21667 : 1565 : MemoryContextDelete(perTupCxt);
21668 : :
21669 : 1565 : systable_endscan(scan);
21670 : 1565 : table_close(pg_trigger, RowExclusiveLock);
21671 : 1565 : }
21672 : :
21673 : : /*
21674 : : * ALTER TABLE DETACH PARTITION
21675 : : *
21676 : : * Return the address of the relation that is no longer a partition of rel.
21677 : : *
21678 : : * If concurrent mode is requested, we run in two transactions. A side-
21679 : : * effect is that this command cannot run in a multi-part ALTER TABLE.
21680 : : * Currently, that's enforced by the grammar.
21681 : : *
21682 : : * The strategy for concurrency is to first modify the partition's
21683 : : * pg_inherit catalog row to make it visible to everyone that the
21684 : : * partition is detached, lock the partition against writes, and commit
21685 : : * the transaction; anyone who requests the partition descriptor from
21686 : : * that point onwards has to ignore such a partition. In a second
21687 : : * transaction, we wait until all transactions that could have seen the
21688 : : * partition as attached are gone, then we remove the rest of partition
21689 : : * metadata (pg_inherits and pg_class.relpartbounds).
21690 : : */
21691 : : static ObjectAddress
21692 : 362 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
21693 : : RangeVar *name, bool concurrent)
21694 : : {
21695 : : Relation partRel;
21696 : : ObjectAddress address;
21697 : : Oid defaultPartOid;
21698 : :
21699 : : /*
21700 : : * We must lock the default partition, because detaching this partition
21701 : : * will change its partition constraint.
21702 : : */
21703 : : defaultPartOid =
21704 : 362 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
21705 [ + + ]: 362 : if (OidIsValid(defaultPartOid))
21706 : : {
21707 : : /*
21708 : : * Concurrent detaching when a default partition exists is not
21709 : : * supported. The main problem is that the default partition
21710 : : * constraint would change. And there's a definitional problem: what
21711 : : * should happen to the tuples that are being inserted that belong to
21712 : : * the partition being detached? Putting them on the partition being
21713 : : * detached would be wrong, since they'd become "lost" after the
21714 : : * detaching completes but we cannot put them in the default partition
21715 : : * either until we alter its partition constraint.
21716 : : *
21717 : : * I think we could solve this problem if we effected the constraint
21718 : : * change before committing the first transaction. But the lock would
21719 : : * have to remain AEL and it would cause concurrent query planning to
21720 : : * be blocked, so changing it that way would be even worse.
21721 : : */
21722 [ + + ]: 70 : if (concurrent)
21723 [ + - ]: 8 : ereport(ERROR,
21724 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21725 : : errmsg("cannot detach partitions concurrently when a default partition exists")));
21726 : 62 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
21727 : : }
21728 : :
21729 : : /*
21730 : : * In concurrent mode, the partition is locked with share-update-exclusive
21731 : : * in the first transaction. This allows concurrent transactions to be
21732 : : * doing DML to the partition.
21733 : : */
21734 [ + + ]: 354 : partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
21735 : : AccessExclusiveLock);
21736 : :
21737 : : /*
21738 : : * Check inheritance conditions and either delete the pg_inherits row (in
21739 : : * non-concurrent mode) or just set the inhdetachpending flag.
21740 : : */
21741 [ + + ]: 346 : if (!concurrent)
21742 : 270 : RemoveInheritance(partRel, rel, false);
21743 : : else
21744 : 76 : MarkInheritDetached(partRel, rel);
21745 : :
21746 : : /*
21747 : : * Ensure that foreign keys still hold after this detach. This keeps
21748 : : * locks on the referencing tables, which prevents concurrent transactions
21749 : : * from adding rows that we wouldn't see. For this to work in concurrent
21750 : : * mode, it is critical that the partition appears as no longer attached
21751 : : * for the RI queries as soon as the first transaction commits.
21752 : : */
21753 : 333 : ATDetachCheckNoForeignKeyRefs(partRel);
21754 : :
21755 : : /*
21756 : : * Concurrent mode has to work harder; first we add a new constraint to
21757 : : * the partition that matches the partition constraint. Then we close our
21758 : : * existing transaction, and in a new one wait for all processes to catch
21759 : : * up on the catalog updates we've done so far; at that point we can
21760 : : * complete the operation.
21761 : : */
21762 [ + + ]: 311 : if (concurrent)
21763 : : {
21764 : : Oid partrelid,
21765 : : parentrelid;
21766 : : LOCKTAG tag;
21767 : : char *parentrelname;
21768 : : char *partrelname;
21769 : :
21770 : : /*
21771 : : * We're almost done now; the only traces that remain are the
21772 : : * pg_inherits tuple and the partition's relpartbounds. Before we can
21773 : : * remove those, we need to wait until all transactions that know that
21774 : : * this is a partition are gone.
21775 : : */
21776 : :
21777 : : /*
21778 : : * Remember relation OIDs to re-acquire them later; and relation names
21779 : : * too, for error messages if something is dropped in between.
21780 : : */
21781 : 73 : partrelid = RelationGetRelid(partRel);
21782 : 73 : parentrelid = RelationGetRelid(rel);
21783 : 73 : parentrelname = MemoryContextStrdup(PortalContext,
21784 : 73 : RelationGetRelationName(rel));
21785 : 73 : partrelname = MemoryContextStrdup(PortalContext,
21786 : 73 : RelationGetRelationName(partRel));
21787 : :
21788 : : /* Invalidate relcache entries for the parent -- must be before close */
21789 : 73 : CacheInvalidateRelcache(rel);
21790 : :
21791 : 73 : table_close(partRel, NoLock);
21792 : 73 : table_close(rel, NoLock);
21793 : 73 : tab->rel = NULL;
21794 : :
21795 : : /* Make updated catalog entry visible */
21796 : 73 : PopActiveSnapshot();
21797 : 73 : CommitTransactionCommand();
21798 : :
21799 : 73 : StartTransactionCommand();
21800 : :
21801 : : /*
21802 : : * Now wait. This ensures that all queries that were planned
21803 : : * including the partition are finished before we remove the rest of
21804 : : * catalog entries. We don't need or indeed want to acquire this
21805 : : * lock, though -- that would block later queries.
21806 : : *
21807 : : * We don't need to concern ourselves with waiting for a lock on the
21808 : : * partition itself, since we will acquire AccessExclusiveLock below.
21809 : : */
21810 : 73 : SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
21811 : 73 : WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
21812 : :
21813 : : /*
21814 : : * Now acquire locks in both relations again. Note they may have been
21815 : : * removed in the meantime, so care is required.
21816 : : */
21817 : 47 : rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
21818 : 47 : partRel = try_relation_open(partrelid, AccessExclusiveLock);
21819 : :
21820 : : /* If the relations aren't there, something bad happened; bail out */
21821 [ - + ]: 47 : if (rel == NULL)
21822 : : {
21823 [ # # ]: 0 : if (partRel != NULL) /* shouldn't happen */
21824 [ # # ]: 0 : elog(WARNING, "dangling partition \"%s\" remains, can't fix",
21825 : : partrelname);
21826 [ # # ]: 0 : ereport(ERROR,
21827 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21828 : : errmsg("partitioned table \"%s\" was removed concurrently",
21829 : : parentrelname)));
21830 : : }
21831 [ - + ]: 47 : if (partRel == NULL)
21832 [ # # ]: 0 : ereport(ERROR,
21833 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21834 : : errmsg("partition \"%s\" was removed concurrently", partrelname)));
21835 : :
21836 : 47 : tab->rel = rel;
21837 : : }
21838 : :
21839 : : /*
21840 : : * Detaching the partition might involve TOAST table access, so ensure we
21841 : : * have a valid snapshot.
21842 : : */
21843 : 285 : PushActiveSnapshot(GetTransactionSnapshot());
21844 : :
21845 : : /* Do the final part of detaching */
21846 : 285 : DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
21847 : :
21848 : 284 : PopActiveSnapshot();
21849 : :
21850 : 284 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21851 : :
21852 : : /* keep our lock until commit */
21853 : 284 : table_close(partRel, NoLock);
21854 : :
21855 : 284 : return address;
21856 : : }
21857 : :
21858 : : /*
21859 : : * Second part of ALTER TABLE .. DETACH.
21860 : : *
21861 : : * This is separate so that it can be run independently when the second
21862 : : * transaction of the concurrent algorithm fails (crash or abort).
21863 : : */
21864 : : static void
21865 : 292 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
21866 : : Oid defaultPartOid)
21867 : : {
21868 : : Relation classRel;
21869 : : List *fks;
21870 : : ListCell *cell;
21871 : : List *indexes;
21872 : : Datum new_val[Natts_pg_class];
21873 : : bool new_null[Natts_pg_class],
21874 : : new_repl[Natts_pg_class];
21875 : : HeapTuple tuple,
21876 : : newtuple;
21877 : 292 : Relation trigrel = NULL;
21878 : 292 : List *fkoids = NIL;
21879 : :
21880 [ + + ]: 292 : if (concurrent)
21881 : : {
21882 : : /*
21883 : : * We can remove the pg_inherits row now. (In the non-concurrent case,
21884 : : * this was already done).
21885 : : */
21886 : 54 : RemoveInheritance(partRel, rel, true);
21887 : : }
21888 : :
21889 : : /* Drop any triggers that were cloned on creation/attach. */
21890 : 292 : DropClonedTriggersFromPartition(RelationGetRelid(partRel));
21891 : :
21892 : : /*
21893 : : * Detach any foreign keys that are inherited. This includes creating
21894 : : * additional action triggers.
21895 : : */
21896 : 292 : fks = copyObject(RelationGetFKeyList(partRel));
21897 [ + + ]: 292 : if (fks != NIL)
21898 : 56 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
21899 : :
21900 : : /*
21901 : : * It's possible that the partition being detached has a foreign key that
21902 : : * references a partitioned table. When that happens, there are multiple
21903 : : * pg_constraint rows for the partition: one points to the partitioned
21904 : : * table itself, while the others point to each of its partitions. Only
21905 : : * the topmost one is to be considered here; the child constraints must be
21906 : : * left alone, because conceptually those aren't coming from our parent
21907 : : * partitioned table, but from this partition itself.
21908 : : *
21909 : : * We implement this by collecting all the constraint OIDs in a first scan
21910 : : * of the FK array, and skipping in the loop below those constraints whose
21911 : : * parents are listed here.
21912 : : */
21913 [ + + + + : 696 : foreach_node(ForeignKeyCacheInfo, fk, fks)
+ + ]
21914 : 112 : fkoids = lappend_oid(fkoids, fk->conoid);
21915 : :
21916 [ + + + + : 404 : foreach(cell, fks)
+ + ]
21917 : : {
21918 : 112 : ForeignKeyCacheInfo *fk = lfirst(cell);
21919 : : HeapTuple contup;
21920 : : Form_pg_constraint conform;
21921 : :
21922 : 112 : contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
21923 [ - + ]: 112 : if (!HeapTupleIsValid(contup))
21924 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
21925 : 112 : conform = (Form_pg_constraint) GETSTRUCT(contup);
21926 : :
21927 : : /*
21928 : : * Consider only inherited foreign keys, and only if their parents
21929 : : * aren't in the list.
21930 : : */
21931 [ + - ]: 112 : if (conform->contype != CONSTRAINT_FOREIGN ||
21932 [ + + + + ]: 208 : !OidIsValid(conform->conparentid) ||
21933 : 96 : list_member_oid(fkoids, conform->conparentid))
21934 : : {
21935 : 44 : ReleaseSysCache(contup);
21936 : 44 : continue;
21937 : : }
21938 : :
21939 : : /*
21940 : : * The constraint on this table must be marked no longer a child of
21941 : : * the parent's constraint, as do its check triggers.
21942 : : */
21943 : 68 : ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
21944 : :
21945 : : /*
21946 : : * Also, look up the partition's "check" triggers corresponding to the
21947 : : * ENFORCED constraint being detached and detach them from the parent
21948 : : * triggers. NOT ENFORCED constraints do not have these triggers;
21949 : : * therefore, this step is not needed.
21950 : : */
21951 [ + - ]: 68 : if (fk->conenforced)
21952 : : {
21953 : : Oid insertTriggerOid,
21954 : : updateTriggerOid;
21955 : :
21956 : 68 : GetForeignKeyCheckTriggers(trigrel,
21957 : : fk->conoid, fk->confrelid, fk->conrelid,
21958 : : &insertTriggerOid, &updateTriggerOid);
21959 : : Assert(OidIsValid(insertTriggerOid));
21960 : 68 : TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
21961 : : RelationGetRelid(partRel));
21962 : : Assert(OidIsValid(updateTriggerOid));
21963 : 68 : TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
21964 : : RelationGetRelid(partRel));
21965 : : }
21966 : :
21967 : : /*
21968 : : * Lastly, create the action triggers on the referenced table, using
21969 : : * addFkRecurseReferenced, which requires some elaborate setup (so put
21970 : : * it in a separate block). While at it, if the table is partitioned,
21971 : : * that function will recurse to create the pg_constraint rows and
21972 : : * action triggers for each partition.
21973 : : *
21974 : : * Note there's no need to do addFkConstraint() here, because the
21975 : : * pg_constraint row already exists.
21976 : : */
21977 : : {
21978 : : Constraint *fkconstraint;
21979 : : int numfks;
21980 : : AttrNumber conkey[INDEX_MAX_KEYS];
21981 : : AttrNumber confkey[INDEX_MAX_KEYS];
21982 : : Oid conpfeqop[INDEX_MAX_KEYS];
21983 : : Oid conppeqop[INDEX_MAX_KEYS];
21984 : : Oid conffeqop[INDEX_MAX_KEYS];
21985 : : int numfkdelsetcols;
21986 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
21987 : : Relation refdRel;
21988 : :
21989 : 68 : DeconstructFkConstraintRow(contup,
21990 : : &numfks,
21991 : : conkey,
21992 : : confkey,
21993 : : conpfeqop,
21994 : : conppeqop,
21995 : : conffeqop,
21996 : : &numfkdelsetcols,
21997 : : confdelsetcols);
21998 : :
21999 : : /* Create a synthetic node we'll use throughout */
22000 : 68 : fkconstraint = makeNode(Constraint);
22001 : 68 : fkconstraint->contype = CONSTRAINT_FOREIGN;
22002 : 68 : fkconstraint->conname = pstrdup(NameStr(conform->conname));
22003 : 68 : fkconstraint->deferrable = conform->condeferrable;
22004 : 68 : fkconstraint->initdeferred = conform->condeferred;
22005 : 68 : fkconstraint->is_enforced = conform->conenforced;
22006 : 68 : fkconstraint->skip_validation = true;
22007 : 68 : fkconstraint->initially_valid = conform->convalidated;
22008 : : /* a few irrelevant fields omitted here */
22009 : 68 : fkconstraint->pktable = NULL;
22010 : 68 : fkconstraint->fk_attrs = NIL;
22011 : 68 : fkconstraint->pk_attrs = NIL;
22012 : 68 : fkconstraint->fk_matchtype = conform->confmatchtype;
22013 : 68 : fkconstraint->fk_upd_action = conform->confupdtype;
22014 : 68 : fkconstraint->fk_del_action = conform->confdeltype;
22015 : 68 : fkconstraint->fk_del_set_cols = NIL;
22016 : 68 : fkconstraint->old_conpfeqop = NIL;
22017 : 68 : fkconstraint->old_pktable_oid = InvalidOid;
22018 : 68 : fkconstraint->location = -1;
22019 : :
22020 : : /* set up colnames, used to generate the constraint name */
22021 [ + + ]: 168 : for (int i = 0; i < numfks; i++)
22022 : : {
22023 : : Form_pg_attribute att;
22024 : :
22025 : 100 : att = TupleDescAttr(RelationGetDescr(partRel),
22026 : 100 : conkey[i] - 1);
22027 : :
22028 : 100 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
22029 : 100 : makeString(NameStr(att->attname)));
22030 : : }
22031 : :
22032 : 68 : refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
22033 : :
22034 : 68 : addFkRecurseReferenced(fkconstraint, partRel,
22035 : : refdRel,
22036 : : conform->conindid,
22037 : : fk->conoid,
22038 : : numfks,
22039 : : confkey,
22040 : : conkey,
22041 : : conpfeqop,
22042 : : conppeqop,
22043 : : conffeqop,
22044 : : numfkdelsetcols,
22045 : : confdelsetcols,
22046 : : true,
22047 : : InvalidOid, InvalidOid,
22048 : 68 : conform->conperiod);
22049 : 68 : table_close(refdRel, NoLock); /* keep lock till end of xact */
22050 : : }
22051 : :
22052 : 68 : ReleaseSysCache(contup);
22053 : : }
22054 : 292 : list_free_deep(fks);
22055 [ + + ]: 292 : if (trigrel)
22056 : 56 : table_close(trigrel, RowExclusiveLock);
22057 : :
22058 : : /*
22059 : : * Any sub-constraints that are in the referenced-side of a larger
22060 : : * constraint have to be removed. This partition is no longer part of the
22061 : : * key space of the constraint.
22062 : : */
22063 [ + + + + : 327 : foreach(cell, GetParentedForeignKeyRefs(partRel))
+ + ]
22064 : : {
22065 : 36 : Oid constrOid = lfirst_oid(cell);
22066 : : ObjectAddress constraint;
22067 : :
22068 : 36 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22069 : 36 : deleteDependencyRecordsForClass(ConstraintRelationId,
22070 : : constrOid,
22071 : : ConstraintRelationId,
22072 : : DEPENDENCY_INTERNAL);
22073 : 36 : CommandCounterIncrement();
22074 : :
22075 : 36 : ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
22076 : 36 : performDeletion(&constraint, DROP_RESTRICT, 0);
22077 : : }
22078 : :
22079 : : /* Now we can detach indexes */
22080 : 291 : indexes = RelationGetIndexList(partRel);
22081 [ + + + + : 415 : foreach(cell, indexes)
+ + ]
22082 : : {
22083 : 124 : Oid idxid = lfirst_oid(cell);
22084 : : Oid parentidx;
22085 : : Relation idx;
22086 : : Oid constrOid;
22087 : : Oid parentConstrOid;
22088 : :
22089 [ + + ]: 124 : if (!has_superclass(idxid))
22090 : 8 : continue;
22091 : :
22092 : 116 : parentidx = get_partition_parent(idxid, false);
22093 : : Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
22094 : :
22095 : 116 : idx = index_open(idxid, AccessExclusiveLock);
22096 : 116 : IndexSetParentIndex(idx, InvalidOid);
22097 : :
22098 : : /*
22099 : : * If there's a constraint associated with the index, detach it too.
22100 : : * Careful: it is possible for a constraint index in a partition to be
22101 : : * the child of a non-constraint index, so verify whether the parent
22102 : : * index does actually have a constraint.
22103 : : */
22104 : 116 : constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
22105 : : idxid);
22106 : 116 : parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
22107 : : parentidx);
22108 [ + + + - ]: 116 : if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
22109 : 51 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22110 : :
22111 : 116 : index_close(idx, NoLock);
22112 : : }
22113 : :
22114 : : /* Update pg_class tuple */
22115 : 291 : classRel = table_open(RelationRelationId, RowExclusiveLock);
22116 : 291 : tuple = SearchSysCacheCopy1(RELOID,
22117 : : ObjectIdGetDatum(RelationGetRelid(partRel)));
22118 [ - + ]: 291 : if (!HeapTupleIsValid(tuple))
22119 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u",
22120 : : RelationGetRelid(partRel));
22121 : : Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
22122 : :
22123 : : /* Clear relpartbound and reset relispartition */
22124 : 291 : memset(new_val, 0, sizeof(new_val));
22125 : 291 : memset(new_null, false, sizeof(new_null));
22126 : 291 : memset(new_repl, false, sizeof(new_repl));
22127 : 291 : new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
22128 : 291 : new_null[Anum_pg_class_relpartbound - 1] = true;
22129 : 291 : new_repl[Anum_pg_class_relpartbound - 1] = true;
22130 : 291 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
22131 : : new_val, new_null, new_repl);
22132 : :
22133 : 291 : ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
22134 : 291 : CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
22135 : 291 : heap_freetuple(newtuple);
22136 : 291 : table_close(classRel, RowExclusiveLock);
22137 : :
22138 : : /*
22139 : : * Drop identity property from all identity columns of partition.
22140 : : */
22141 [ + + ]: 840 : for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
22142 : : {
22143 : 549 : Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
22144 : :
22145 [ + + + + ]: 549 : if (!attr->attisdropped && attr->attidentity)
22146 : 4 : ATExecDropIdentity(partRel, NameStr(attr->attname), false,
22147 : : AccessExclusiveLock, true, true);
22148 : : }
22149 : :
22150 [ + + ]: 291 : if (OidIsValid(defaultPartOid))
22151 : : {
22152 : : /*
22153 : : * If the relation being detached is the default partition itself,
22154 : : * remove it from the parent's pg_partitioned_table entry.
22155 : : *
22156 : : * If not, we must invalidate default partition's relcache entry, as
22157 : : * in StorePartitionBound: its partition constraint depends on every
22158 : : * other partition's partition constraint.
22159 : : */
22160 [ + + ]: 30 : if (RelationGetRelid(partRel) == defaultPartOid)
22161 : 1 : update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
22162 : : else
22163 : 29 : CacheInvalidateRelcacheByRelid(defaultPartOid);
22164 : : }
22165 : :
22166 : : /*
22167 : : * Invalidate the parent's relcache so that the partition is no longer
22168 : : * included in its partition descriptor.
22169 : : */
22170 : 291 : CacheInvalidateRelcache(rel);
22171 : :
22172 : : /*
22173 : : * If the partition we just detached is partitioned itself, invalidate
22174 : : * relcache for all descendent partitions too to ensure that their
22175 : : * rd_partcheck expression trees are rebuilt; must lock partitions before
22176 : : * doing so, using the same lockmode as what partRel has been locked with
22177 : : * by the caller.
22178 : : */
22179 [ + + ]: 291 : if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
22180 : : {
22181 : : List *children;
22182 : :
22183 : 41 : children = find_all_inheritors(RelationGetRelid(partRel),
22184 : : AccessExclusiveLock, NULL);
22185 [ + - + + : 135 : foreach(cell, children)
+ + ]
22186 : : {
22187 : 94 : CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
22188 : : }
22189 : : }
22190 : 291 : }
22191 : :
22192 : : /*
22193 : : * ALTER TABLE ... DETACH PARTITION ... FINALIZE
22194 : : *
22195 : : * To use when a DETACH PARTITION command previously did not run to
22196 : : * completion; this completes the detaching process.
22197 : : */
22198 : : static ObjectAddress
22199 : 7 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
22200 : : {
22201 : : Relation partRel;
22202 : : ObjectAddress address;
22203 : 7 : Snapshot snap = GetActiveSnapshot();
22204 : :
22205 : 7 : partRel = table_openrv(name, AccessExclusiveLock);
22206 : :
22207 : : /*
22208 : : * Wait until existing snapshots are gone. This is important if the
22209 : : * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
22210 : : * user could immediately run DETACH FINALIZE without actually waiting for
22211 : : * existing transactions. We must not complete the detach action until
22212 : : * all such queries are complete (otherwise we would present them with an
22213 : : * inconsistent view of catalogs).
22214 : : */
22215 : 7 : WaitForOlderSnapshots(snap->xmin, false);
22216 : :
22217 : 7 : DetachPartitionFinalize(rel, partRel, true, InvalidOid);
22218 : :
22219 : 7 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
22220 : :
22221 : 7 : table_close(partRel, NoLock);
22222 : :
22223 : 7 : return address;
22224 : : }
22225 : :
22226 : : /*
22227 : : * DropClonedTriggersFromPartition
22228 : : * subroutine for ATExecDetachPartition to remove any triggers that were
22229 : : * cloned to the partition when it was created-as-partition or attached.
22230 : : * This undoes what CloneRowTriggersToPartition did.
22231 : : */
22232 : : static void
22233 : 292 : DropClonedTriggersFromPartition(Oid partitionId)
22234 : : {
22235 : : ScanKeyData skey;
22236 : : SysScanDesc scan;
22237 : : HeapTuple trigtup;
22238 : : Relation tgrel;
22239 : : ObjectAddresses *objects;
22240 : :
22241 : 292 : objects = new_object_addresses();
22242 : :
22243 : : /*
22244 : : * Scan pg_trigger to search for all triggers on this rel.
22245 : : */
22246 : 292 : ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
22247 : : F_OIDEQ, ObjectIdGetDatum(partitionId));
22248 : 292 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
22249 : 292 : scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
22250 : : true, NULL, 1, &skey);
22251 [ + + ]: 556 : while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
22252 : : {
22253 : 264 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
22254 : : ObjectAddress trig;
22255 : :
22256 : : /* Ignore triggers that weren't cloned */
22257 [ + + ]: 264 : if (!OidIsValid(pg_trigger->tgparentid))
22258 : 252 : continue;
22259 : :
22260 : : /*
22261 : : * Ignore internal triggers that are implementation objects of foreign
22262 : : * keys, because these will be detached when the foreign keys
22263 : : * themselves are.
22264 : : */
22265 [ + + ]: 220 : if (OidIsValid(pg_trigger->tgconstrrelid))
22266 : 208 : continue;
22267 : :
22268 : : /*
22269 : : * This is ugly, but necessary: remove the dependency markings on the
22270 : : * trigger so that it can be removed.
22271 : : */
22272 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22273 : : TriggerRelationId,
22274 : : DEPENDENCY_PARTITION_PRI);
22275 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22276 : : RelationRelationId,
22277 : : DEPENDENCY_PARTITION_SEC);
22278 : :
22279 : : /* remember this trigger to remove it below */
22280 : 12 : ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
22281 : 12 : add_exact_object_address(&trig, objects);
22282 : : }
22283 : :
22284 : : /* make the dependency removal visible to the deletion below */
22285 : 292 : CommandCounterIncrement();
22286 : 292 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
22287 : :
22288 : : /* done */
22289 : 292 : free_object_addresses(objects);
22290 : 292 : systable_endscan(scan);
22291 : 292 : table_close(tgrel, RowExclusiveLock);
22292 : 292 : }
22293 : :
22294 : : /*
22295 : : * Before acquiring lock on an index, acquire the same lock on the owning
22296 : : * table.
22297 : : */
22298 : : struct AttachIndexCallbackState
22299 : : {
22300 : : Oid partitionOid;
22301 : : Oid parentTblOid;
22302 : : bool lockedParentTbl;
22303 : : };
22304 : :
22305 : : static void
22306 : 284 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
22307 : : void *arg)
22308 : : {
22309 : : struct AttachIndexCallbackState *state;
22310 : : Form_pg_class classform;
22311 : : HeapTuple tuple;
22312 : :
22313 : 284 : state = (struct AttachIndexCallbackState *) arg;
22314 : :
22315 [ + + ]: 284 : if (!state->lockedParentTbl)
22316 : : {
22317 : 280 : LockRelationOid(state->parentTblOid, AccessShareLock);
22318 : 280 : state->lockedParentTbl = true;
22319 : : }
22320 : :
22321 : : /*
22322 : : * If we previously locked some other heap, and the name we're looking up
22323 : : * no longer refers to an index on that relation, release the now-useless
22324 : : * lock. XXX maybe we should do *after* we verify whether the index does
22325 : : * not actually belong to the same relation ...
22326 : : */
22327 [ + + - + ]: 284 : if (relOid != oldRelOid && OidIsValid(state->partitionOid))
22328 : : {
22329 : 0 : UnlockRelationOid(state->partitionOid, AccessShareLock);
22330 : 0 : state->partitionOid = InvalidOid;
22331 : : }
22332 : :
22333 : : /* Didn't find a relation, so no need for locking or permission checks. */
22334 [ + + ]: 284 : if (!OidIsValid(relOid))
22335 : 4 : return;
22336 : :
22337 : 280 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
22338 [ - + ]: 280 : if (!HeapTupleIsValid(tuple))
22339 : 0 : return; /* concurrently dropped, so nothing to do */
22340 : 280 : classform = (Form_pg_class) GETSTRUCT(tuple);
22341 [ + + ]: 280 : if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
22342 [ + + ]: 216 : classform->relkind != RELKIND_INDEX)
22343 [ + - ]: 4 : ereport(ERROR,
22344 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22345 : : errmsg("\"%s\" is not an index", rv->relname)));
22346 : 276 : ReleaseSysCache(tuple);
22347 : :
22348 : : /*
22349 : : * Since we need only examine the heap's tupledesc, an access share lock
22350 : : * on it (preventing any DDL) is sufficient.
22351 : : */
22352 : 276 : state->partitionOid = IndexGetRelation(relOid, false);
22353 : 276 : LockRelationOid(state->partitionOid, AccessShareLock);
22354 : : }
22355 : :
22356 : : /*
22357 : : * ALTER INDEX i1 ATTACH PARTITION i2
22358 : : */
22359 : : static ObjectAddress
22360 : 280 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
22361 : : {
22362 : : Relation partIdx;
22363 : : Relation partTbl;
22364 : : Relation parentTbl;
22365 : : ObjectAddress address;
22366 : : Oid partIdxId;
22367 : : Oid currParent;
22368 : : struct AttachIndexCallbackState state;
22369 : :
22370 : : /*
22371 : : * We need to obtain lock on the index 'name' to modify it, but we also
22372 : : * need to read its owning table's tuple descriptor -- so we need to lock
22373 : : * both. To avoid deadlocks, obtain lock on the table before doing so on
22374 : : * the index. Furthermore, we need to examine the parent table of the
22375 : : * partition, so lock that one too.
22376 : : */
22377 : 280 : state.partitionOid = InvalidOid;
22378 : 280 : state.parentTblOid = parentIdx->rd_index->indrelid;
22379 : 280 : state.lockedParentTbl = false;
22380 : : partIdxId =
22381 : 280 : RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
22382 : : RangeVarCallbackForAttachIndex,
22383 : : &state);
22384 : : /* Not there? */
22385 [ - + ]: 272 : if (!OidIsValid(partIdxId))
22386 [ # # ]: 0 : ereport(ERROR,
22387 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
22388 : : errmsg("index \"%s\" does not exist", name->relname)));
22389 : :
22390 : : /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
22391 : 272 : partIdx = relation_open(partIdxId, AccessExclusiveLock);
22392 : :
22393 : : /* we already hold locks on both tables, so this is safe: */
22394 : 272 : parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
22395 : 272 : partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
22396 : :
22397 : 272 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
22398 : :
22399 : : /*
22400 : : * Check if the index is already attached to the correct parent,
22401 : : * ultimately attempting one round of validation if already the case.
22402 : : */
22403 : 544 : currParent = partIdx->rd_rel->relispartition ?
22404 [ + + ]: 272 : get_partition_parent(partIdxId, false) : InvalidOid;
22405 [ + + ]: 272 : if (currParent != RelationGetRelid(parentIdx))
22406 : : {
22407 : : IndexInfo *childInfo;
22408 : : IndexInfo *parentInfo;
22409 : : AttrMap *attmap;
22410 : : bool found;
22411 : : int i;
22412 : : PartitionDesc partDesc;
22413 : : Oid constraintOid,
22414 : 248 : cldConstrId = InvalidOid;
22415 : :
22416 : : /*
22417 : : * If this partition already has an index attached, refuse the
22418 : : * operation.
22419 : : */
22420 : 248 : refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
22421 : :
22422 [ - + ]: 244 : if (OidIsValid(currParent))
22423 [ # # ]: 0 : ereport(ERROR,
22424 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22425 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22426 : : RelationGetRelationName(partIdx),
22427 : : RelationGetRelationName(parentIdx)),
22428 : : errdetail("Index \"%s\" is already attached to another index.",
22429 : : RelationGetRelationName(partIdx))));
22430 : :
22431 : : /* Make sure it indexes a partition of the other index's table */
22432 : 244 : partDesc = RelationGetPartitionDesc(parentTbl, true);
22433 : 244 : found = false;
22434 [ + + ]: 367 : for (i = 0; i < partDesc->nparts; i++)
22435 : : {
22436 [ + + ]: 363 : if (partDesc->oids[i] == state.partitionOid)
22437 : : {
22438 : 240 : found = true;
22439 : 240 : break;
22440 : : }
22441 : : }
22442 [ + + ]: 244 : if (!found)
22443 [ + - ]: 4 : ereport(ERROR,
22444 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22445 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22446 : : RelationGetRelationName(partIdx),
22447 : : RelationGetRelationName(parentIdx)),
22448 : : errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
22449 : : RelationGetRelationName(partIdx),
22450 : : RelationGetRelationName(parentTbl))));
22451 : :
22452 : : /* Ensure the indexes are compatible */
22453 : 240 : childInfo = BuildIndexInfo(partIdx);
22454 : 240 : parentInfo = BuildIndexInfo(parentIdx);
22455 : 240 : attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
22456 : : RelationGetDescr(parentTbl),
22457 : : false);
22458 [ + + ]: 240 : if (!CompareIndexInfo(childInfo, parentInfo,
22459 : 240 : partIdx->rd_indcollation,
22460 : 240 : parentIdx->rd_indcollation,
22461 : 240 : partIdx->rd_opfamily,
22462 : 240 : parentIdx->rd_opfamily,
22463 : : attmap))
22464 [ + - ]: 32 : ereport(ERROR,
22465 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22466 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22467 : : RelationGetRelationName(partIdx),
22468 : : RelationGetRelationName(parentIdx)),
22469 : : errdetail("The index definitions do not match.")));
22470 : :
22471 : : /*
22472 : : * If there is a constraint in the parent, make sure there is one in
22473 : : * the child too.
22474 : : */
22475 : 208 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
22476 : : RelationGetRelid(parentIdx));
22477 : :
22478 [ + + ]: 208 : if (OidIsValid(constraintOid))
22479 : : {
22480 : 66 : cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
22481 : : partIdxId);
22482 [ + + ]: 66 : if (!OidIsValid(cldConstrId))
22483 [ + - ]: 4 : ereport(ERROR,
22484 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22485 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22486 : : RelationGetRelationName(partIdx),
22487 : : RelationGetRelationName(parentIdx)),
22488 : : errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
22489 : : RelationGetRelationName(parentIdx),
22490 : : RelationGetRelationName(parentTbl),
22491 : : RelationGetRelationName(partIdx))));
22492 : : }
22493 : :
22494 : : /*
22495 : : * If it's a primary key, make sure the columns in the partition are
22496 : : * NOT NULL.
22497 : : */
22498 [ + + ]: 204 : if (parentIdx->rd_index->indisprimary)
22499 : 51 : verifyPartitionIndexNotNull(childInfo, partTbl);
22500 : :
22501 : : /* All good -- do it */
22502 : 204 : IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
22503 [ + + ]: 204 : if (OidIsValid(constraintOid))
22504 : 62 : ConstraintSetParentConstraint(cldConstrId, constraintOid,
22505 : : RelationGetRelid(partTbl));
22506 : :
22507 : 204 : free_attrmap(attmap);
22508 : :
22509 : 204 : validatePartitionedIndex(parentIdx, parentTbl);
22510 : : }
22511 [ + + ]: 24 : else if (!parentIdx->rd_index->indisvalid)
22512 : : {
22513 : : /*
22514 : : * The index is attached, but the parent is still invalid; see if it
22515 : : * can be validated now.
22516 : : */
22517 : 12 : validatePartitionedIndex(parentIdx, parentTbl);
22518 : : }
22519 : :
22520 : 228 : relation_close(parentTbl, AccessShareLock);
22521 : : /* keep these locks till commit */
22522 : 228 : relation_close(partTbl, NoLock);
22523 : 228 : relation_close(partIdx, NoLock);
22524 : :
22525 : 228 : return address;
22526 : : }
22527 : :
22528 : : /*
22529 : : * Verify whether the given partition already contains an index attached
22530 : : * to the given partitioned index. If so, raise an error.
22531 : : */
22532 : : static void
22533 : 248 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
22534 : : {
22535 : : Oid existingIdx;
22536 : :
22537 : 248 : existingIdx = index_get_partition(partitionTbl,
22538 : : RelationGetRelid(parentIdx));
22539 [ + + ]: 248 : if (OidIsValid(existingIdx))
22540 [ + - ]: 4 : ereport(ERROR,
22541 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22542 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22543 : : RelationGetRelationName(partIdx),
22544 : : RelationGetRelationName(parentIdx)),
22545 : : errdetail("Another index \"%s\" is already attached for partition \"%s\".",
22546 : : get_rel_name(existingIdx),
22547 : : RelationGetRelationName(partitionTbl))));
22548 : 244 : }
22549 : :
22550 : : /*
22551 : : * Verify whether the set of attached partition indexes to a parent index on
22552 : : * a partitioned table is complete. If it is, mark the parent index valid.
22553 : : *
22554 : : * This should be called each time a partition index is attached.
22555 : : */
22556 : : static void
22557 : 248 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
22558 : : {
22559 : : Relation inheritsRel;
22560 : : SysScanDesc scan;
22561 : : ScanKeyData key;
22562 : 248 : int tuples = 0;
22563 : : HeapTuple inhTup;
22564 : 248 : bool updated = false;
22565 : :
22566 : : Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
22567 : :
22568 : : /*
22569 : : * Scan pg_inherits for this parent index. Count each valid index we find
22570 : : * (verifying the pg_index entry for each), and if we reach the total
22571 : : * amount we expect, we can mark this parent index as valid.
22572 : : */
22573 : 248 : inheritsRel = table_open(InheritsRelationId, AccessShareLock);
22574 : 248 : ScanKeyInit(&key, Anum_pg_inherits_inhparent,
22575 : : BTEqualStrategyNumber, F_OIDEQ,
22576 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22577 : 248 : scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
22578 : : NULL, 1, &key);
22579 [ + + ]: 629 : while ((inhTup = systable_getnext(scan)) != NULL)
22580 : : {
22581 : 381 : Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
22582 : : HeapTuple indTup;
22583 : : Form_pg_index indexForm;
22584 : :
22585 : 381 : indTup = SearchSysCache1(INDEXRELID,
22586 : : ObjectIdGetDatum(inhForm->inhrelid));
22587 [ - + ]: 381 : if (!HeapTupleIsValid(indTup))
22588 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
22589 : 381 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22590 [ + + ]: 381 : if (indexForm->indisvalid)
22591 : 315 : tuples += 1;
22592 : 381 : ReleaseSysCache(indTup);
22593 : : }
22594 : :
22595 : : /* Done with pg_inherits */
22596 : 248 : systable_endscan(scan);
22597 : 248 : table_close(inheritsRel, AccessShareLock);
22598 : :
22599 : : /*
22600 : : * If we found as many inherited indexes as the partitioned table has
22601 : : * partitions, we're good; update pg_index to set indisvalid.
22602 : : */
22603 [ + + ]: 248 : if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
22604 : : {
22605 : : Relation idxRel;
22606 : : HeapTuple indTup;
22607 : : Form_pg_index indexForm;
22608 : :
22609 : 119 : idxRel = table_open(IndexRelationId, RowExclusiveLock);
22610 : 119 : indTup = SearchSysCacheCopy1(INDEXRELID,
22611 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22612 [ - + ]: 119 : if (!HeapTupleIsValid(indTup))
22613 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u",
22614 : : RelationGetRelid(partedIdx));
22615 : 119 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22616 : :
22617 : 119 : indexForm->indisvalid = true;
22618 : 119 : updated = true;
22619 : :
22620 : 119 : CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
22621 : :
22622 : 119 : table_close(idxRel, RowExclusiveLock);
22623 : 119 : heap_freetuple(indTup);
22624 : : }
22625 : :
22626 : : /*
22627 : : * If this index is in turn a partition of a larger index, validating it
22628 : : * might cause the parent to become valid also. Try that.
22629 : : */
22630 [ + + + + ]: 248 : if (updated && partedIdx->rd_rel->relispartition)
22631 : : {
22632 : : Oid parentIdxId,
22633 : : parentTblId;
22634 : : Relation parentIdx,
22635 : : parentTbl;
22636 : :
22637 : : /* make sure we see the validation we just did */
22638 : 32 : CommandCounterIncrement();
22639 : :
22640 : 32 : parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
22641 : 32 : parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
22642 : 32 : parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
22643 : 32 : parentTbl = relation_open(parentTblId, AccessExclusiveLock);
22644 : : Assert(!parentIdx->rd_index->indisvalid);
22645 : :
22646 : 32 : validatePartitionedIndex(parentIdx, parentTbl);
22647 : :
22648 : : /*
22649 : : * Keep these locks until commit so that the concurrent validator of
22650 : : * another index partition cannot miss our uncommitted changes, which
22651 : : * would leave the parent index invalid.
22652 : : */
22653 : 32 : relation_close(parentIdx, NoLock);
22654 : 32 : relation_close(parentTbl, NoLock);
22655 : : }
22656 : 248 : }
22657 : :
22658 : : /*
22659 : : * When attaching an index as a partition of a partitioned index which is a
22660 : : * primary key, verify that all the columns in the partition are marked NOT
22661 : : * NULL.
22662 : : */
22663 : : static void
22664 : 51 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
22665 : : {
22666 [ + + ]: 103 : for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
22667 : : {
22668 : 52 : Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
22669 : 52 : iinfo->ii_IndexAttrNumbers[i] - 1);
22670 : :
22671 [ - + ]: 52 : if (!att->attnotnull)
22672 [ # # ]: 0 : ereport(ERROR,
22673 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
22674 : : errmsg("invalid primary key definition"),
22675 : : errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
22676 : : NameStr(att->attname),
22677 : : RelationGetRelationName(partition)));
22678 : : }
22679 : 51 : }
22680 : :
22681 : : /*
22682 : : * Return an OID list of constraints that reference the given relation
22683 : : * that are marked as having a parent constraints.
22684 : : */
22685 : : static List *
22686 : 625 : GetParentedForeignKeyRefs(Relation partition)
22687 : : {
22688 : : Relation pg_constraint;
22689 : : HeapTuple tuple;
22690 : : SysScanDesc scan;
22691 : : ScanKeyData key[2];
22692 : 625 : List *constraints = NIL;
22693 : :
22694 : : /*
22695 : : * If no indexes, or no columns are referenceable by FKs, we can avoid the
22696 : : * scan.
22697 : : */
22698 [ + + + + ]: 896 : if (RelationGetIndexList(partition) == NIL ||
22699 : 271 : bms_is_empty(RelationGetIndexAttrBitmap(partition,
22700 : : INDEX_ATTR_BITMAP_KEY)))
22701 : 458 : return NIL;
22702 : :
22703 : : /* Search for constraints referencing this table */
22704 : 167 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
22705 : 167 : ScanKeyInit(&key[0],
22706 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
22707 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
22708 : 167 : ScanKeyInit(&key[1],
22709 : : Anum_pg_constraint_contype, BTEqualStrategyNumber,
22710 : : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
22711 : :
22712 : : /* XXX This is a seqscan, as we don't have a usable index */
22713 : 167 : scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
22714 [ + + ]: 268 : while ((tuple = systable_getnext(scan)) != NULL)
22715 : : {
22716 : 101 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22717 : :
22718 : : /*
22719 : : * We only need to process constraints that are part of larger ones.
22720 : : */
22721 [ - + ]: 101 : if (!OidIsValid(constrForm->conparentid))
22722 : 0 : continue;
22723 : :
22724 : 101 : constraints = lappend_oid(constraints, constrForm->oid);
22725 : : }
22726 : :
22727 : 167 : systable_endscan(scan);
22728 : 167 : table_close(pg_constraint, AccessShareLock);
22729 : :
22730 : 167 : return constraints;
22731 : : }
22732 : :
22733 : : /*
22734 : : * During DETACH PARTITION, verify that any foreign keys pointing to the
22735 : : * partitioned table would not become invalid. An error is raised if any
22736 : : * referenced values exist.
22737 : : */
22738 : : static void
22739 : 333 : ATDetachCheckNoForeignKeyRefs(Relation partition)
22740 : : {
22741 : : List *constraints;
22742 : : ListCell *cell;
22743 : :
22744 : 333 : constraints = GetParentedForeignKeyRefs(partition);
22745 : :
22746 [ + + + + : 376 : foreach(cell, constraints)
+ + ]
22747 : : {
22748 : 65 : Oid constrOid = lfirst_oid(cell);
22749 : : HeapTuple tuple;
22750 : : Form_pg_constraint constrForm;
22751 : : Relation rel;
22752 : 65 : Trigger trig = {0};
22753 : :
22754 : 65 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
22755 [ - + ]: 65 : if (!HeapTupleIsValid(tuple))
22756 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
22757 : 65 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22758 : :
22759 : : Assert(OidIsValid(constrForm->conparentid));
22760 : : Assert(constrForm->confrelid == RelationGetRelid(partition));
22761 : :
22762 : : /* prevent data changes into the referencing table until commit */
22763 : 65 : rel = table_open(constrForm->conrelid, ShareLock);
22764 : :
22765 : 65 : trig.tgoid = InvalidOid;
22766 : 65 : trig.tgname = NameStr(constrForm->conname);
22767 : 65 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
22768 : 65 : trig.tgisinternal = true;
22769 : 65 : trig.tgconstrrelid = RelationGetRelid(partition);
22770 : 65 : trig.tgconstrindid = constrForm->conindid;
22771 : 65 : trig.tgconstraint = constrForm->oid;
22772 : 65 : trig.tgdeferrable = false;
22773 : 65 : trig.tginitdeferred = false;
22774 : : /* we needn't fill in remaining fields */
22775 : :
22776 : 65 : RI_PartitionRemove_Check(&trig, rel, partition);
22777 : :
22778 : 43 : ReleaseSysCache(tuple);
22779 : :
22780 : 43 : table_close(rel, NoLock);
22781 : : }
22782 : 311 : }
22783 : :
22784 : : /*
22785 : : * resolve column compression specification to compression method.
22786 : : */
22787 : : static char
22788 : 166012 : GetAttributeCompression(Oid atttypid, const char *compression)
22789 : : {
22790 : : char cmethod;
22791 : :
22792 [ + + + + ]: 166012 : if (compression == NULL || strcmp(compression, "default") == 0)
22793 : 165891 : return InvalidCompressionMethod;
22794 : :
22795 : : /*
22796 : : * To specify a nondefault method, the column data type must be toastable.
22797 : : * Note this says nothing about whether the column's attstorage setting
22798 : : * permits compression; we intentionally allow attstorage and
22799 : : * attcompression to be independent. But with a non-toastable type,
22800 : : * attstorage could not be set to a value that would permit compression.
22801 : : *
22802 : : * We don't actually need to enforce this, since nothing bad would happen
22803 : : * if attcompression were non-default; it would never be consulted. But
22804 : : * it seems more user-friendly to complain about a certainly-useless
22805 : : * attempt to set the property.
22806 : : */
22807 [ + + ]: 121 : if (!TypeIsToastable(atttypid))
22808 [ + - ]: 4 : ereport(ERROR,
22809 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22810 : : errmsg("column data type %s does not support compression",
22811 : : format_type_be(atttypid))));
22812 : :
22813 : 117 : cmethod = CompressionNameToMethod(compression);
22814 [ + + ]: 117 : if (!CompressionMethodIsValid(cmethod))
22815 [ + - ]: 8 : ereport(ERROR,
22816 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22817 : : errmsg("invalid compression method \"%s\"", compression)));
22818 : :
22819 : 109 : return cmethod;
22820 : : }
22821 : :
22822 : : /*
22823 : : * resolve column storage specification
22824 : : */
22825 : : static char
22826 : 252 : GetAttributeStorage(Oid atttypid, const char *storagemode)
22827 : : {
22828 : 252 : char cstorage = 0;
22829 : :
22830 [ + + ]: 252 : if (pg_strcasecmp(storagemode, "plain") == 0)
22831 : 39 : cstorage = TYPSTORAGE_PLAIN;
22832 [ + + ]: 213 : else if (pg_strcasecmp(storagemode, "external") == 0)
22833 : 147 : cstorage = TYPSTORAGE_EXTERNAL;
22834 [ + + ]: 66 : else if (pg_strcasecmp(storagemode, "extended") == 0)
22835 : 41 : cstorage = TYPSTORAGE_EXTENDED;
22836 [ + + ]: 25 : else if (pg_strcasecmp(storagemode, "main") == 0)
22837 : 21 : cstorage = TYPSTORAGE_MAIN;
22838 [ + - ]: 4 : else if (pg_strcasecmp(storagemode, "default") == 0)
22839 : 4 : cstorage = get_typstorage(atttypid);
22840 : : else
22841 [ # # ]: 0 : ereport(ERROR,
22842 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22843 : : errmsg("invalid storage type \"%s\"",
22844 : : storagemode)));
22845 : :
22846 : : /*
22847 : : * safety check: do not allow toasted storage modes unless column datatype
22848 : : * is TOAST-aware.
22849 : : */
22850 [ + + + + ]: 252 : if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
22851 [ + - ]: 4 : ereport(ERROR,
22852 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22853 : : errmsg("column data type %s can only have storage PLAIN",
22854 : : format_type_be(atttypid))));
22855 : :
22856 : 248 : return cstorage;
22857 : : }
|