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 : 41041 : 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 : 41041 : List *connames = NIL;
797 : : Datum reloptions;
798 : : ListCell *listptr;
799 : : AttrNumber attnum;
800 : : bool partitioned;
801 : 41041 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
802 : : Oid ofTypeId;
803 : : ObjectAddress address;
804 : : LOCKMODE parentLockmode;
805 : 41041 : 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 : 41041 : strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
812 : :
813 : : /*
814 : : * Check consistency of arguments
815 : : */
816 [ + + ]: 41041 : 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 [ + + ]: 41033 : if (stmt->partspec != NULL)
823 : : {
824 [ - + ]: 3425 : if (relkind != RELKIND_RELATION)
825 [ # # ]: 0 : elog(ERROR, "unexpected relkind: %d", (int) relkind);
826 : :
827 : 3425 : relkind = RELKIND_PARTITIONED_TABLE;
828 : 3425 : partitioned = true;
829 : : }
830 : : else
831 : 37608 : partitioned = false;
832 : :
833 [ + + ]: 41033 : if (relkind == RELKIND_PARTITIONED_TABLE &&
834 [ + + ]: 3425 : 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 : 41029 : 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 [ + + ]: 41029 : if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
854 [ - + ]: 2363 : && 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 [ + + ]: 41029 : parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
876 : : ShareUpdateExclusiveLock);
877 : :
878 : : /* Determine the list of OIDs of the parents. */
879 : 41029 : inheritOids = NIL;
880 [ + + + + : 48709 : foreach(listptr, stmt->inhRelations)
+ + ]
881 : : {
882 : 7680 : RangeVar *rv = (RangeVar *) lfirst(listptr);
883 : : Oid parentOid;
884 : :
885 : 7680 : parentOid = RangeVarGetRelid(rv, parentLockmode, false);
886 : :
887 : : /*
888 : : * Reject duplications in the list of parents.
889 : : */
890 [ - + ]: 7680 : 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 : 7680 : 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 [ + + ]: 41029 : if (stmt->tablespacename)
904 : : {
905 : 84 : tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
906 : :
907 [ + + + + ]: 80 : 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 [ + + ]: 40945 : else if (stmt->partbound)
913 : : {
914 : : Assert(list_length(inheritOids) == 1);
915 : 6002 : tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
916 : : }
917 : : else
918 : 34943 : tablespaceId = InvalidOid;
919 : :
920 : : /* still nothing? use the default */
921 [ + + ]: 41021 : if (!OidIsValid(tablespaceId))
922 : 40931 : tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
923 : : partitioned);
924 : :
925 : : /* Check permissions except when using database's default */
926 [ + + + + ]: 41017 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
927 : : {
928 : : AclResult aclresult;
929 : :
930 : 106 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
931 : : ACL_CREATE);
932 [ + + ]: 106 : if (aclresult != ACLCHECK_OK)
933 : 4 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
934 : 4 : get_tablespace_name(tablespaceId));
935 : : }
936 : :
937 : : /* In all cases disallow placing user relations in pg_global */
938 [ + + ]: 41013 : 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 [ + + ]: 41001 : if (!OidIsValid(ownerId))
945 : 40846 : ownerId = GetUserId();
946 : :
947 : : /*
948 : : * Parse and validate reloptions, if any.
949 : : */
950 : 41001 : reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
951 : : true, false);
952 : :
953 [ + + + ]: 40989 : switch (relkind)
954 : : {
955 : 10533 : case RELKIND_VIEW:
956 : 10533 : (void) view_reloptions(reloptions, true);
957 : 10521 : break;
958 : 3409 : case RELKIND_PARTITIONED_TABLE:
959 : 3409 : (void) partitioned_table_reloptions(reloptions, true);
960 : 3401 : break;
961 : 27047 : default:
962 : 27047 : (void) heap_reloptions(relkind, reloptions, true);
963 : : }
964 : :
965 [ + + ]: 40901 : 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 : 40844 : 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 : 40733 : stmt->tableElts =
984 : 40897 : MergeAttributes(stmt->tableElts, inheritOids,
985 : 40897 : stmt->relation->relpersistence,
986 : 40897 : 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 : 40733 : 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 : 40701 : rawDefaults = NIL;
1014 : 40701 : cookedDefaults = NIL;
1015 : 40701 : attnum = 0;
1016 : :
1017 [ + + + + : 204120 : foreach(listptr, stmt->tableElts)
+ + ]
1018 : : {
1019 : 163419 : ColumnDef *colDef = lfirst(listptr);
1020 : :
1021 : 163419 : attnum++;
1022 [ + + ]: 163419 : if (colDef->raw_default != NULL)
1023 : : {
1024 : : RawColumnDefault *rawEnt;
1025 : :
1026 : : Assert(colDef->cooked_default == NULL);
1027 : :
1028 : 2150 : rawEnt = palloc_object(RawColumnDefault);
1029 : 2150 : rawEnt->attnum = attnum;
1030 : 2150 : rawEnt->raw_default = colDef->raw_default;
1031 : 2150 : rawEnt->generated = colDef->generated;
1032 : 2150 : rawDefaults = lappend(rawDefaults, rawEnt);
1033 : : }
1034 [ + + ]: 161269 : 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 : 40701 : 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 [ + + ]: 40701 : 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 [ + + + - : 40622 : else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
+ + + + ]
1066 : : {
1067 [ + + ]: 26220 : if (stmt->partbound)
1068 : : {
1069 : : Assert(list_length(inheritOids) == 1);
1070 : 5887 : accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1071 : : }
1072 : :
1073 [ + + + - : 26220 : if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
+ + + + ]
1074 : 22810 : 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 : 40689 : 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 : 40689 : 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 : 40656 : 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 : 40656 : 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 [ + + ]: 40656 : if (rawDefaults)
1132 : 1844 : AddRelationNewConstraints(rel, rawDefaults, NIL,
1133 : : true, true, false, queryString);
1134 : :
1135 : : /*
1136 : : * Make column generation expressions visible for use by partitioning.
1137 : : */
1138 : 40524 : CommandCounterIncrement();
1139 : :
1140 : : /* Process and store partition bound, if any. */
1141 [ + + ]: 40524 : if (stmt->partbound)
1142 : : {
1143 : : PartitionBoundSpec *bound;
1144 : : ParseState *pstate;
1145 : 5950 : Oid parentId = linitial_oid(inheritOids),
1146 : : defaultPartOid;
1147 : : Relation parent,
1148 : 5950 : defaultRel = NULL;
1149 : : ParseNamespaceItem *nsitem;
1150 : :
1151 : : /* Already have strong enough lock on the parent */
1152 : 5950 : 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 [ + + ]: 5950 : 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 : 5938 : get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
1185 : : true));
1186 [ + + ]: 5938 : if (OidIsValid(defaultPartOid))
1187 : 267 : defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1188 : :
1189 : : /* Transform the bound values */
1190 : 5938 : pstate = make_parsestate(NULL);
1191 : 5938 : 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 : 5938 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1199 : : NULL, false, false);
1200 : 5938 : addNSItemToQuery(pstate, nsitem, false, true, true);
1201 : :
1202 : 5938 : 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 : 5802 : 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 [ + + ]: 5726 : if (OidIsValid(defaultPartOid))
1218 : : {
1219 : 247 : check_default_partition_contents(parent, defaultRel, bound);
1220 : : /* Keep the lock until commit. */
1221 : 235 : table_close(defaultRel, NoLock);
1222 : : }
1223 : :
1224 : : /* Update the pg_class entry. */
1225 : 5714 : StorePartitionBound(rel, parent, bound);
1226 : :
1227 : 5714 : table_close(parent, NoLock);
1228 : : }
1229 : :
1230 : : /* Store inheritance information for new rel. */
1231 : 40288 : 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 [ + + ]: 40288 : 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 : 3400 : List *partexprs = NIL;
1245 : :
1246 : 3400 : pstate = make_parsestate(NULL);
1247 : 3400 : pstate->p_sourcetext = queryString;
1248 : :
1249 : 3400 : partnatts = list_length(stmt->partspec->partParams);
1250 : :
1251 : : /* Protect fixed-size arrays here and in executor */
1252 [ - + ]: 3400 : 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 : 3400 : stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1265 : :
1266 : 3380 : ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1267 : : partattrs, &partexprs, partopclass,
1268 : 3380 : partcollation, stmt->partspec->strategy);
1269 : :
1270 : 3292 : StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1271 : : partexprs,
1272 : : partopclass, partcollation);
1273 : :
1274 : : /* make it all visible */
1275 : 3288 : 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 [ + + ]: 40176 : if (stmt->partbound)
1286 : : {
1287 : 5710 : 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 : 5710 : parent = table_open(parentId, NoLock);
1294 : 5710 : idxlist = RelationGetIndexList(parent);
1295 : :
1296 : : /*
1297 : : * For each index in the parent table, create one in the partition
1298 : : */
1299 [ + + + + : 6648 : foreach(cell, idxlist)
+ + ]
1300 : : {
1301 : 950 : Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1302 : : AttrMap *attmap;
1303 : : IndexStmt *idxstmt;
1304 : : Oid constraintOid;
1305 : :
1306 [ + + ]: 950 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1307 : : {
1308 [ + + ]: 24 : 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 : 16 : index_close(idxRel, AccessShareLock);
1318 : 16 : continue;
1319 : : }
1320 : : }
1321 : :
1322 : 926 : attmap = build_attrmap_by_name(RelationGetDescr(rel),
1323 : : RelationGetDescr(parent),
1324 : : false);
1325 : : idxstmt =
1326 : 926 : generateClonedIndexStmt(NULL, idxRel,
1327 : : attmap, &constraintOid);
1328 : 926 : DefineIndex(NULL,
1329 : : RelationGetRelid(rel),
1330 : : idxstmt,
1331 : : InvalidOid,
1332 : : RelationGetRelid(idxRel),
1333 : : constraintOid,
1334 : : -1,
1335 : : false, false, false, false, false);
1336 : :
1337 : 922 : index_close(idxRel, AccessShareLock);
1338 : : }
1339 : :
1340 : 5698 : list_free(idxlist);
1341 : :
1342 : : /*
1343 : : * If there are any row-level triggers, clone them to the new
1344 : : * partition.
1345 : : */
1346 [ + + ]: 5698 : 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 : 5698 : CloneForeignKeyConstraints(NULL, parent, rel);
1354 : :
1355 : 5698 : 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 [ + + ]: 40164 : if (stmt->constraints)
1364 : : {
1365 : : List *conlist;
1366 : :
1367 : 522 : conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1368 : : true, true, false, queryString);
1369 [ + + + + : 1569 : foreach_ptr(CookedConstraint, cons, conlist)
+ + ]
1370 : : {
1371 [ + - ]: 573 : if (cons->name != NULL)
1372 : 573 : 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 : 40140 : nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1383 : : old_notnulls, connames);
1384 [ + + + + : 89884 : foreach_int(attrnum, nncols)
+ + ]
1385 : 9708 : set_attnotnull(NULL, rel, attrnum, false);
1386 : :
1387 : 40088 : 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 : 40088 : relation_close(rel, NoLock);
1394 : :
1395 : 40088 : 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 : 42871 : 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 : 42871 : natts = list_length(columns);
1424 : 42871 : desc = CreateTemplateTupleDesc(natts);
1425 : :
1426 : 42871 : attnum = 0;
1427 : :
1428 [ + + + + : 208652 : foreach(l, columns)
+ + ]
1429 : : {
1430 : 165821 : 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 : 165821 : attnum++;
1440 : :
1441 : 165821 : attname = entry->colname;
1442 : 165821 : typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1443 : :
1444 : 165821 : aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1445 [ + + ]: 165821 : if (aclresult != ACLCHECK_OK)
1446 : 28 : aclcheck_error_type(aclresult, atttypid);
1447 : :
1448 : 165793 : attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1449 : 165793 : attdim = list_length(entry->typeName->arrayBounds);
1450 [ - + ]: 165793 : if (attdim > PG_INT16_MAX)
1451 [ # # ]: 0 : ereport(ERROR,
1452 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1453 : : errmsg("too many array dimensions"));
1454 : :
1455 [ - + ]: 165793 : 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 : 165793 : TupleDescInitEntry(desc, attnum, attname,
1462 : : atttypid, atttypmod, attdim);
1463 : 165793 : att = TupleDescAttr(desc, attnum - 1);
1464 : :
1465 : : /* Override TupleDescInitEntry's settings as requested */
1466 : 165793 : TupleDescInitEntryCollation(desc, attnum, attcollation);
1467 : :
1468 : : /* Fill in additional stuff not handled by TupleDescInitEntry */
1469 : 165793 : att->attnotnull = entry->is_not_null;
1470 : 165793 : att->attislocal = entry->is_local;
1471 : 165793 : att->attinhcount = entry->inhcount;
1472 : 165793 : att->attidentity = entry->identity;
1473 : 165793 : att->attgenerated = entry->generated;
1474 : 165793 : att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1475 [ + + ]: 165785 : if (entry->storage)
1476 : 14133 : att->attstorage = entry->storage;
1477 [ + + ]: 151652 : else if (entry->storage_name)
1478 : 24 : att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1479 : :
1480 : 165781 : populate_compact_attribute(desc, attnum - 1);
1481 : : }
1482 : :
1483 : 42831 : TupleDescFinalize(desc);
1484 : :
1485 : 42831 : 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 : 11499 : RemoveRelations(DropStmt *drop)
1569 : : {
1570 : : ObjectAddresses *objects;
1571 : : char relkind;
1572 : : ListCell *cell;
1573 : 11499 : int flags = 0;
1574 : 11499 : LOCKMODE lockmode = AccessExclusiveLock;
1575 : :
1576 : : /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1577 [ + + ]: 11499 : 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 : 119 : lockmode = ShareUpdateExclusiveLock;
1585 : : Assert(drop->removeType == OBJECT_INDEX);
1586 [ + + ]: 119 : 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 [ - + ]: 115 : 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 [ + + + + : 11495 : switch (drop->removeType)
+ + - ]
1604 : : {
1605 : 9940 : case OBJECT_TABLE:
1606 : 9940 : relkind = RELKIND_RELATION;
1607 : 9940 : break;
1608 : :
1609 : 566 : case OBJECT_INDEX:
1610 : 566 : relkind = RELKIND_INDEX;
1611 : 566 : break;
1612 : :
1613 : 123 : case OBJECT_SEQUENCE:
1614 : 123 : relkind = RELKIND_SEQUENCE;
1615 : 123 : break;
1616 : :
1617 : 672 : case OBJECT_VIEW:
1618 : 672 : relkind = RELKIND_VIEW;
1619 : 672 : break;
1620 : :
1621 : 84 : case OBJECT_MATVIEW:
1622 : 84 : relkind = RELKIND_MATVIEW;
1623 : 84 : break;
1624 : :
1625 : 110 : case OBJECT_FOREIGN_TABLE:
1626 : 110 : relkind = RELKIND_FOREIGN_TABLE;
1627 : 110 : 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 : 11495 : objects = new_object_addresses();
1638 : :
1639 [ + - + + : 25473 : foreach(cell, drop->objects)
+ + ]
1640 : : {
1641 : 14085 : 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 : 14085 : AcceptInvalidationMessages();
1657 : :
1658 : : /* Look up the appropriate relation using namespace search. */
1659 : 14085 : state.expected_relkind = relkind;
1660 : 28170 : state.heap_lockmode = drop->concurrent ?
1661 [ + + ]: 14085 : ShareUpdateExclusiveLock : AccessExclusiveLock;
1662 : : /* We must initialize these fields to show that no locks are held: */
1663 : 14085 : state.heapOid = InvalidOid;
1664 : 14085 : state.partParentOid = InvalidOid;
1665 : :
1666 : 14085 : relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1667 : : RangeVarCallbackForDropRelation,
1668 : : &state);
1669 : :
1670 : : /* Not there? */
1671 [ + + ]: 14068 : 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 [ + + ]: 13449 : if (drop->concurrent &&
1682 [ + + ]: 111 : state.actual_relpersistence != RELPERSISTENCE_TEMP)
1683 : : {
1684 : : Assert(list_length(drop->objects) == 1 &&
1685 : : drop->removeType == OBJECT_INDEX);
1686 : 99 : flags |= PERFORM_DELETION_CONCURRENTLY;
1687 : : }
1688 : :
1689 : : /*
1690 : : * Concurrent index drop cannot be used with partitioned indexes,
1691 : : * either.
1692 : : */
1693 [ + + ]: 13449 : if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1694 [ + + ]: 99 : 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 [ + + ]: 13445 : 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 : 13445 : obj.classId = RelationRelationId;
1714 : 13445 : obj.objectId = relOid;
1715 : 13445 : obj.objectSubId = 0;
1716 : :
1717 : 13445 : add_exact_object_address(&obj, objects);
1718 : : }
1719 : :
1720 : 11388 : performMultipleDeletions(objects, drop->behavior, flags);
1721 : :
1722 : 11293 : free_object_addresses(objects);
1723 : 11293 : }
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 : 14308 : 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 : 14308 : bool invalid_system_index = false;
1742 : :
1743 : 14308 : state = (struct DropRelationCallbackState *) arg;
1744 : 14308 : 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 [ + + - + ]: 14308 : 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 [ + + - + ]: 14308 : 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 [ + + ]: 14308 : if (!OidIsValid(relOid))
1770 : 620 : return;
1771 : :
1772 : 13688 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1773 [ - + ]: 13688 : if (!HeapTupleIsValid(tuple))
1774 : 0 : return; /* concurrently dropped, so nothing to do */
1775 : 13688 : classform = (Form_pg_class) GETSTRUCT(tuple);
1776 : 13688 : is_partition = classform->relispartition;
1777 : :
1778 : : /* Pass back some data to save lookups in RemoveRelations */
1779 : 13688 : state->actual_relkind = classform->relkind;
1780 : 13688 : 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 [ + + ]: 13688 : if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1791 : 2003 : expected_relkind = RELKIND_RELATION;
1792 [ + + ]: 11685 : else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1793 : 56 : expected_relkind = RELKIND_INDEX;
1794 : : else
1795 : 11629 : expected_relkind = classform->relkind;
1796 : :
1797 [ - + ]: 13688 : 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 [ + + ]: 13688 : 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 [ + + - + ]: 13676 : 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 [ + - + + : 13676 : 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 : 13671 : 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 [ + + + + ]: 13671 : if (expected_relkind == RELKIND_INDEX &&
1854 : : relOid != oldRelOid)
1855 : : {
1856 : 558 : state->heapOid = IndexGetRelation(relOid, true);
1857 [ + - ]: 558 : if (OidIsValid(state->heapOid))
1858 : 558 : 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 [ + + + + ]: 13671 : if (is_partition && relOid != oldRelOid)
1868 : : {
1869 : 403 : state->partParentOid = get_partition_parent(relOid, true);
1870 [ + - ]: 403 : if (OidIsValid(state->partParentOid))
1871 : 403 : 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 : 1181 : ExecuteTruncate(TruncateStmt *stmt)
1892 : : {
1893 : 1181 : List *rels = NIL;
1894 : 1181 : List *relids = NIL;
1895 : 1181 : List *relids_logged = NIL;
1896 : : ListCell *cell;
1897 : :
1898 : : /*
1899 : : * Open, exclusive-lock, and check all the explicitly-specified relations
1900 : : */
1901 [ + - + + : 2498 : foreach(cell, stmt->relations)
+ + ]
1902 : : {
1903 : 1353 : RangeVar *rv = lfirst(cell);
1904 : : Relation rel;
1905 : 1353 : bool recurse = rv->inh;
1906 : : Oid myrelid;
1907 : 1353 : LOCKMODE lockmode = AccessExclusiveLock;
1908 : :
1909 : 1353 : myrelid = RangeVarGetRelidExtended(rv, lockmode,
1910 : : 0, RangeVarCallbackForTruncate,
1911 : : NULL);
1912 : :
1913 : : /* don't throw error for "TRUNCATE foo, foo" */
1914 [ + + ]: 1330 : if (list_member_oid(relids, myrelid))
1915 : 1 : continue;
1916 : :
1917 : : /* open the relation, we already hold a lock on it */
1918 : 1329 : 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 : 1329 : truncate_check_activity(rel);
1925 : :
1926 : 1324 : rels = lappend(rels, rel);
1927 : 1324 : relids = lappend_oid(relids, myrelid);
1928 : :
1929 : : /* Log this relation only if needed for logical decoding */
1930 [ + + - + : 1324 : if (RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ + ]
1931 : 39 : relids_logged = lappend_oid(relids_logged, myrelid);
1932 : :
1933 [ + + ]: 1324 : if (recurse)
1934 : : {
1935 : : ListCell *child;
1936 : : List *children;
1937 : :
1938 : 1287 : children = find_all_inheritors(myrelid, lockmode, NULL);
1939 : :
1940 [ + - + + : 3794 : foreach(child, children)
+ + ]
1941 : : {
1942 : 2507 : Oid childrelid = lfirst_oid(child);
1943 : :
1944 [ + + ]: 2507 : if (list_member_oid(relids, childrelid))
1945 : 1287 : 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 [ + + ]: 37 : 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 : 1145 : ExecuteTruncateGuts(rels, relids, relids_logged,
1990 : 1145 : stmt->behavior, stmt->restart_seqs, false);
1991 : :
1992 : : /* And close the rels */
1993 [ + - + + : 3523 : foreach(cell, rels)
+ + ]
1994 : : {
1995 : 2431 : Relation rel = (Relation) lfirst(cell);
1996 : :
1997 : 2431 : table_close(rel, NoLock);
1998 : : }
1999 : 1092 : }
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 : 1165 : 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 : 1165 : List *seq_relids = NIL;
2023 : 1165 : 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 : 1165 : rels = list_copy(explicit_rels);
2042 [ + + ]: 1165 : 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 [ + + ]: 1165 : if (behavior == DROP_RESTRICT)
2083 : 1140 : 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 [ + + ]: 1116 : if (restart_seqs)
2093 : : {
2094 [ + - + + : 32 : foreach(cell, rels)
+ + ]
2095 : : {
2096 : 16 : Relation rel = (Relation) lfirst(cell);
2097 : 16 : List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2098 : : ListCell *seqcell;
2099 : :
2100 [ + + + + : 39 : foreach(seqcell, seqlist)
+ + ]
2101 : : {
2102 : 23 : Oid seq_relid = lfirst_oid(seqcell);
2103 : : Relation seq_rel;
2104 : :
2105 : 23 : seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2106 : :
2107 : : /* This check must match AlterSequence! */
2108 [ - + ]: 23 : if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2109 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
2110 : 0 : RelationGetRelationName(seq_rel));
2111 : :
2112 : 23 : seq_relids = lappend_oid(seq_relids, seq_relid);
2113 : :
2114 : 23 : relation_close(seq_rel, NoLock);
2115 : : }
2116 : : }
2117 : : }
2118 : :
2119 : : /* Prepare to catch AFTER triggers. */
2120 : 1116 : 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 : 1116 : estate = CreateExecutorState();
2132 : 1116 : resultRelInfos = palloc_array(ResultRelInfo, list_length(rels));
2133 : 1116 : resultRelInfo = resultRelInfos;
2134 [ + - + + : 3649 : foreach(cell, rels)
+ + ]
2135 : : {
2136 : 2533 : Relation rel = (Relation) lfirst(cell);
2137 : :
2138 : 2533 : InitResultRelInfo(resultRelInfo,
2139 : : rel,
2140 : : 0, /* dummy rangetable index */
2141 : : NULL,
2142 : : 0);
2143 : 2533 : estate->es_opened_result_relations =
2144 : 2533 : lappend(estate->es_opened_result_relations, resultRelInfo);
2145 : 2533 : 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 : 1116 : resultRelInfo = resultRelInfos;
2155 [ + - + + : 3649 : foreach(cell, rels)
+ + ]
2156 : : {
2157 : : UserContext ucxt;
2158 : :
2159 [ + + ]: 2533 : if (run_as_table_owner)
2160 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2161 : : &ucxt);
2162 : 2533 : ExecBSTruncateTriggers(estate, resultRelInfo);
2163 [ + + ]: 2533 : if (run_as_table_owner)
2164 : 36 : RestoreUserContext(&ucxt);
2165 : 2533 : resultRelInfo++;
2166 : : }
2167 : :
2168 : : /*
2169 : : * OK, truncate each table.
2170 : : */
2171 : 1116 : mySubid = GetCurrentSubTransactionId();
2172 : :
2173 [ + - + + : 3649 : foreach(cell, rels)
+ + ]
2174 : : {
2175 : 2533 : Relation rel = (Relation) lfirst(cell);
2176 : :
2177 : : /* Skip partitioned tables as there is nothing to do */
2178 [ + + ]: 2533 : 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 [ + + ]: 2056 : 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 [ + + ]: 2039 : if (rel->rd_createSubid == mySubid ||
2231 [ + + ]: 2017 : rel->rd_newRelfilelocatorSubid == mySubid)
2232 : : {
2233 : : /* Immediate, non-rollbackable truncation is OK */
2234 : 54 : heap_truncate_one_rel(rel);
2235 : : }
2236 : : else
2237 : : {
2238 : : Oid heap_relid;
2239 : : Oid toast_relid;
2240 : 1985 : 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 : 1985 : 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 : 1985 : RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2258 : :
2259 : 1985 : heap_relid = RelationGetRelid(rel);
2260 : :
2261 : : /*
2262 : : * The same for the toast table, if any.
2263 : : */
2264 : 1985 : toast_relid = rel->rd_rel->reltoastrelid;
2265 [ + + ]: 1985 : if (OidIsValid(toast_relid))
2266 : : {
2267 : 1197 : Relation toastrel = relation_open(toast_relid,
2268 : : AccessExclusiveLock);
2269 : :
2270 : 1197 : RelationSetNewRelfilenumber(toastrel,
2271 : 1197 : toastrel->rd_rel->relpersistence);
2272 : 1197 : table_close(toastrel, NoLock);
2273 : : }
2274 : :
2275 : : /*
2276 : : * Reconstruct the indexes to match, and we're done.
2277 : : */
2278 : 1985 : reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2279 : : &reindex_params);
2280 : : }
2281 : :
2282 : 2039 : pgstat_count_truncate(rel);
2283 : : }
2284 : :
2285 : : /* Now go through the hash table, and truncate foreign tables */
2286 [ + + ]: 1116 : 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 [ + + + + : 1135 : foreach(cell, seq_relids)
+ + ]
2318 : : {
2319 : 23 : Oid seq_relid = lfirst_oid(cell);
2320 : :
2321 : 23 : 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 [ + + ]: 1112 : 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 : 1112 : resultRelInfo = resultRelInfos;
2364 [ + - + + : 3641 : foreach(cell, rels)
+ + ]
2365 : : {
2366 : : UserContext ucxt;
2367 : :
2368 [ + + ]: 2529 : if (run_as_table_owner)
2369 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2370 : : &ucxt);
2371 : 2529 : ExecASTruncateTriggers(estate, resultRelInfo);
2372 [ + + ]: 2529 : if (run_as_table_owner)
2373 : 36 : RestoreUserContext(&ucxt);
2374 : 2529 : resultRelInfo++;
2375 : : }
2376 : :
2377 : : /* Handle queued AFTER triggers */
2378 : 1112 : AfterTriggerEndQuery(estate);
2379 : :
2380 : : /* We can clean up the EState now */
2381 : 1112 : FreeExecutorState(estate);
2382 : :
2383 : : /*
2384 : : * Close any rels opened by CASCADE (can't do this while EState still
2385 : : * holds refs)
2386 : : */
2387 : 1112 : rels = list_difference_ptr(rels, explicit_rels);
2388 [ + + + + : 1174 : foreach(cell, rels)
+ + ]
2389 : : {
2390 : 62 : Relation rel = (Relation) lfirst(cell);
2391 : :
2392 : 62 : table_close(rel, NoLock);
2393 : : }
2394 : 1112 : }
2395 : :
2396 : : /*
2397 : : * Check that a given relation is safe to truncate. Subroutine for
2398 : : * ExecuteTruncate() and RangeVarCallbackForTruncate().
2399 : : */
2400 : : static void
2401 : 2717 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
2402 : : {
2403 : 2717 : 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 [ + + ]: 2717 : 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 [ + + ]: 2698 : else if (reltuple->relkind != RELKIND_RELATION &&
2423 [ - + ]: 490 : 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 [ + + + + ]: 2715 : 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 [ - + ]: 2714 : InvokeObjectTruncateHook(relid);
2448 : 2714 : }
2449 : :
2450 : : /*
2451 : : * Check that current user has the permission to truncate given relation.
2452 : : */
2453 : : static void
2454 : 1498 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
2455 : : {
2456 : 1498 : char *relname = NameStr(reltuple->relname);
2457 : : AclResult aclresult;
2458 : :
2459 : : /* Permissions checks */
2460 : 1498 : aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2461 [ + + ]: 1498 : if (aclresult != ACLCHECK_OK)
2462 : 20 : aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2463 : : relname);
2464 : 1478 : }
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 : 2607 : 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 [ + + + + ]: 2607 : 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 : 2606 : CheckTableNotInUse(rel, "TRUNCATE");
2488 : 2602 : }
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 : 40897 : MergeAttributes(List *columns, const List *supers, char relpersistence,
2581 : : bool is_partition, List **supconstr, List **supnotnulls)
2582 : : {
2583 : 40897 : List *inh_columns = NIL;
2584 : 40897 : List *constraints = NIL;
2585 : 40897 : List *nnconstraints = NIL;
2586 : 40897 : bool have_bogus_defaults = false;
2587 : : int child_attno;
2588 : : static Node bogus_marker = {0}; /* marks conflicting defaults */
2589 : 40897 : 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 [ - + ]: 40897 : 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 [ + + ]: 190775 : for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
2624 : : {
2625 : 149894 : ColumnDef *coldef = list_nth_node(ColumnDef, columns, coldefpos);
2626 : :
2627 [ + + + + ]: 149894 : 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 [ + + ]: 4110887 : for (int restpos = coldefpos + 1; restpos < list_length(columns);)
2643 : : {
2644 : 3961009 : ColumnDef *restdef = list_nth_node(ColumnDef, columns, restpos);
2645 : :
2646 [ + + ]: 3961009 : 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 : 3960976 : 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 [ + + ]: 40881 : if (is_partition)
2677 : : {
2678 : 5994 : saved_columns = columns;
2679 : 5994 : 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 : 40881 : child_attno = 0;
2687 [ + + + + : 48485 : foreach(lc, supers)
+ + ]
2688 : : {
2689 : 7664 : 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 : 7664 : Bitmapset *nncols = NULL;
2700 : :
2701 : : /* caller already got lock */
2702 : 7664 : 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 [ + + ]: 7664 : if (is_partition)
2710 : 5994 : 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 [ + + + + ]: 7660 : 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 [ + + + + ]: 7656 : 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 [ + + ]: 7652 : 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 [ + + ]: 7648 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2740 [ + + ]: 5990 : relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2741 [ - + ]: 5978 : 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 [ + + ]: 7648 : if (is_partition &&
2752 [ + + + + ]: 5990 : 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 [ + + ]: 7644 : if (relpersistence != RELPERSISTENCE_TEMP &&
2761 [ + + ]: 7406 : 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 [ + + - + ]: 7628 : 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 [ - + ]: 7628 : 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 : 7628 : tupleDesc = RelationGetDescr(relation);
2786 : 7628 : 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 : 7628 : newattmap = make_attrmap(tupleDesc->natts);
2794 : :
2795 : : /* We can't process inherited defaults until newattmap is complete. */
2796 : 7628 : 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 : 7628 : nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
2803 : : true, false);
2804 [ + + + + : 16896 : foreach_ptr(CookedConstraint, cc, nnconstrs)
+ + ]
2805 : 1640 : nncols = bms_add_member(nncols, cc->attnum);
2806 : :
2807 [ + + ]: 22296 : for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
2808 : 14668 : parent_attno++)
2809 : : {
2810 : 14692 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2811 : : parent_attno - 1);
2812 : 14692 : 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 [ + + ]: 14692 : if (attribute->attisdropped)
2821 : 132 : continue; /* leave newattmap->attnums entry as zero */
2822 : :
2823 : : /*
2824 : : * Create new column definition
2825 : : */
2826 : 14560 : newdef = makeColumnDef(attributeName, attribute->atttypid,
2827 : : attribute->atttypmod, attribute->attcollation);
2828 : 14560 : newdef->storage = attribute->attstorage;
2829 : 14560 : newdef->generated = attribute->attgenerated;
2830 [ + + ]: 14560 : 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 [ + + ]: 14560 : if (is_partition)
2840 : 11604 : newdef->identity = attribute->attidentity;
2841 : :
2842 : : /*
2843 : : * Does it match some previously considered column from another
2844 : : * parent?
2845 : : */
2846 : 14560 : exist_attno = findAttrByName(attributeName, inh_columns);
2847 [ + + ]: 14560 : 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 : 14307 : newdef->inhcount = 1;
2868 : 14307 : newdef->is_local = false;
2869 : 14307 : inh_columns = lappend(inh_columns, newdef);
2870 : :
2871 : 14307 : newattmap->attnums[parent_attno - 1] = ++child_attno;
2872 : 14307 : mergeddef = newdef;
2873 : : }
2874 : :
2875 : : /*
2876 : : * mark attnotnull if parent has it
2877 : : */
2878 [ + + ]: 14536 : 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 [ + + ]: 14536 : 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 [ + + + + : 8074 : 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 [ + + + + ]: 7604 : 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 [ + + + + : 16848 : 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 : 7604 : 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 : 7604 : 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 [ + + ]: 40821 : if (inh_columns != NIL)
3023 : : {
3024 : 7306 : int newcol_attno = 0;
3025 : :
3026 [ + + + + : 7954 : 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 : 7254 : columns = inh_columns;
3061 : :
3062 : : /*
3063 : : * Check that we haven't exceeded the legal # of columns after merging
3064 : : * in inherited columns.
3065 : : */
3066 [ - + ]: 7254 : 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 [ + + ]: 40769 : if (is_partition)
3079 : : {
3080 [ + + + + : 6105 : 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 [ + + ]: 40745 : 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 : 40733 : *supconstr = constraints;
3190 : 40733 : *supnotnulls = nnconstraints;
3191 : :
3192 : 40733 : 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 : 40288 : 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 [ + + ]: 40288 : if (supers == NIL)
3579 : 33274 : 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 : 7014 : relation = table_open(InheritsRelationId, RowExclusiveLock);
3591 : :
3592 : 7014 : seqNumber = 1;
3593 [ + - + + : 14258 : foreach(entry, supers)
+ + ]
3594 : : {
3595 : 7244 : Oid parentOid = lfirst_oid(entry);
3596 : :
3597 : 7244 : StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
3598 : : child_is_partition);
3599 : 7244 : seqNumber++;
3600 : : }
3601 : :
3602 : 7014 : 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 : 8802 : 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 : 8802 : StoreSingleInheritance(relationId, parentOid, seqNumber);
3619 : :
3620 : : /*
3621 : : * Store a dependency too
3622 : : */
3623 : 8802 : parentobject.classId = RelationRelationId;
3624 : 8802 : parentobject.objectId = parentOid;
3625 : 8802 : parentobject.objectSubId = 0;
3626 : 8802 : childobject.classId = RelationRelationId;
3627 : 8802 : childobject.objectId = relationId;
3628 : 8802 : childobject.objectSubId = 0;
3629 : :
3630 [ + + ]: 8802 : 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 [ - + ]: 8802 : InvokeObjectPostAlterHookArg(InheritsRelationId,
3639 : : relationId, 0,
3640 : : parentOid, false);
3641 : :
3642 : : /*
3643 : : * Mark the parent as having subclasses.
3644 : : */
3645 : 8802 : SetRelationHasSubclass(parentOid, true);
3646 : 8802 : }
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 : 15260 : findAttrByName(const char *attributeName, const List *columns)
3656 : : {
3657 : : ListCell *lc;
3658 : 15260 : int i = 1;
3659 : :
3660 [ + + + + : 26651 : 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 : 14756 : 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 : 10866 : 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 : 10866 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3707 : 10866 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3708 [ - + ]: 10866 : if (!HeapTupleIsValid(tuple))
3709 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationId);
3710 : 10866 : classtuple = (Form_pg_class) GETSTRUCT(tuple);
3711 : :
3712 [ + + ]: 10866 : if (classtuple->relhassubclass != relhassubclass)
3713 : : {
3714 : 5270 : classtuple->relhassubclass = relhassubclass;
3715 : 5270 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3716 : : }
3717 : : else
3718 : : {
3719 : : /* no need to change tuple, but force relcache rebuild anyway */
3720 : 5596 : CacheInvalidateRelcacheByTuple(tuple);
3721 : : }
3722 : :
3723 : 10866 : heap_freetuple(tuple);
3724 : 10866 : table_close(relationRelation, RowExclusiveLock);
3725 : 10866 : }
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 : 174 : 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 : 174 : oldTableSpaceId = rel->rd_rel->reltablespace;
3747 [ + + ]: 174 : if (newTableSpaceId == oldTableSpaceId ||
3748 [ + + + + ]: 169 : (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 [ + + + + : 164 : 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 [ + + ]: 164 : 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 [ + + - + ]: 156 : 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 : 156 : 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 : 156 : 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 : 156 : Oid reloid = RelationGetRelid(rel);
3804 : :
3805 : : Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3806 : :
3807 : : /* Get a modifiable copy of the relation's pg_class row. */
3808 : 156 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
3809 : :
3810 : 156 : tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3811 [ - + ]: 156 : if (!HeapTupleIsValid(tuple))
3812 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
3813 : 156 : otid = tuple->t_self;
3814 : 156 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3815 : :
3816 : : /* Update the pg_class row. */
3817 : 312 : rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3818 [ + + ]: 156 : InvalidOid : newTableSpaceId;
3819 [ + + ]: 156 : if (RelFileNumberIsValid(newRelFilenumber))
3820 : 127 : rd_rel->relfilenode = newRelFilenumber;
3821 : 156 : CatalogTupleUpdate(pg_class, &otid, tuple);
3822 : 156 : 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 [ + + + + : 156 : if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
+ - + + +
+ ]
3829 : 20 : changeDependencyOnTablespace(RelationRelationId, reloid,
3830 : : rd_rel->reltablespace);
3831 : :
3832 : 156 : heap_freetuple(tuple);
3833 : 156 : table_close(pg_class, RowExclusiveLock);
3834 : 156 : }
3835 : :
3836 : : /*
3837 : : * renameatt_check - basic sanity checks before attribute rename
3838 : : */
3839 : : static void
3840 : 684 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3841 : : {
3842 : 684 : char relkind = classform->relkind;
3843 : :
3844 [ + + + + ]: 684 : 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 [ + + + + ]: 680 : 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 [ - + ]: 680 : 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 [ + + ]: 680 : 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 [ + + + + ]: 676 : 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 : 675 : }
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 : 283 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
4048 : : void *arg)
4049 : : {
4050 : : HeapTuple tuple;
4051 : : Form_pg_class form;
4052 : :
4053 : 283 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
4054 [ + + ]: 283 : if (!HeapTupleIsValid(tuple))
4055 : 25 : return; /* concurrently dropped */
4056 : 258 : form = (Form_pg_class) GETSTRUCT(tuple);
4057 : 258 : renameatt_check(relid, form, false);
4058 : 249 : 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 : 111892 : CheckTableNotInUse(Relation rel, const char *stmt)
4475 : : {
4476 : : int expected_refcnt;
4477 : :
4478 [ + + ]: 111892 : expected_refcnt = rel->rd_isnailed ? 2 : 1;
4479 [ + + ]: 111892 : 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 [ + + ]: 111864 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
4487 [ + + + + ]: 182943 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4488 : 90758 : 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 : 111852 : }
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 : 39570 : 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 [ + + + + ]: 39570 : 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 : 39568 : CheckTableNotInUse(rel, "ALTER TABLE");
4525 : 39544 : }
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 : 21044 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
4534 : : {
4535 : 42022 : return RangeVarGetRelidExtended(stmt->relation, lockmode,
4536 : 21044 : 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 : 20870 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
4593 : : AlterTableUtilityContext *context)
4594 : : {
4595 : : Relation rel;
4596 : :
4597 : : /* Caller is required to provide an adequate lock. */
4598 : 20870 : rel = relation_open(context->relid, NoLock);
4599 : :
4600 : 20870 : CheckAlterTableIsSafe(rel);
4601 : :
4602 : 20856 : ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4603 : 18136 : }
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 : 203 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
4622 : : {
4623 : : Relation rel;
4624 : 203 : LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4625 : :
4626 : 203 : rel = relation_open(relid, lockmode);
4627 : :
4628 : 203 : EventTriggerAlterTableRelid(relid);
4629 : :
4630 : 203 : ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4631 : 203 : }
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 : 21247 : AlterTableGetLockLevel(List *cmds)
4667 : : {
4668 : : /*
4669 : : * This only works if we read catalog tables using MVCC snapshots.
4670 : : */
4671 : : ListCell *lcmd;
4672 : 21247 : LOCKMODE lockmode = ShareUpdateExclusiveLock;
4673 : :
4674 [ + - + + : 43352 : foreach(lcmd, cmds)
+ + ]
4675 : : {
4676 : 22105 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4677 : 22105 : LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4678 : :
4679 [ + + + + : 22105 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + + + +
- ]
4680 : : {
4681 : : /*
4682 : : * These subcommands rewrite the heap, so require full locks.
4683 : : */
4684 : 2649 : 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 : 2649 : cmd_lockmode = AccessExclusiveLock;
4690 : 2649 : 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 : 220 : case AT_SetStorage: /* may add toast tables, see
4699 : : * ATRewriteCatalogs() */
4700 : 220 : cmd_lockmode = AccessExclusiveLock;
4701 : 220 : 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 : 785 : case AT_DropConstraint: /* as DROP INDEX */
4709 : : case AT_DropNotNull: /* may change some SQL plans */
4710 : 785 : cmd_lockmode = AccessExclusiveLock;
4711 : 785 : 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 : 1141 : case AT_ChangeOwner: /* change visible to SELECT */
4730 : 1141 : cmd_lockmode = AccessExclusiveLock;
4731 : 1141 : 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 : 2161 : 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 : 2161 : cmd_lockmode = AccessExclusiveLock;
4777 : 2161 : break;
4778 : :
4779 : 9769 : case AT_AddConstraint:
4780 : : case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4781 : : case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4782 [ + - ]: 9769 : if (IsA(cmd->def, Constraint))
4783 : : {
4784 : 9769 : Constraint *con = (Constraint *) cmd->def;
4785 : :
4786 [ + + + ]: 9769 : switch (con->contype)
4787 : : {
4788 : 7182 : 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 : 7182 : cmd_lockmode = AccessExclusiveLock;
4801 : 7182 : break;
4802 : 1812 : 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 : 1812 : cmd_lockmode = ShareRowExclusiveLock;
4810 : 1812 : break;
4811 : :
4812 : 775 : default:
4813 : 775 : cmd_lockmode = AccessExclusiveLock;
4814 : : }
4815 : : }
4816 : 9769 : 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 : 374 : case AT_AddInherit:
4827 : : case AT_DropInherit:
4828 : 374 : cmd_lockmode = AccessExclusiveLock;
4829 : 374 : 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 : 288 : case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4874 : 288 : cmd_lockmode = ShareUpdateExclusiveLock;
4875 : 288 : 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 : 1847 : case AT_AttachPartition:
4891 : 1847 : cmd_lockmode = ShareUpdateExclusiveLock;
4892 : 1847 : 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 [ + + ]: 22105 : if (cmd_lockmode > lockmode)
4915 : 18430 : lockmode = cmd_lockmode;
4916 : : }
4917 : :
4918 : 21247 : 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 : 21059 : ATController(AlterTableStmt *parsetree,
4929 : : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4930 : : AlterTableUtilityContext *context)
4931 : : {
4932 : 21059 : List *wqueue = NIL;
4933 : : ListCell *lcmd;
4934 : :
4935 : : /* Phase 1: preliminary examination of commands, create work queue */
4936 [ + - + + : 42687 : foreach(lcmd, cmds)
+ + ]
4937 : : {
4938 : 21913 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4939 : :
4940 : 21913 : ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4941 : : }
4942 : :
4943 : : /* Close the relation, but keep lock until commit */
4944 : 20774 : relation_close(rel, NoLock);
4945 : :
4946 : : /* Phase 2: update system catalogs */
4947 : 20774 : ATRewriteCatalogs(&wqueue, lockmode, context);
4948 : :
4949 : : /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4950 : 18756 : ATRewriteTables(parsetree, &wqueue, lockmode, context);
4951 : 18339 : }
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 : 22237 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4964 : : bool recurse, bool recursing, LOCKMODE lockmode,
4965 : : AlterTableUtilityContext *context)
4966 : : {
4967 : : AlteredTableInfo *tab;
4968 : 22237 : AlterTablePass pass = AT_PASS_UNSET;
4969 : :
4970 : : /* Find or create work queue entry for this table */
4971 : 22237 : 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 [ + + ]: 22237 : if (rel->rd_rel->relispartition &&
4978 [ + - + + ]: 1760 : cmd->subtype != AT_DetachPartitionFinalize &&
4979 : 880 : 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 : 22236 : 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 [ + + + + : 22236 : 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 : 197 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5071 : 197 : 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 [ + + ]: 193 : if (recurse)
5075 : 181 : cmd->recurse = true;
5076 : 193 : pass = AT_PASS_DROP;
5077 : 193 : 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 : 234 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5116 : 234 : ATSimplePermissions(cmd->subtype, rel,
5117 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5118 : : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5119 : 234 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5120 : : /* No command-specific prep needed */
5121 : 234 : pass = AT_PASS_MISC;
5122 : 234 : 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 : 9751 : case AT_AddConstraint: /* ADD CONSTRAINT */
5146 : 9751 : ATSimplePermissions(cmd->subtype, rel,
5147 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5148 [ + + ]: 9751 : if (recurse)
5149 : : {
5150 : : /* recurses at exec time; lock descendants and set flag */
5151 : 9526 : (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5152 : 9526 : cmd->recurse = true;
5153 : : }
5154 : 9751 : pass = AT_PASS_ADD_CONSTR;
5155 : 9751 : 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 : 563 : case AT_DropConstraint: /* DROP CONSTRAINT */
5163 : 563 : ATSimplePermissions(cmd->subtype, rel,
5164 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5165 : 563 : ATCheckPartitionsNotInUse(rel, lockmode);
5166 : : /* Other recursion occurs during execution phase */
5167 : : /* No command-specific prep needed except saving recurse flag */
5168 [ + + ]: 559 : if (recurse)
5169 : 535 : cmd->recurse = true;
5170 : 559 : pass = AT_PASS_DROP;
5171 : 559 : break;
5172 : 964 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5173 : 964 : ATSimplePermissions(cmd->subtype, rel,
5174 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5175 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5176 : : /* See comments for ATPrepAlterColumnType */
5177 : 964 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
5178 : : AT_PASS_UNSET, context);
5179 : : Assert(cmd != NULL);
5180 : : /* Performs own recursion */
5181 : 960 : ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
5182 : : lockmode, context);
5183 : 829 : pass = AT_PASS_ALTER_TYPE;
5184 : 829 : 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 : 1121 : case AT_ChangeOwner: /* ALTER OWNER */
5192 : : /* This command never recurses */
5193 : : /* No command-specific prep needed */
5194 : 1121 : pass = AT_PASS_MISC;
5195 : 1121 : 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 : 122 : case AT_SetTableSpace: /* SET TABLESPACE */
5233 : 122 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
5234 : : ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
5235 : : /* This command never recurses */
5236 : 122 : ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
5237 : 122 : pass = AT_PASS_MISC; /* doesn't actually matter */
5238 : 122 : 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 : 301 : case AT_AddInherit: /* INHERIT */
5250 : 301 : ATSimplePermissions(cmd->subtype, rel,
5251 : : ATT_TABLE | ATT_FOREIGN_TABLE);
5252 : : /* This command never recurses */
5253 : 297 : ATPrepChangeInherit(rel);
5254 : 285 : pass = AT_PASS_MISC;
5255 : 285 : 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 : 336 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5264 : 336 : ATSimplePermissions(cmd->subtype, rel,
5265 : : ATT_TABLE | ATT_PARTITIONED_TABLE);
5266 : : /* Recursion occurs during execution phase */
5267 [ + + ]: 332 : if (recurse)
5268 : 320 : cmd->recurse = true;
5269 : 332 : pass = AT_PASS_MISC;
5270 : 332 : break;
5271 : 288 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5272 : 288 : 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 [ + - ]: 288 : if (recurse)
5277 : 288 : cmd->recurse = true;
5278 : 288 : pass = AT_PASS_MISC;
5279 : 288 : break;
5280 : 321 : case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
5281 : 321 : ATSimplePermissions(cmd->subtype, rel,
5282 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5283 : 321 : pass = AT_PASS_MISC;
5284 : : /* This command never recurses */
5285 : : /* No command-specific prep needed */
5286 : 321 : 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 : 1839 : case AT_AttachPartition:
5324 : 1839 : ATSimplePermissions(cmd->subtype, rel,
5325 : : ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
5326 : : /* No command-specific prep needed */
5327 : 1835 : pass = AT_PASS_MISC;
5328 : 1835 : 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 : 21944 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
5349 : 21944 : }
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 : 20774 : 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 [ + + ]: 260777 : for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
5372 : : {
5373 : : /* Go through each table that needs to be processed */
5374 [ + - + + : 493411 : foreach(ltab, *wqueue)
+ + ]
5375 : : {
5376 : 253408 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5377 : 253408 : List *subcmds = tab->subcmds[pass];
5378 : : ListCell *lcmd;
5379 : :
5380 [ + + ]: 253408 : if (subcmds == NIL)
5381 : 217808 : 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 : 35600 : tab->rel = relation_open(tab->relid, NoLock);
5389 : :
5390 [ + - + + : 71274 : foreach(lcmd, subcmds)
+ + ]
5391 : 37672 : ATExecCmd(wqueue, tab,
5392 : 37672 : 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 [ + + ]: 33602 : if (pass == AT_PASS_ADD_CONSTR)
5403 : : {
5404 [ + - + + : 28923 : foreach_node(AlterTableCmd, cmd, subcmds)
+ + ]
5405 : 9731 : 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 [ + + + + ]: 33582 : if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
5414 : 926 : ATPostAlterTypeCleanup(wqueue, tab, lockmode);
5415 : :
5416 [ + - ]: 33582 : if (tab->rel)
5417 : : {
5418 : 33582 : relation_close(tab->rel, NoLock);
5419 : 33582 : tab->rel = NULL;
5420 : : }
5421 : : }
5422 : : }
5423 : :
5424 : : /* Check to see if a toast table must be added. */
5425 [ + - + + : 40414 : foreach(ltab, *wqueue)
+ + ]
5426 : : {
5427 : 21658 : 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 [ + + ]: 21658 : if (((tab->relkind == RELKIND_RELATION ||
5435 [ + + ]: 4013 : tab->relkind == RELKIND_PARTITIONED_TABLE) &&
5436 [ + + ]: 20408 : tab->partition_constraint == NULL) ||
5437 [ + + ]: 2570 : tab->relkind == RELKIND_MATVIEW)
5438 : 19118 : AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
5439 : : }
5440 : 18756 : }
5441 : :
5442 : : /*
5443 : : * ATExecCmd: dispatch a subcommand to appropriate execution routine
5444 : : */
5445 : : static void
5446 : 37672 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
5447 : : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
5448 : : AlterTableUtilityContext *context)
5449 : : {
5450 : 37672 : ObjectAddress address = InvalidObjectAddress;
5451 : 37672 : Relation rel = tab->rel;
5452 : :
5453 [ + + + + : 37672 : 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 : 193 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5483 : 193 : address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
5484 : 125 : 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 : 234 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5505 : 234 : address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
5506 : 226 : 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 : 804 : case AT_AddIndex: /* ADD INDEX */
5518 : 804 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
5519 : : lockmode);
5520 : 691 : break;
5521 : 331 : case AT_ReAddIndex: /* ADD INDEX */
5522 : 331 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
5523 : : lockmode);
5524 : 331 : break;
5525 : 57 : case AT_ReAddStatistics: /* ADD STATISTICS */
5526 : 57 : address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
5527 : : true, lockmode);
5528 : 57 : break;
5529 : 17678 : case AT_AddConstraint: /* ADD CONSTRAINT */
5530 : : /* Transform the command only during initial examination */
5531 [ + + ]: 17678 : if (cur_pass == AT_PASS_ADD_CONSTR)
5532 : 9731 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
5533 : 9751 : cmd->recurse, lockmode,
5534 : : cur_pass, context);
5535 : : /* Depending on constraint type, might be no more work to do now */
5536 [ + + ]: 17658 : if (cmd != NULL)
5537 : : address =
5538 : 7927 : ATExecAddConstraint(wqueue, tab, rel,
5539 : 7927 : (Constraint *) cmd->def,
5540 : 7927 : cmd->recurse, false, lockmode);
5541 : 17197 : 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 : 332 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5562 : 332 : address = ATExecAlterConstraint(wqueue, rel,
5563 : 332 : castNode(ATAlterConstraint, cmd->def),
5564 : 332 : cmd->recurse, lockmode);
5565 : 256 : break;
5566 : 288 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5567 : 288 : address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
5568 : : false, lockmode);
5569 : 284 : break;
5570 : 559 : case AT_DropConstraint: /* DROP CONSTRAINT */
5571 : 559 : ATExecDropConstraint(rel, cmd->name, cmd->behavior,
5572 : 559 : cmd->recurse,
5573 : 559 : cmd->missing_ok, lockmode);
5574 : 419 : break;
5575 : 805 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5576 : : /* parse transformation was done earlier */
5577 : 805 : address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
5578 : 777 : 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 : 1121 : case AT_ChangeOwner: /* ALTER OWNER */
5585 : 1118 : ATExecChangeOwner(RelationGetRelid(rel),
5586 : 1121 : get_rolespec_oid(cmd->newowner, false),
5587 : : false, lockmode);
5588 : 1110 : 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 : 122 : 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 [ + + ]: 122 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
5619 [ + + ]: 114 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
5620 : 24 : ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
5621 : :
5622 : 118 : 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 : 285 : case AT_AddInherit:
5695 : 285 : address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
5696 : 205 : 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 : 333 : case AT_ReplicaIdentity:
5707 : 333 : ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
5708 : 297 : 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 : 1835 : case AT_AttachPartition:
5725 : 1835 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5726 : : cur_pass, context);
5727 : : Assert(cmd != NULL);
5728 [ + + ]: 1819 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5729 : 1533 : address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
5730 : : context);
5731 : : else
5732 : 286 : address = ATExecAttachPartitionIdx(wqueue, rel,
5733 : 286 : ((PartitionCmd *) cmd->def)->name);
5734 : 1551 : 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 [ + + ]: 35674 : if (cmd)
5758 : 25943 : 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 : 35674 : CommandCounterIncrement();
5765 : 35674 : }
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 : 14554 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
5782 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
5783 : : AlterTablePass cur_pass, AlterTableUtilityContext *context)
5784 : : {
5785 : 14554 : AlterTableCmd *newcmd = NULL;
5786 : 14554 : 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 : 14554 : atstmt->relation =
5793 : 14554 : makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5794 : 14554 : pstrdup(RelationGetRelationName(rel)),
5795 : : -1);
5796 : 14554 : atstmt->relation->inh = recurse;
5797 : 14554 : atstmt->cmds = list_make1(cmd);
5798 : 14554 : atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
5799 : 14554 : atstmt->missing_ok = false;
5800 : :
5801 : : /* Transform the AlterTableStmt */
5802 : 14554 : 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 [ + + + + : 14817 : 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 [ + - + + : 34031 : foreach(lc, atstmt->cmds)
+ + ]
5819 : : {
5820 : 19529 : 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 [ + + + - : 19529 : switch (cmd2->subtype)
+ ]
5834 : : {
5835 : 840 : case AT_AddIndex:
5836 : 840 : pass = AT_PASS_ADD_INDEX;
5837 : 840 : break;
5838 : 6323 : case AT_AddIndexConstraint:
5839 : 6323 : pass = AT_PASS_ADD_INDEXCONSTR;
5840 : 6323 : break;
5841 : 7595 : case AT_AddConstraint:
5842 : : /* Recursion occurs during execution phase */
5843 [ + + ]: 7595 : if (recurse)
5844 : 7568 : cmd2->recurse = true;
5845 [ + - + ]: 7595 : 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 : 2452 : default:
5856 : 2452 : pass = AT_PASS_ADD_OTHERCONSTR;
5857 : 2452 : break;
5858 : : }
5859 : 7595 : 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 : 4771 : default:
5866 : 4771 : pass = cur_pass;
5867 : 4771 : break;
5868 : : }
5869 : :
5870 [ - + ]: 19529 : 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 [ + + ]: 19529 : else if (pass > cur_pass)
5877 : : {
5878 : : /* OK, queue it up for later */
5879 : 14758 : 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 [ + - + - ]: 4771 : if (newcmd == NULL && cmd->subtype == cmd2->subtype)
5888 : : {
5889 : : /* Found the transformed version of our subcommand */
5890 : 4771 : 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 : 14502 : tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
5900 : :
5901 : 14502 : return newcmd;
5902 : : }
5903 : :
5904 : : /*
5905 : : * ATRewriteTables: ALTER TABLE phase 3
5906 : : */
5907 : : static void
5908 : 18756 : 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 [ + - + + : 40000 : foreach(ltab, *wqueue)
+ + ]
5915 : : {
5916 : 21574 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5917 : :
5918 : : /* Relations without storage may be ignored here */
5919 [ + + + + : 21574 : 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 [ + + + + : 17747 : if (tab->newvals != NIL || (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE))
+ + ]
5936 : : {
5937 : : Relation rel;
5938 : :
5939 : 1311 : rel = table_open(tab->relid, NoLock);
5940 : 1311 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
5941 : 1275 : 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 [ + + + + ]: 17711 : if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
5956 : 725 : {
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 : 786 : 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 [ - + ]: 786 : 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 [ + + - + : 786 : 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 [ + + - + ]: 785 : 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 [ - + ]: 785 : if (tab->newTableSpace)
5999 : 0 : NewTableSpace = tab->newTableSpace;
6000 : : else
6001 : 785 : NewTableSpace = OldHeap->rd_rel->reltablespace;
6002 : :
6003 : : /*
6004 : : * Select destination access method (same as original unless user
6005 : : * requested a change)
6006 : : */
6007 [ + + ]: 785 : if (tab->chgAccessMethod)
6008 : 24 : NewAccessMethod = tab->newAccessMethod;
6009 : : else
6010 : 761 : NewAccessMethod = OldHeap->rd_rel->relam;
6011 : :
6012 : : /*
6013 : : * Select persistence of transient table (same as original unless
6014 : : * user requested a change)
6015 : : */
6016 [ + + ]: 785 : persistence = tab->chgPersistence ?
6017 : 750 : tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
6018 : :
6019 : 785 : 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 [ + - ]: 785 : if (parsetree)
6032 : 785 : 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 : 781 : 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 : 781 : 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 : 729 : finish_heap_swap(tab->relid, OIDNewHeap,
6071 : : false, false, true,
6072 : 729 : !OidIsValid(tab->newTableSpace),
6073 : : true, /* reindex */
6074 : : RecentXmin,
6075 : : ReadNextMultiXactId(),
6076 : : persistence);
6077 : :
6078 [ - + ]: 725 : InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
6079 : : }
6080 [ + + + - ]: 16925 : 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 [ + + + + ]: 16909 : if (tab->constraints != NIL || tab->verify_new_notnull ||
6093 [ + + ]: 14752 : tab->partition_constraint != NULL)
6094 : 3379 : 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 [ + + ]: 16676 : if (tab->newTableSpace)
6101 : 98 : 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 [ + + ]: 17417 : 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 [ + - + + : 39405 : foreach(ltab, *wqueue)
+ + ]
6130 : : {
6131 : 21066 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6132 : 21066 : Relation rel = NULL;
6133 : : ListCell *lcon;
6134 : :
6135 : : /* Relations without storage may be ignored here too */
6136 [ + + + + : 21066 : if (!RELKIND_HAS_STORAGE(tab->relkind))
+ + + - +
+ ]
6137 : 3722 : continue;
6138 : :
6139 [ + + + + : 18658 : foreach(lcon, tab->constraints)
+ + ]
6140 : : {
6141 : 1401 : NewConstraint *con = lfirst(lcon);
6142 : :
6143 [ + + ]: 1401 : 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 [ + + ]: 17257 : if (rel)
6171 : 744 : table_close(rel, NoLock);
6172 : : }
6173 : :
6174 : : /* Finally, run any afterStmts that were queued up */
6175 [ + - + + : 39291 : foreach(ltab, *wqueue)
+ + ]
6176 : : {
6177 : 20952 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6178 : : ListCell *lc;
6179 : :
6180 [ + + + + : 21008 : foreach(lc, tab->afterStmts)
+ + ]
6181 : : {
6182 : 56 : Node *stmt = (Node *) lfirst(lc);
6183 : :
6184 : 56 : ProcessUtilityForAlterTable(stmt, context);
6185 : 56 : CommandCounterIncrement();
6186 : : }
6187 : : }
6188 : 18339 : }
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 : 4160 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
6198 : : {
6199 : : Relation oldrel;
6200 : : Relation newrel;
6201 : : TupleDesc oldTupDesc;
6202 : : TupleDesc newTupDesc;
6203 : 4160 : 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 : 4160 : ExprState *partqualstate = NULL;
6213 : :
6214 : : /*
6215 : : * Open the relation(s). We have surely already locked the existing
6216 : : * table.
6217 : : */
6218 : 4160 : oldrel = table_open(tab->relid, NoLock);
6219 : 4160 : oldTupDesc = tab->oldDesc;
6220 : 4160 : newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
6221 : :
6222 [ + + ]: 4160 : if (OidIsValid(OIDNewHeap))
6223 : : {
6224 : : Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
6225 : : false));
6226 : 781 : newrel = table_open(OIDNewHeap, NoLock);
6227 : : }
6228 : : else
6229 : 3379 : 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 [ + + ]: 4160 : if (newrel)
6236 : : {
6237 : 781 : mycid = GetCurrentCommandId(true);
6238 : 781 : bistate = GetBulkInsertState();
6239 : 781 : ti_options = TABLE_INSERT_SKIP_FSM;
6240 : : }
6241 : : else
6242 : : {
6243 : : /* keep compiler quiet about using these uninitialized */
6244 : 3379 : mycid = 0;
6245 : 3379 : bistate = NULL;
6246 : 3379 : ti_options = 0;
6247 : : }
6248 : :
6249 : : /*
6250 : : * Generate the constraint and default execution states
6251 : : */
6252 : :
6253 : 4160 : estate = CreateExecutorState();
6254 : :
6255 : : /* Build the needed expression execution states */
6256 [ + + + + : 5725 : foreach(l, tab->constraints)
+ + ]
6257 : : {
6258 : 1565 : NewConstraint *con = lfirst(l);
6259 : :
6260 [ + + - ]: 1565 : switch (con->contype)
6261 : : {
6262 : 722 : case CONSTR_CHECK:
6263 : 722 : needscan = true;
6264 : 722 : con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
6265 : 722 : 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 [ + + ]: 4160 : if (tab->partition_constraint)
6277 : : {
6278 : 1316 : needscan = true;
6279 : 1316 : partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
6280 : : }
6281 : :
6282 [ + + + + : 5002 : foreach(l, tab->newvals)
+ + ]
6283 : : {
6284 : 842 : NewColumnValue *ex = lfirst(l);
6285 : :
6286 : : /* expr already planned */
6287 : 842 : ex->exprstate = ExecInitExpr(ex->expr, NULL);
6288 : : }
6289 : :
6290 : 4160 : notnull_attrs = notnull_virtual_attrs = NIL;
6291 [ + + + + ]: 4160 : 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 [ + + ]: 5417 : for (i = 0; i < newTupDesc->natts; i++)
6304 : : {
6305 : 3923 : CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
6306 : :
6307 [ + + ]: 3923 : 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 [ + + + + ]: 1494 : if (notnull_attrs || notnull_virtual_attrs)
6320 : 1095 : needscan = true;
6321 : : }
6322 : :
6323 [ + + + + ]: 4160 : if (newrel || needscan)
6324 : : {
6325 : : ExprContext *econtext;
6326 : : TupleTableSlot *oldslot;
6327 : : TupleTableSlot *newslot;
6328 : : TableScanDesc scan;
6329 : : MemoryContext oldCxt;
6330 : 3447 : List *dropped_attrs = NIL;
6331 : : ListCell *lc;
6332 : : Snapshot snapshot;
6333 : 3447 : 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 [ + + ]: 3447 : 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 [ + + ]: 3447 : if (newrel)
6358 [ - + ]: 781 : ereport(DEBUG1,
6359 : : (errmsg_internal("rewriting table \"%s\"",
6360 : : RelationGetRelationName(oldrel))));
6361 : : else
6362 [ + + ]: 2666 : ereport(DEBUG1,
6363 : : (errmsg_internal("verifying table \"%s\"",
6364 : : RelationGetRelationName(oldrel))));
6365 : :
6366 [ + + ]: 3447 : 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 : 781 : TransferPredicateLocksToHeapRelation(oldrel);
6374 : : }
6375 : :
6376 [ - + ]: 3447 : 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 [ + + ]: 3447 : if (tab->rewrite)
6387 : : {
6388 : : Assert(newrel != NULL);
6389 : 781 : oldslot = MakeSingleTupleTableSlot(oldTupDesc,
6390 : : table_slot_callbacks(oldrel));
6391 : 781 : 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 : 781 : ExecStoreAllNullTuple(newslot);
6403 : : }
6404 : : else
6405 : : {
6406 : 2666 : oldslot = MakeSingleTupleTableSlot(newTupDesc,
6407 : : table_slot_callbacks(oldrel));
6408 : 2666 : 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 [ + + ]: 11986 : for (i = 0; i < newTupDesc->natts; i++)
6417 : : {
6418 [ + + ]: 8539 : 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 : 3447 : snapshot = RegisterSnapshot(GetLatestSnapshot());
6427 : 3447 : 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 [ + - ]: 3447 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6435 : :
6436 [ + + ]: 490821 : 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 : 3162 : MemoryContextSwitchTo(oldCxt);
6609 : 3162 : table_endscan(scan);
6610 : 3162 : UnregisterSnapshot(snapshot);
6611 : :
6612 : 3162 : ExecDropSingleTupleTableSlot(oldslot);
6613 [ + + ]: 3162 : if (newslot)
6614 : 729 : ExecDropSingleTupleTableSlot(newslot);
6615 : : }
6616 : :
6617 : 3875 : FreeExecutorState(estate);
6618 : :
6619 : 3875 : table_close(oldrel, NoLock);
6620 [ + + ]: 3875 : if (newrel)
6621 : : {
6622 : 729 : FreeBulkInsertState(bistate);
6623 : :
6624 : 729 : table_finish_bulk_insert(newrel, ti_options);
6625 : :
6626 : 729 : table_close(newrel, NoLock);
6627 : : }
6628 : 3875 : }
6629 : :
6630 : : /*
6631 : : * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
6632 : : */
6633 : : static AlteredTableInfo *
6634 : 27284 : ATGetQueueEntry(List **wqueue, Relation rel)
6635 : : {
6636 : 27284 : Oid relid = RelationGetRelid(rel);
6637 : : AlteredTableInfo *tab;
6638 : : ListCell *ltab;
6639 : :
6640 [ + + + + : 34013 : foreach(ltab, *wqueue)
+ + ]
6641 : : {
6642 : 9952 : tab = (AlteredTableInfo *) lfirst(ltab);
6643 [ + + ]: 9952 : if (tab->relid == relid)
6644 : 3223 : 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 : 24061 : tab = palloc0_object(AlteredTableInfo);
6652 : 24061 : tab->relid = relid;
6653 : 24061 : tab->rel = NULL; /* set later */
6654 : 24061 : tab->relkind = rel->rd_rel->relkind;
6655 : 24061 : tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
6656 : 24061 : tab->newAccessMethod = InvalidOid;
6657 : 24061 : tab->chgAccessMethod = false;
6658 : 24061 : tab->newTableSpace = InvalidOid;
6659 : 24061 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
6660 : 24061 : tab->chgPersistence = false;
6661 : :
6662 : 24061 : *wqueue = lappend(*wqueue, tab);
6663 : :
6664 : 24061 : 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 : 24786 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
6812 : : {
6813 : : int actual_target;
6814 : :
6815 [ + + + + : 24786 : switch (rel->rd_rel->relkind)
+ + + + +
+ ]
6816 : : {
6817 : 19578 : case RELKIND_RELATION:
6818 : 19578 : actual_target = ATT_TABLE;
6819 : 19578 : break;
6820 : 3679 : case RELKIND_PARTITIONED_TABLE:
6821 : 3679 : actual_target = ATT_PARTITIONED_TABLE;
6822 : 3679 : break;
6823 : 280 : case RELKIND_VIEW:
6824 : 280 : actual_target = ATT_VIEW;
6825 : 280 : break;
6826 : 30 : case RELKIND_MATVIEW:
6827 : 30 : actual_target = ATT_MATVIEW;
6828 : 30 : break;
6829 : 147 : case RELKIND_INDEX:
6830 : 147 : actual_target = ATT_INDEX;
6831 : 147 : break;
6832 : 314 : case RELKIND_PARTITIONED_INDEX:
6833 : 314 : actual_target = ATT_PARTITIONED_INDEX;
6834 : 314 : 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 [ + + ]: 24786 : 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 [ + + ]: 24717 : 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 [ - + ]: 24709 : 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 [ + + - + ]: 24709 : 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 : 24709 : }
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 : 1044 : 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 [ + + + + ]: 1044 : 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 : 1044 : }
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 : 563 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
6950 : : {
6951 [ + + ]: 563 : 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 : 559 : }
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 : 3360 : 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 : 3360 : 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 : 3360 : depRel = table_open(DependRelationId, AccessShareLock);
7042 : :
7043 : 3360 : ScanKeyInit(&key[0],
7044 : : Anum_pg_depend_refclassid,
7045 : : BTEqualStrategyNumber, F_OIDEQ,
7046 : : ObjectIdGetDatum(TypeRelationId));
7047 : 3360 : ScanKeyInit(&key[1],
7048 : : Anum_pg_depend_refobjid,
7049 : : BTEqualStrategyNumber, F_OIDEQ,
7050 : : ObjectIdGetDatum(typeOid));
7051 : :
7052 : 3360 : depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
7053 : : NULL, 2, key);
7054 : :
7055 [ + + ]: 5169 : while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
7056 : : {
7057 : 1913 : 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 [ + + ]: 1913 : 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 : 1635 : find_composite_type_dependencies(pg_depend->objid,
7072 : : origRelation, origTypeName);
7073 : 1619 : 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 : 3256 : systable_endscan(depScan);
7171 : :
7172 : 3256 : relation_close(depRel, AccessShareLock);
7173 : 3256 : }
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 : 2634 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
7790 : : {
7791 : : ObjectAddress myself,
7792 : : referenced;
7793 : :
7794 : 2634 : myself.classId = RelationRelationId;
7795 : 2634 : myself.objectId = relid;
7796 : 2634 : myself.objectSubId = attnum;
7797 : 2634 : referenced.classId = TypeRelationId;
7798 : 2634 : referenced.objectId = typid;
7799 : 2634 : referenced.objectSubId = 0;
7800 : 2634 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7801 : 2634 : }
7802 : :
7803 : : /*
7804 : : * Install a column's dependency on its collation.
7805 : : */
7806 : : static void
7807 : 2634 : 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 [ + + + + ]: 2634 : 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 : 2634 : }
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 : 193 : 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 : 193 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7846 : :
7847 : 193 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7848 [ + + ]: 193 : 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 : 181 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7854 : 181 : attnum = attTup->attnum;
7855 : 181 : ObjectAddressSubSet(address, RelationRelationId,
7856 : : RelationGetRelid(rel), attnum);
7857 : :
7858 : : /* If the column is already nullable there's nothing to do. */
7859 [ - + ]: 181 : 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 [ - + ]: 181 : if (attnum <= 0)
7867 [ # # ]: 0 : ereport(ERROR,
7868 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7869 : : errmsg("cannot alter system column \"%s\"",
7870 : : colName)));
7871 : :
7872 [ + + ]: 181 : 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 [ + + ]: 169 : 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 : 161 : conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7902 [ - + ]: 161 : 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 : 161 : dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
7908 : : false, lockmode);
7909 : 125 : heap_freetuple(conTup);
7910 : :
7911 [ - + ]: 125 : InvokeObjectPostAlterHook(RelationRelationId,
7912 : : RelationGetRelid(rel), attnum);
7913 : :
7914 : 125 : table_close(attr_rel, RowExclusiveLock);
7915 : :
7916 : 125 : 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 : 15882 : 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 : 15882 : CheckAlterTableIsSafe(rel);
7938 : :
7939 : : /*
7940 : : * Exit quickly by testing attnotnull from the tupledesc's copy of the
7941 : : * attribute.
7942 : : */
7943 : 15882 : attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
7944 [ - + ]: 15882 : if (attr->attisdropped)
7945 : 0 : return;
7946 : :
7947 [ + + ]: 15882 : 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 : 14887 : 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 : 271 : 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 [ + + + + : 334 : 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 : 271 : }
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 : 234 : 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 : 234 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9284 : :
9285 : 234 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9286 : :
9287 [ + + ]: 234 : 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 : 226 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9293 : :
9294 : 226 : attnum = attrtuple->attnum;
9295 [ - + ]: 226 : if (attnum <= 0)
9296 [ # # ]: 0 : ereport(ERROR,
9297 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9298 : : errmsg("cannot alter system column \"%s\"",
9299 : : colName)));
9300 : :
9301 : 226 : attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
9302 : :
9303 : 226 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9304 : :
9305 [ - + ]: 226 : 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 : 226 : SetIndexStorageProperties(rel, attrelation, attnum,
9314 : 226 : true, attrtuple->attstorage,
9315 : : false, 0,
9316 : : lockmode);
9317 : :
9318 : 226 : heap_freetuple(tuple);
9319 : :
9320 : 226 : table_close(attrelation, RowExclusiveLock);
9321 : :
9322 : 226 : ObjectAddressSubSet(address, RelationRelationId,
9323 : : RelationGetRelid(rel), attnum);
9324 : 226 : 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 : 9731 : ATPrepAddPrimaryKey(AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd,
9582 : : LOCKMODE lockmode)
9583 : : {
9584 : : Constraint *pkconstr;
9585 : 9731 : List *children = NIL;
9586 : 9731 : bool got_children = false;
9587 : :
9588 : 9731 : pkconstr = castNode(Constraint, cmd->def);
9589 : :
9590 : : /* USING INDEX queues its own NOT NULL constraints during transformation */
9591 [ + + + + ]: 9731 : if (pkconstr->contype != CONSTR_PRIMARY || pkconstr->indexname != NULL)
9592 : 9207 : 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 : 1135 : 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 : 1135 : check_rights = !is_rebuild;
9721 : : /* skip index build if phase 3 will do it or we're reusing an old one */
9722 [ + + + + ]: 1135 : skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
9723 : : /* suppress notices when rebuilding existing index */
9724 : 1135 : quiet = is_rebuild;
9725 : :
9726 : 1135 : 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 [ + + ]: 1022 : 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 : 1022 : 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 : 8196 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9887 : : Constraint *newConstraint, bool recurse, bool is_readd,
9888 : : LOCKMODE lockmode)
9889 : : {
9890 : 8196 : 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 [ + + - ]: 8196 : switch (newConstraint->contype)
9900 : : {
9901 : 6332 : case CONSTR_CHECK:
9902 : : case CONSTR_NOTNULL:
9903 : : address =
9904 : 6332 : ATAddCheckNNConstraint(wqueue, tab, rel,
9905 : : newConstraint, recurse, false, is_readd,
9906 : : lockmode);
9907 : 6232 : break;
9908 : :
9909 : 1864 : case CONSTR_FOREIGN:
9910 : :
9911 : : /*
9912 : : * Assign or validate constraint name
9913 : : */
9914 [ + + ]: 1864 : 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 : 1110 : newConstraint->conname =
9927 : 1110 : ChooseConstraintName(RelationGetRelationName(rel),
9928 : 1110 : ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
9929 : : "fkey",
9930 : 1110 : RelationGetNamespace(rel),
9931 : : NIL);
9932 : :
9933 : 1864 : address = ATAddForeignKeyConstraint(wqueue, tab, rel,
9934 : : newConstraint,
9935 : : recurse, false,
9936 : : lockmode);
9937 : 1495 : break;
9938 : :
9939 : 0 : default:
9940 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
9941 : : (int) newConstraint->contype);
9942 : : }
9943 : :
9944 : 7727 : 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 : 1110 : ChooseForeignKeyConstraintNameAddition(List *colnames)
9961 : : {
9962 : : char buf[NAMEDATALEN * 2];
9963 : 1110 : int buflen = 0;
9964 : : ListCell *lc;
9965 : :
9966 : 1110 : buf[0] = '\0';
9967 [ + - + + : 2514 : foreach(lc, colnames)
+ + ]
9968 : : {
9969 : 1404 : const char *name = strVal(lfirst(lc));
9970 : :
9971 [ + + ]: 1404 : 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 : 1404 : strlcpy(buf + buflen, name, NAMEDATALEN);
9979 : 1404 : buflen += strlen(buf + buflen);
9980 [ - + ]: 1404 : if (buflen >= NAMEDATALEN)
9981 : 0 : break;
9982 : : }
9983 : 1110 : 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 : 6942 : 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 : 6942 : ObjectAddress address = InvalidObjectAddress;
10011 : :
10012 : : /* Guard against stack overflow due to overly deep inheritance tree. */
10013 : 6942 : check_stack_depth();
10014 : :
10015 : : /* At top level, permission check was done in ATPrepCmd, else do it */
10016 [ + + ]: 6942 : 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 : 6942 : newcons = AddRelationNewConstraints(rel, NIL,
10031 : : list_make1(copyObject(constr)),
10032 [ + + ]: 6942 : recursing || is_readd, /* allow_merge */
10033 : : !recursing, /* is_local */
10034 : : is_readd, /* is_internal */
10035 [ + + ]: 13884 : 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 [ + + + + : 13554 : foreach(lcon, newcons)
+ + ]
10043 : : {
10044 : 6708 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
10045 : :
10046 [ + + + + ]: 6708 : 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 [ + + ]: 6708 : 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 [ + + ]: 6708 : if (constr->contype == CONSTR_NOTNULL)
10069 : 5748 : set_attnotnull(wqueue, rel, ccon->attnum,
10070 : 5748 : !constr->skip_validation);
10071 : :
10072 : 6708 : 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 : 6846 : 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 [ + + ]: 6846 : if (newcons == NIL)
10088 : 138 : return address;
10089 : :
10090 : : /*
10091 : : * If adding a NO INHERIT constraint, no need to find our children.
10092 : : */
10093 [ + + ]: 6708 : 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 : 6652 : 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 [ + + + + ]: 6652 : 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 [ + + + + : 7238 : 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 : 6628 : 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 : 1864 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10157 : : Constraint *fkconstraint,
10158 : : bool recurse, bool recursing, LOCKMODE lockmode)
10159 : : {
10160 : : Relation pkrel;
10161 : 1864 : int16 pkattnum[INDEX_MAX_KEYS] = {0};
10162 : 1864 : int16 fkattnum[INDEX_MAX_KEYS] = {0};
10163 : 1864 : Oid pktypoid[INDEX_MAX_KEYS] = {0};
10164 : 1864 : Oid fktypoid[INDEX_MAX_KEYS] = {0};
10165 : 1864 : Oid pkcolloid[INDEX_MAX_KEYS] = {0};
10166 : 1864 : Oid fkcolloid[INDEX_MAX_KEYS] = {0};
10167 : 1864 : Oid opclasses[INDEX_MAX_KEYS] = {0};
10168 : 1864 : Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
10169 : 1864 : Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
10170 : 1864 : Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
10171 : 1864 : 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 : 1864 : 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 [ + + ]: 1864 : if (OidIsValid(fkconstraint->old_pktable_oid))
10188 : 48 : pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
10189 : : else
10190 : 1816 : pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
10191 : :
10192 : : /*
10193 : : * Validity checks (permission checks wait till we have the column
10194 : : * numbers)
10195 : : */
10196 [ + + + + ]: 1860 : 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 [ + + ]: 1856 : 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 [ + + ]: 1856 : 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 [ + + + + ]: 1852 : 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 [ + + + - ]: 1851 : switch (rel->rd_rel->relpersistence)
10237 : : {
10238 : 1654 : case RELPERSISTENCE_PERMANENT:
10239 [ - + ]: 1654 : 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 : 1654 : 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 : 1851 : numfks = transformColumnNameList(RelationGetRelid(rel),
10268 : : fkconstraint->fk_attrs,
10269 : : fkattnum, fktypoid, fkcolloid);
10270 [ + + + + ]: 1831 : with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
10271 [ + + + + ]: 1831 : 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 : 1815 : numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
10277 : : fkconstraint->fk_del_set_cols,
10278 : : fkdelsetcols, NULL, NULL);
10279 : 1811 : 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 [ + + ]: 1807 : 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 : 903 : 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 [ + + + + ]: 883 : 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 : 867 : 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 [ + + + + ]: 1731 : 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 : 1723 : checkFkeyPermissions(pkrel, pkattnum, numpks);
10334 : :
10335 : : /*
10336 : : * Check some things for generated columns.
10337 : : */
10338 [ + + ]: 4039 : for (i = 0; i < numfks; i++)
10339 : : {
10340 : 2336 : char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
10341 : :
10342 [ + + ]: 2336 : 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 [ + + ]: 2320 : 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 [ + + ]: 1703 : 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 [ - + ]: 1655 : 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 : 1655 : old_check_ok = (fkconstraint->old_conpfeqop != NIL);
10418 : : Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
10419 : :
10420 [ + + ]: 3619 : for (i = 0; i < numpks; i++)
10421 : : {
10422 : 2124 : Oid pktype = pktypoid[i];
10423 : 2124 : Oid fktype = fktypoid[i];
10424 : : Oid fktyped;
10425 : 2124 : Oid pkcoll = pkcolloid[i];
10426 : 2124 : 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 : 2124 : cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
10442 [ - + ]: 2124 : if (!HeapTupleIsValid(cla_ht))
10443 [ # # ]: 0 : elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
10444 : 2124 : cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
10445 : 2124 : amid = cla_tup->opcmethod;
10446 : 2124 : opfamily = cla_tup->opcfamily;
10447 : 2124 : opcintype = cla_tup->opcintype;
10448 : 2124 : 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 [ + + + + ]: 2124 : for_overlaps = with_period && i == numpks - 1;
10461 [ + + ]: 2124 : cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
10462 : 2124 : eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
10463 [ - + ]: 2124 : 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 : 2124 : ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
10477 : : eqstrategy);
10478 : :
10479 [ - + ]: 2124 : 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 : 2124 : fktyped = getBaseType(fktype);
10488 : :
10489 : 2124 : pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
10490 : : eqstrategy);
10491 [ + + ]: 2124 : if (OidIsValid(pfeqop))
10492 : : {
10493 : 1643 : pfeqop_right = fktyped;
10494 : 1643 : ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
10495 : : eqstrategy);
10496 : : }
10497 : : else
10498 : : {
10499 : : /* keep compiler quiet */
10500 : 481 : pfeqop_right = InvalidOid;
10501 : 481 : ffeqop = InvalidOid;
10502 : : }
10503 : :
10504 [ + + - + ]: 2124 : 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 : 481 : input_typeids[0] = pktype;
10519 : 481 : input_typeids[1] = fktype;
10520 : 481 : target_typeids[0] = opcintype;
10521 : 481 : target_typeids[1] = opcintype;
10522 [ + + ]: 481 : if (can_coerce_type(2, input_typeids, target_typeids,
10523 : : COERCION_IMPLICIT))
10524 : : {
10525 : 329 : pfeqop = ffeqop = ppeqop;
10526 : 329 : pfeqop_right = opcintype;
10527 : : }
10528 : : }
10529 : :
10530 [ + + - + ]: 2124 : 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 [ + + + - : 1972 : if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
+ + - + ]
10547 [ # # ]: 0 : elog(ERROR, "key columns are not both collatable");
10548 : :
10549 [ + + + - ]: 1972 : 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 [ + + ]: 1964 : 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 [ + + ]: 1964 : 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 : 1964 : pfeqoperators[i] = pfeqop;
10659 : 1964 : ppeqoperators[i] = ppeqop;
10660 : 1964 : 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 [ + + ]: 1495 : 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 : 1495 : 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 : 1495 : 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 : 1495 : 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 : 1495 : table_close(pkrel, NoLock);
10734 : :
10735 : 1495 : 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 : 1811 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
10748 : : int numfksetcols, int16 *fksetcolsattnums,
10749 : : List *fksetcols)
10750 : : {
10751 : 1811 : int numcolsout = 0;
10752 : :
10753 [ + + ]: 1831 : 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 : 1807 : 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 : 2762 : 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 [ + + ]: 2762 : 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 [ + + ]: 2762 : 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 : 2007 : conname = constraintname;
10864 : :
10865 [ + + ]: 2762 : if (fkconstraint->conname == NULL)
10866 : 243 : fkconstraint->conname = pstrdup(conname);
10867 : :
10868 [ + + ]: 2762 : if (OidIsValid(parentConstr))
10869 : : {
10870 : 1267 : conislocal = false;
10871 : 1267 : coninhcount = 1;
10872 : 1267 : connoinherit = false;
10873 : : }
10874 : : else
10875 : : {
10876 : 1495 : conislocal = true;
10877 : 1495 : coninhcount = 0;
10878 : :
10879 : : /*
10880 : : * always inherit for partitioned tables, never for legacy inheritance
10881 : : */
10882 : 1495 : connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
10883 : : }
10884 : :
10885 : : /*
10886 : : * Record the FK constraint in pg_constraint.
10887 : : */
10888 : 2762 : constrOid = CreateConstraintEntry(conname,
10889 : 2762 : RelationGetNamespace(rel),
10890 : : CONSTRAINT_FOREIGN,
10891 : 2762 : fkconstraint->deferrable,
10892 : 2762 : fkconstraint->initdeferred,
10893 : 2762 : fkconstraint->is_enforced,
10894 : 2762 : 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 : 2762 : fkconstraint->fk_upd_action,
10909 : 2762 : fkconstraint->fk_del_action,
10910 : : fkdelsetcols,
10911 : : numfkdelsetcols,
10912 : 2762 : 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 : 2762 : 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 [ + + ]: 2762 : 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 : 2762 : CommandCounterIncrement();
10964 : :
10965 : 2762 : 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 : 2314 : 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 : 2314 : Oid deleteTriggerOid = InvalidOid,
11012 : 2314 : 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 [ + + ]: 2314 : if (fkconstraint->is_enforced)
11022 : 2277 : 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 [ + + ]: 2314 : 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 : 2314 : }
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 : 2011 : 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 : 2011 : Oid insertTriggerOid = InvalidOid,
11149 : 2011 : updateTriggerOid = InvalidOid;
11150 : :
11151 : : Assert(OidIsValid(parentConstr));
11152 : : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11153 : : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11154 : :
11155 [ - + ]: 2011 : 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 [ + + ]: 2011 : if (fkconstraint->is_enforced)
11167 : 1978 : createForeignKeyCheckTriggers(RelationGetRelid(rel),
11168 : : RelationGetRelid(pkrel),
11169 : : fkconstraint,
11170 : : parentConstr,
11171 : : indexOid,
11172 : : parentInsTrigger, parentUpdTrigger,
11173 : : &insertTriggerOid, &updateTriggerOid);
11174 : :
11175 [ + + ]: 2011 : 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 [ + + + + : 1702 : 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 : 2007 : }
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 : 7027 : 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 : 7027 : CloneFkReferencing(wqueue, parentRel, partitionRel);
11328 : :
11329 : : /*
11330 : : * Clone constraints for which the parent is on the referenced side.
11331 : : */
11332 : 7015 : CloneFkReferenced(parentRel, partitionRel);
11333 : 7015 : }
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 : 7015 : 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 : 7015 : 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 : 7015 : pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11368 : 7015 : ScanKeyInit(&key[0],
11369 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
11370 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
11371 : 7015 : 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 : 7015 : scan = systable_beginscan(pg_constraint, InvalidOid, true,
11376 : : NULL, 2, key);
11377 [ + + ]: 7267 : 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 : 7015 : systable_endscan(scan);
11384 : 7015 : 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 : 7015 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11393 : :
11394 : 7015 : attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
11395 : : RelationGetDescr(parentRel),
11396 : : false);
11397 [ + + + + : 7267 : 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 : 7015 : table_close(trigrel, RowExclusiveLock);
11532 : 7015 : }
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 : 7027 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
11549 : : {
11550 : : AttrMap *attmap;
11551 : : List *partFKs;
11552 : 7027 : List *clone = NIL;
11553 : : ListCell *cell;
11554 : : Relation trigrel;
11555 : :
11556 : : /* obtain a list of constraints that we need to clone */
11557 [ + + + + : 7814 : 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 [ + + ]: 7023 : if (clone == NIL)
11586 : 6700 : 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 [ + - ]: 216 : while ((trigtup = systable_getnext(scan)) != NULL)
12190 : : {
12191 : 216 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12192 : :
12193 [ + + ]: 216 : if (trgform->tgconstrrelid != conrelid)
12194 : 8 : continue;
12195 [ - + ]: 208 : if (trgform->tgrelid != confrelid)
12196 : 0 : continue;
12197 : : /* Only ever look at "action" triggers on the PK side. */
12198 [ - + ]: 208 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
12199 : 0 : 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 [ + - ]: 1600 : while ((trigtup = systable_getnext(scan)) != NULL)
12251 : : {
12252 : 1600 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12253 : :
12254 [ + + ]: 1600 : if (trgform->tgconstrrelid != confrelid)
12255 : 514 : continue;
12256 [ - + ]: 1086 : if (trgform->tgrelid != conrelid)
12257 : 0 : continue;
12258 : : /* Only ever look at "check" triggers on the FK side. */
12259 [ + + ]: 1086 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
12260 : 72 : 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 : 332 : 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 [ + + - + ]: 332 : 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 : 332 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12322 : 332 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
12323 : :
12324 : : /*
12325 : : * Find and check the target constraint
12326 : : */
12327 : 332 : ScanKeyInit(&skey[0],
12328 : : Anum_pg_constraint_conrelid,
12329 : : BTEqualStrategyNumber, F_OIDEQ,
12330 : : ObjectIdGetDatum(RelationGetRelid(rel)));
12331 : 332 : ScanKeyInit(&skey[1],
12332 : : Anum_pg_constraint_contypid,
12333 : : BTEqualStrategyNumber, F_OIDEQ,
12334 : : ObjectIdGetDatum(InvalidOid));
12335 : 332 : ScanKeyInit(&skey[2],
12336 : : Anum_pg_constraint_conname,
12337 : : BTEqualStrategyNumber, F_NAMEEQ,
12338 : 332 : CStringGetDatum(cmdcon->conname));
12339 : 332 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12340 : : true, NULL, 3, skey);
12341 : :
12342 : : /* There can be at most one matching row */
12343 [ + + ]: 332 : 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 : 328 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12350 [ + + - + ]: 328 : 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 [ + + ]: 328 : if (cmdcon->alterEnforceability &&
12356 [ + + + + ]: 192 : (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 [ + + ]: 320 : 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 [ + + ]: 304 : 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 [ + + ]: 300 : 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 [ + + ]: 296 : 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 : 288 : address = InvalidObjectAddress;
12429 : :
12430 : : /*
12431 : : * Do the actual catalog work, and recurse if necessary.
12432 : : */
12433 [ + + ]: 288 : if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
12434 : : contuple, recurse, lockmode))
12435 : 240 : ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
12436 : :
12437 : 256 : systable_endscan(scan);
12438 : :
12439 : 256 : table_close(tgrel, RowExclusiveLock);
12440 : 256 : table_close(conrel, RowExclusiveLock);
12441 : :
12442 : 256 : 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 : 288 : 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 : 288 : bool changed = false;
12457 : 288 : List *otherrelids = NIL;
12458 : :
12459 : 288 : 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 [ + + ]: 288 : if (cmdcon->alterEnforceability)
12474 : : {
12475 [ + + ]: 184 : 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 [ + - ]: 128 : else if (currcon->contype == CONSTRAINT_CHECK)
12483 : 128 : 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 [ + + + - ]: 296 : if (cmdcon->alterInheritability &&
12508 : 40 : ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
12509 : : lockmode))
12510 : 36 : changed = true;
12511 : :
12512 : 256 : 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 : 336 : 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 : 336 : bool changed = false;
12679 : 336 : List *children = NIL;
12680 : 336 : bool target_enforced = cmdcon->is_enforced;
12681 : 336 : Oid enforced_parentoid = InvalidOid;
12682 : :
12683 : : /* Since this function recurses, it could be driven to stack overflow */
12684 : 336 : check_stack_depth();
12685 : :
12686 : : Assert(cmdcon->alterEnforceability);
12687 : :
12688 : 336 : 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 : 336 : 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 [ + + ]: 336 : 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 : : * Update to the merged enforceability if needed. This may differ from the
12732 : : * requested enforceability when another matching parent constraint
12733 : : * remains enforced.
12734 : : */
12735 [ + + ]: 316 : if (currcon->conenforced != target_enforced)
12736 : : {
12737 : 248 : ATAlterConstraint updatecon = *cmdcon;
12738 : :
12739 : 248 : updatecon.is_enforced = target_enforced;
12740 : 248 : AlterConstrUpdateConstraintEntry(&updatecon, conrel, contuple);
12741 : 248 : changed = true;
12742 : : }
12743 : :
12744 : : /*
12745 : : * Note that we must recurse even when trying to change a check constraint
12746 : : * to not enforced if it is already not enforced, in case descendant
12747 : : * constraints might be enforced and need to be changed to not enforced,
12748 : : * unless they still inherit an enforced constraint from another parent.
12749 : : * Conversely, we should do nothing if a constraint is being set to
12750 : : * enforced and is already enforced, as descendant constraints cannot be
12751 : : * different in that case.
12752 : : */
12753 [ + + + + ]: 316 : if (!cmdcon->is_enforced || changed)
12754 : : {
12755 : : /*
12756 : : * If we're recursing, the parent has already done this, so skip it.
12757 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't
12758 : : * try to look for it in the children.
12759 : : */
12760 [ + + + + ]: 300 : if (!recursing && !currcon->connoinherit)
12761 : : {
12762 : : Assert(changing_conids == NIL);
12763 : :
12764 : 104 : children = find_all_inheritors(RelationGetRelid(rel),
12765 : : lockmode, NULL);
12766 : :
12767 : : /*
12768 : : * When setting NOT ENFORCED, build the set of equivalent CHECK
12769 : : * constraints that this command will attempt to change before
12770 : : * visiting descendants. The root itself has already been checked
12771 : : * above.
12772 : : */
12773 [ + + ]: 104 : if (!cmdcon->is_enforced)
12774 : 48 : changing_conids = list_make1_oid(currcon->oid);
12775 : :
12776 [ + - + + : 512 : foreach_oid(childoid, children)
+ + ]
12777 : : {
12778 [ + + ]: 320 : if (childoid == RelationGetRelid(rel))
12779 : 104 : continue;
12780 : :
12781 : : /*
12782 : : * If we are told not to recurse, there had better not be any
12783 : : * child tables, because we can't change constraint
12784 : : * enforceability on the parent unless we have changed
12785 : : * enforceability for all child.
12786 : : */
12787 [ + + ]: 216 : if (!recurse)
12788 [ + - ]: 8 : ereport(ERROR,
12789 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12790 : : errmsg("constraint must be altered on child tables too"),
12791 : : errhint("Do not specify the ONLY keyword."));
12792 : :
12793 : : /*
12794 : : * It is sufficient to look up the constraint by name here.
12795 : : * Supported DDL ensures that inheritable CHECK constraints
12796 : : * with the same name have equivalent definitions when they
12797 : : * are propagated to children or when inheritance is
12798 : : * established. All descendants returned by
12799 : : * find_all_inheritors must have this constraint: inherited
12800 : : * CHECK constraints propagate to all children at
12801 : : * inheritance-link creation time and cannot be dropped
12802 : : * independently on child tables.
12803 : : */
12804 [ + + ]: 208 : if (!cmdcon->is_enforced)
12805 : : changing_conids =
12806 : 92 : list_append_unique_oid(changing_conids,
12807 : : get_relation_constraint_oid(childoid,
12808 : 92 : cmdcon->conname,
12809 : : false));
12810 : : }
12811 : : }
12812 : :
12813 [ + + + + : 888 : foreach_oid(childoid, children)
+ + ]
12814 : : {
12815 [ + + ]: 304 : if (childoid == RelationGetRelid(rel))
12816 : 96 : continue;
12817 : :
12818 : 208 : AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel,
12819 : : childoid, false, true,
12820 : : changing_conids,
12821 : : lockmode);
12822 : : }
12823 : : }
12824 : :
12825 : : /*
12826 : : * Tell Phase 3 to check that the constraint is satisfied by existing
12827 : : * rows. We only need do this when altering the constraint from NOT
12828 : : * ENFORCED to ENFORCED.
12829 : : */
12830 [ + + ]: 308 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12831 [ + + + + ]: 260 : !currcon->conenforced &&
12832 : : target_enforced)
12833 : : {
12834 : : AlteredTableInfo *tab;
12835 : : NewConstraint *newcon;
12836 : : Datum val;
12837 : : char *conbin;
12838 : :
12839 : 116 : newcon = palloc0_object(NewConstraint);
12840 : 116 : newcon->name = pstrdup(NameStr(currcon->conname));
12841 : 116 : newcon->contype = CONSTR_CHECK;
12842 : :
12843 : 116 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
12844 : : Anum_pg_constraint_conbin);
12845 : 116 : conbin = TextDatumGetCString(val);
12846 : 116 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
12847 : :
12848 : : /* Find or create work queue entry for this table */
12849 : 116 : tab = ATGetQueueEntry(wqueue, rel);
12850 : 116 : tab->constraints = lappend(tab->constraints, newcon);
12851 : : }
12852 : :
12853 : 308 : table_close(rel, NoLock);
12854 : :
12855 : 308 : return changed;
12856 : : }
12857 : :
12858 : : /*
12859 : : * Invokes ATExecAlterCheckConstrEnforceability for each CHECK constraint that
12860 : : * is a child of the specified constraint.
12861 : : *
12862 : : * We rely on the parent and child tables having identical CHECK constraint
12863 : : * names to retrieve the child's pg_constraint tuple.
12864 : : *
12865 : : * The arguments to this function have the same meaning as the arguments to
12866 : : * ATExecAlterCheckConstrEnforceability.
12867 : : */
12868 : : static void
12869 : 208 : AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12870 : : Relation conrel, Oid conrelid,
12871 : : bool recurse, bool recursing,
12872 : : List *changing_conids,
12873 : : LOCKMODE lockmode)
12874 : : {
12875 : : SysScanDesc pscan;
12876 : : HeapTuple childtup;
12877 : : ScanKeyData skey[3];
12878 : :
12879 : 208 : ScanKeyInit(&skey[0],
12880 : : Anum_pg_constraint_conrelid,
12881 : : BTEqualStrategyNumber, F_OIDEQ,
12882 : : ObjectIdGetDatum(conrelid));
12883 : 208 : ScanKeyInit(&skey[1],
12884 : : Anum_pg_constraint_contypid,
12885 : : BTEqualStrategyNumber, F_OIDEQ,
12886 : : ObjectIdGetDatum(InvalidOid));
12887 : 208 : ScanKeyInit(&skey[2],
12888 : : Anum_pg_constraint_conname,
12889 : : BTEqualStrategyNumber, F_NAMEEQ,
12890 : 208 : CStringGetDatum(cmdcon->conname));
12891 : :
12892 : 208 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
12893 : : NULL, 3, skey);
12894 : :
12895 [ - + ]: 208 : if (!HeapTupleIsValid(childtup = systable_getnext(pscan)))
12896 [ # # ]: 0 : ereport(ERROR,
12897 : : errcode(ERRCODE_UNDEFINED_OBJECT),
12898 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12899 : : cmdcon->conname, get_rel_name(conrelid)));
12900 : :
12901 : 208 : ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup,
12902 : : recurse, recursing, changing_conids,
12903 : : lockmode);
12904 : :
12905 : 208 : systable_endscan(pscan);
12906 : 208 : }
12907 : :
12908 : : /*
12909 : : * When setting an inherited CHECK constraint to NOT ENFORCED, look for a
12910 : : * matching parent constraint that remains ENFORCED and is not part of the same
12911 : : * ALTER.
12912 : : */
12913 : : static bool
12914 : 268 : ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel,
12915 : : HeapTuple contuple,
12916 : : List *changing_conids,
12917 : : Oid *enforced_parentoid)
12918 : : {
12919 : : Form_pg_constraint currcon;
12920 : : Relation inhrel;
12921 : : SysScanDesc scan;
12922 : : ScanKeyData skey;
12923 : : HeapTuple inheritsTuple;
12924 : :
12925 : : /* Since this function recurses, it could be driven to stack overflow */
12926 : 268 : check_stack_depth();
12927 : :
12928 : 268 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12929 : : Assert(currcon->contype == CONSTRAINT_CHECK);
12930 : :
12931 [ + + ]: 268 : if (currcon->coninhcount <= 0)
12932 : 124 : return false;
12933 : :
12934 : 144 : inhrel = table_open(InheritsRelationId, AccessShareLock);
12935 : :
12936 : 144 : ScanKeyInit(&skey,
12937 : : Anum_pg_inherits_inhrelid,
12938 : : BTEqualStrategyNumber, F_OIDEQ,
12939 : : ObjectIdGetDatum(RelationGetRelid(rel)));
12940 : 144 : scan = systable_beginscan(inhrel, InheritsRelidSeqnoIndexId,
12941 : : true, NULL, 1, &skey);
12942 : :
12943 [ + + ]: 304 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
12944 : : {
12945 : : Oid parentoid;
12946 : 200 : Relation parentrel = NULL;
12947 : : SysScanDesc pscan;
12948 : : ScanKeyData pkey[3];
12949 : : HeapTuple parenttup;
12950 : :
12951 : 200 : parentoid = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
12952 : :
12953 : 200 : ScanKeyInit(&pkey[0],
12954 : : Anum_pg_constraint_conrelid,
12955 : : BTEqualStrategyNumber, F_OIDEQ,
12956 : : ObjectIdGetDatum(parentoid));
12957 : 200 : ScanKeyInit(&pkey[1],
12958 : : Anum_pg_constraint_contypid,
12959 : : BTEqualStrategyNumber, F_OIDEQ,
12960 : : ObjectIdGetDatum(InvalidOid));
12961 : 200 : ScanKeyInit(&pkey[2],
12962 : : Anum_pg_constraint_conname,
12963 : : BTEqualStrategyNumber, F_NAMEEQ,
12964 : 200 : NameGetDatum(&currcon->conname));
12965 : :
12966 : 200 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12967 : : true, NULL, 3, pkey);
12968 : :
12969 : : /*
12970 : : * ConstraintRelidTypidNameIndexId is unique on (conrelid, contypid,
12971 : : * conname), so this loop body executes at most once per parent.
12972 : : */
12973 [ + + ]: 360 : while (HeapTupleIsValid(parenttup = systable_getnext(pscan)))
12974 : : {
12975 : : Form_pg_constraint parentcon;
12976 : :
12977 : 200 : parentcon = (Form_pg_constraint) GETSTRUCT(parenttup);
12978 : :
12979 [ + - ]: 200 : if (parentcon->contype != CONSTRAINT_CHECK ||
12980 [ + - ]: 200 : parentcon->connoinherit ||
12981 [ + + ]: 200 : !parentcon->conenforced)
12982 : 44 : continue;
12983 : :
12984 [ - + ]: 156 : if (!constraints_equivalent(parenttup, contuple,
12985 : : RelationGetDescr(conrel)))
12986 [ # # ]: 0 : elog(ERROR, "child table \"%s\" has different definition for check constraint \"%s\"",
12987 : : RelationGetRelationName(rel),
12988 : : NameStr(parentcon->conname));
12989 : :
12990 : : /*
12991 : : * A parent listed in changing_conids is being changed by the same
12992 : : * ALTER, but it may not have been updated yet. For regular
12993 : : * inheritance, recurse upward to check whether an equivalent
12994 : : * enforced parent outside the ALTER will make it remain enforced.
12995 : : * Partitions cannot have multiple parents, so they do not need
12996 : : * this check.
12997 : : */
12998 [ + + + + ]: 300 : if (!rel->rd_rel->relispartition &&
12999 : 144 : list_member_oid(changing_conids, parentcon->oid))
13000 : : {
13001 : 124 : Oid parent_enforced_parentoid = InvalidOid;
13002 : :
13003 [ + - ]: 124 : if (parentrel == NULL)
13004 : 124 : parentrel = table_open(parentoid, NoLock);
13005 : :
13006 [ + + ]: 124 : if (!ATCheckCheckConstrHasEnforcedParent(conrel,
13007 : : parentrel,
13008 : : parenttup,
13009 : : changing_conids,
13010 : : &parent_enforced_parentoid))
13011 : 116 : continue;
13012 : : }
13013 : :
13014 : 40 : *enforced_parentoid = parentoid;
13015 [ + + ]: 40 : if (parentrel != NULL)
13016 : 8 : table_close(parentrel, NoLock);
13017 : 40 : systable_endscan(pscan);
13018 : 40 : systable_endscan(scan);
13019 : 40 : table_close(inhrel, AccessShareLock);
13020 : 40 : return true;
13021 : : }
13022 : :
13023 [ + + ]: 160 : if (parentrel != NULL)
13024 : 116 : table_close(parentrel, NoLock);
13025 : 160 : systable_endscan(pscan);
13026 : : }
13027 : :
13028 : 104 : systable_endscan(scan);
13029 : 104 : table_close(inhrel, AccessShareLock);
13030 : :
13031 : 104 : return false;
13032 : : }
13033 : :
13034 : : /*
13035 : : * Returns true if the constraint's deferrability is altered.
13036 : : *
13037 : : * *otherrelids is appended OIDs of relations containing affected triggers.
13038 : : *
13039 : : * Note that we must recurse even when the values are correct, in case
13040 : : * indirect descendants have had their constraints altered locally.
13041 : : * (This could be avoided if we forbade altering constraints in partitions
13042 : : * but existing releases don't do that.)
13043 : : */
13044 : : static bool
13045 : 108 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
13046 : : Relation conrel, Relation tgrel, Relation rel,
13047 : : HeapTuple contuple, bool recurse,
13048 : : List **otherrelids, LOCKMODE lockmode)
13049 : : {
13050 : : Form_pg_constraint currcon;
13051 : : Oid refrelid;
13052 : 108 : bool changed = false;
13053 : :
13054 : : /* since this function recurses, it could be driven to stack overflow */
13055 : 108 : check_stack_depth();
13056 : :
13057 : : Assert(cmdcon->alterDeferrability);
13058 : :
13059 : 108 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13060 : 108 : refrelid = currcon->confrelid;
13061 : :
13062 : : /* Should be foreign key constraint */
13063 : : Assert(currcon->contype == CONSTRAINT_FOREIGN);
13064 : :
13065 : : /*
13066 : : * If called to modify a constraint that's already in the desired state,
13067 : : * silently do nothing.
13068 : : */
13069 [ + + ]: 108 : if (currcon->condeferrable != cmdcon->deferrable ||
13070 [ + - ]: 4 : currcon->condeferred != cmdcon->initdeferred)
13071 : : {
13072 : 108 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13073 : 108 : changed = true;
13074 : :
13075 : : /*
13076 : : * Now we need to update the multiple entries in pg_trigger that
13077 : : * implement the constraint.
13078 : : */
13079 : 108 : AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
13080 : 108 : cmdcon->deferrable,
13081 : 108 : cmdcon->initdeferred, otherrelids);
13082 : : }
13083 : :
13084 : : /*
13085 : : * If the table at either end of the constraint is partitioned, we need to
13086 : : * handle every constraint that is a child of this one.
13087 : : */
13088 [ + - + - ]: 108 : if (recurse && changed &&
13089 [ + + + + ]: 200 : (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13090 : 92 : get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
13091 : 28 : AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
13092 : : contuple, recurse, otherrelids,
13093 : : lockmode);
13094 : :
13095 : 108 : return changed;
13096 : : }
13097 : :
13098 : : /*
13099 : : * Returns true if the constraint's inheritability is altered.
13100 : : */
13101 : : static bool
13102 : 40 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
13103 : : Relation conrel, Relation rel,
13104 : : HeapTuple contuple, LOCKMODE lockmode)
13105 : : {
13106 : : Form_pg_constraint currcon;
13107 : : AttrNumber colNum;
13108 : : char *colName;
13109 : : List *children;
13110 : :
13111 : : Assert(cmdcon->alterInheritability);
13112 : :
13113 : 40 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13114 : :
13115 : : /* The current implementation only works for NOT NULL constraints */
13116 : : Assert(currcon->contype == CONSTRAINT_NOTNULL);
13117 : :
13118 : : /*
13119 : : * If called to modify a constraint that's already in the desired state,
13120 : : * silently do nothing.
13121 : : */
13122 [ - + ]: 40 : if (cmdcon->noinherit == currcon->connoinherit)
13123 : 0 : return false;
13124 : :
13125 : 40 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13126 : 40 : CommandCounterIncrement();
13127 : :
13128 : : /* Fetch the column number and name */
13129 : 40 : colNum = extractNotNullColumn(contuple);
13130 : 40 : colName = get_attname(currcon->conrelid, colNum, false);
13131 : :
13132 : : /*
13133 : : * Propagate the change to children. For this subcommand type we don't
13134 : : * recursively affect children, just the immediate level.
13135 : : */
13136 : 40 : children = find_inheritance_children(RelationGetRelid(rel),
13137 : : lockmode);
13138 [ + + + + : 128 : foreach_oid(childoid, children)
+ + ]
13139 : : {
13140 : : ObjectAddress addr;
13141 : :
13142 [ + + ]: 56 : if (cmdcon->noinherit)
13143 : : {
13144 : : HeapTuple childtup;
13145 : : Form_pg_constraint childcon;
13146 : :
13147 : 20 : childtup = findNotNullConstraint(childoid, colName);
13148 [ - + ]: 20 : if (!childtup)
13149 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
13150 : : colName, childoid);
13151 : 20 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13152 : : Assert(childcon->coninhcount > 0);
13153 : 20 : childcon->coninhcount--;
13154 : 20 : childcon->conislocal = true;
13155 : 20 : CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
13156 : 20 : heap_freetuple(childtup);
13157 : : }
13158 : : else
13159 : : {
13160 : 36 : Relation childrel = table_open(childoid, NoLock);
13161 : :
13162 : 36 : addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
13163 : : colName, true, true, lockmode);
13164 [ + - ]: 32 : if (OidIsValid(addr.objectId))
13165 : 32 : CommandCounterIncrement();
13166 : 32 : table_close(childrel, NoLock);
13167 : : }
13168 : : }
13169 : :
13170 : 36 : return true;
13171 : : }
13172 : :
13173 : : /*
13174 : : * A subroutine of ATExecAlterConstrDeferrability that updated constraint
13175 : : * trigger's deferrability.
13176 : : *
13177 : : * The arguments to this function have the same meaning as the arguments to
13178 : : * ATExecAlterConstrDeferrability.
13179 : : */
13180 : : static void
13181 : 108 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
13182 : : bool deferrable, bool initdeferred,
13183 : : List **otherrelids)
13184 : : {
13185 : : HeapTuple tgtuple;
13186 : : ScanKeyData tgkey;
13187 : : SysScanDesc tgscan;
13188 : :
13189 : 108 : ScanKeyInit(&tgkey,
13190 : : Anum_pg_trigger_tgconstraint,
13191 : : BTEqualStrategyNumber, F_OIDEQ,
13192 : : ObjectIdGetDatum(conoid));
13193 : 108 : tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
13194 : : NULL, 1, &tgkey);
13195 [ + + ]: 420 : while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
13196 : : {
13197 : 312 : Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
13198 : : Form_pg_trigger copy_tg;
13199 : : HeapTuple tgCopyTuple;
13200 : :
13201 : : /*
13202 : : * Remember OIDs of other relation(s) involved in FK constraint.
13203 : : * (Note: it's likely that we could skip forcing a relcache inval for
13204 : : * other rels that don't have a trigger whose properties change, but
13205 : : * let's be conservative.)
13206 : : */
13207 [ + + ]: 312 : if (tgform->tgrelid != RelationGetRelid(rel))
13208 : 152 : *otherrelids = list_append_unique_oid(*otherrelids,
13209 : : tgform->tgrelid);
13210 : :
13211 : : /*
13212 : : * Update enable status and deferrability of RI_FKey_noaction_del,
13213 : : * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
13214 : : * triggers, but not others; see createForeignKeyActionTriggers and
13215 : : * CreateFKCheckTrigger.
13216 : : */
13217 [ + + ]: 312 : if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
13218 [ + + ]: 248 : tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
13219 [ + + ]: 172 : tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
13220 [ + + ]: 92 : tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
13221 : 12 : continue;
13222 : :
13223 : 300 : tgCopyTuple = heap_copytuple(tgtuple);
13224 : 300 : copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
13225 : :
13226 : 300 : copy_tg->tgdeferrable = deferrable;
13227 : 300 : copy_tg->tginitdeferred = initdeferred;
13228 : 300 : CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
13229 : :
13230 [ - + ]: 300 : InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
13231 : :
13232 : 300 : heap_freetuple(tgCopyTuple);
13233 : : }
13234 : :
13235 : 108 : systable_endscan(tgscan);
13236 : 108 : }
13237 : :
13238 : : /*
13239 : : * Invokes ATExecAlterFKConstrEnforceability for each foreign key constraint
13240 : : * that is a child of the specified constraint.
13241 : : *
13242 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13243 : : * list of child relations and recursing; instead it uses the conparentid
13244 : : * relationships. This may need to be reconsidered.
13245 : : *
13246 : : * The arguments to this function have the same meaning as the arguments to
13247 : : * ATExecAlterFKConstrEnforceability.
13248 : : */
13249 : : static void
13250 : 28 : AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13251 : : Relation conrel, Relation tgrel,
13252 : : Oid fkrelid, Oid pkrelid,
13253 : : HeapTuple contuple, LOCKMODE lockmode,
13254 : : Oid ReferencedParentDelTrigger,
13255 : : Oid ReferencedParentUpdTrigger,
13256 : : Oid ReferencingParentInsTrigger,
13257 : : Oid ReferencingParentUpdTrigger)
13258 : : {
13259 : : Form_pg_constraint currcon;
13260 : : Oid conoid;
13261 : : ScanKeyData pkey;
13262 : : SysScanDesc pscan;
13263 : : HeapTuple childtup;
13264 : :
13265 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13266 : 28 : conoid = currcon->oid;
13267 : :
13268 : 28 : ScanKeyInit(&pkey,
13269 : : Anum_pg_constraint_conparentid,
13270 : : BTEqualStrategyNumber, F_OIDEQ,
13271 : : ObjectIdGetDatum(conoid));
13272 : :
13273 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13274 : : true, NULL, 1, &pkey);
13275 : :
13276 [ + + ]: 92 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13277 : 64 : ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
13278 : : pkrelid, childtup, lockmode,
13279 : : ReferencedParentDelTrigger,
13280 : : ReferencedParentUpdTrigger,
13281 : : ReferencingParentInsTrigger,
13282 : : ReferencingParentUpdTrigger);
13283 : :
13284 : 28 : systable_endscan(pscan);
13285 : 28 : }
13286 : :
13287 : : /*
13288 : : * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
13289 : : * the specified constraint.
13290 : : *
13291 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13292 : : * list of child relations and recursing; instead it uses the conparentid
13293 : : * relationships. This may need to be reconsidered.
13294 : : *
13295 : : * The arguments to this function have the same meaning as the arguments to
13296 : : * ATExecAlterConstrDeferrability.
13297 : : */
13298 : : static void
13299 : 28 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13300 : : Relation conrel, Relation tgrel, Relation rel,
13301 : : HeapTuple contuple, bool recurse,
13302 : : List **otherrelids, LOCKMODE lockmode)
13303 : : {
13304 : : Form_pg_constraint currcon;
13305 : : Oid conoid;
13306 : : ScanKeyData pkey;
13307 : : SysScanDesc pscan;
13308 : : HeapTuple childtup;
13309 : :
13310 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13311 : 28 : conoid = currcon->oid;
13312 : :
13313 : 28 : ScanKeyInit(&pkey,
13314 : : Anum_pg_constraint_conparentid,
13315 : : BTEqualStrategyNumber, F_OIDEQ,
13316 : : ObjectIdGetDatum(conoid));
13317 : :
13318 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13319 : : true, NULL, 1, &pkey);
13320 : :
13321 [ + + ]: 72 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13322 : : {
13323 : 44 : Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13324 : : Relation childrel;
13325 : :
13326 : 44 : childrel = table_open(childcon->conrelid, lockmode);
13327 : :
13328 : 44 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
13329 : : childtup, recurse, otherrelids, lockmode);
13330 : 44 : table_close(childrel, NoLock);
13331 : : }
13332 : :
13333 : 28 : systable_endscan(pscan);
13334 : 28 : }
13335 : :
13336 : : /*
13337 : : * Update the constraint entry for the given ATAlterConstraint command, and
13338 : : * invoke the appropriate hooks.
13339 : : */
13340 : : static void
13341 : 512 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
13342 : : HeapTuple contuple)
13343 : : {
13344 : : HeapTuple copyTuple;
13345 : : Form_pg_constraint copy_con;
13346 : :
13347 : : Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
13348 : : cmdcon->alterInheritability);
13349 : :
13350 : 512 : copyTuple = heap_copytuple(contuple);
13351 : 512 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13352 : :
13353 [ + + ]: 512 : if (cmdcon->alterEnforceability)
13354 : : {
13355 : 364 : copy_con->conenforced = cmdcon->is_enforced;
13356 : :
13357 : : /*
13358 : : * NB: The convalidated status is irrelevant when the constraint is
13359 : : * set to NOT ENFORCED, but for consistency, it should still be set
13360 : : * appropriately. Similarly, if the constraint is later changed to
13361 : : * ENFORCED, validation will be performed during phase 3, so it makes
13362 : : * sense to mark it as valid in that case.
13363 : : */
13364 : 364 : copy_con->convalidated = cmdcon->is_enforced;
13365 : : }
13366 [ + + ]: 512 : if (cmdcon->alterDeferrability)
13367 : : {
13368 : 112 : copy_con->condeferrable = cmdcon->deferrable;
13369 : 112 : copy_con->condeferred = cmdcon->initdeferred;
13370 : : }
13371 [ + + ]: 512 : if (cmdcon->alterInheritability)
13372 : 40 : copy_con->connoinherit = cmdcon->noinherit;
13373 : :
13374 : 512 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13375 [ - + ]: 512 : InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
13376 : :
13377 : : /* Make new constraint flags visible to others */
13378 : 512 : CacheInvalidateRelcacheByRelid(copy_con->conrelid);
13379 : :
13380 : 512 : heap_freetuple(copyTuple);
13381 : 512 : }
13382 : :
13383 : : /*
13384 : : * ALTER TABLE VALIDATE CONSTRAINT
13385 : : *
13386 : : * XXX The reason we handle recursion here rather than at Phase 1 is because
13387 : : * there's no good way to skip recursing when handling foreign keys: there is
13388 : : * no need to lock children in that case, yet we wouldn't be able to avoid
13389 : : * doing so at that level.
13390 : : *
13391 : : * Return value is the address of the validated constraint. If the constraint
13392 : : * was already validated, InvalidObjectAddress is returned.
13393 : : */
13394 : : static ObjectAddress
13395 : 360 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
13396 : : bool recurse, bool recursing, LOCKMODE lockmode)
13397 : : {
13398 : : Relation conrel;
13399 : : SysScanDesc scan;
13400 : : ScanKeyData skey[3];
13401 : : HeapTuple tuple;
13402 : : Form_pg_constraint con;
13403 : : ObjectAddress address;
13404 : :
13405 : 360 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
13406 : :
13407 : : /*
13408 : : * Find and check the target constraint
13409 : : */
13410 : 360 : ScanKeyInit(&skey[0],
13411 : : Anum_pg_constraint_conrelid,
13412 : : BTEqualStrategyNumber, F_OIDEQ,
13413 : : ObjectIdGetDatum(RelationGetRelid(rel)));
13414 : 360 : ScanKeyInit(&skey[1],
13415 : : Anum_pg_constraint_contypid,
13416 : : BTEqualStrategyNumber, F_OIDEQ,
13417 : : ObjectIdGetDatum(InvalidOid));
13418 : 360 : ScanKeyInit(&skey[2],
13419 : : Anum_pg_constraint_conname,
13420 : : BTEqualStrategyNumber, F_NAMEEQ,
13421 : : CStringGetDatum(constrName));
13422 : 360 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
13423 : : true, NULL, 3, skey);
13424 : :
13425 : : /* There can be at most one matching row */
13426 [ - + ]: 360 : if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
13427 [ # # ]: 0 : ereport(ERROR,
13428 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
13429 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
13430 : : constrName, RelationGetRelationName(rel))));
13431 : :
13432 : 360 : con = (Form_pg_constraint) GETSTRUCT(tuple);
13433 [ + + ]: 360 : if (con->contype != CONSTRAINT_FOREIGN &&
13434 [ + + ]: 174 : con->contype != CONSTRAINT_CHECK &&
13435 [ - + ]: 78 : con->contype != CONSTRAINT_NOTNULL)
13436 [ # # ]: 0 : ereport(ERROR,
13437 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
13438 : : errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
13439 : : constrName, RelationGetRelationName(rel)),
13440 : : errdetail("This operation is not supported for this type of constraint."));
13441 : :
13442 [ + + ]: 360 : if (!con->conenforced)
13443 [ + - ]: 4 : ereport(ERROR,
13444 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13445 : : errmsg("cannot validate NOT ENFORCED constraint")));
13446 : :
13447 [ + + ]: 356 : if (!con->convalidated)
13448 : : {
13449 [ + + ]: 344 : if (con->contype == CONSTRAINT_FOREIGN)
13450 : : {
13451 : 182 : QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
13452 : : tuple, lockmode);
13453 : : }
13454 [ + + ]: 162 : else if (con->contype == CONSTRAINT_CHECK)
13455 : : {
13456 : 84 : QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
13457 : : tuple, recurse, recursing, lockmode);
13458 : : }
13459 [ + - ]: 78 : else if (con->contype == CONSTRAINT_NOTNULL)
13460 : : {
13461 : 78 : QueueNNConstraintValidation(wqueue, conrel, rel,
13462 : : tuple, recurse, recursing, lockmode);
13463 : : }
13464 : :
13465 : 344 : ObjectAddressSet(address, ConstraintRelationId, con->oid);
13466 : : }
13467 : : else
13468 : 12 : address = InvalidObjectAddress; /* already validated */
13469 : :
13470 : 356 : systable_endscan(scan);
13471 : :
13472 : 356 : table_close(conrel, RowExclusiveLock);
13473 : :
13474 : 356 : return address;
13475 : : }
13476 : :
13477 : : /*
13478 : : * QueueFKConstraintValidation
13479 : : *
13480 : : * Add an entry to the wqueue to validate the given foreign key constraint in
13481 : : * Phase 3 and update the convalidated field in the pg_constraint catalog
13482 : : * for the specified relation and all its children.
13483 : : */
13484 : : static void
13485 : 230 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
13486 : : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
13487 : : {
13488 : : Form_pg_constraint con;
13489 : : AlteredTableInfo *tab;
13490 : : HeapTuple copyTuple;
13491 : : Form_pg_constraint copy_con;
13492 : :
13493 : : /* since this function recurses, it could be driven to stack overflow */
13494 : 230 : check_stack_depth();
13495 : :
13496 : 230 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13497 : : Assert(con->contype == CONSTRAINT_FOREIGN);
13498 : : Assert(!con->convalidated);
13499 : :
13500 : : /*
13501 : : * Add the validation to phase 3's queue; not needed for partitioned
13502 : : * tables themselves, only for their partitions.
13503 : : *
13504 : : * When the referenced table (pkrelid) is partitioned, the referencing
13505 : : * table (fkrel) has one pg_constraint row pointing to each partition
13506 : : * thereof. These rows are there only to support action triggers and no
13507 : : * table scan is needed, therefore skip this for them as well.
13508 : : */
13509 [ + + ]: 230 : if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
13510 [ + + ]: 198 : con->confrelid == pkrelid)
13511 : : {
13512 : : NewConstraint *newcon;
13513 : : Constraint *fkconstraint;
13514 : :
13515 : : /* Queue validation for phase 3 */
13516 : 190 : fkconstraint = makeNode(Constraint);
13517 : : /* for now this is all we need */
13518 : 190 : fkconstraint->conname = pstrdup(NameStr(con->conname));
13519 : :
13520 : 190 : newcon = palloc0_object(NewConstraint);
13521 : 190 : newcon->name = fkconstraint->conname;
13522 : 190 : newcon->contype = CONSTR_FOREIGN;
13523 : 190 : newcon->refrelid = con->confrelid;
13524 : 190 : newcon->refindid = con->conindid;
13525 : 190 : newcon->conid = con->oid;
13526 : 190 : newcon->qual = (Node *) fkconstraint;
13527 : :
13528 : : /* Find or create work queue entry for this table */
13529 : 190 : tab = ATGetQueueEntry(wqueue, fkrel);
13530 : 190 : tab->constraints = lappend(tab->constraints, newcon);
13531 : : }
13532 : :
13533 : : /*
13534 : : * If the table at either end of the constraint is partitioned, we need to
13535 : : * recurse and handle every unvalidated constraint that is a child of this
13536 : : * constraint.
13537 : : */
13538 [ + + + + ]: 428 : if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13539 : 198 : get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
13540 : : {
13541 : : ScanKeyData pkey;
13542 : : SysScanDesc pscan;
13543 : : HeapTuple childtup;
13544 : :
13545 : 48 : ScanKeyInit(&pkey,
13546 : : Anum_pg_constraint_conparentid,
13547 : : BTEqualStrategyNumber, F_OIDEQ,
13548 : : ObjectIdGetDatum(con->oid));
13549 : :
13550 : 48 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13551 : : true, NULL, 1, &pkey);
13552 : :
13553 [ + + ]: 96 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13554 : : {
13555 : : Form_pg_constraint childcon;
13556 : : Relation childrel;
13557 : :
13558 : 48 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13559 : :
13560 : : /*
13561 : : * If the child constraint has already been validated, no further
13562 : : * action is required for it or its descendants, as they are all
13563 : : * valid.
13564 : : */
13565 [ + + ]: 48 : if (childcon->convalidated)
13566 : 12 : continue;
13567 : :
13568 : 36 : childrel = table_open(childcon->conrelid, lockmode);
13569 : :
13570 : : /*
13571 : : * NB: Note that pkrelid should be passed as-is during recursion,
13572 : : * as it is required to identify the root referenced table.
13573 : : */
13574 : 36 : QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
13575 : : childtup, lockmode);
13576 : 36 : table_close(childrel, NoLock);
13577 : : }
13578 : :
13579 : 48 : systable_endscan(pscan);
13580 : : }
13581 : :
13582 : : /*
13583 : : * Now mark the pg_constraint row as validated (even if we didn't check,
13584 : : * notably the ones for partitions on the referenced side).
13585 : : *
13586 : : * We rely on transaction abort to roll back this change if phase 3
13587 : : * ultimately finds violating rows. This is a bit ugly.
13588 : : */
13589 : 230 : copyTuple = heap_copytuple(contuple);
13590 : 230 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13591 : 230 : copy_con->convalidated = true;
13592 : 230 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13593 : :
13594 [ - + ]: 230 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13595 : :
13596 : 230 : heap_freetuple(copyTuple);
13597 : 230 : }
13598 : :
13599 : : /*
13600 : : * QueueCheckConstraintValidation
13601 : : *
13602 : : * Add an entry to the wqueue to validate the given check constraint in Phase 3
13603 : : * and update the convalidated field in the pg_constraint catalog for the
13604 : : * specified relation and all its inheriting children.
13605 : : */
13606 : : static void
13607 : 84 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13608 : : char *constrName, HeapTuple contuple,
13609 : : bool recurse, bool recursing, LOCKMODE lockmode)
13610 : : {
13611 : : Form_pg_constraint con;
13612 : : AlteredTableInfo *tab;
13613 : : HeapTuple copyTuple;
13614 : : Form_pg_constraint copy_con;
13615 : :
13616 : 84 : List *children = NIL;
13617 : : ListCell *child;
13618 : : NewConstraint *newcon;
13619 : : Datum val;
13620 : : char *conbin;
13621 : :
13622 : 84 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13623 : : Assert(con->contype == CONSTRAINT_CHECK);
13624 : :
13625 : : /*
13626 : : * If we're recursing, the parent has already done this, so skip it. Also,
13627 : : * if the constraint is a NO INHERIT constraint, we shouldn't try to look
13628 : : * for it in the children.
13629 : : */
13630 [ + + + + ]: 84 : if (!recursing && !con->connoinherit)
13631 : 48 : children = find_all_inheritors(RelationGetRelid(rel),
13632 : : lockmode, NULL);
13633 : :
13634 : : /*
13635 : : * For CHECK constraints, we must ensure that we only mark the constraint
13636 : : * as validated on the parent if it's already validated on the children.
13637 : : *
13638 : : * We recurse before validating on the parent, to reduce risk of
13639 : : * deadlocks.
13640 : : */
13641 [ + + + + : 164 : foreach(child, children)
+ + ]
13642 : : {
13643 : 80 : Oid childoid = lfirst_oid(child);
13644 : : Relation childrel;
13645 : :
13646 [ + + ]: 80 : if (childoid == RelationGetRelid(rel))
13647 : 48 : continue;
13648 : :
13649 : : /*
13650 : : * If we are told not to recurse, there had better not be any child
13651 : : * tables, because we can't mark the constraint on the parent valid
13652 : : * unless it is valid for all child tables.
13653 : : */
13654 [ - + ]: 32 : if (!recurse)
13655 [ # # ]: 0 : ereport(ERROR,
13656 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13657 : : errmsg("constraint must be validated on child tables too")));
13658 : :
13659 : : /* find_all_inheritors already got lock */
13660 : 32 : childrel = table_open(childoid, NoLock);
13661 : :
13662 : 32 : ATExecValidateConstraint(wqueue, childrel, constrName, false,
13663 : : true, lockmode);
13664 : 32 : table_close(childrel, NoLock);
13665 : : }
13666 : :
13667 : : /* Queue validation for phase 3 */
13668 : 84 : newcon = palloc0_object(NewConstraint);
13669 : 84 : newcon->name = constrName;
13670 : 84 : newcon->contype = CONSTR_CHECK;
13671 : 84 : newcon->refrelid = InvalidOid;
13672 : 84 : newcon->refindid = InvalidOid;
13673 : 84 : newcon->conid = con->oid;
13674 : :
13675 : 84 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
13676 : : Anum_pg_constraint_conbin);
13677 : 84 : conbin = TextDatumGetCString(val);
13678 : 84 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
13679 : :
13680 : : /* Find or create work queue entry for this table */
13681 : 84 : tab = ATGetQueueEntry(wqueue, rel);
13682 : 84 : tab->constraints = lappend(tab->constraints, newcon);
13683 : :
13684 : : /*
13685 : : * Invalidate relcache so that others see the new validated constraint.
13686 : : */
13687 : 84 : CacheInvalidateRelcache(rel);
13688 : :
13689 : : /*
13690 : : * Now update the catalog, while we have the door open.
13691 : : */
13692 : 84 : copyTuple = heap_copytuple(contuple);
13693 : 84 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13694 : 84 : copy_con->convalidated = true;
13695 : 84 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13696 : :
13697 [ - + ]: 84 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13698 : :
13699 : 84 : heap_freetuple(copyTuple);
13700 : 84 : }
13701 : :
13702 : : /*
13703 : : * QueueNNConstraintValidation
13704 : : *
13705 : : * Add an entry to the wqueue to validate the given not-null constraint in
13706 : : * Phase 3 and update the convalidated field in the pg_constraint catalog for
13707 : : * the specified relation and all its inheriting children.
13708 : : */
13709 : : static void
13710 : 78 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13711 : : HeapTuple contuple, bool recurse, bool recursing,
13712 : : LOCKMODE lockmode)
13713 : : {
13714 : : Form_pg_constraint con;
13715 : : AlteredTableInfo *tab;
13716 : : HeapTuple copyTuple;
13717 : : Form_pg_constraint copy_con;
13718 : 78 : List *children = NIL;
13719 : : AttrNumber attnum;
13720 : : char *colname;
13721 : :
13722 : 78 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13723 : : Assert(con->contype == CONSTRAINT_NOTNULL);
13724 : :
13725 : 78 : attnum = extractNotNullColumn(contuple);
13726 : :
13727 : : /*
13728 : : * If we're recursing, we've already done this for parent, so skip it.
13729 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
13730 : : * look for it in the children.
13731 : : *
13732 : : * We recurse before validating on the parent, to reduce risk of
13733 : : * deadlocks.
13734 : : */
13735 [ + + + - ]: 78 : if (!recursing && !con->connoinherit)
13736 : 54 : children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
13737 : :
13738 : 78 : colname = get_attname(RelationGetRelid(rel), attnum, false);
13739 [ + + + + : 262 : foreach_oid(childoid, children)
+ + ]
13740 : : {
13741 : : Relation childrel;
13742 : : HeapTuple contup;
13743 : : Form_pg_constraint childcon;
13744 : : char *conname;
13745 : :
13746 [ + + ]: 106 : if (childoid == RelationGetRelid(rel))
13747 : 54 : continue;
13748 : :
13749 : : /*
13750 : : * If we are told not to recurse, there had better not be any child
13751 : : * tables, because we can't mark the constraint on the parent valid
13752 : : * unless it is valid for all child tables.
13753 : : */
13754 [ - + ]: 52 : if (!recurse)
13755 [ # # ]: 0 : ereport(ERROR,
13756 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13757 : : errmsg("constraint must be validated on child tables too"));
13758 : :
13759 : : /*
13760 : : * The column on child might have a different attnum, so search by
13761 : : * column name.
13762 : : */
13763 : 52 : contup = findNotNullConstraint(childoid, colname);
13764 [ - + ]: 52 : if (!contup)
13765 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
13766 : : colname, get_rel_name(childoid));
13767 : 52 : childcon = (Form_pg_constraint) GETSTRUCT(contup);
13768 [ + + ]: 52 : if (childcon->convalidated)
13769 : 28 : continue;
13770 : :
13771 : : /* find_all_inheritors already got lock */
13772 : 24 : childrel = table_open(childoid, NoLock);
13773 : 24 : conname = pstrdup(NameStr(childcon->conname));
13774 : :
13775 : : /* XXX improve ATExecValidateConstraint API to avoid double search */
13776 : 24 : ATExecValidateConstraint(wqueue, childrel, conname,
13777 : : false, true, lockmode);
13778 : 24 : table_close(childrel, NoLock);
13779 : : }
13780 : :
13781 : : /* Set attnotnull appropriately without queueing another validation */
13782 : 78 : set_attnotnull(NULL, rel, attnum, false);
13783 : :
13784 : 78 : tab = ATGetQueueEntry(wqueue, rel);
13785 : 78 : tab->verify_new_notnull = true;
13786 : :
13787 : : /*
13788 : : * Invalidate relcache so that others see the new validated constraint.
13789 : : */
13790 : 78 : CacheInvalidateRelcache(rel);
13791 : :
13792 : : /*
13793 : : * Now update the catalogs, while we have the door open.
13794 : : */
13795 : 78 : copyTuple = heap_copytuple(contuple);
13796 : 78 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13797 : 78 : copy_con->convalidated = true;
13798 : 78 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13799 : :
13800 [ - + ]: 78 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13801 : :
13802 : 78 : heap_freetuple(copyTuple);
13803 : 78 : }
13804 : :
13805 : : /*
13806 : : * transformColumnNameList - transform list of column names
13807 : : *
13808 : : * Lookup each name and return its attnum and, optionally, type and collation
13809 : : * OIDs
13810 : : *
13811 : : * Note: the name of this function suggests that it's general-purpose,
13812 : : * but actually it's only used to look up names appearing in foreign-key
13813 : : * clauses. The error messages would need work to use it in other cases,
13814 : : * and perhaps the validity checks as well.
13815 : : */
13816 : : static int
13817 : 4569 : transformColumnNameList(Oid relId, List *colList,
13818 : : int16 *attnums, Oid *atttypids, Oid *attcollids)
13819 : : {
13820 : : ListCell *l;
13821 : : int attnum;
13822 : :
13823 : 4569 : attnum = 0;
13824 [ + + + + : 8329 : foreach(l, colList)
+ + ]
13825 : : {
13826 : 3804 : char *attname = strVal(lfirst(l));
13827 : : HeapTuple atttuple;
13828 : : Form_pg_attribute attform;
13829 : :
13830 : 3804 : atttuple = SearchSysCacheAttName(relId, attname);
13831 [ + + ]: 3804 : if (!HeapTupleIsValid(atttuple))
13832 [ + - ]: 36 : ereport(ERROR,
13833 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
13834 : : errmsg("column \"%s\" referenced in foreign key constraint does not exist",
13835 : : attname)));
13836 : 3768 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
13837 [ + + ]: 3768 : if (attform->attnum < 0)
13838 [ + - ]: 8 : ereport(ERROR,
13839 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13840 : : errmsg("system columns cannot be used in foreign keys")));
13841 [ - + ]: 3760 : if (attnum >= INDEX_MAX_KEYS)
13842 [ # # ]: 0 : ereport(ERROR,
13843 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
13844 : : errmsg("cannot have more than %d keys in a foreign key",
13845 : : INDEX_MAX_KEYS)));
13846 : 3760 : attnums[attnum] = attform->attnum;
13847 [ + + ]: 3760 : if (atttypids != NULL)
13848 : 3736 : atttypids[attnum] = attform->atttypid;
13849 [ + + ]: 3760 : if (attcollids != NULL)
13850 : 3736 : attcollids[attnum] = attform->attcollation;
13851 : 3760 : ReleaseSysCache(atttuple);
13852 : 3760 : attnum++;
13853 : : }
13854 : :
13855 : 4525 : return attnum;
13856 : : }
13857 : :
13858 : : /*
13859 : : * transformFkeyGetPrimaryKey -
13860 : : *
13861 : : * Look up the names, attnums, types, and collations of the primary key attributes
13862 : : * for the pkrel. Also return the index OID and index opclasses of the
13863 : : * index supporting the primary key. Also return whether the index has
13864 : : * WITHOUT OVERLAPS.
13865 : : *
13866 : : * All parameters except pkrel are output parameters. Also, the function
13867 : : * return value is the number of attributes in the primary key.
13868 : : *
13869 : : * Used when the column list in the REFERENCES specification is omitted.
13870 : : */
13871 : : static int
13872 : 904 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
13873 : : List **attnamelist,
13874 : : int16 *attnums, Oid *atttypids, Oid *attcollids,
13875 : : Oid *opclasses, bool *pk_has_without_overlaps)
13876 : : {
13877 : : List *indexoidlist;
13878 : : ListCell *indexoidscan;
13879 : 904 : HeapTuple indexTuple = NULL;
13880 : 904 : Form_pg_index indexStruct = NULL;
13881 : : Datum indclassDatum;
13882 : : oidvector *indclass;
13883 : : int i;
13884 : :
13885 : : /*
13886 : : * Get the list of index OIDs for the table from the relcache, and look up
13887 : : * each one in the pg_index syscache until we find one marked primary key
13888 : : * (hopefully there isn't more than one such). Insist it's valid, too.
13889 : : */
13890 : 904 : *indexOid = InvalidOid;
13891 : :
13892 : 904 : indexoidlist = RelationGetIndexList(pkrel);
13893 : :
13894 [ + - + - : 908 : foreach(indexoidscan, indexoidlist)
+ - ]
13895 : : {
13896 : 908 : Oid indexoid = lfirst_oid(indexoidscan);
13897 : :
13898 : 908 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13899 [ - + ]: 908 : if (!HeapTupleIsValid(indexTuple))
13900 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
13901 : 908 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13902 [ + + + - ]: 908 : if (indexStruct->indisprimary && indexStruct->indisvalid)
13903 : : {
13904 : : /*
13905 : : * Refuse to use a deferrable primary key. This is per SQL spec,
13906 : : * and there would be a lot of interesting semantic problems if we
13907 : : * tried to allow it.
13908 : : */
13909 [ - + ]: 904 : if (!indexStruct->indimmediate)
13910 [ # # ]: 0 : ereport(ERROR,
13911 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13912 : : errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
13913 : : RelationGetRelationName(pkrel))));
13914 : :
13915 : 904 : *indexOid = indexoid;
13916 : 904 : break;
13917 : : }
13918 : 4 : ReleaseSysCache(indexTuple);
13919 : : }
13920 : :
13921 : 904 : list_free(indexoidlist);
13922 : :
13923 : : /*
13924 : : * Check that we found it
13925 : : */
13926 [ - + ]: 904 : if (!OidIsValid(*indexOid))
13927 [ # # ]: 0 : ereport(ERROR,
13928 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
13929 : : errmsg("there is no primary key for referenced table \"%s\"",
13930 : : RelationGetRelationName(pkrel))));
13931 : :
13932 : : /* Must get indclass the hard way */
13933 : 904 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13934 : : Anum_pg_index_indclass);
13935 : 904 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
13936 : :
13937 : : /*
13938 : : * Now build the list of PK attributes from the indkey definition (we
13939 : : * assume a primary key cannot have expressional elements)
13940 : : */
13941 : 904 : *attnamelist = NIL;
13942 [ + + ]: 2124 : for (i = 0; i < indexStruct->indnkeyatts; i++)
13943 : : {
13944 : 1220 : int pkattno = indexStruct->indkey.values[i];
13945 : :
13946 : 1220 : attnums[i] = pkattno;
13947 : 1220 : atttypids[i] = attnumTypeId(pkrel, pkattno);
13948 : 1220 : attcollids[i] = attnumCollationId(pkrel, pkattno);
13949 : 1220 : opclasses[i] = indclass->values[i];
13950 : 1220 : *attnamelist = lappend(*attnamelist,
13951 : 1220 : makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
13952 : : }
13953 : :
13954 : 904 : *pk_has_without_overlaps = indexStruct->indisexclusion;
13955 : :
13956 : 904 : ReleaseSysCache(indexTuple);
13957 : :
13958 : 904 : return i;
13959 : : }
13960 : :
13961 : : /*
13962 : : * transformFkeyCheckAttrs -
13963 : : *
13964 : : * Validate that the 'attnums' columns in the 'pkrel' relation are valid to
13965 : : * reference as part of a foreign key constraint.
13966 : : *
13967 : : * Returns the OID of the unique index supporting the constraint and
13968 : : * populates the caller-provided 'opclasses' array with the opclasses
13969 : : * associated with the index columns. Also sets whether the index
13970 : : * uses WITHOUT OVERLAPS.
13971 : : *
13972 : : * Raises an ERROR on validation failure.
13973 : : */
13974 : : static Oid
13975 : 867 : transformFkeyCheckAttrs(Relation pkrel,
13976 : : int numattrs, int16 *attnums,
13977 : : bool with_period, Oid *opclasses,
13978 : : bool *pk_has_without_overlaps)
13979 : : {
13980 : 867 : Oid indexoid = InvalidOid;
13981 : 867 : bool found = false;
13982 : 867 : bool found_deferrable = false;
13983 : : List *indexoidlist;
13984 : : ListCell *indexoidscan;
13985 : : int i,
13986 : : j;
13987 : :
13988 : : /*
13989 : : * Reject duplicate appearances of columns in the referenced-columns list.
13990 : : * Such a case is forbidden by the SQL standard, and even if we thought it
13991 : : * useful to allow it, there would be ambiguity about how to match the
13992 : : * list to unique indexes (in particular, it'd be unclear which index
13993 : : * opclass goes with which FK column).
13994 : : */
13995 [ + + ]: 2039 : for (i = 0; i < numattrs; i++)
13996 : : {
13997 [ + + ]: 1559 : for (j = i + 1; j < numattrs; j++)
13998 : : {
13999 [ + + ]: 387 : if (attnums[i] == attnums[j])
14000 [ + - ]: 16 : ereport(ERROR,
14001 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
14002 : : errmsg("foreign key referenced-columns list must not contain duplicates")));
14003 : : }
14004 : : }
14005 : :
14006 : : /*
14007 : : * Get the list of index OIDs for the table from the relcache, and look up
14008 : : * each one in the pg_index syscache, and match unique indexes to the list
14009 : : * of attnums we are given.
14010 : : */
14011 : 851 : indexoidlist = RelationGetIndexList(pkrel);
14012 : :
14013 [ + - + + : 970 : foreach(indexoidscan, indexoidlist)
+ + ]
14014 : : {
14015 : : HeapTuple indexTuple;
14016 : : Form_pg_index indexStruct;
14017 : :
14018 : 962 : indexoid = lfirst_oid(indexoidscan);
14019 : 962 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
14020 [ - + ]: 962 : if (!HeapTupleIsValid(indexTuple))
14021 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
14022 : 962 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
14023 : :
14024 : : /*
14025 : : * Must have the right number of columns; must be unique (or if
14026 : : * temporal then exclusion instead) and not a partial index; forget it
14027 : : * if there are any expressions, too. Invalid indexes are out as well.
14028 : : */
14029 [ + + + + : 962 : if (indexStruct->indnkeyatts == numattrs &&
+ + ]
14030 : 881 : (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
14031 [ + - + - ]: 1762 : indexStruct->indisvalid &&
14032 [ + - ]: 1762 : heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
14033 : 881 : heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
14034 : : {
14035 : : Datum indclassDatum;
14036 : : oidvector *indclass;
14037 : :
14038 : : /* Must get indclass the hard way */
14039 : 881 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
14040 : : Anum_pg_index_indclass);
14041 : 881 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
14042 : :
14043 : : /*
14044 : : * The given attnum list may match the index columns in any order.
14045 : : * Check for a match, and extract the appropriate opclasses while
14046 : : * we're at it.
14047 : : *
14048 : : * We know that attnums[] is duplicate-free per the test at the
14049 : : * start of this function, and we checked above that the number of
14050 : : * index columns agrees, so if we find a match for each attnums[]
14051 : : * entry then we must have a one-to-one match in some order.
14052 : : */
14053 [ + + ]: 2045 : for (i = 0; i < numattrs; i++)
14054 : : {
14055 : 1202 : found = false;
14056 [ + + ]: 1611 : for (j = 0; j < numattrs; j++)
14057 : : {
14058 [ + + ]: 1573 : if (attnums[i] == indexStruct->indkey.values[j])
14059 : : {
14060 : 1164 : opclasses[i] = indclass->values[j];
14061 : 1164 : found = true;
14062 : 1164 : break;
14063 : : }
14064 : : }
14065 [ + + ]: 1202 : if (!found)
14066 : 38 : break;
14067 : : }
14068 : : /* The last attribute in the index must be the PERIOD FK part */
14069 [ + + + + ]: 881 : if (found && with_period)
14070 : : {
14071 : 80 : int16 periodattnum = attnums[numattrs - 1];
14072 : :
14073 : 80 : found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
14074 : : }
14075 : :
14076 : : /*
14077 : : * Refuse to use a deferrable unique/primary key. This is per SQL
14078 : : * spec, and there would be a lot of interesting semantic problems
14079 : : * if we tried to allow it.
14080 : : */
14081 [ + + - + ]: 881 : if (found && !indexStruct->indimmediate)
14082 : : {
14083 : : /*
14084 : : * Remember that we found an otherwise matching index, so that
14085 : : * we can generate a more appropriate error message.
14086 : : */
14087 : 0 : found_deferrable = true;
14088 : 0 : found = false;
14089 : : }
14090 : :
14091 : : /* We need to know whether the index has WITHOUT OVERLAPS */
14092 [ + + ]: 881 : if (found)
14093 : 843 : *pk_has_without_overlaps = indexStruct->indisexclusion;
14094 : : }
14095 : 962 : ReleaseSysCache(indexTuple);
14096 [ + + ]: 962 : if (found)
14097 : 843 : break;
14098 : : }
14099 : :
14100 [ + + ]: 851 : if (!found)
14101 : : {
14102 [ - + ]: 8 : if (found_deferrable)
14103 [ # # ]: 0 : ereport(ERROR,
14104 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14105 : : errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
14106 : : RelationGetRelationName(pkrel))));
14107 : : else
14108 [ + - ]: 8 : ereport(ERROR,
14109 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
14110 : : errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
14111 : : RelationGetRelationName(pkrel))));
14112 : : }
14113 : :
14114 : 843 : list_free(indexoidlist);
14115 : :
14116 : 843 : return indexoid;
14117 : : }
14118 : :
14119 : : /*
14120 : : * findFkeyCast -
14121 : : *
14122 : : * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
14123 : : * Caller has equal regard for binary coercibility and for an exact match.
14124 : : */
14125 : : static CoercionPathType
14126 : 8 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
14127 : : {
14128 : : CoercionPathType ret;
14129 : :
14130 [ + - ]: 8 : if (targetTypeId == sourceTypeId)
14131 : : {
14132 : 8 : ret = COERCION_PATH_RELABELTYPE;
14133 : 8 : *funcid = InvalidOid;
14134 : : }
14135 : : else
14136 : : {
14137 : 0 : ret = find_coercion_pathway(targetTypeId, sourceTypeId,
14138 : : COERCION_IMPLICIT, funcid);
14139 [ # # ]: 0 : if (ret == COERCION_PATH_NONE)
14140 : : /* A previously-relied-upon cast is now gone. */
14141 [ # # ]: 0 : elog(ERROR, "could not find cast from %u to %u",
14142 : : sourceTypeId, targetTypeId);
14143 : : }
14144 : :
14145 : 8 : return ret;
14146 : : }
14147 : :
14148 : : /*
14149 : : * Permissions checks on the referenced table for ADD FOREIGN KEY
14150 : : *
14151 : : * Note: we have already checked that the user owns the referencing table,
14152 : : * else we'd have failed much earlier; no additional checks are needed for it.
14153 : : */
14154 : : static void
14155 : 1723 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
14156 : : {
14157 : 1723 : Oid roleid = GetUserId();
14158 : : AclResult aclresult;
14159 : : int i;
14160 : :
14161 : : /* Okay if we have relation-level REFERENCES permission */
14162 : 1723 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
14163 : : ACL_REFERENCES);
14164 [ + - ]: 1723 : if (aclresult == ACLCHECK_OK)
14165 : 1723 : return;
14166 : : /* Else we must have REFERENCES on each column */
14167 [ # # ]: 0 : for (i = 0; i < natts; i++)
14168 : : {
14169 : 0 : aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
14170 : : roleid, ACL_REFERENCES);
14171 [ # # ]: 0 : if (aclresult != ACLCHECK_OK)
14172 : 0 : aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
14173 : 0 : RelationGetRelationName(rel));
14174 : : }
14175 : : }
14176 : :
14177 : : /*
14178 : : * Scan the existing rows in a table to verify they meet a proposed FK
14179 : : * constraint.
14180 : : *
14181 : : * Caller must have opened and locked both relations appropriately.
14182 : : */
14183 : : static void
14184 : 839 : validateForeignKeyConstraint(char *conname,
14185 : : Relation rel,
14186 : : Relation pkrel,
14187 : : Oid pkindOid,
14188 : : Oid constraintOid,
14189 : : bool hasperiod)
14190 : : {
14191 : : TupleTableSlot *slot;
14192 : : TableScanDesc scan;
14193 : 839 : Trigger trig = {0};
14194 : : Snapshot snapshot;
14195 : : MemoryContext oldcxt;
14196 : : MemoryContext perTupCxt;
14197 : :
14198 [ - + ]: 839 : ereport(DEBUG1,
14199 : : (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
14200 : :
14201 : : /*
14202 : : * Build a trigger call structure; we'll need it either way.
14203 : : */
14204 : 839 : trig.tgoid = InvalidOid;
14205 : 839 : trig.tgname = conname;
14206 : 839 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
14207 : 839 : trig.tgisinternal = true;
14208 : 839 : trig.tgconstrrelid = RelationGetRelid(pkrel);
14209 : 839 : trig.tgconstrindid = pkindOid;
14210 : 839 : trig.tgconstraint = constraintOid;
14211 : 839 : trig.tgdeferrable = false;
14212 : 839 : trig.tginitdeferred = false;
14213 : : /* we needn't fill in remaining fields */
14214 : :
14215 : : /*
14216 : : * See if we can do it with a single LEFT JOIN query. A false result
14217 : : * indicates we must proceed with the fire-the-trigger method. We can't do
14218 : : * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
14219 : : * left joins.
14220 : : */
14221 [ + + + + ]: 839 : if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
14222 : 680 : return;
14223 : :
14224 : : /*
14225 : : * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
14226 : : * if that tuple had just been inserted. If any of those fail, it should
14227 : : * ereport(ERROR) and that's that.
14228 : : */
14229 : 112 : snapshot = RegisterSnapshot(GetLatestSnapshot());
14230 : 112 : slot = table_slot_create(rel, NULL);
14231 : 112 : scan = table_beginscan(rel, snapshot, 0, NULL,
14232 : : SO_NONE);
14233 : 112 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
14234 : : "validateForeignKeyConstraint",
14235 : : ALLOCSET_SMALL_SIZES);
14236 : 112 : oldcxt = MemoryContextSwitchTo(perTupCxt);
14237 : :
14238 [ + + ]: 581 : while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
14239 : : {
14240 : 509 : LOCAL_FCINFO(fcinfo, 0);
14241 : 509 : TriggerData trigdata = {0};
14242 : :
14243 [ - + ]: 509 : CHECK_FOR_INTERRUPTS();
14244 : :
14245 : : /*
14246 : : * Make a call to the trigger function
14247 : : *
14248 : : * No parameters are passed, but we do set a context
14249 : : */
14250 [ + - + - : 2545 : MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
+ - + - +
+ ]
14251 : :
14252 : : /*
14253 : : * We assume RI_FKey_check_ins won't look at flinfo...
14254 : : */
14255 : 509 : trigdata.type = T_TriggerData;
14256 : 509 : trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
14257 : 509 : trigdata.tg_relation = rel;
14258 : 509 : trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
14259 : 509 : trigdata.tg_trigslot = slot;
14260 : 509 : trigdata.tg_trigger = &trig;
14261 : :
14262 : 509 : fcinfo->context = (Node *) &trigdata;
14263 : :
14264 : 509 : RI_FKey_check_ins(fcinfo);
14265 : :
14266 : 469 : MemoryContextReset(perTupCxt);
14267 : : }
14268 : :
14269 : 72 : MemoryContextSwitchTo(oldcxt);
14270 : 72 : MemoryContextDelete(perTupCxt);
14271 : 72 : table_endscan(scan);
14272 : 72 : UnregisterSnapshot(snapshot);
14273 : 72 : ExecDropSingleTupleTableSlot(slot);
14274 : : }
14275 : :
14276 : : /*
14277 : : * CreateFKCheckTrigger
14278 : : * Creates the insert (on_insert=true) or update "check" trigger that
14279 : : * implements a given foreign key
14280 : : *
14281 : : * Returns the OID of the so created trigger.
14282 : : */
14283 : : static Oid
14284 : 4076 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14285 : : Oid constraintOid, Oid indexOid, Oid parentTrigOid,
14286 : : bool on_insert)
14287 : : {
14288 : : ObjectAddress trigAddress;
14289 : : CreateTrigStmt *fk_trigger;
14290 : :
14291 : : /*
14292 : : * Note: for a self-referential FK (referencing and referenced tables are
14293 : : * the same), it is important that the ON UPDATE action fires before the
14294 : : * CHECK action, since both triggers will fire on the same row during an
14295 : : * UPDATE event; otherwise the CHECK trigger will be checking a non-final
14296 : : * state of the row. Triggers fire in name order, so we ensure this by
14297 : : * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
14298 : : * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
14299 : : */
14300 : 4076 : fk_trigger = makeNode(CreateTrigStmt);
14301 : 4076 : fk_trigger->replace = false;
14302 : 4076 : fk_trigger->isconstraint = true;
14303 : 4076 : fk_trigger->trigname = "RI_ConstraintTrigger_c";
14304 : 4076 : fk_trigger->relation = NULL;
14305 : :
14306 : : /* Either ON INSERT or ON UPDATE */
14307 [ + + ]: 4076 : if (on_insert)
14308 : : {
14309 : 2038 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
14310 : 2038 : fk_trigger->events = TRIGGER_TYPE_INSERT;
14311 : : }
14312 : : else
14313 : : {
14314 : 2038 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
14315 : 2038 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14316 : : }
14317 : :
14318 : 4076 : fk_trigger->args = NIL;
14319 : 4076 : fk_trigger->row = true;
14320 : 4076 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14321 : 4076 : fk_trigger->columns = NIL;
14322 : 4076 : fk_trigger->whenClause = NULL;
14323 : 4076 : fk_trigger->transitionRels = NIL;
14324 : 4076 : fk_trigger->deferrable = fkconstraint->deferrable;
14325 : 4076 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14326 : 4076 : fk_trigger->constrrel = NULL;
14327 : :
14328 : 4076 : trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
14329 : : constraintOid, indexOid, InvalidOid,
14330 : : parentTrigOid, NULL, true, false);
14331 : :
14332 : : /* Make changes-so-far visible */
14333 : 4076 : CommandCounterIncrement();
14334 : :
14335 : 4076 : return trigAddress.objectId;
14336 : : }
14337 : :
14338 : : /*
14339 : : * createForeignKeyActionTriggers
14340 : : * Create the referenced-side "action" triggers that implement a foreign
14341 : : * key.
14342 : : *
14343 : : * Returns the OIDs of the so created triggers in *deleteTrigOid and
14344 : : * *updateTrigOid.
14345 : : */
14346 : : static void
14347 : 2317 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14348 : : Oid constraintOid, Oid indexOid,
14349 : : Oid parentDelTrigger, Oid parentUpdTrigger,
14350 : : Oid *deleteTrigOid, Oid *updateTrigOid)
14351 : : {
14352 : : CreateTrigStmt *fk_trigger;
14353 : : ObjectAddress trigAddress;
14354 : :
14355 : : /*
14356 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14357 : : * DELETE action on the referenced table.
14358 : : */
14359 : 2317 : fk_trigger = makeNode(CreateTrigStmt);
14360 : 2317 : fk_trigger->replace = false;
14361 : 2317 : fk_trigger->isconstraint = true;
14362 : 2317 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14363 : 2317 : fk_trigger->relation = NULL;
14364 : 2317 : fk_trigger->args = NIL;
14365 : 2317 : fk_trigger->row = true;
14366 : 2317 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14367 : 2317 : fk_trigger->events = TRIGGER_TYPE_DELETE;
14368 : 2317 : fk_trigger->columns = NIL;
14369 : 2317 : fk_trigger->whenClause = NULL;
14370 : 2317 : fk_trigger->transitionRels = NIL;
14371 : 2317 : fk_trigger->constrrel = NULL;
14372 : :
14373 [ + + + + : 2317 : switch (fkconstraint->fk_del_action)
+ - ]
14374 : : {
14375 : 1888 : case FKCONSTR_ACTION_NOACTION:
14376 : 1888 : fk_trigger->deferrable = fkconstraint->deferrable;
14377 : 1888 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14378 : 1888 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
14379 : 1888 : break;
14380 : 20 : case FKCONSTR_ACTION_RESTRICT:
14381 : 20 : fk_trigger->deferrable = false;
14382 : 20 : fk_trigger->initdeferred = false;
14383 : 20 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
14384 : 20 : break;
14385 : 306 : case FKCONSTR_ACTION_CASCADE:
14386 : 306 : fk_trigger->deferrable = false;
14387 : 306 : fk_trigger->initdeferred = false;
14388 : 306 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
14389 : 306 : break;
14390 : 63 : case FKCONSTR_ACTION_SETNULL:
14391 : 63 : fk_trigger->deferrable = false;
14392 : 63 : fk_trigger->initdeferred = false;
14393 : 63 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
14394 : 63 : break;
14395 : 40 : case FKCONSTR_ACTION_SETDEFAULT:
14396 : 40 : fk_trigger->deferrable = false;
14397 : 40 : fk_trigger->initdeferred = false;
14398 : 40 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
14399 : 40 : break;
14400 : 0 : default:
14401 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
14402 : : (int) fkconstraint->fk_del_action);
14403 : : break;
14404 : : }
14405 : :
14406 : 2317 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14407 : : constraintOid, indexOid, InvalidOid,
14408 : : parentDelTrigger, NULL, true, false);
14409 [ + - ]: 2317 : if (deleteTrigOid)
14410 : 2317 : *deleteTrigOid = trigAddress.objectId;
14411 : :
14412 : : /* Make changes-so-far visible */
14413 : 2317 : CommandCounterIncrement();
14414 : :
14415 : : /*
14416 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14417 : : * UPDATE action on the referenced table.
14418 : : */
14419 : 2317 : fk_trigger = makeNode(CreateTrigStmt);
14420 : 2317 : fk_trigger->replace = false;
14421 : 2317 : fk_trigger->isconstraint = true;
14422 : 2317 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14423 : 2317 : fk_trigger->relation = NULL;
14424 : 2317 : fk_trigger->args = NIL;
14425 : 2317 : fk_trigger->row = true;
14426 : 2317 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14427 : 2317 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14428 : 2317 : fk_trigger->columns = NIL;
14429 : 2317 : fk_trigger->whenClause = NULL;
14430 : 2317 : fk_trigger->transitionRels = NIL;
14431 : 2317 : fk_trigger->constrrel = NULL;
14432 : :
14433 [ + + + + : 2317 : switch (fkconstraint->fk_upd_action)
+ - ]
14434 : : {
14435 : 2013 : case FKCONSTR_ACTION_NOACTION:
14436 : 2013 : fk_trigger->deferrable = fkconstraint->deferrable;
14437 : 2013 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14438 : 2013 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
14439 : 2013 : break;
14440 : 24 : case FKCONSTR_ACTION_RESTRICT:
14441 : 24 : fk_trigger->deferrable = false;
14442 : 24 : fk_trigger->initdeferred = false;
14443 : 24 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
14444 : 24 : break;
14445 : 211 : case FKCONSTR_ACTION_CASCADE:
14446 : 211 : fk_trigger->deferrable = false;
14447 : 211 : fk_trigger->initdeferred = false;
14448 : 211 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
14449 : 211 : break;
14450 : 41 : case FKCONSTR_ACTION_SETNULL:
14451 : 41 : fk_trigger->deferrable = false;
14452 : 41 : fk_trigger->initdeferred = false;
14453 : 41 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
14454 : 41 : break;
14455 : 28 : case FKCONSTR_ACTION_SETDEFAULT:
14456 : 28 : fk_trigger->deferrable = false;
14457 : 28 : fk_trigger->initdeferred = false;
14458 : 28 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
14459 : 28 : break;
14460 : 0 : default:
14461 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
14462 : : (int) fkconstraint->fk_upd_action);
14463 : : break;
14464 : : }
14465 : :
14466 : 2317 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14467 : : constraintOid, indexOid, InvalidOid,
14468 : : parentUpdTrigger, NULL, true, false);
14469 [ + - ]: 2317 : if (updateTrigOid)
14470 : 2317 : *updateTrigOid = trigAddress.objectId;
14471 : 2317 : }
14472 : :
14473 : : /*
14474 : : * createForeignKeyCheckTriggers
14475 : : * Create the referencing-side "check" triggers that implement a foreign
14476 : : * key.
14477 : : *
14478 : : * Returns the OIDs of the so created triggers in *insertTrigOid and
14479 : : * *updateTrigOid.
14480 : : */
14481 : : static void
14482 : 2038 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
14483 : : Constraint *fkconstraint, Oid constraintOid,
14484 : : Oid indexOid,
14485 : : Oid parentInsTrigger, Oid parentUpdTrigger,
14486 : : Oid *insertTrigOid, Oid *updateTrigOid)
14487 : : {
14488 : 2038 : *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14489 : : constraintOid, indexOid,
14490 : : parentInsTrigger, true);
14491 : 2038 : *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14492 : : constraintOid, indexOid,
14493 : : parentUpdTrigger, false);
14494 : 2038 : }
14495 : :
14496 : : /*
14497 : : * ALTER TABLE DROP CONSTRAINT
14498 : : *
14499 : : * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
14500 : : */
14501 : : static void
14502 : 559 : ATExecDropConstraint(Relation rel, const char *constrName,
14503 : : DropBehavior behavior, bool recurse,
14504 : : bool missing_ok, LOCKMODE lockmode)
14505 : : {
14506 : : Relation conrel;
14507 : : SysScanDesc scan;
14508 : : ScanKeyData skey[3];
14509 : : HeapTuple tuple;
14510 : 559 : bool found = false;
14511 : :
14512 : 559 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14513 : :
14514 : : /*
14515 : : * Find and drop the target constraint
14516 : : */
14517 : 559 : ScanKeyInit(&skey[0],
14518 : : Anum_pg_constraint_conrelid,
14519 : : BTEqualStrategyNumber, F_OIDEQ,
14520 : : ObjectIdGetDatum(RelationGetRelid(rel)));
14521 : 559 : ScanKeyInit(&skey[1],
14522 : : Anum_pg_constraint_contypid,
14523 : : BTEqualStrategyNumber, F_OIDEQ,
14524 : : ObjectIdGetDatum(InvalidOid));
14525 : 559 : ScanKeyInit(&skey[2],
14526 : : Anum_pg_constraint_conname,
14527 : : BTEqualStrategyNumber, F_NAMEEQ,
14528 : : CStringGetDatum(constrName));
14529 : 559 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14530 : : true, NULL, 3, skey);
14531 : :
14532 : : /* There can be at most one matching row */
14533 [ + + ]: 559 : if (HeapTupleIsValid(tuple = systable_getnext(scan)))
14534 : : {
14535 : 535 : dropconstraint_internal(rel, tuple, behavior, recurse, false,
14536 : : missing_ok, lockmode);
14537 : 411 : found = true;
14538 : : }
14539 : :
14540 : 435 : systable_endscan(scan);
14541 : :
14542 [ + + ]: 435 : if (!found)
14543 : : {
14544 [ + + ]: 24 : if (!missing_ok)
14545 [ + - ]: 16 : ereport(ERROR,
14546 : : errcode(ERRCODE_UNDEFINED_OBJECT),
14547 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14548 : : constrName, RelationGetRelationName(rel)));
14549 : : else
14550 [ + - ]: 8 : ereport(NOTICE,
14551 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
14552 : : constrName, RelationGetRelationName(rel)));
14553 : : }
14554 : :
14555 : 419 : table_close(conrel, RowExclusiveLock);
14556 : 419 : }
14557 : :
14558 : : /*
14559 : : * Remove a constraint, using its pg_constraint tuple
14560 : : *
14561 : : * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
14562 : : * DROP NOT NULL.
14563 : : *
14564 : : * Returns the address of the constraint being removed.
14565 : : */
14566 : : static ObjectAddress
14567 : 859 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
14568 : : bool recurse, bool recursing, bool missing_ok,
14569 : : LOCKMODE lockmode)
14570 : : {
14571 : : Relation conrel;
14572 : : Form_pg_constraint con;
14573 : : ObjectAddress conobj;
14574 : : List *children;
14575 : 859 : bool is_no_inherit_constraint = false;
14576 : : char *constrName;
14577 : 859 : char *colname = NULL;
14578 : :
14579 : : /* Guard against stack overflow due to overly deep inheritance tree. */
14580 : 859 : check_stack_depth();
14581 : :
14582 : : /* At top level, permission check was done in ATPrepCmd, else do it */
14583 [ + + ]: 859 : if (recursing)
14584 : 163 : ATSimplePermissions(AT_DropConstraint, rel,
14585 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
14586 : :
14587 : 855 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14588 : :
14589 : 855 : con = (Form_pg_constraint) GETSTRUCT(constraintTup);
14590 : 855 : constrName = NameStr(con->conname);
14591 : :
14592 : : /* Don't allow drop of inherited constraints */
14593 [ + + + + ]: 855 : if (con->coninhcount > 0 && !recursing)
14594 [ + - ]: 104 : ereport(ERROR,
14595 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14596 : : errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
14597 : : constrName, RelationGetRelationName(rel))));
14598 : :
14599 : : /*
14600 : : * Reset pg_constraint.attnotnull, if this is a not-null constraint.
14601 : : *
14602 : : * While doing that, we're in a good position to disallow dropping a not-
14603 : : * null constraint underneath a primary key, a replica identity index, or
14604 : : * a generated identity column.
14605 : : */
14606 [ + + ]: 751 : if (con->contype == CONSTRAINT_NOTNULL)
14607 : : {
14608 : 231 : Relation attrel = table_open(AttributeRelationId, RowExclusiveLock);
14609 : 231 : AttrNumber attnum = extractNotNullColumn(constraintTup);
14610 : : Bitmapset *pkattrs;
14611 : : Bitmapset *irattrs;
14612 : : HeapTuple atttup;
14613 : : Form_pg_attribute attForm;
14614 : :
14615 : : /* save column name for recursion step */
14616 : 231 : colname = get_attname(RelationGetRelid(rel), attnum, false);
14617 : :
14618 : : /*
14619 : : * Disallow if it's in the primary key. For partitioned tables we
14620 : : * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
14621 : : * return NULL if the primary key is invalid; but we still need to
14622 : : * protect not-null constraints under such a constraint, so check the
14623 : : * slow way.
14624 : : */
14625 : 231 : pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
14626 : :
14627 [ + + ]: 231 : if (pkattrs == NULL &&
14628 [ + + ]: 211 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14629 : : {
14630 : 16 : Oid pkindex = RelationGetPrimaryKeyIndex(rel, true);
14631 : :
14632 [ - + ]: 16 : if (OidIsValid(pkindex))
14633 : : {
14634 : 0 : Relation pk = relation_open(pkindex, AccessShareLock);
14635 : :
14636 : 0 : pkattrs = NULL;
14637 [ # # ]: 0 : for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
14638 : 0 : pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
14639 : :
14640 : 0 : relation_close(pk, AccessShareLock);
14641 : : }
14642 : : }
14643 : :
14644 [ + + + + ]: 251 : if (pkattrs &&
14645 : 20 : bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
14646 [ + - ]: 16 : ereport(ERROR,
14647 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14648 : : errmsg("column \"%s\" is in a primary key",
14649 : : get_attname(RelationGetRelid(rel), attnum, false)));
14650 : :
14651 : : /* Disallow if it's in the replica identity */
14652 : 215 : irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
14653 [ + + ]: 215 : if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
14654 [ + - ]: 8 : ereport(ERROR,
14655 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14656 : : errmsg("column \"%s\" is in index used as replica identity",
14657 : : get_attname(RelationGetRelid(rel), attnum, false)));
14658 : :
14659 : : /* Disallow if it's a GENERATED AS IDENTITY column */
14660 : 207 : atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
14661 [ - + ]: 207 : if (!HeapTupleIsValid(atttup))
14662 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
14663 : : attnum, RelationGetRelid(rel));
14664 : 207 : attForm = (Form_pg_attribute) GETSTRUCT(atttup);
14665 [ - + ]: 207 : if (attForm->attidentity != '\0')
14666 [ # # ]: 0 : ereport(ERROR,
14667 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14668 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
14669 : : get_attname(RelationGetRelid(rel), attnum,
14670 : : false),
14671 : : RelationGetRelationName(rel)));
14672 : :
14673 : : /* All good -- reset attnotnull if needed */
14674 [ + - ]: 207 : if (attForm->attnotnull)
14675 : : {
14676 : 207 : attForm->attnotnull = false;
14677 : 207 : CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
14678 : : }
14679 : :
14680 : 207 : table_close(attrel, RowExclusiveLock);
14681 : : }
14682 : :
14683 : 727 : is_no_inherit_constraint = con->connoinherit;
14684 : :
14685 : : /*
14686 : : * If it's a foreign-key constraint, we'd better lock the referenced table
14687 : : * and check that that's not in use, just as we've already done for the
14688 : : * constrained table (else we might, eg, be dropping a trigger that has
14689 : : * unfired events). But we can/must skip that in the self-referential
14690 : : * case.
14691 : : */
14692 [ + + ]: 727 : if (con->contype == CONSTRAINT_FOREIGN &&
14693 [ + - ]: 112 : con->confrelid != RelationGetRelid(rel))
14694 : : {
14695 : : Relation frel;
14696 : :
14697 : : /* Must match lock taken by RemoveTriggerById: */
14698 : 112 : frel = table_open(con->confrelid, AccessExclusiveLock);
14699 : 112 : CheckAlterTableIsSafe(frel);
14700 : 108 : table_close(frel, NoLock);
14701 : : }
14702 : :
14703 : : /*
14704 : : * Perform the actual constraint deletion
14705 : : */
14706 : 723 : ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
14707 : 723 : performDeletion(&conobj, behavior, 0);
14708 : :
14709 : : /*
14710 : : * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
14711 : : * are dropped via the dependency mechanism, so we're done here.
14712 : : */
14713 [ + + ]: 699 : if (con->contype != CONSTRAINT_CHECK &&
14714 [ + + ]: 446 : con->contype != CONSTRAINT_NOTNULL &&
14715 [ + + ]: 239 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14716 : : {
14717 : 52 : table_close(conrel, RowExclusiveLock);
14718 : 52 : return conobj;
14719 : : }
14720 : :
14721 : : /*
14722 : : * Propagate to children as appropriate. Unlike most other ALTER
14723 : : * routines, we have to do this one level of recursion at a time; we can't
14724 : : * use find_all_inheritors to do it in one pass.
14725 : : */
14726 [ + + ]: 647 : if (!is_no_inherit_constraint)
14727 : 452 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
14728 : : else
14729 : 195 : children = NIL;
14730 : :
14731 [ + + + + : 1573 : foreach_oid(childrelid, children)
+ + ]
14732 : : {
14733 : : Relation childrel;
14734 : : HeapTuple tuple;
14735 : : Form_pg_constraint childcon;
14736 : :
14737 : : /* find_inheritance_children already got lock */
14738 : 287 : childrel = table_open(childrelid, NoLock);
14739 : 287 : CheckAlterTableIsSafe(childrel);
14740 : :
14741 : : /*
14742 : : * We search for not-null constraints by column name, and others by
14743 : : * constraint name.
14744 : : */
14745 [ + + ]: 287 : if (con->contype == CONSTRAINT_NOTNULL)
14746 : : {
14747 : 102 : tuple = findNotNullConstraint(childrelid, colname);
14748 [ - + ]: 102 : if (!HeapTupleIsValid(tuple))
14749 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
14750 : : colname, RelationGetRelid(childrel));
14751 : : }
14752 : : else
14753 : : {
14754 : : SysScanDesc scan;
14755 : : ScanKeyData skey[3];
14756 : :
14757 : 185 : ScanKeyInit(&skey[0],
14758 : : Anum_pg_constraint_conrelid,
14759 : : BTEqualStrategyNumber, F_OIDEQ,
14760 : : ObjectIdGetDatum(childrelid));
14761 : 185 : ScanKeyInit(&skey[1],
14762 : : Anum_pg_constraint_contypid,
14763 : : BTEqualStrategyNumber, F_OIDEQ,
14764 : : ObjectIdGetDatum(InvalidOid));
14765 : 185 : ScanKeyInit(&skey[2],
14766 : : Anum_pg_constraint_conname,
14767 : : BTEqualStrategyNumber, F_NAMEEQ,
14768 : : CStringGetDatum(constrName));
14769 : 185 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14770 : : true, NULL, 3, skey);
14771 : : /* There can only be one, so no need to loop */
14772 : 185 : tuple = systable_getnext(scan);
14773 [ - + ]: 185 : if (!HeapTupleIsValid(tuple))
14774 [ # # ]: 0 : ereport(ERROR,
14775 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
14776 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14777 : : constrName,
14778 : : RelationGetRelationName(childrel))));
14779 : 185 : tuple = heap_copytuple(tuple);
14780 : 185 : systable_endscan(scan);
14781 : : }
14782 : :
14783 : 287 : childcon = (Form_pg_constraint) GETSTRUCT(tuple);
14784 : :
14785 : : /* Right now only CHECK and not-null constraints can be inherited */
14786 [ + + ]: 287 : if (childcon->contype != CONSTRAINT_CHECK &&
14787 [ - + ]: 102 : childcon->contype != CONSTRAINT_NOTNULL)
14788 [ # # ]: 0 : elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
14789 : :
14790 [ - + ]: 287 : if (childcon->coninhcount <= 0) /* shouldn't happen */
14791 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
14792 : : childrelid, NameStr(childcon->conname));
14793 : :
14794 [ + + ]: 287 : if (recurse)
14795 : : {
14796 : : /*
14797 : : * If the child constraint has other definition sources, just
14798 : : * decrement its inheritance count; if not, recurse to delete it.
14799 : : */
14800 [ + + + + ]: 219 : if (childcon->coninhcount == 1 && !childcon->conislocal)
14801 : : {
14802 : : /* Time to delete this child constraint, too */
14803 : 163 : dropconstraint_internal(childrel, tuple, behavior,
14804 : : recurse, true, missing_ok,
14805 : : lockmode);
14806 : : }
14807 : : else
14808 : : {
14809 : : /* Child constraint must survive my deletion */
14810 : 56 : childcon->coninhcount--;
14811 : 56 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14812 : :
14813 : : /* Make update visible */
14814 : 56 : CommandCounterIncrement();
14815 : : }
14816 : : }
14817 : : else
14818 : : {
14819 : : /*
14820 : : * If we were told to drop ONLY in this table (no recursion) and
14821 : : * there are no further parents for this constraint, we need to
14822 : : * mark the inheritors' constraints as locally defined rather than
14823 : : * inherited.
14824 : : */
14825 : 68 : childcon->coninhcount--;
14826 [ + - ]: 68 : if (childcon->coninhcount == 0)
14827 : 68 : childcon->conislocal = true;
14828 : :
14829 : 68 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14830 : :
14831 : : /* Make update visible */
14832 : 68 : CommandCounterIncrement();
14833 : : }
14834 : :
14835 : 283 : heap_freetuple(tuple);
14836 : :
14837 : 283 : table_close(childrel, NoLock);
14838 : : }
14839 : :
14840 : 643 : table_close(conrel, RowExclusiveLock);
14841 : :
14842 : 643 : return conobj;
14843 : : }
14844 : :
14845 : : /*
14846 : : * ALTER COLUMN TYPE
14847 : : *
14848 : : * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
14849 : : * TYPE during phase 1 --- the AlterTableCmd passed in here is already
14850 : : * transformed (and must be, because we rely on some transformed fields).
14851 : : *
14852 : : * The point of this is that the execution of all ALTER COLUMN TYPEs for a
14853 : : * table will be done "in parallel" during phase 3, so all the USING
14854 : : * expressions should be parsed assuming the original column types. Also,
14855 : : * this allows a USING expression to refer to a field that will be dropped.
14856 : : *
14857 : : * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
14858 : : * the first two execution steps in phase 2; they must not see the effects
14859 : : * of any other subcommand types, since the USING expressions are parsed
14860 : : * against the unmodified table's state.
14861 : : */
14862 : : static void
14863 : 960 : ATPrepAlterColumnType(List **wqueue,
14864 : : AlteredTableInfo *tab, Relation rel,
14865 : : bool recurse, bool recursing,
14866 : : AlterTableCmd *cmd, LOCKMODE lockmode,
14867 : : AlterTableUtilityContext *context)
14868 : : {
14869 : 960 : char *colName = cmd->name;
14870 : 960 : ColumnDef *def = (ColumnDef *) cmd->def;
14871 : 960 : TypeName *typeName = def->typeName;
14872 : 960 : Node *transform = def->cooked_default;
14873 : : HeapTuple tuple;
14874 : : Form_pg_attribute attTup;
14875 : : AttrNumber attnum;
14876 : : Oid targettype;
14877 : : int32 targettypmod;
14878 : : Oid targetcollid;
14879 : : NewColumnValue *newval;
14880 : 960 : ParseState *pstate = make_parsestate(NULL);
14881 : : AclResult aclresult;
14882 : : bool is_expr;
14883 : :
14884 : 960 : pstate->p_sourcetext = context->queryString;
14885 : :
14886 [ + + + + ]: 960 : if (rel->rd_rel->reloftype && !recursing)
14887 [ + - ]: 4 : ereport(ERROR,
14888 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14889 : : errmsg("cannot alter column type of typed table"),
14890 : : parser_errposition(pstate, def->location)));
14891 : :
14892 : : /* lookup the attribute so we can check inheritance status */
14893 : 956 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
14894 [ - + ]: 956 : if (!HeapTupleIsValid(tuple))
14895 [ # # ]: 0 : ereport(ERROR,
14896 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
14897 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
14898 : : colName, RelationGetRelationName(rel)),
14899 : : parser_errposition(pstate, def->location)));
14900 : 956 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
14901 : 956 : attnum = attTup->attnum;
14902 : :
14903 : : /* Can't alter a system attribute */
14904 [ + + ]: 956 : if (attnum <= 0)
14905 [ + - ]: 4 : ereport(ERROR,
14906 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14907 : : errmsg("cannot alter system column \"%s\"", colName),
14908 : : parser_errposition(pstate, def->location)));
14909 : :
14910 : : /*
14911 : : * Cannot specify USING when altering type of a generated column, because
14912 : : * that would violate the generation expression.
14913 : : */
14914 [ + + + + ]: 952 : if (attTup->attgenerated && def->cooked_default)
14915 [ + - ]: 8 : ereport(ERROR,
14916 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
14917 : : errmsg("cannot specify USING when altering type of generated column"),
14918 : : errdetail("Column \"%s\" is a generated column.", colName),
14919 : : parser_errposition(pstate, def->location)));
14920 : :
14921 : : /*
14922 : : * Don't alter inherited columns. At outer level, there had better not be
14923 : : * any inherited definition; when recursing, we assume this was checked at
14924 : : * the parent level (see below).
14925 : : */
14926 [ + + + + ]: 944 : if (attTup->attinhcount > 0 && !recursing)
14927 [ + - ]: 4 : ereport(ERROR,
14928 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14929 : : errmsg("cannot alter inherited column \"%s\"", colName),
14930 : : parser_errposition(pstate, def->location)));
14931 : :
14932 : : /* Don't alter columns used in the partition key */
14933 [ + + ]: 940 : if (has_partition_attrs(rel,
14934 : : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
14935 : : &is_expr))
14936 [ + - ]: 12 : ereport(ERROR,
14937 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14938 : : errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
14939 : : colName, RelationGetRelationName(rel)),
14940 : : parser_errposition(pstate, def->location)));
14941 : :
14942 : : /* Look up the target type */
14943 : 928 : typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
14944 : :
14945 : 924 : aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
14946 [ + + ]: 924 : if (aclresult != ACLCHECK_OK)
14947 : 8 : aclcheck_error_type(aclresult, targettype);
14948 : :
14949 : : /* And the collation */
14950 : 916 : targetcollid = GetColumnDefCollation(pstate, def, targettype);
14951 : :
14952 : : /* make sure datatype is legal for a column */
14953 : 1824 : CheckAttributeType(colName, targettype, targetcollid,
14954 : 912 : list_make1_oid(rel->rd_rel->reltype),
14955 [ + + ]: 912 : (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
14956 : :
14957 [ + + ]: 904 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14958 : : {
14959 : : /* do nothing */
14960 : : }
14961 [ + + ]: 880 : else if (tab->relkind == RELKIND_RELATION ||
14962 [ + + ]: 137 : tab->relkind == RELKIND_PARTITIONED_TABLE)
14963 : : {
14964 : : /*
14965 : : * Set up an expression to transform the old data value to the new
14966 : : * type. If a USING option was given, use the expression as
14967 : : * transformed by transformAlterTableStmt, else just take the old
14968 : : * value and try to coerce it. We do this first so that type
14969 : : * incompatibility can be detected before we waste effort, and because
14970 : : * we need the expression to be parsed against the original table row
14971 : : * type.
14972 : : */
14973 [ + + ]: 787 : if (!transform)
14974 : : {
14975 : 636 : transform = (Node *) makeVar(1, attnum,
14976 : : attTup->atttypid, attTup->atttypmod,
14977 : : attTup->attcollation,
14978 : : 0);
14979 : : }
14980 : :
14981 : 787 : transform = coerce_to_target_type(pstate,
14982 : : transform, exprType(transform),
14983 : : targettype, targettypmod,
14984 : : COERCION_ASSIGNMENT,
14985 : : COERCE_IMPLICIT_CAST,
14986 : : -1);
14987 [ + + ]: 787 : if (transform == NULL)
14988 : : {
14989 : : /* error text depends on whether USING was specified or not */
14990 [ + + ]: 15 : if (def->cooked_default != NULL)
14991 [ + - ]: 4 : ereport(ERROR,
14992 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
14993 : : errmsg("result of USING clause for column \"%s\""
14994 : : " cannot be cast automatically to type %s",
14995 : : colName, format_type_be(targettype)),
14996 : : errhint("You might need to add an explicit cast.")));
14997 : : else
14998 [ + - + - ]: 11 : ereport(ERROR,
14999 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15000 : : errmsg("column \"%s\" cannot be cast automatically to type %s",
15001 : : colName, format_type_be(targettype)),
15002 : : !attTup->attgenerated ?
15003 : : /* translator: USING is SQL, don't translate it */
15004 : : errhint("You might need to specify \"USING %s::%s\".",
15005 : : quote_identifier(colName),
15006 : : format_type_with_typemod(targettype,
15007 : : targettypmod)) : 0));
15008 : : }
15009 : :
15010 : : /* Fix collations after all else */
15011 : 772 : assign_expr_collations(pstate, transform);
15012 : :
15013 : : /* Expand virtual generated columns in the expr. */
15014 : 772 : transform = expand_generated_columns_in_expr(transform, rel, 1);
15015 : :
15016 : : /* Plan the expr now so we can accurately assess the need to rewrite. */
15017 : 772 : transform = (Node *) expression_planner((Expr *) transform);
15018 : :
15019 : : /*
15020 : : * Add a work queue item to make ATRewriteTable update the column
15021 : : * contents.
15022 : : */
15023 : 772 : newval = palloc0_object(NewColumnValue);
15024 : 772 : newval->attnum = attnum;
15025 : 772 : newval->expr = (Expr *) transform;
15026 : 772 : newval->is_generated = false;
15027 : :
15028 : 772 : tab->newvals = lappend(tab->newvals, newval);
15029 [ + + ]: 1412 : if (ATColumnChangeRequiresRewrite(transform, attnum))
15030 : 640 : tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
15031 : : }
15032 [ + + ]: 93 : else if (transform)
15033 [ + - ]: 8 : ereport(ERROR,
15034 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15035 : : errmsg("\"%s\" is not a table",
15036 : : RelationGetRelationName(rel))));
15037 : :
15038 [ + + + - : 881 : if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ - + - -
+ + + ]
15039 : : {
15040 : : /*
15041 : : * For relations or columns without storage, do this check now.
15042 : : * Regular tables will check it later when the table is being
15043 : : * rewritten.
15044 : : */
15045 : 153 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
15046 : : }
15047 : :
15048 : 849 : ReleaseSysCache(tuple);
15049 : :
15050 : : /*
15051 : : * Recurse manually by queueing a new command for each child, if
15052 : : * necessary. We cannot apply ATSimpleRecursion here because we need to
15053 : : * remap attribute numbers in the USING expression, if any.
15054 : : *
15055 : : * If we are told not to recurse, there had better not be any child
15056 : : * tables; else the alter would put them out of step.
15057 : : */
15058 [ + + ]: 849 : if (recurse)
15059 : : {
15060 : 674 : Oid relid = RelationGetRelid(rel);
15061 : : List *child_oids,
15062 : : *child_numparents;
15063 : : ListCell *lo,
15064 : : *li;
15065 : :
15066 : 674 : child_oids = find_all_inheritors(relid, lockmode,
15067 : : &child_numparents);
15068 : :
15069 : : /*
15070 : : * find_all_inheritors does the recursive search of the inheritance
15071 : : * hierarchy, so all we have to do is process all of the relids in the
15072 : : * list that it returns.
15073 : : */
15074 [ + - + + : 1486 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
15075 : : {
15076 : 828 : Oid childrelid = lfirst_oid(lo);
15077 : 828 : int numparents = lfirst_int(li);
15078 : : Relation childrel;
15079 : : HeapTuple childtuple;
15080 : : Form_pg_attribute childattTup;
15081 : :
15082 [ + + ]: 828 : if (childrelid == relid)
15083 : 674 : continue;
15084 : :
15085 : : /* find_all_inheritors already got lock */
15086 : 154 : childrel = relation_open(childrelid, NoLock);
15087 : 154 : CheckAlterTableIsSafe(childrel);
15088 : :
15089 : : /*
15090 : : * Verify that the child doesn't have any inherited definitions of
15091 : : * this column that came from outside this inheritance hierarchy.
15092 : : * (renameatt makes a similar test, though in a different way
15093 : : * because of its different recursion mechanism.)
15094 : : */
15095 : 154 : childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
15096 : : colName);
15097 [ - + ]: 154 : if (!HeapTupleIsValid(childtuple))
15098 [ # # ]: 0 : ereport(ERROR,
15099 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15100 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15101 : : colName, RelationGetRelationName(childrel))));
15102 : 154 : childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
15103 : :
15104 [ + + ]: 154 : if (childattTup->attinhcount > numparents)
15105 [ + - ]: 4 : ereport(ERROR,
15106 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15107 : : errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
15108 : : colName, RelationGetRelationName(childrel))));
15109 : :
15110 : 150 : ReleaseSysCache(childtuple);
15111 : :
15112 : : /*
15113 : : * Remap the attribute numbers. If no USING expression was
15114 : : * specified, there is no need for this step.
15115 : : */
15116 [ + + ]: 150 : if (def->cooked_default)
15117 : : {
15118 : : AttrMap *attmap;
15119 : : bool found_whole_row;
15120 : :
15121 : : /* create a copy to scribble on */
15122 : 52 : cmd = copyObject(cmd);
15123 : :
15124 : 52 : attmap = build_attrmap_by_name(RelationGetDescr(childrel),
15125 : : RelationGetDescr(rel),
15126 : : false);
15127 : 104 : ((ColumnDef *) cmd->def)->cooked_default =
15128 : 52 : map_variable_attnos(def->cooked_default,
15129 : : 1, 0,
15130 : : attmap,
15131 : : InvalidOid, &found_whole_row);
15132 [ + + ]: 52 : if (found_whole_row)
15133 [ + - ]: 4 : ereport(ERROR,
15134 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15135 : : errmsg("cannot convert whole-row table reference"),
15136 : : errdetail("USING expression contains a whole-row table reference.")));
15137 : 48 : pfree(attmap);
15138 : : }
15139 : 146 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
15140 : 138 : relation_close(childrel, NoLock);
15141 : : }
15142 : : }
15143 [ + + - + ]: 212 : else if (!recursing &&
15144 : 37 : find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
15145 [ # # ]: 0 : ereport(ERROR,
15146 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15147 : : errmsg("type of inherited column \"%s\" must be changed in child tables too",
15148 : : colName)));
15149 : :
15150 [ + + ]: 833 : if (tab->relkind == RELKIND_COMPOSITE_TYPE)
15151 : 37 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
15152 : 829 : }
15153 : :
15154 : : /*
15155 : : * When the data type of a column is changed, a rewrite might not be required
15156 : : * if the new type is sufficiently identical to the old one, and the USING
15157 : : * clause isn't trying to insert some other value. It's safe to skip the
15158 : : * rewrite in these cases:
15159 : : *
15160 : : * - the old type is binary coercible to the new type
15161 : : * - the new type is an unconstrained domain over the old type
15162 : : * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
15163 : : *
15164 : : * In the case of a constrained domain, we could get by with scanning the
15165 : : * table and checking the constraint rather than actually rewriting it, but we
15166 : : * don't currently try to do that.
15167 : : */
15168 : : static bool
15169 : 772 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
15170 : : {
15171 : : Assert(expr != NULL);
15172 : :
15173 : : for (;;)
15174 : : {
15175 : : /* only one varno, so no need to check that */
15176 [ + + + - ]: 848 : if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
15177 : 132 : return false;
15178 [ + + ]: 716 : else if (IsA(expr, RelabelType))
15179 : 68 : expr = (Node *) ((RelabelType *) expr)->arg;
15180 [ + + ]: 648 : else if (IsA(expr, CoerceToDomain))
15181 : : {
15182 : 4 : CoerceToDomain *d = (CoerceToDomain *) expr;
15183 : :
15184 [ + - ]: 4 : if (DomainHasConstraints(d->resulttype, NULL))
15185 : 4 : return true;
15186 : 0 : expr = (Node *) d->arg;
15187 : : }
15188 [ + + ]: 644 : else if (IsA(expr, FuncExpr))
15189 : : {
15190 : 511 : FuncExpr *f = (FuncExpr *) expr;
15191 : :
15192 [ + + ]: 511 : switch (f->funcid)
15193 : : {
15194 : 12 : case F_TIMESTAMPTZ_TIMESTAMP:
15195 : : case F_TIMESTAMP_TIMESTAMPTZ:
15196 [ + + ]: 12 : if (TimestampTimestampTzRequiresRewrite())
15197 : 4 : return true;
15198 : : else
15199 : 8 : expr = linitial(f->args);
15200 : 8 : break;
15201 : 499 : default:
15202 : 499 : return true;
15203 : : }
15204 : : }
15205 : : else
15206 : 133 : return true;
15207 : : }
15208 : : }
15209 : :
15210 : : /*
15211 : : * ALTER COLUMN .. SET DATA TYPE
15212 : : *
15213 : : * Return the address of the modified column.
15214 : : */
15215 : : static ObjectAddress
15216 : 805 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
15217 : : AlterTableCmd *cmd, LOCKMODE lockmode)
15218 : : {
15219 : 805 : char *colName = cmd->name;
15220 : 805 : ColumnDef *def = (ColumnDef *) cmd->def;
15221 : 805 : TypeName *typeName = def->typeName;
15222 : : HeapTuple heapTup;
15223 : : Form_pg_attribute attTup,
15224 : : attOldTup;
15225 : : AttrNumber attnum;
15226 : : HeapTuple typeTuple;
15227 : : Form_pg_type tform;
15228 : : Oid targettype;
15229 : : int32 targettypmod;
15230 : : Oid targetcollid;
15231 : : Node *defaultexpr;
15232 : : Relation attrelation;
15233 : : Relation depRel;
15234 : : ScanKeyData key[3];
15235 : : SysScanDesc scan;
15236 : : HeapTuple depTup;
15237 : : ObjectAddress address;
15238 : :
15239 : : /*
15240 : : * Clear all the missing values if we're rewriting the table, since this
15241 : : * renders them pointless.
15242 : : */
15243 [ + + ]: 805 : if (tab->rewrite)
15244 : : {
15245 : : Relation newrel;
15246 : :
15247 : 600 : newrel = table_open(RelationGetRelid(rel), NoLock);
15248 : 600 : RelationClearMissing(newrel);
15249 : 600 : relation_close(newrel, NoLock);
15250 : : /* make sure we don't conflict with later attribute modifications */
15251 : 600 : CommandCounterIncrement();
15252 : : }
15253 : :
15254 : 805 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
15255 : :
15256 : : /* Look up the target column */
15257 : 805 : heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
15258 [ - + ]: 805 : if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
15259 [ # # ]: 0 : ereport(ERROR,
15260 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15261 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15262 : : colName, RelationGetRelationName(rel))));
15263 : 805 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15264 : 805 : attnum = attTup->attnum;
15265 : 805 : attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
15266 : :
15267 : : /* Check for multiple ALTER TYPE on same column --- can't cope */
15268 [ + - ]: 805 : if (attTup->atttypid != attOldTup->atttypid ||
15269 [ - + ]: 805 : attTup->atttypmod != attOldTup->atttypmod)
15270 [ # # ]: 0 : ereport(ERROR,
15271 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15272 : : errmsg("cannot alter type of column \"%s\" twice",
15273 : : colName)));
15274 : :
15275 : : /* Look up the target type (should not fail, since prep found it) */
15276 : 805 : typeTuple = typenameType(NULL, typeName, &targettypmod);
15277 : 805 : tform = (Form_pg_type) GETSTRUCT(typeTuple);
15278 : 805 : targettype = tform->oid;
15279 : : /* And the collation */
15280 : 805 : targetcollid = GetColumnDefCollation(NULL, def, targettype);
15281 : :
15282 : : /*
15283 : : * If there is a default expression for the column, get it and ensure we
15284 : : * can coerce it to the new datatype. (We must do this before changing
15285 : : * the column type, because build_column_default itself will try to
15286 : : * coerce, and will not issue the error message we want if it fails.)
15287 : : *
15288 : : * We remove any implicit coercion steps at the top level of the old
15289 : : * default expression; this has been agreed to satisfy the principle of
15290 : : * least surprise. (The conversion to the new column type should act like
15291 : : * it started from what the user sees as the stored expression, and the
15292 : : * implicit coercions aren't going to be shown.)
15293 : : */
15294 [ + + ]: 805 : if (attTup->atthasdef)
15295 : : {
15296 : 68 : defaultexpr = build_column_default(rel, attnum);
15297 : : Assert(defaultexpr);
15298 : 68 : defaultexpr = strip_implicit_coercions(defaultexpr);
15299 : 68 : defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
15300 : : defaultexpr, exprType(defaultexpr),
15301 : : targettype, targettypmod,
15302 : : COERCION_ASSIGNMENT,
15303 : : COERCE_IMPLICIT_CAST,
15304 : : -1);
15305 [ + + ]: 68 : if (defaultexpr == NULL)
15306 : : {
15307 [ - + ]: 4 : if (attTup->attgenerated)
15308 [ # # ]: 0 : ereport(ERROR,
15309 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15310 : : errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
15311 : : colName, format_type_be(targettype))));
15312 : : else
15313 [ + - ]: 4 : ereport(ERROR,
15314 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15315 : : errmsg("default for column \"%s\" cannot be cast automatically to type %s",
15316 : : colName, format_type_be(targettype))));
15317 : : }
15318 : : }
15319 : : else
15320 : 737 : defaultexpr = NULL;
15321 : :
15322 : : /*
15323 : : * Find everything that depends on the column (constraints, indexes, etc),
15324 : : * and record enough information to let us recreate the objects.
15325 : : *
15326 : : * The actual recreation does not happen here, but only after we have
15327 : : * performed all the individual ALTER TYPE operations. We have to save
15328 : : * the info before executing ALTER TYPE, though, else the deparser will
15329 : : * get confused.
15330 : : */
15331 : 801 : RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
15332 : :
15333 : : /*
15334 : : * Now scan for dependencies of this column on other things. The only
15335 : : * things we should find are the dependency on the column datatype and
15336 : : * possibly a collation dependency. Those can be removed.
15337 : : */
15338 : 777 : depRel = table_open(DependRelationId, RowExclusiveLock);
15339 : :
15340 : 777 : ScanKeyInit(&key[0],
15341 : : Anum_pg_depend_classid,
15342 : : BTEqualStrategyNumber, F_OIDEQ,
15343 : : ObjectIdGetDatum(RelationRelationId));
15344 : 777 : ScanKeyInit(&key[1],
15345 : : Anum_pg_depend_objid,
15346 : : BTEqualStrategyNumber, F_OIDEQ,
15347 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15348 : 777 : ScanKeyInit(&key[2],
15349 : : Anum_pg_depend_objsubid,
15350 : : BTEqualStrategyNumber, F_INT4EQ,
15351 : : Int32GetDatum((int32) attnum));
15352 : :
15353 : 777 : scan = systable_beginscan(depRel, DependDependerIndexId, true,
15354 : : NULL, 3, key);
15355 : :
15356 [ + + ]: 779 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15357 : : {
15358 : 2 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15359 : : ObjectAddress foundObject;
15360 : :
15361 : 2 : foundObject.classId = foundDep->refclassid;
15362 : 2 : foundObject.objectId = foundDep->refobjid;
15363 : 2 : foundObject.objectSubId = foundDep->refobjsubid;
15364 : :
15365 [ - + ]: 2 : if (foundDep->deptype != DEPENDENCY_NORMAL)
15366 [ # # ]: 0 : elog(ERROR, "found unexpected dependency type '%c'",
15367 : : foundDep->deptype);
15368 [ + - ]: 2 : if (!(foundDep->refclassid == TypeRelationId &&
15369 [ - + ]: 2 : foundDep->refobjid == attTup->atttypid) &&
15370 [ # # ]: 0 : !(foundDep->refclassid == CollationRelationId &&
15371 [ # # ]: 0 : foundDep->refobjid == attTup->attcollation))
15372 [ # # ]: 0 : elog(ERROR, "found unexpected dependency for column: %s",
15373 : : getObjectDescription(&foundObject, false));
15374 : :
15375 : 2 : CatalogTupleDelete(depRel, &depTup->t_self);
15376 : : }
15377 : :
15378 : 777 : systable_endscan(scan);
15379 : :
15380 : 777 : table_close(depRel, RowExclusiveLock);
15381 : :
15382 : : /*
15383 : : * Here we go --- change the recorded column type and collation. (Note
15384 : : * heapTup is a copy of the syscache entry, so okay to scribble on.) First
15385 : : * fix up the missing value if any.
15386 : : */
15387 [ + + ]: 777 : if (attTup->atthasmissing)
15388 : : {
15389 : : Datum missingval;
15390 : : bool missingNull;
15391 : :
15392 : : /* if rewrite is true the missing value should already be cleared */
15393 : : Assert(tab->rewrite == 0);
15394 : :
15395 : : /* Get the missing value datum */
15396 : 4 : missingval = heap_getattr(heapTup,
15397 : : Anum_pg_attribute_attmissingval,
15398 : : attrelation->rd_att,
15399 : : &missingNull);
15400 : :
15401 : : /* if it's a null array there is nothing to do */
15402 : :
15403 [ + - ]: 4 : if (!missingNull)
15404 : : {
15405 : : /*
15406 : : * Get the datum out of the array and repack it in a new array
15407 : : * built with the new type data. We assume that since the table
15408 : : * doesn't need rewriting, the actual Datum doesn't need to be
15409 : : * changed, only the array metadata.
15410 : : */
15411 : :
15412 : 4 : int one = 1;
15413 : : bool isNull;
15414 : 4 : Datum valuesAtt[Natts_pg_attribute] = {0};
15415 : 4 : bool nullsAtt[Natts_pg_attribute] = {0};
15416 : 4 : bool replacesAtt[Natts_pg_attribute] = {0};
15417 : : HeapTuple newTup;
15418 : :
15419 : 8 : missingval = array_get_element(missingval,
15420 : : 1,
15421 : : &one,
15422 : : 0,
15423 : 4 : attTup->attlen,
15424 : 4 : attTup->attbyval,
15425 : 4 : attTup->attalign,
15426 : : &isNull);
15427 : 4 : missingval = PointerGetDatum(construct_array(&missingval,
15428 : : 1,
15429 : : targettype,
15430 : : tform->typlen,
15431 : : tform->typbyval,
15432 : : tform->typalign));
15433 : :
15434 : 4 : valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
15435 : 4 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
15436 : 4 : nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
15437 : :
15438 : 4 : newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
15439 : : valuesAtt, nullsAtt, replacesAtt);
15440 : 4 : heap_freetuple(heapTup);
15441 : 4 : heapTup = newTup;
15442 : 4 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15443 : : }
15444 : : }
15445 : :
15446 : 777 : attTup->atttypid = targettype;
15447 : 777 : attTup->atttypmod = targettypmod;
15448 : 777 : attTup->attcollation = targetcollid;
15449 [ - + ]: 777 : if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
15450 [ # # ]: 0 : ereport(ERROR,
15451 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
15452 : : errmsg("too many array dimensions"));
15453 : 777 : attTup->attndims = list_length(typeName->arrayBounds);
15454 : 777 : attTup->attlen = tform->typlen;
15455 : 777 : attTup->attbyval = tform->typbyval;
15456 : 777 : attTup->attalign = tform->typalign;
15457 : 777 : attTup->attstorage = tform->typstorage;
15458 : 777 : attTup->attcompression = InvalidCompressionMethod;
15459 : :
15460 : 777 : ReleaseSysCache(typeTuple);
15461 : :
15462 : 777 : CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
15463 : :
15464 : 777 : table_close(attrelation, RowExclusiveLock);
15465 : :
15466 : : /* Install dependencies on new datatype and collation */
15467 : 777 : add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
15468 : 777 : add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
15469 : :
15470 : : /*
15471 : : * Drop any pg_statistic entry for the column, since it's now wrong type
15472 : : */
15473 : 777 : RemoveStatistics(RelationGetRelid(rel), attnum);
15474 : :
15475 [ - + ]: 777 : InvokeObjectPostAlterHook(RelationRelationId,
15476 : : RelationGetRelid(rel), attnum);
15477 : :
15478 : : /*
15479 : : * Update the default, if present, by brute force --- remove and re-add
15480 : : * the default. Probably unsafe to take shortcuts, since the new version
15481 : : * may well have additional dependencies. (It's okay to do this now,
15482 : : * rather than after other ALTER TYPE commands, since the default won't
15483 : : * depend on other column types.)
15484 : : */
15485 [ + + ]: 777 : if (defaultexpr)
15486 : : {
15487 : : /*
15488 : : * If it's a GENERATED default, drop its dependency records, in
15489 : : * particular its INTERNAL dependency on the column, which would
15490 : : * otherwise cause dependency.c to refuse to perform the deletion.
15491 : : */
15492 [ + + ]: 64 : if (attTup->attgenerated)
15493 : : {
15494 : 28 : Oid attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
15495 : :
15496 [ - + ]: 28 : if (!OidIsValid(attrdefoid))
15497 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
15498 : : RelationGetRelid(rel), attnum);
15499 : 28 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
15500 : : }
15501 : :
15502 : : /*
15503 : : * Make updates-so-far visible, particularly the new pg_attribute row
15504 : : * which will be updated again.
15505 : : */
15506 : 64 : CommandCounterIncrement();
15507 : :
15508 : : /*
15509 : : * We use RESTRICT here for safety, but at present we do not expect
15510 : : * anything to depend on the default.
15511 : : */
15512 : 64 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
15513 : : true);
15514 : :
15515 : 64 : (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
15516 : : }
15517 : :
15518 : 777 : ObjectAddressSubSet(address, RelationRelationId,
15519 : : RelationGetRelid(rel), attnum);
15520 : :
15521 : : /* Cleanup */
15522 : 777 : heap_freetuple(heapTup);
15523 : :
15524 : 777 : return address;
15525 : : }
15526 : :
15527 : : /*
15528 : : * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
15529 : : * that depends on the column (constraints, indexes, etc), and record enough
15530 : : * information to let us recreate the objects.
15531 : : */
15532 : : static void
15533 : 982 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
15534 : : Relation rel, AttrNumber attnum, const char *colName)
15535 : : {
15536 : : Relation depRel;
15537 : : ScanKeyData key[3];
15538 : : SysScanDesc scan;
15539 : : HeapTuple depTup;
15540 : :
15541 : : Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
15542 : :
15543 : 982 : depRel = table_open(DependRelationId, RowExclusiveLock);
15544 : :
15545 : 982 : ScanKeyInit(&key[0],
15546 : : Anum_pg_depend_refclassid,
15547 : : BTEqualStrategyNumber, F_OIDEQ,
15548 : : ObjectIdGetDatum(RelationRelationId));
15549 : 982 : ScanKeyInit(&key[1],
15550 : : Anum_pg_depend_refobjid,
15551 : : BTEqualStrategyNumber, F_OIDEQ,
15552 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15553 : 982 : ScanKeyInit(&key[2],
15554 : : Anum_pg_depend_refobjsubid,
15555 : : BTEqualStrategyNumber, F_INT4EQ,
15556 : : Int32GetDatum((int32) attnum));
15557 : :
15558 : 982 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15559 : : NULL, 3, key);
15560 : :
15561 [ + + ]: 2005 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15562 : : {
15563 : 1047 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15564 : : ObjectAddress foundObject;
15565 : :
15566 : 1047 : foundObject.classId = foundDep->classid;
15567 : 1047 : foundObject.objectId = foundDep->objid;
15568 : 1047 : foundObject.objectSubId = foundDep->objsubid;
15569 : :
15570 [ + + - + : 1047 : switch (foundObject.classId)
- - + + -
- ]
15571 : : {
15572 : 193 : case RelationRelationId:
15573 : : {
15574 : 193 : char relKind = get_rel_relkind(foundObject.objectId);
15575 : :
15576 [ + + + + ]: 193 : if (relKind == RELKIND_INDEX ||
15577 : : relKind == RELKIND_PARTITIONED_INDEX)
15578 : : {
15579 : : Assert(foundObject.objectSubId == 0);
15580 : 168 : RememberIndexForRebuilding(foundObject.objectId, tab);
15581 : : }
15582 [ - + ]: 25 : else if (relKind == RELKIND_SEQUENCE)
15583 : : {
15584 : : /*
15585 : : * This must be a SERIAL column's sequence. We need
15586 : : * not do anything to it.
15587 : : */
15588 : : Assert(foundObject.objectSubId == 0);
15589 : : }
15590 : : else
15591 : : {
15592 : : /* Not expecting any other direct dependencies... */
15593 [ # # ]: 0 : elog(ERROR, "unexpected object depending on column: %s",
15594 : : getObjectDescription(&foundObject, false));
15595 : : }
15596 : 193 : break;
15597 : : }
15598 : :
15599 : 528 : case ConstraintRelationId:
15600 : : Assert(foundObject.objectSubId == 0);
15601 : 528 : RememberConstraintForRebuilding(foundObject.objectId, tab);
15602 : 528 : break;
15603 : :
15604 : 0 : case ProcedureRelationId:
15605 : :
15606 : : /*
15607 : : * A new-style SQL function can depend on a column, if that
15608 : : * column is referenced in the parsed function body. Ideally
15609 : : * we'd automatically update the function by deparsing and
15610 : : * reparsing it, but that's risky and might well fail anyhow.
15611 : : * FIXME someday.
15612 : : *
15613 : : * This is only a problem for AT_AlterColumnType, not
15614 : : * AT_SetExpression.
15615 : : */
15616 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15617 [ # # ]: 0 : ereport(ERROR,
15618 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15619 : : errmsg("cannot alter type of a column used by a function or procedure"),
15620 : : errdetail("%s depends on column \"%s\".",
15621 : : getObjectDescription(&foundObject, false),
15622 : : colName)));
15623 : 0 : break;
15624 : :
15625 : 8 : case RewriteRelationId:
15626 : :
15627 : : /*
15628 : : * View/rule bodies have pretty much the same issues as
15629 : : * function bodies. FIXME someday.
15630 : : */
15631 [ + - ]: 8 : if (subtype == AT_AlterColumnType)
15632 [ + - ]: 8 : ereport(ERROR,
15633 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15634 : : errmsg("cannot alter type of a column used by a view or rule"),
15635 : : errdetail("%s depends on column \"%s\".",
15636 : : getObjectDescription(&foundObject, false),
15637 : : colName)));
15638 : 0 : break;
15639 : :
15640 : 0 : case TriggerRelationId:
15641 : :
15642 : : /*
15643 : : * A trigger can depend on a column because the column is
15644 : : * specified as an update target, or because the column is
15645 : : * used in the trigger's WHEN condition. The first case would
15646 : : * not require any extra work, but the second case would
15647 : : * require updating the WHEN expression, which has the same
15648 : : * issues as above. Since we can't easily tell which case
15649 : : * applies, we punt for both. FIXME someday.
15650 : : */
15651 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15652 [ # # ]: 0 : ereport(ERROR,
15653 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15654 : : errmsg("cannot alter type of a column used in a trigger definition"),
15655 : : errdetail("%s depends on column \"%s\".",
15656 : : getObjectDescription(&foundObject, false),
15657 : : colName)));
15658 : 0 : break;
15659 : :
15660 : 0 : case PolicyRelationId:
15661 : :
15662 : : /*
15663 : : * A policy can depend on a column because the column is
15664 : : * specified in the policy's USING or WITH CHECK qual
15665 : : * expressions. It might be possible to rewrite and recheck
15666 : : * the policy expression, but punt for now. It's certainly
15667 : : * easy enough to remove and recreate the policy; still, FIXME
15668 : : * someday.
15669 : : */
15670 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15671 [ # # ]: 0 : ereport(ERROR,
15672 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15673 : : errmsg("cannot alter type of a column used in a policy definition"),
15674 : : errdetail("%s depends on column \"%s\".",
15675 : : getObjectDescription(&foundObject, false),
15676 : : colName)));
15677 : 0 : break;
15678 : :
15679 : 261 : case AttrDefaultRelationId:
15680 : : {
15681 : 261 : ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
15682 : :
15683 [ + - ]: 506 : if (col.objectId == RelationGetRelid(rel) &&
15684 [ + + ]: 261 : col.objectSubId == attnum)
15685 : : {
15686 : : /*
15687 : : * Ignore the column's own default expression. The
15688 : : * caller deals with it.
15689 : : */
15690 : : }
15691 : : else
15692 : : {
15693 : : /*
15694 : : * This must be a reference from the expression of a
15695 : : * generated column elsewhere in the same table.
15696 : : * Changing the type/generated expression of a column
15697 : : * that is used by a generated column is not allowed
15698 : : * by SQL standard, so just punt for now. It might be
15699 : : * doable with some thinking and effort.
15700 : : */
15701 [ + - ]: 16 : if (subtype == AT_AlterColumnType)
15702 [ + - ]: 16 : ereport(ERROR,
15703 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15704 : : errmsg("cannot alter type of a column used by a generated column"),
15705 : : errdetail("Column \"%s\" is used by generated column \"%s\".",
15706 : : colName,
15707 : : get_attname(col.objectId,
15708 : : col.objectSubId,
15709 : : false))));
15710 : : }
15711 : 245 : break;
15712 : : }
15713 : :
15714 : 57 : case StatisticExtRelationId:
15715 : :
15716 : : /*
15717 : : * Give the extended-stats machinery a chance to fix anything
15718 : : * that this column type change would break.
15719 : : */
15720 : 57 : RememberStatisticsForRebuilding(foundObject.objectId, tab);
15721 : 57 : break;
15722 : :
15723 : 0 : case PublicationRelRelationId:
15724 : :
15725 : : /*
15726 : : * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
15727 : : * clause. Same issues as above. FIXME someday.
15728 : : */
15729 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15730 [ # # ]: 0 : ereport(ERROR,
15731 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15732 : : errmsg("cannot alter type of a column used by a publication WHERE clause"),
15733 : : errdetail("%s depends on column \"%s\".",
15734 : : getObjectDescription(&foundObject, false),
15735 : : colName)));
15736 : 0 : break;
15737 : :
15738 : 0 : default:
15739 : :
15740 : : /*
15741 : : * We don't expect any other sorts of objects to depend on a
15742 : : * column.
15743 : : */
15744 [ # # ]: 0 : elog(ERROR, "unexpected object depending on column: %s",
15745 : : getObjectDescription(&foundObject, false));
15746 : : break;
15747 : : }
15748 : : }
15749 : :
15750 : 958 : systable_endscan(scan);
15751 : 958 : table_close(depRel, NoLock);
15752 : 958 : }
15753 : :
15754 : : /*
15755 : : * Record information about dependencies between objects with whole-row Var
15756 : : * references (indexes, check constraints, etc.) and the relation.
15757 : : *
15758 : : * See also RememberAllDependentForRebuilding, which handles non-whole-row Var
15759 : : * references.
15760 : : *
15761 : : * This function currently applies only to ALTER COLUMN SET EXPRESSION.
15762 : : */
15763 : : static void
15764 : 181 : RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, Relation rel)
15765 : : {
15766 : : ScanKeyData skey;
15767 : : Relation pg_constraint;
15768 : : Relation pg_index;
15769 : : SysScanDesc conscan;
15770 : : SysScanDesc indscan;
15771 : : HeapTuple constrTuple;
15772 : : HeapTuple indexTuple;
15773 : : bool isnull;
15774 : :
15775 : : Assert(subtype == AT_SetExpression);
15776 : :
15777 : : /*
15778 : : * Check CHECK constraints with whole-row references first.
15779 : : */
15780 [ + - ]: 181 : if (RelationGetDescr(rel)->constr &&
15781 [ + + ]: 181 : RelationGetDescr(rel)->constr->num_check > 0)
15782 : : {
15783 : 28 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
15784 : :
15785 : 28 : ScanKeyInit(&skey,
15786 : : Anum_pg_constraint_conrelid,
15787 : : BTEqualStrategyNumber, F_OIDEQ,
15788 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15789 : :
15790 : 28 : conscan = systable_beginscan(pg_constraint,
15791 : : ConstraintRelidTypidNameIndexId,
15792 : : true,
15793 : : NULL,
15794 : : 1,
15795 : : &skey);
15796 : :
15797 [ + + ]: 96 : while (HeapTupleIsValid(constrTuple = systable_getnext(conscan)))
15798 : : {
15799 : 68 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(constrTuple);
15800 : : Datum exprDatum;
15801 : :
15802 [ + + ]: 68 : if (conform->contype != CONSTRAINT_CHECK)
15803 : 40 : continue;
15804 : :
15805 : 28 : exprDatum = heap_getattr(constrTuple,
15806 : : Anum_pg_constraint_conbin,
15807 : : RelationGetDescr(pg_constraint),
15808 : : &isnull);
15809 [ - + ]: 28 : if (isnull)
15810 [ # # ]: 0 : elog(ERROR, "null conbin for relation \"%s\"",
15811 : : RelationGetRelationName(rel));
15812 : : else
15813 : : {
15814 : : char *exprString;
15815 : : Node *expr;
15816 : 28 : Bitmapset *expr_attrs = NULL;
15817 : :
15818 : 28 : exprString = TextDatumGetCString(exprDatum);
15819 : 28 : expr = stringToNode(exprString);
15820 : 28 : pfree(exprString);
15821 : :
15822 : : /* Find all attributes referenced */
15823 : 28 : pull_varattnos(expr, 1, &expr_attrs);
15824 : :
15825 : : /*
15826 : : * If the CHECK constraint contains whole-row reference then
15827 : : * remember it.
15828 : : */
15829 [ + + ]: 28 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15830 : : {
15831 : 8 : RememberConstraintForRebuilding(conform->oid, tab);
15832 : : }
15833 : : }
15834 : : }
15835 : 28 : systable_endscan(conscan);
15836 : 28 : table_close(pg_constraint, AccessShareLock);
15837 : : }
15838 : :
15839 : : /*
15840 : : * Now check indexes with whole-row references. Prepare to scan pg_index
15841 : : * for entries having indrelid matching this relation.
15842 : : */
15843 : 181 : ScanKeyInit(&skey,
15844 : : Anum_pg_index_indrelid,
15845 : : BTEqualStrategyNumber, F_OIDEQ,
15846 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15847 : :
15848 : 181 : pg_index = table_open(IndexRelationId, AccessShareLock);
15849 : :
15850 : 181 : indscan = systable_beginscan(pg_index,
15851 : : IndexIndrelidIndexId,
15852 : : true,
15853 : : NULL,
15854 : : 1,
15855 : : &skey);
15856 : :
15857 [ + + ]: 261 : while (HeapTupleIsValid(indexTuple = systable_getnext(indscan)))
15858 : : {
15859 : 80 : Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
15860 : : Datum exprDatum;
15861 : :
15862 : 80 : exprDatum = heap_getattr(indexTuple,
15863 : : Anum_pg_index_indexprs,
15864 : : RelationGetDescr(pg_index),
15865 : : &isnull);
15866 [ + + ]: 80 : if (!isnull)
15867 : : {
15868 : : char *exprString;
15869 : : Node *expr;
15870 : 12 : Bitmapset *expr_attrs = NULL;
15871 : :
15872 : 12 : exprString = TextDatumGetCString(exprDatum);
15873 : 12 : expr = stringToNode(exprString);
15874 : 12 : pfree(exprString);
15875 : :
15876 : : /* Find all attributes referenced */
15877 : 12 : pull_varattnos(expr, 1, &expr_attrs);
15878 : :
15879 : : /*
15880 : : * If the index expression contains a whole-row reference then
15881 : : * remember it.
15882 : : */
15883 [ + + ]: 12 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15884 : : {
15885 : 8 : RememberIndexForRebuilding(index->indexrelid, tab);
15886 : 8 : continue;
15887 : : }
15888 : : }
15889 : :
15890 : 72 : exprDatum = heap_getattr(indexTuple,
15891 : : Anum_pg_index_indpred,
15892 : : RelationGetDescr(pg_index),
15893 : : &isnull);
15894 [ + + ]: 72 : if (!isnull)
15895 : : {
15896 : : char *exprString;
15897 : : Node *expr;
15898 : 20 : Bitmapset *expr_attrs = NULL;
15899 : :
15900 : 20 : exprString = TextDatumGetCString(exprDatum);
15901 : 20 : expr = stringToNode(exprString);
15902 : 20 : pfree(exprString);
15903 : :
15904 : : /* Find all attributes referenced */
15905 : 20 : pull_varattnos(expr, 1, &expr_attrs);
15906 : :
15907 : : /*
15908 : : * If the index predicate expression contains a whole-row
15909 : : * reference then remember it.
15910 : : */
15911 [ + + ]: 20 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15912 : : {
15913 : 16 : RememberIndexForRebuilding(index->indexrelid, tab);
15914 : : }
15915 : : }
15916 : : }
15917 : :
15918 : 181 : systable_endscan(indscan);
15919 : 181 : table_close(pg_index, AccessShareLock);
15920 : 181 : }
15921 : :
15922 : : /*
15923 : : * Subroutine for ATExecAlterColumnType: remember that a replica identity
15924 : : * needs to be reset.
15925 : : */
15926 : : static void
15927 : 331 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
15928 : : {
15929 [ + + ]: 331 : if (!get_index_isreplident(indoid))
15930 : 319 : return;
15931 : :
15932 [ - + ]: 12 : if (tab->replicaIdentityIndex)
15933 [ # # ]: 0 : elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
15934 : :
15935 : 12 : tab->replicaIdentityIndex = get_rel_name(indoid);
15936 : : }
15937 : :
15938 : : /*
15939 : : * Subroutine for ATExecAlterColumnType: remember any clustered index.
15940 : : */
15941 : : static void
15942 : 331 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
15943 : : {
15944 [ + + ]: 331 : if (!get_index_isclustered(indoid))
15945 : 319 : return;
15946 : :
15947 [ - + ]: 12 : if (tab->clusterOnIndex)
15948 [ # # ]: 0 : elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
15949 : :
15950 : 12 : tab->clusterOnIndex = get_rel_name(indoid);
15951 : : }
15952 : :
15953 : : /*
15954 : : * Subroutine for ATExecAlterColumnType: remember that a constraint needs
15955 : : * to be rebuilt (which we might already know).
15956 : : */
15957 : : static void
15958 : 544 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
15959 : : {
15960 : : /*
15961 : : * This de-duplication check is critical for two independent reasons: we
15962 : : * mustn't try to recreate the same constraint twice, and if a constraint
15963 : : * depends on more than one column whose type is to be altered, we must
15964 : : * capture its definition string before applying any of the column type
15965 : : * changes. ruleutils.c will get confused if we ask again later.
15966 : : */
15967 [ + + ]: 544 : if (!list_member_oid(tab->changedConstraintOids, conoid))
15968 : : {
15969 : : /* OK, capture the constraint's existing definition string */
15970 : 468 : char *defstring = pg_get_constraintdef_command(conoid);
15971 : : Oid indoid;
15972 : :
15973 : : /*
15974 : : * It is critical to create not-null constraints ahead of primary key
15975 : : * indexes; otherwise, the not-null constraint would be created by the
15976 : : * primary key, and the constraint name would be wrong.
15977 : : */
15978 [ + + ]: 468 : if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
15979 : : {
15980 : 163 : tab->changedConstraintOids = lcons_oid(conoid,
15981 : : tab->changedConstraintOids);
15982 : 163 : tab->changedConstraintDefs = lcons(defstring,
15983 : : tab->changedConstraintDefs);
15984 : : }
15985 : : else
15986 : : {
15987 : :
15988 : 305 : tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
15989 : : conoid);
15990 : 305 : tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
15991 : : defstring);
15992 : : }
15993 : :
15994 : : /*
15995 : : * For the index of a constraint, if any, remember if it is used for
15996 : : * the table's replica identity or if it is a clustered index, so that
15997 : : * ATPostAlterTypeCleanup() can queue up commands necessary to restore
15998 : : * those properties.
15999 : : */
16000 : 468 : indoid = get_constraint_index(conoid);
16001 [ + + ]: 468 : if (OidIsValid(indoid))
16002 : : {
16003 : 152 : RememberReplicaIdentityForRebuilding(indoid, tab);
16004 : 152 : RememberClusterOnForRebuilding(indoid, tab);
16005 : : }
16006 : : }
16007 : 544 : }
16008 : :
16009 : : /*
16010 : : * Subroutine for ATExecAlterColumnType: remember that an index needs
16011 : : * to be rebuilt (which we might already know).
16012 : : */
16013 : : static void
16014 : 192 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
16015 : : {
16016 : : /*
16017 : : * This de-duplication check is critical for two independent reasons: we
16018 : : * mustn't try to recreate the same index twice, and if an index depends
16019 : : * on more than one column whose type is to be altered, we must capture
16020 : : * its definition string before applying any of the column type changes.
16021 : : * ruleutils.c will get confused if we ask again later.
16022 : : */
16023 [ + + ]: 192 : if (!list_member_oid(tab->changedIndexOids, indoid))
16024 : : {
16025 : : /*
16026 : : * Before adding it as an index-to-rebuild, we'd better see if it
16027 : : * belongs to a constraint, and if so rebuild the constraint instead.
16028 : : * Typically this check fails, because constraint indexes normally
16029 : : * have only dependencies on their constraint. But it's possible for
16030 : : * such an index to also have direct dependencies on table columns,
16031 : : * for example with a partial exclusion constraint.
16032 : : */
16033 : 187 : Oid conoid = get_index_constraint(indoid);
16034 : :
16035 [ + + ]: 187 : if (OidIsValid(conoid))
16036 : : {
16037 : 8 : RememberConstraintForRebuilding(conoid, tab);
16038 : : }
16039 : : else
16040 : : {
16041 : : /* OK, capture the index's existing definition string */
16042 : 179 : char *defstring = pg_get_indexdef_string(indoid);
16043 : :
16044 : 179 : tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
16045 : : indoid);
16046 : 179 : tab->changedIndexDefs = lappend(tab->changedIndexDefs,
16047 : : defstring);
16048 : :
16049 : : /*
16050 : : * Remember if this index is used for the table's replica identity
16051 : : * or if it is a clustered index, so that ATPostAlterTypeCleanup()
16052 : : * can queue up commands necessary to restore those properties.
16053 : : */
16054 : 179 : RememberReplicaIdentityForRebuilding(indoid, tab);
16055 : 179 : RememberClusterOnForRebuilding(indoid, tab);
16056 : : }
16057 : : }
16058 : 192 : }
16059 : :
16060 : : /*
16061 : : * Subroutine for ATExecAlterColumnType: remember that a statistics object
16062 : : * needs to be rebuilt (which we might already know).
16063 : : */
16064 : : static void
16065 : 57 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
16066 : : {
16067 : : /*
16068 : : * This de-duplication check is critical for two independent reasons: we
16069 : : * mustn't try to recreate the same statistics object twice, and if the
16070 : : * statistics object depends on more than one column whose type is to be
16071 : : * altered, we must capture its definition string before applying any of
16072 : : * the type changes. ruleutils.c will get confused if we ask again later.
16073 : : */
16074 [ + - ]: 57 : if (!list_member_oid(tab->changedStatisticsOids, stxoid))
16075 : : {
16076 : : /* OK, capture the statistics object's existing definition string */
16077 : 57 : char *defstring = pg_get_statisticsobjdef_string(stxoid);
16078 : : HeapTuple tup;
16079 : : Form_pg_statistic_ext statext;
16080 : :
16081 : 57 : tup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
16082 : :
16083 [ - + ]: 57 : if (!HeapTupleIsValid(tup)) /* should not happen */
16084 [ # # ]: 0 : elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
16085 : :
16086 : 57 : statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
16087 : :
16088 : 57 : tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
16089 : : stxoid);
16090 : 57 : tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
16091 : : defstring);
16092 : :
16093 : 57 : tab->changedStatisticsOwners = lappend_oid(tab->changedStatisticsOwners,
16094 : : statext->stxowner);
16095 : :
16096 : 57 : ReleaseSysCache(tup);
16097 : : }
16098 : 57 : }
16099 : :
16100 : : /*
16101 : : * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
16102 : : * operations for a particular relation. We have to drop and recreate all the
16103 : : * indexes and constraints that depend on the altered columns. We do the
16104 : : * actual dropping here, but re-creation is managed by adding work queue
16105 : : * entries to do those steps later.
16106 : : */
16107 : : static void
16108 : 926 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
16109 : : {
16110 : : ObjectAddress obj;
16111 : : ObjectAddresses *objects;
16112 : : ListCell *def_item;
16113 : : ListCell *oid_item;
16114 : : ListCell *owner_item;
16115 : :
16116 : : /*
16117 : : * Collect all the constraints and indexes to drop so we can process them
16118 : : * in a single call. That way we don't have to worry about dependencies
16119 : : * among them.
16120 : : */
16121 : 926 : objects = new_object_addresses();
16122 : :
16123 : : /*
16124 : : * Re-parse the index and constraint definitions, and attach them to the
16125 : : * appropriate work queue entries. We do this before dropping because in
16126 : : * the case of a constraint on another table, we might not yet have
16127 : : * exclusive lock on the table the constraint is attached to, and we need
16128 : : * to get that before reparsing/dropping. (That's possible at least for
16129 : : * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
16130 : : * requires a dependency on the target table's composite type in the other
16131 : : * table's constraint expressions.)
16132 : : *
16133 : : * We can't rely on the output of deparsing to tell us which relation to
16134 : : * operate on, because concurrent activity might have made the name
16135 : : * resolve differently. Instead, we've got to use the OID of the
16136 : : * constraint or index we're processing to figure out which relation to
16137 : : * operate on.
16138 : : */
16139 [ + + + + : 1394 : forboth(oid_item, tab->changedConstraintOids,
+ + + + +
+ + - +
+ ]
16140 : : def_item, tab->changedConstraintDefs)
16141 : : {
16142 : 468 : Oid oldId = lfirst_oid(oid_item);
16143 : : HeapTuple tup;
16144 : : Form_pg_constraint con;
16145 : : Oid relid;
16146 : : Oid confrelid;
16147 : : bool conislocal;
16148 : :
16149 : 468 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16150 [ - + ]: 468 : if (!HeapTupleIsValid(tup)) /* should not happen */
16151 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16152 : 468 : con = (Form_pg_constraint) GETSTRUCT(tup);
16153 [ + + ]: 468 : if (OidIsValid(con->conrelid))
16154 : 455 : relid = con->conrelid;
16155 : : else
16156 : : {
16157 : : /* must be a domain constraint */
16158 : 13 : relid = get_typ_typrelid(getBaseType(con->contypid));
16159 [ - + ]: 13 : if (!OidIsValid(relid))
16160 [ # # ]: 0 : elog(ERROR, "could not identify relation associated with constraint %u", oldId);
16161 : : }
16162 : 468 : confrelid = con->confrelid;
16163 : 468 : conislocal = con->conislocal;
16164 : 468 : ReleaseSysCache(tup);
16165 : :
16166 : 468 : ObjectAddressSet(obj, ConstraintRelationId, oldId);
16167 : 468 : add_exact_object_address(&obj, objects);
16168 : :
16169 : : /*
16170 : : * If the constraint is inherited (only), we don't want to inject a
16171 : : * new definition here; it'll get recreated when
16172 : : * ATAddCheckNNConstraint recurses from adding the parent table's
16173 : : * constraint. But we had to carry the info this far so that we can
16174 : : * drop the constraint below.
16175 : : */
16176 [ + + ]: 468 : if (!conislocal)
16177 : 34 : continue;
16178 : :
16179 : : /*
16180 : : * When rebuilding another table's constraint that references the
16181 : : * table we're modifying, we might not yet have any lock on the other
16182 : : * table, so get one now. We'll need AccessExclusiveLock for the DROP
16183 : : * CONSTRAINT step, so there's no value in asking for anything weaker.
16184 : : */
16185 [ + + ]: 434 : if (relid != tab->relid)
16186 : 36 : LockRelationOid(relid, AccessExclusiveLock);
16187 : :
16188 : 434 : ATPostAlterTypeParse(oldId, relid, confrelid, InvalidOid,
16189 : 434 : (char *) lfirst(def_item),
16190 : 434 : wqueue, lockmode, tab->rewrite);
16191 : : }
16192 [ + + + + : 1105 : forboth(oid_item, tab->changedIndexOids,
+ + + + +
+ + - +
+ ]
16193 : : def_item, tab->changedIndexDefs)
16194 : : {
16195 : 179 : Oid oldId = lfirst_oid(oid_item);
16196 : : Oid relid;
16197 : :
16198 : 179 : relid = IndexGetRelation(oldId, false);
16199 : :
16200 : : /*
16201 : : * As above, make sure we have lock on the index's table if it's not
16202 : : * the same table.
16203 : : */
16204 [ + + ]: 179 : if (relid != tab->relid)
16205 : 12 : LockRelationOid(relid, AccessExclusiveLock);
16206 : :
16207 : 179 : ATPostAlterTypeParse(oldId, relid, InvalidOid, InvalidOid,
16208 : 179 : (char *) lfirst(def_item),
16209 : 179 : wqueue, lockmode, tab->rewrite);
16210 : :
16211 : 179 : ObjectAddressSet(obj, RelationRelationId, oldId);
16212 : 179 : add_exact_object_address(&obj, objects);
16213 : : }
16214 : :
16215 : : /* add dependencies for new statistics */
16216 [ + + + + : 983 : forthree(oid_item, tab->changedStatisticsOids,
+ + + + +
+ + + + +
+ - + - +
+ ]
16217 : : def_item, tab->changedStatisticsDefs,
16218 : : owner_item, tab->changedStatisticsOwners)
16219 : : {
16220 : 57 : Oid oldId = lfirst_oid(oid_item);
16221 : : Oid relid;
16222 : :
16223 : 57 : relid = StatisticsGetRelation(oldId, false);
16224 : :
16225 : : /*
16226 : : * As above, make sure we have lock on the statistics object's table
16227 : : * if it's not the same table. However, we take
16228 : : * ShareUpdateExclusiveLock here, aligning with the lock level used in
16229 : : * CreateStatistics and RemoveStatisticsById.
16230 : : *
16231 : : * CAUTION: this should be done after all cases that grab
16232 : : * AccessExclusiveLock, else we risk causing deadlock due to needing
16233 : : * to promote our table lock.
16234 : : */
16235 [ + + ]: 57 : if (relid != tab->relid)
16236 : 12 : LockRelationOid(relid, ShareUpdateExclusiveLock);
16237 : :
16238 : 57 : ATPostAlterTypeParse(oldId, relid, InvalidOid, lfirst_oid(owner_item),
16239 : 57 : (char *) lfirst(def_item),
16240 : 57 : wqueue, lockmode, tab->rewrite);
16241 : :
16242 : 57 : ObjectAddressSet(obj, StatisticExtRelationId, oldId);
16243 : 57 : add_exact_object_address(&obj, objects);
16244 : : }
16245 : :
16246 : : /*
16247 : : * Queue up command to restore replica identity index marking
16248 : : */
16249 [ + + ]: 926 : if (tab->replicaIdentityIndex)
16250 : : {
16251 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16252 : 12 : ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
16253 : :
16254 : 12 : subcmd->identity_type = REPLICA_IDENTITY_INDEX;
16255 : 12 : subcmd->name = tab->replicaIdentityIndex;
16256 : 12 : cmd->subtype = AT_ReplicaIdentity;
16257 : 12 : cmd->def = (Node *) subcmd;
16258 : :
16259 : : /* do it after indexes and constraints */
16260 : 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16261 : 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16262 : : }
16263 : :
16264 : : /*
16265 : : * Queue up command to restore marking of index used for cluster.
16266 : : */
16267 [ + + ]: 926 : if (tab->clusterOnIndex)
16268 : : {
16269 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16270 : :
16271 : 12 : cmd->subtype = AT_ClusterOn;
16272 : 12 : cmd->name = tab->clusterOnIndex;
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 : : * It should be okay to use DROP_RESTRICT here, since nothing else should
16281 : : * be depending on these objects.
16282 : : */
16283 : 926 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
16284 : :
16285 : 926 : free_object_addresses(objects);
16286 : :
16287 : : /*
16288 : : * The objects will get recreated during subsequent passes over the work
16289 : : * queue.
16290 : : */
16291 : 926 : }
16292 : :
16293 : : /*
16294 : : * Parse the previously-saved definition string for a constraint, index or
16295 : : * statistics object against the newly-established column data type(s), and
16296 : : * queue up the resulting command parsetrees for execution.
16297 : : *
16298 : : * This might fail if, for example, you have a WHERE clause that uses an
16299 : : * operator that's not available for the new column type.
16300 : : */
16301 : : static void
16302 : 670 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
16303 : : const char *cmdstring, List **wqueue, LOCKMODE lockmode,
16304 : : bool rewrite)
16305 : : {
16306 : : List *raw_parsetree_list;
16307 : : List *querytree_list;
16308 : : ListCell *list_item;
16309 : : Relation rel;
16310 : :
16311 : : /*
16312 : : * We expect that we will get only ALTER TABLE and CREATE INDEX
16313 : : * statements. Hence, there is no need to pass them through
16314 : : * parse_analyze_*() or the rewriter, but instead we need to pass them
16315 : : * through parse_utilcmd.c to make them ready for execution.
16316 : : */
16317 : 670 : raw_parsetree_list = raw_parser(cmdstring, RAW_PARSE_DEFAULT);
16318 : 670 : querytree_list = NIL;
16319 [ + - + + : 1340 : foreach(list_item, raw_parsetree_list)
+ + ]
16320 : : {
16321 : 670 : RawStmt *rs = lfirst_node(RawStmt, list_item);
16322 : 670 : Node *stmt = rs->stmt;
16323 : :
16324 [ + + ]: 670 : if (IsA(stmt, IndexStmt))
16325 : 179 : querytree_list = lappend(querytree_list,
16326 : 179 : transformIndexStmt(oldRelId,
16327 : : (IndexStmt *) stmt,
16328 : : cmdstring));
16329 [ + + ]: 491 : else if (IsA(stmt, AlterTableStmt))
16330 : : {
16331 : : List *beforeStmts;
16332 : : List *afterStmts;
16333 : :
16334 : 421 : stmt = (Node *) transformAlterTableStmt(oldRelId,
16335 : : (AlterTableStmt *) stmt,
16336 : : cmdstring,
16337 : : &beforeStmts,
16338 : : &afterStmts);
16339 : 421 : querytree_list = list_concat(querytree_list, beforeStmts);
16340 : 421 : querytree_list = lappend(querytree_list, stmt);
16341 : 421 : querytree_list = list_concat(querytree_list, afterStmts);
16342 : : }
16343 [ + + ]: 70 : else if (IsA(stmt, CreateStatsStmt))
16344 : : {
16345 : : CreateStatsStmt *csstmt;
16346 : :
16347 : 57 : csstmt = transformStatsStmt(oldRelId, (CreateStatsStmt *) stmt, cmdstring);
16348 : 57 : csstmt->owner = ownerId;
16349 : :
16350 : 57 : querytree_list = lappend(querytree_list, csstmt);
16351 : : }
16352 : : else
16353 : 13 : querytree_list = lappend(querytree_list, stmt);
16354 : : }
16355 : :
16356 : : /* Caller should already have acquired whatever lock we need. */
16357 : 670 : rel = relation_open(oldRelId, NoLock);
16358 : :
16359 : : /*
16360 : : * Attach each generated command to the proper place in the work queue.
16361 : : * Note this could result in creation of entirely new work-queue entries.
16362 : : *
16363 : : * Also note that we have to tweak the command subtypes, because it turns
16364 : : * out that re-creation of indexes and constraints has to act a bit
16365 : : * differently from initial creation.
16366 : : */
16367 [ + - + + : 1340 : foreach(list_item, querytree_list)
+ + ]
16368 : : {
16369 : 670 : Node *stm = (Node *) lfirst(list_item);
16370 : : AlteredTableInfo *tab;
16371 : :
16372 : 670 : tab = ATGetQueueEntry(wqueue, rel);
16373 : :
16374 [ + + ]: 670 : if (IsA(stm, IndexStmt))
16375 : : {
16376 : 179 : IndexStmt *stmt = (IndexStmt *) stm;
16377 : : AlterTableCmd *newcmd;
16378 : :
16379 [ + + ]: 179 : if (!rewrite)
16380 : 53 : TryReuseIndex(oldId, stmt);
16381 : 179 : stmt->reset_default_tblspc = true;
16382 : : /* keep the index's comment */
16383 : 179 : stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
16384 : :
16385 : 179 : newcmd = makeNode(AlterTableCmd);
16386 : 179 : newcmd->subtype = AT_ReAddIndex;
16387 : 179 : newcmd->def = (Node *) stmt;
16388 : 179 : tab->subcmds[AT_PASS_OLD_INDEX] =
16389 : 179 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
16390 : : }
16391 [ + + ]: 491 : else if (IsA(stm, AlterTableStmt))
16392 : : {
16393 : 421 : AlterTableStmt *stmt = (AlterTableStmt *) stm;
16394 : : ListCell *lcmd;
16395 : :
16396 [ + - + + : 842 : foreach(lcmd, stmt->cmds)
+ + ]
16397 : : {
16398 : 421 : AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
16399 : :
16400 [ + + ]: 421 : if (cmd->subtype == AT_AddIndex)
16401 : : {
16402 : : IndexStmt *indstmt;
16403 : : Oid indoid;
16404 : :
16405 : 152 : indstmt = castNode(IndexStmt, cmd->def);
16406 : 152 : indoid = get_constraint_index(oldId);
16407 : :
16408 [ + + ]: 152 : if (!rewrite)
16409 : 32 : TryReuseIndex(indoid, indstmt);
16410 : : /* keep any comment on the index */
16411 : 152 : indstmt->idxcomment = GetComment(indoid,
16412 : : RelationRelationId, 0);
16413 : 152 : indstmt->reset_default_tblspc = true;
16414 : :
16415 : 152 : cmd->subtype = AT_ReAddIndex;
16416 : 152 : tab->subcmds[AT_PASS_OLD_INDEX] =
16417 : 152 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
16418 : :
16419 : : /* recreate any comment on the constraint */
16420 : 152 : RebuildConstraintComment(tab,
16421 : : AT_PASS_OLD_INDEX,
16422 : : oldId,
16423 : : rel,
16424 : : NIL,
16425 : 152 : indstmt->idxname);
16426 : : }
16427 [ + - ]: 269 : else if (cmd->subtype == AT_AddConstraint)
16428 : : {
16429 : 269 : Constraint *con = castNode(Constraint, cmd->def);
16430 : :
16431 : 269 : con->old_pktable_oid = refRelId;
16432 : : /* rewriting neither side of a FK */
16433 [ + + ]: 269 : if (con->contype == CONSTR_FOREIGN &&
16434 [ + + + - ]: 48 : !rewrite && tab->rewrite == 0)
16435 : 4 : TryReuseForeignKey(oldId, con);
16436 : 269 : con->reset_default_tblspc = true;
16437 : 269 : cmd->subtype = AT_ReAddConstraint;
16438 : 269 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16439 : 269 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16440 : :
16441 : : /*
16442 : : * Recreate any comment on the constraint. If we have
16443 : : * recreated a primary key, then transformTableConstraint
16444 : : * has added an unnamed not-null constraint here; skip
16445 : : * this in that case.
16446 : : */
16447 [ + - ]: 269 : if (con->conname)
16448 : 269 : RebuildConstraintComment(tab,
16449 : : AT_PASS_OLD_CONSTR,
16450 : : oldId,
16451 : : rel,
16452 : : NIL,
16453 : 269 : con->conname);
16454 : : else
16455 : : Assert(con->contype == CONSTR_NOTNULL);
16456 : : }
16457 : : else
16458 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
16459 : : (int) cmd->subtype);
16460 : : }
16461 : : }
16462 [ + + ]: 70 : else if (IsA(stm, AlterDomainStmt))
16463 : : {
16464 : 13 : AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
16465 : :
16466 [ + - ]: 13 : if (stmt->subtype == AD_AddConstraint)
16467 : : {
16468 : 13 : Constraint *con = castNode(Constraint, stmt->def);
16469 : 13 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16470 : :
16471 : 13 : cmd->subtype = AT_ReAddDomainConstraint;
16472 : 13 : cmd->def = (Node *) stmt;
16473 : 13 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16474 : 13 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16475 : :
16476 : : /* recreate any comment on the constraint */
16477 : 13 : RebuildConstraintComment(tab,
16478 : : AT_PASS_OLD_CONSTR,
16479 : : oldId,
16480 : : NULL,
16481 : : stmt->typeName,
16482 : 13 : con->conname);
16483 : : }
16484 : : else
16485 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
16486 : : (int) stmt->subtype);
16487 : : }
16488 [ + - ]: 57 : else if (IsA(stm, CreateStatsStmt))
16489 : : {
16490 : 57 : CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
16491 : : AlterTableCmd *newcmd;
16492 : :
16493 : : /* keep the statistics object's comment */
16494 : 57 : stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
16495 : :
16496 : 57 : newcmd = makeNode(AlterTableCmd);
16497 : 57 : newcmd->subtype = AT_ReAddStatistics;
16498 : 57 : newcmd->def = (Node *) stmt;
16499 : 57 : tab->subcmds[AT_PASS_MISC] =
16500 : 57 : lappend(tab->subcmds[AT_PASS_MISC], newcmd);
16501 : : }
16502 : : else
16503 [ # # ]: 0 : elog(ERROR, "unexpected statement type: %d",
16504 : : (int) nodeTag(stm));
16505 : : }
16506 : :
16507 : 670 : relation_close(rel, NoLock);
16508 : 670 : }
16509 : :
16510 : : /*
16511 : : * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
16512 : : * for a table or domain constraint that is being rebuilt.
16513 : : *
16514 : : * objid is the OID of the constraint.
16515 : : * Pass "rel" for a table constraint, or "domname" (domain's qualified name
16516 : : * as a string list) for a domain constraint.
16517 : : * (We could dig that info, as well as the conname, out of the pg_constraint
16518 : : * entry; but callers already have them so might as well pass them.)
16519 : : */
16520 : : static void
16521 : 434 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
16522 : : Relation rel, List *domname,
16523 : : const char *conname)
16524 : : {
16525 : : CommentStmt *cmd;
16526 : : char *comment_str;
16527 : : AlterTableCmd *newcmd;
16528 : :
16529 : : /* Look for comment for object wanted, and leave if none */
16530 : 434 : comment_str = GetComment(objid, ConstraintRelationId, 0);
16531 [ + + ]: 434 : if (comment_str == NULL)
16532 : 374 : return;
16533 : :
16534 : : /* Build CommentStmt node, copying all input data for safety */
16535 : 60 : cmd = makeNode(CommentStmt);
16536 [ + + ]: 60 : if (rel)
16537 : : {
16538 : 52 : cmd->objtype = OBJECT_TABCONSTRAINT;
16539 : 52 : cmd->object = (Node *)
16540 : 52 : list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
16541 : : makeString(pstrdup(RelationGetRelationName(rel))),
16542 : : makeString(pstrdup(conname)));
16543 : : }
16544 : : else
16545 : : {
16546 : 8 : cmd->objtype = OBJECT_DOMCONSTRAINT;
16547 : 8 : cmd->object = (Node *)
16548 : 8 : list_make2(makeTypeNameFromNameList(copyObject(domname)),
16549 : : makeString(pstrdup(conname)));
16550 : : }
16551 : 60 : cmd->comment = comment_str;
16552 : :
16553 : : /* Append it to list of commands */
16554 : 60 : newcmd = makeNode(AlterTableCmd);
16555 : 60 : newcmd->subtype = AT_ReAddComment;
16556 : 60 : newcmd->def = (Node *) cmd;
16557 : 60 : tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
16558 : : }
16559 : :
16560 : : /*
16561 : : * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
16562 : : * for the real analysis, then mutates the IndexStmt based on that verdict.
16563 : : */
16564 : : static void
16565 : 85 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
16566 : : {
16567 [ + + ]: 85 : if (CheckIndexCompatible(oldId,
16568 : 85 : stmt->accessMethod,
16569 : 85 : stmt->indexParams,
16570 : 85 : stmt->excludeOpNames,
16571 : 85 : stmt->iswithoutoverlaps))
16572 : : {
16573 : 69 : Relation irel = index_open(oldId, NoLock);
16574 : :
16575 : : /* If it's a partitioned index, there is no storage to share. */
16576 [ + + ]: 69 : if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
16577 : : {
16578 : 49 : stmt->oldNumber = irel->rd_locator.relNumber;
16579 : 49 : stmt->oldCreateSubid = irel->rd_createSubid;
16580 : 49 : stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
16581 : : }
16582 : 69 : index_close(irel, NoLock);
16583 : : }
16584 : 85 : }
16585 : :
16586 : : /*
16587 : : * Subroutine for ATPostAlterTypeParse().
16588 : : *
16589 : : * Stash the old P-F equality operator into the Constraint node, for possible
16590 : : * use by ATAddForeignKeyConstraint() in determining whether revalidation of
16591 : : * this constraint can be skipped.
16592 : : */
16593 : : static void
16594 : 4 : TryReuseForeignKey(Oid oldId, Constraint *con)
16595 : : {
16596 : : HeapTuple tup;
16597 : : Datum adatum;
16598 : : ArrayType *arr;
16599 : : Oid *rawarr;
16600 : : int numkeys;
16601 : : int i;
16602 : :
16603 : : Assert(con->contype == CONSTR_FOREIGN);
16604 : : Assert(con->old_conpfeqop == NIL); /* already prepared this node */
16605 : :
16606 : 4 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16607 [ - + ]: 4 : if (!HeapTupleIsValid(tup)) /* should not happen */
16608 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16609 : :
16610 : 4 : adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
16611 : : Anum_pg_constraint_conpfeqop);
16612 : 4 : arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
16613 : 4 : numkeys = ARR_DIMS(arr)[0];
16614 : : /* test follows the one in ri_FetchConstraintInfo() */
16615 [ + - ]: 4 : if (ARR_NDIM(arr) != 1 ||
16616 [ + - ]: 4 : ARR_HASNULL(arr) ||
16617 [ - + ]: 4 : ARR_ELEMTYPE(arr) != OIDOID)
16618 [ # # ]: 0 : elog(ERROR, "conpfeqop is not a 1-D Oid array");
16619 [ - + ]: 4 : rawarr = (Oid *) ARR_DATA_PTR(arr);
16620 : :
16621 : : /* stash a List of the operator Oids in our Constraint node */
16622 [ + + ]: 8 : for (i = 0; i < numkeys; i++)
16623 : 4 : con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
16624 : :
16625 : 4 : ReleaseSysCache(tup);
16626 : 4 : }
16627 : :
16628 : : /*
16629 : : * ALTER COLUMN .. OPTIONS ( ... )
16630 : : *
16631 : : * Returns the address of the modified column
16632 : : */
16633 : : static ObjectAddress
16634 : 94 : ATExecAlterColumnGenericOptions(Relation rel,
16635 : : const char *colName,
16636 : : List *options,
16637 : : LOCKMODE lockmode)
16638 : : {
16639 : : Relation ftrel;
16640 : : Relation attrel;
16641 : : ForeignServer *server;
16642 : : ForeignDataWrapper *fdw;
16643 : : HeapTuple tuple;
16644 : : HeapTuple newtuple;
16645 : : bool isnull;
16646 : : Datum repl_val[Natts_pg_attribute];
16647 : : bool repl_null[Natts_pg_attribute];
16648 : : bool repl_repl[Natts_pg_attribute];
16649 : : Datum datum;
16650 : : Form_pg_foreign_table fttableform;
16651 : : Form_pg_attribute atttableform;
16652 : : AttrNumber attnum;
16653 : : ObjectAddress address;
16654 : :
16655 [ - + ]: 94 : if (options == NIL)
16656 : 0 : return InvalidObjectAddress;
16657 : :
16658 : : /* First, determine FDW validator associated to the foreign table. */
16659 : 94 : ftrel = table_open(ForeignTableRelationId, AccessShareLock);
16660 : 94 : tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
16661 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
16662 [ # # ]: 0 : ereport(ERROR,
16663 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
16664 : : errmsg("foreign table \"%s\" does not exist",
16665 : : RelationGetRelationName(rel))));
16666 : 94 : fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
16667 : 94 : server = GetForeignServer(fttableform->ftserver);
16668 : 94 : fdw = GetForeignDataWrapper(server->fdwid);
16669 : :
16670 : 94 : table_close(ftrel, AccessShareLock);
16671 : 94 : ReleaseSysCache(tuple);
16672 : :
16673 : 94 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
16674 : 94 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
16675 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
16676 [ # # ]: 0 : ereport(ERROR,
16677 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
16678 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
16679 : : colName, RelationGetRelationName(rel))));
16680 : :
16681 : : /* Prevent them from altering a system attribute */
16682 : 94 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
16683 : 94 : attnum = atttableform->attnum;
16684 [ + + ]: 94 : if (attnum <= 0)
16685 [ + - ]: 4 : ereport(ERROR,
16686 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16687 : : errmsg("cannot alter system column \"%s\"", colName)));
16688 : :
16689 : :
16690 : : /* Initialize buffers for new tuple values */
16691 : 90 : memset(repl_val, 0, sizeof(repl_val));
16692 : 90 : memset(repl_null, false, sizeof(repl_null));
16693 : 90 : memset(repl_repl, false, sizeof(repl_repl));
16694 : :
16695 : : /* Extract the current options */
16696 : 90 : datum = SysCacheGetAttr(ATTNAME,
16697 : : tuple,
16698 : : Anum_pg_attribute_attfdwoptions,
16699 : : &isnull);
16700 [ + + ]: 90 : if (isnull)
16701 : 84 : datum = PointerGetDatum(NULL);
16702 : :
16703 : : /* Transform the options */
16704 : 90 : datum = transformGenericOptions(AttributeRelationId,
16705 : : datum,
16706 : : options,
16707 : : fdw->fdwvalidator);
16708 : :
16709 [ + - ]: 90 : if (DatumGetPointer(datum) != NULL)
16710 : 90 : repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
16711 : : else
16712 : 0 : repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
16713 : :
16714 : 90 : repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
16715 : :
16716 : : /* Everything looks good - update the tuple */
16717 : :
16718 : 90 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
16719 : : repl_val, repl_null, repl_repl);
16720 : :
16721 : 90 : CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
16722 : :
16723 [ - + ]: 90 : InvokeObjectPostAlterHook(RelationRelationId,
16724 : : RelationGetRelid(rel),
16725 : : atttableform->attnum);
16726 : 90 : ObjectAddressSubSet(address, RelationRelationId,
16727 : : RelationGetRelid(rel), attnum);
16728 : :
16729 : 90 : ReleaseSysCache(tuple);
16730 : :
16731 : 90 : table_close(attrel, RowExclusiveLock);
16732 : :
16733 : 90 : heap_freetuple(newtuple);
16734 : :
16735 : 90 : return address;
16736 : : }
16737 : :
16738 : : /*
16739 : : * ALTER TABLE OWNER
16740 : : *
16741 : : * recursing is true if we are recursing from a table to its indexes,
16742 : : * sequences, or toast table. We don't allow the ownership of those things to
16743 : : * be changed separately from the parent table. Also, we can skip permission
16744 : : * checks (this is necessary not just an optimization, else we'd fail to
16745 : : * handle toast tables properly).
16746 : : *
16747 : : * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
16748 : : * free-standing composite type.
16749 : : */
16750 : : void
16751 : 1353 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
16752 : : {
16753 : : Relation target_rel;
16754 : : Relation class_rel;
16755 : : HeapTuple tuple;
16756 : : Form_pg_class tuple_class;
16757 : :
16758 : : /*
16759 : : * Get exclusive lock till end of transaction on the target table. Use
16760 : : * relation_open so that we can work on indexes and sequences.
16761 : : */
16762 : 1353 : target_rel = relation_open(relationOid, lockmode);
16763 : :
16764 : : /* Get its pg_class tuple, too */
16765 : 1353 : class_rel = table_open(RelationRelationId, RowExclusiveLock);
16766 : :
16767 : 1353 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16768 [ - + ]: 1353 : if (!HeapTupleIsValid(tuple))
16769 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationOid);
16770 : 1353 : tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16771 : :
16772 : : /* Can we change the ownership of this tuple? */
16773 [ + + + + : 1353 : switch (tuple_class->relkind)
+ + - ]
16774 : : {
16775 : 1102 : case RELKIND_RELATION:
16776 : : case RELKIND_VIEW:
16777 : : case RELKIND_MATVIEW:
16778 : : case RELKIND_FOREIGN_TABLE:
16779 : : case RELKIND_PARTITIONED_TABLE:
16780 : : /* ok to change owner */
16781 : 1102 : break;
16782 : 108 : case RELKIND_INDEX:
16783 [ - + ]: 108 : if (!recursing)
16784 : : {
16785 : : /*
16786 : : * Because ALTER INDEX OWNER used to be allowed, and in fact
16787 : : * is generated by old versions of pg_dump, we give a warning
16788 : : * and do nothing rather than erroring out. Also, to avoid
16789 : : * unnecessary chatter while restoring those old dumps, say
16790 : : * nothing at all if the command would be a no-op anyway.
16791 : : */
16792 [ # # ]: 0 : if (tuple_class->relowner != newOwnerId)
16793 [ # # ]: 0 : ereport(WARNING,
16794 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16795 : : errmsg("cannot change owner of index \"%s\"",
16796 : : NameStr(tuple_class->relname)),
16797 : : errhint("Change the ownership of the index's table instead.")));
16798 : : /* quick hack to exit via the no-op path */
16799 : 0 : newOwnerId = tuple_class->relowner;
16800 : : }
16801 : 108 : break;
16802 : 22 : case RELKIND_PARTITIONED_INDEX:
16803 [ + - ]: 22 : if (recursing)
16804 : 22 : break;
16805 [ # # ]: 0 : ereport(ERROR,
16806 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16807 : : errmsg("cannot change owner of index \"%s\"",
16808 : : NameStr(tuple_class->relname)),
16809 : : errhint("Change the ownership of the index's table instead.")));
16810 : : break;
16811 : 65 : case RELKIND_SEQUENCE:
16812 [ + + ]: 65 : if (!recursing &&
16813 [ - + ]: 35 : tuple_class->relowner != newOwnerId)
16814 : : {
16815 : : /* if it's an owned sequence, disallow changing it by itself */
16816 : : Oid tableId;
16817 : : int32 colId;
16818 : :
16819 [ # # # # ]: 0 : if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16820 : 0 : sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16821 [ # # ]: 0 : ereport(ERROR,
16822 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16823 : : errmsg("cannot change owner of sequence \"%s\"",
16824 : : NameStr(tuple_class->relname)),
16825 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
16826 : : NameStr(tuple_class->relname),
16827 : : get_rel_name(tableId))));
16828 : : }
16829 : 65 : break;
16830 : 5 : case RELKIND_COMPOSITE_TYPE:
16831 [ + - ]: 5 : if (recursing)
16832 : 5 : break;
16833 [ # # ]: 0 : ereport(ERROR,
16834 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16835 : : errmsg("\"%s\" is a composite type",
16836 : : NameStr(tuple_class->relname)),
16837 : : /* translator: %s is an SQL ALTER command */
16838 : : errhint("Use %s instead.",
16839 : : "ALTER TYPE")));
16840 : : break;
16841 : 51 : case RELKIND_TOASTVALUE:
16842 [ + - ]: 51 : if (recursing)
16843 : 51 : break;
16844 : : pg_fallthrough;
16845 : : default:
16846 [ # # ]: 0 : ereport(ERROR,
16847 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16848 : : errmsg("cannot change owner of relation \"%s\"",
16849 : : NameStr(tuple_class->relname)),
16850 : : errdetail_relkind_not_supported(tuple_class->relkind)));
16851 : : }
16852 : :
16853 : : /*
16854 : : * If the new owner is the same as the existing owner, consider the
16855 : : * command to have succeeded. This is for dump restoration purposes.
16856 : : */
16857 [ + + ]: 1353 : if (tuple_class->relowner != newOwnerId)
16858 : : {
16859 : : Datum repl_val[Natts_pg_class];
16860 : : bool repl_null[Natts_pg_class];
16861 : : bool repl_repl[Natts_pg_class];
16862 : : Acl *newAcl;
16863 : : Datum aclDatum;
16864 : : bool isNull;
16865 : : HeapTuple newtuple;
16866 : :
16867 : : /* skip permission checks when recursing to index or toast table */
16868 [ + + ]: 463 : if (!recursing)
16869 : : {
16870 : : /* Superusers can always do it */
16871 [ + + ]: 237 : if (!superuser())
16872 : : {
16873 : 28 : Oid namespaceOid = tuple_class->relnamespace;
16874 : : AclResult aclresult;
16875 : :
16876 : : /* Otherwise, must be owner of the existing object */
16877 [ - + ]: 28 : if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16878 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
16879 : 0 : RelationGetRelationName(target_rel));
16880 : :
16881 : : /* Must be able to become new owner */
16882 : 28 : check_can_set_role(GetUserId(), newOwnerId);
16883 : :
16884 : : /* New owner must have CREATE privilege on namespace */
16885 : 20 : aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16886 : : ACL_CREATE);
16887 [ - + ]: 20 : if (aclresult != ACLCHECK_OK)
16888 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
16889 : 0 : get_namespace_name(namespaceOid));
16890 : : }
16891 : : }
16892 : :
16893 : 455 : memset(repl_null, false, sizeof(repl_null));
16894 : 455 : memset(repl_repl, false, sizeof(repl_repl));
16895 : :
16896 : 455 : repl_repl[Anum_pg_class_relowner - 1] = true;
16897 : 455 : repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16898 : :
16899 : : /*
16900 : : * Determine the modified ACL for the new owner. This is only
16901 : : * necessary when the ACL is non-null.
16902 : : */
16903 : 455 : aclDatum = SysCacheGetAttr(RELOID, tuple,
16904 : : Anum_pg_class_relacl,
16905 : : &isNull);
16906 [ + + ]: 455 : if (!isNull)
16907 : : {
16908 : 36 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
16909 : : tuple_class->relowner, newOwnerId);
16910 : 36 : repl_repl[Anum_pg_class_relacl - 1] = true;
16911 : 36 : repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16912 : : }
16913 : :
16914 : 455 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16915 : :
16916 : 455 : CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16917 : :
16918 : 455 : heap_freetuple(newtuple);
16919 : :
16920 : : /*
16921 : : * We must similarly update any per-column ACLs to reflect the new
16922 : : * owner; for neatness reasons that's split out as a subroutine.
16923 : : */
16924 : 455 : change_owner_fix_column_acls(relationOid,
16925 : : tuple_class->relowner,
16926 : : newOwnerId);
16927 : :
16928 : : /*
16929 : : * Update owner dependency reference, if any. A composite type has
16930 : : * none, because it's tracked for the pg_type entry instead of here;
16931 : : * indexes and TOAST tables don't have their own entries either.
16932 : : */
16933 [ + + ]: 455 : if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16934 [ + + ]: 450 : tuple_class->relkind != RELKIND_INDEX &&
16935 [ + + ]: 342 : tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16936 [ + + ]: 320 : tuple_class->relkind != RELKIND_TOASTVALUE)
16937 : 269 : changeDependencyOnOwner(RelationRelationId, relationOid,
16938 : : newOwnerId);
16939 : :
16940 : : /*
16941 : : * Also change the ownership of the table's row type, if it has one
16942 : : */
16943 [ + + ]: 455 : if (OidIsValid(tuple_class->reltype))
16944 : 253 : AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16945 : :
16946 : : /*
16947 : : * If we are operating on a table or materialized view, also change
16948 : : * the ownership of any indexes and sequences that belong to the
16949 : : * relation, as well as its toast table (if it has one).
16950 : : */
16951 [ + + ]: 455 : if (tuple_class->relkind == RELKIND_RELATION ||
16952 [ + + ]: 254 : tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16953 [ + - ]: 221 : tuple_class->relkind == RELKIND_MATVIEW ||
16954 [ + + ]: 221 : tuple_class->relkind == RELKIND_TOASTVALUE)
16955 : : {
16956 : : List *index_oid_list;
16957 : : ListCell *i;
16958 : :
16959 : : /* Find all the indexes belonging to this relation */
16960 : 285 : index_oid_list = RelationGetIndexList(target_rel);
16961 : :
16962 : : /* For each index, recursively change its ownership */
16963 [ + + + + : 415 : foreach(i, index_oid_list)
+ + ]
16964 : 130 : ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16965 : :
16966 : 285 : list_free(index_oid_list);
16967 : : }
16968 : :
16969 : : /* If it has a toast table, recurse to change its ownership */
16970 [ + + ]: 455 : if (tuple_class->reltoastrelid != InvalidOid)
16971 : 51 : ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16972 : : true, lockmode);
16973 : :
16974 : : /* If it has dependent sequences, recurse to change them too */
16975 : 455 : change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16976 : : }
16977 : :
16978 [ - + ]: 1345 : InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16979 : :
16980 : 1345 : ReleaseSysCache(tuple);
16981 : 1345 : table_close(class_rel, RowExclusiveLock);
16982 : 1345 : relation_close(target_rel, NoLock);
16983 : 1345 : }
16984 : :
16985 : : /*
16986 : : * change_owner_fix_column_acls
16987 : : *
16988 : : * Helper function for ATExecChangeOwner. Scan the columns of the table
16989 : : * and fix any non-null column ACLs to reflect the new owner.
16990 : : */
16991 : : static void
16992 : 455 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
16993 : : {
16994 : : Relation attRelation;
16995 : : SysScanDesc scan;
16996 : : ScanKeyData key[1];
16997 : : HeapTuple attributeTuple;
16998 : :
16999 : 455 : attRelation = table_open(AttributeRelationId, RowExclusiveLock);
17000 : 455 : ScanKeyInit(&key[0],
17001 : : Anum_pg_attribute_attrelid,
17002 : : BTEqualStrategyNumber, F_OIDEQ,
17003 : : ObjectIdGetDatum(relationOid));
17004 : 455 : scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
17005 : : true, NULL, 1, key);
17006 [ + + ]: 3187 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
17007 : : {
17008 : 2732 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
17009 : : Datum repl_val[Natts_pg_attribute];
17010 : : bool repl_null[Natts_pg_attribute];
17011 : : bool repl_repl[Natts_pg_attribute];
17012 : : Acl *newAcl;
17013 : : Datum aclDatum;
17014 : : bool isNull;
17015 : : HeapTuple newtuple;
17016 : :
17017 : : /* Ignore dropped columns */
17018 [ - + ]: 2732 : if (att->attisdropped)
17019 : 2731 : continue;
17020 : :
17021 : 2732 : aclDatum = heap_getattr(attributeTuple,
17022 : : Anum_pg_attribute_attacl,
17023 : : RelationGetDescr(attRelation),
17024 : : &isNull);
17025 : : /* Null ACLs do not require changes */
17026 [ + + ]: 2732 : if (isNull)
17027 : 2731 : continue;
17028 : :
17029 : 1 : memset(repl_null, false, sizeof(repl_null));
17030 : 1 : memset(repl_repl, false, sizeof(repl_repl));
17031 : :
17032 : 1 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
17033 : : oldOwnerId, newOwnerId);
17034 : 1 : repl_repl[Anum_pg_attribute_attacl - 1] = true;
17035 : 1 : repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
17036 : :
17037 : 1 : newtuple = heap_modify_tuple(attributeTuple,
17038 : : RelationGetDescr(attRelation),
17039 : : repl_val, repl_null, repl_repl);
17040 : :
17041 : 1 : CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
17042 : :
17043 : 1 : heap_freetuple(newtuple);
17044 : : }
17045 : 455 : systable_endscan(scan);
17046 : 455 : table_close(attRelation, RowExclusiveLock);
17047 : 455 : }
17048 : :
17049 : : /*
17050 : : * change_owner_recurse_to_sequences
17051 : : *
17052 : : * Helper function for ATExecChangeOwner. Examines pg_depend searching
17053 : : * for sequences that are dependent on serial columns, and changes their
17054 : : * ownership.
17055 : : */
17056 : : static void
17057 : 455 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
17058 : : {
17059 : : Relation depRel;
17060 : : SysScanDesc scan;
17061 : : ScanKeyData key[2];
17062 : : HeapTuple tup;
17063 : :
17064 : : /*
17065 : : * SERIAL sequences are those having an auto dependency on one of the
17066 : : * table's columns (we don't care *which* column, exactly).
17067 : : */
17068 : 455 : depRel = table_open(DependRelationId, AccessShareLock);
17069 : :
17070 : 455 : ScanKeyInit(&key[0],
17071 : : Anum_pg_depend_refclassid,
17072 : : BTEqualStrategyNumber, F_OIDEQ,
17073 : : ObjectIdGetDatum(RelationRelationId));
17074 : 455 : ScanKeyInit(&key[1],
17075 : : Anum_pg_depend_refobjid,
17076 : : BTEqualStrategyNumber, F_OIDEQ,
17077 : : ObjectIdGetDatum(relationOid));
17078 : : /* we leave refobjsubid unspecified */
17079 : :
17080 : 455 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
17081 : : NULL, 2, key);
17082 : :
17083 [ + + ]: 1307 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
17084 : : {
17085 : 852 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
17086 : : Relation seqRel;
17087 : :
17088 : : /* skip dependencies other than auto dependencies on columns */
17089 [ + + ]: 852 : if (depForm->refobjsubid == 0 ||
17090 [ + + ]: 381 : depForm->classid != RelationRelationId ||
17091 [ + - ]: 148 : depForm->objsubid != 0 ||
17092 [ + + - + ]: 148 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
17093 : 704 : continue;
17094 : :
17095 : : /* Use relation_open just in case it's an index */
17096 : 148 : seqRel = relation_open(depForm->objid, lockmode);
17097 : :
17098 : : /* skip non-sequence relations */
17099 [ + + ]: 148 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
17100 : : {
17101 : : /* No need to keep the lock */
17102 : 131 : relation_close(seqRel, lockmode);
17103 : 131 : continue;
17104 : : }
17105 : :
17106 : : /* We don't need to close the sequence while we alter it. */
17107 : 17 : ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
17108 : :
17109 : : /* Now we can close it. Keep the lock till end of transaction. */
17110 : 17 : relation_close(seqRel, NoLock);
17111 : : }
17112 : :
17113 : 455 : systable_endscan(scan);
17114 : :
17115 : 455 : relation_close(depRel, AccessShareLock);
17116 : 455 : }
17117 : :
17118 : : /*
17119 : : * ALTER TABLE CLUSTER ON
17120 : : *
17121 : : * The only thing we have to do is to change the indisclustered bits.
17122 : : *
17123 : : * Return the address of the new clustering index.
17124 : : */
17125 : : static ObjectAddress
17126 : 39 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
17127 : : {
17128 : : Oid indexOid;
17129 : : ObjectAddress address;
17130 : :
17131 : 39 : indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
17132 : :
17133 [ - + ]: 39 : if (!OidIsValid(indexOid))
17134 [ # # ]: 0 : ereport(ERROR,
17135 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
17136 : : errmsg("index \"%s\" for table \"%s\" does not exist",
17137 : : indexName, RelationGetRelationName(rel))));
17138 : :
17139 : : /* Check index is valid to cluster on */
17140 : 39 : check_index_is_clusterable(rel, indexOid, lockmode);
17141 : :
17142 : : /* And do the work */
17143 : 39 : mark_index_clustered(rel, indexOid, false);
17144 : :
17145 : 39 : ObjectAddressSet(address,
17146 : : RelationRelationId, indexOid);
17147 : :
17148 : 39 : return address;
17149 : : }
17150 : :
17151 : : /*
17152 : : * ALTER TABLE SET WITHOUT CLUSTER
17153 : : *
17154 : : * We have to find any indexes on the table that have indisclustered bit
17155 : : * set and turn it off.
17156 : : */
17157 : : static void
17158 : 8 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
17159 : : {
17160 : 8 : mark_index_clustered(rel, InvalidOid, false);
17161 : 8 : }
17162 : :
17163 : : /*
17164 : : * Preparation phase for SET ACCESS METHOD
17165 : : *
17166 : : * Check that the access method exists and determine whether a change is
17167 : : * actually needed.
17168 : : */
17169 : : static void
17170 : 73 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
17171 : : {
17172 : : Oid amoid;
17173 : :
17174 : : /*
17175 : : * Look up the access method name and check that it differs from the
17176 : : * table's current AM. If DEFAULT was specified for a partitioned table
17177 : : * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
17178 : : */
17179 [ + + ]: 73 : if (amname != NULL)
17180 : 49 : amoid = get_table_am_oid(amname, false);
17181 [ + + ]: 24 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17182 : 12 : amoid = InvalidOid;
17183 : : else
17184 : 12 : amoid = get_table_am_oid(default_table_access_method, false);
17185 : :
17186 : : /* if it's a match, phase 3 doesn't need to do anything */
17187 [ + + ]: 73 : if (rel->rd_rel->relam == amoid)
17188 : 8 : return;
17189 : :
17190 : : /* Save info for Phase 3 to do the real work */
17191 : 65 : tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
17192 : 65 : tab->newAccessMethod = amoid;
17193 : 65 : tab->chgAccessMethod = true;
17194 : : }
17195 : :
17196 : : /*
17197 : : * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
17198 : : * storage that have an interest in preserving AM.
17199 : : *
17200 : : * Since these have no storage, setting the access method is a catalog only
17201 : : * operation.
17202 : : */
17203 : : static void
17204 : 29 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
17205 : : {
17206 : : Relation pg_class;
17207 : : Oid oldAccessMethodId;
17208 : : HeapTuple tuple;
17209 : : Form_pg_class rd_rel;
17210 : 29 : Oid reloid = RelationGetRelid(rel);
17211 : :
17212 : : /*
17213 : : * Shouldn't be called on relations having storage; these are processed in
17214 : : * phase 3.
17215 : : */
17216 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17217 : :
17218 : : /* Get a modifiable copy of the relation's pg_class row. */
17219 : 29 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
17220 : :
17221 : 29 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
17222 [ - + ]: 29 : if (!HeapTupleIsValid(tuple))
17223 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
17224 : 29 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
17225 : :
17226 : : /* Update the pg_class row. */
17227 : 29 : oldAccessMethodId = rd_rel->relam;
17228 : 29 : rd_rel->relam = newAccessMethodId;
17229 : :
17230 : : /* Leave if no update required */
17231 [ - + ]: 29 : if (rd_rel->relam == oldAccessMethodId)
17232 : : {
17233 : 0 : heap_freetuple(tuple);
17234 : 0 : table_close(pg_class, RowExclusiveLock);
17235 : 0 : return;
17236 : : }
17237 : :
17238 : 29 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
17239 : :
17240 : : /*
17241 : : * Update the dependency on the new access method. No dependency is added
17242 : : * if the new access method is InvalidOid (default case). Be very careful
17243 : : * that this has to compare the previous value stored in pg_class with the
17244 : : * new one.
17245 : : */
17246 [ + + + - ]: 29 : if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
17247 : 13 : {
17248 : : ObjectAddress relobj,
17249 : : referenced;
17250 : :
17251 : : /*
17252 : : * New access method is defined and there was no dependency
17253 : : * previously, so record a new one.
17254 : : */
17255 : 13 : ObjectAddressSet(relobj, RelationRelationId, reloid);
17256 : 13 : ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
17257 : 13 : recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
17258 : : }
17259 [ + - ]: 16 : else if (OidIsValid(oldAccessMethodId) &&
17260 [ + + ]: 16 : !OidIsValid(rd_rel->relam))
17261 : : {
17262 : : /*
17263 : : * There was an access method defined, and no new one, so just remove
17264 : : * the existing dependency.
17265 : : */
17266 : 8 : deleteDependencyRecordsForClass(RelationRelationId, reloid,
17267 : : AccessMethodRelationId,
17268 : : DEPENDENCY_NORMAL);
17269 : : }
17270 : : else
17271 : : {
17272 : : Assert(OidIsValid(oldAccessMethodId) &&
17273 : : OidIsValid(rd_rel->relam));
17274 : :
17275 : : /* Both are valid, so update the dependency */
17276 : 8 : changeDependencyFor(RelationRelationId, reloid,
17277 : : AccessMethodRelationId,
17278 : : oldAccessMethodId, rd_rel->relam);
17279 : : }
17280 : :
17281 : : /* make the relam and dependency changes visible */
17282 : 29 : CommandCounterIncrement();
17283 : :
17284 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17285 : :
17286 : 29 : heap_freetuple(tuple);
17287 : 29 : table_close(pg_class, RowExclusiveLock);
17288 : : }
17289 : :
17290 : : /*
17291 : : * ALTER TABLE SET TABLESPACE
17292 : : */
17293 : : static void
17294 : 122 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
17295 : : {
17296 : : Oid tablespaceId;
17297 : :
17298 : : /* Check that the tablespace exists */
17299 : 122 : tablespaceId = get_tablespace_oid(tablespacename, false);
17300 : :
17301 : : /* Check permissions except when moving to database's default */
17302 [ + - + + ]: 122 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
17303 : : {
17304 : : AclResult aclresult;
17305 : :
17306 : 53 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
17307 [ - + ]: 53 : if (aclresult != ACLCHECK_OK)
17308 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
17309 : : }
17310 : :
17311 : : /* Save info for Phase 3 to do the real work */
17312 [ - + ]: 122 : if (OidIsValid(tab->newTableSpace))
17313 [ # # ]: 0 : ereport(ERROR,
17314 : : (errcode(ERRCODE_SYNTAX_ERROR),
17315 : : errmsg("cannot have multiple SET TABLESPACE subcommands")));
17316 : :
17317 : 122 : tab->newTableSpace = tablespaceId;
17318 : 122 : }
17319 : :
17320 : : /*
17321 : : * Set, reset, or replace reloptions.
17322 : : */
17323 : : static void
17324 : 675 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
17325 : : LOCKMODE lockmode)
17326 : : {
17327 : : Oid relid;
17328 : : Relation pgclass;
17329 : : HeapTuple tuple;
17330 : : HeapTuple newtuple;
17331 : : Datum datum;
17332 : : Datum newOptions;
17333 : : Datum repl_val[Natts_pg_class];
17334 : : bool repl_null[Natts_pg_class];
17335 : : bool repl_repl[Natts_pg_class];
17336 : 675 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
17337 : :
17338 [ + + - + ]: 675 : if (defList == NIL && operation != AT_ReplaceRelOptions)
17339 : 0 : return; /* nothing to do */
17340 : :
17341 : 675 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
17342 : :
17343 : : /* Fetch heap tuple */
17344 : 675 : relid = RelationGetRelid(rel);
17345 : 675 : tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
17346 [ - + ]: 675 : if (!HeapTupleIsValid(tuple))
17347 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
17348 : :
17349 [ + + ]: 675 : if (operation == AT_ReplaceRelOptions)
17350 : : {
17351 : : /*
17352 : : * If we're supposed to replace the reloptions list, we just pretend
17353 : : * there were none before.
17354 : : */
17355 : 137 : datum = (Datum) 0;
17356 : : }
17357 : : else
17358 : : {
17359 : : bool isnull;
17360 : :
17361 : : /* Get the old reloptions */
17362 : 538 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
17363 : : &isnull);
17364 [ + + ]: 538 : if (isnull)
17365 : 302 : datum = (Datum) 0;
17366 : : }
17367 : :
17368 : : /* Generate new proposed reloptions (text array) */
17369 : 675 : newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
17370 : : operation == AT_ResetRelOptions);
17371 : :
17372 : : /* Validate */
17373 [ + + + + : 671 : switch (rel->rd_rel->relkind)
- ]
17374 : : {
17375 : 391 : case RELKIND_RELATION:
17376 : : case RELKIND_MATVIEW:
17377 : 391 : (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
17378 : 391 : break;
17379 : 4 : case RELKIND_PARTITIONED_TABLE:
17380 : 4 : (void) partitioned_table_reloptions(newOptions, true);
17381 : 0 : break;
17382 : 205 : case RELKIND_VIEW:
17383 : 205 : (void) view_reloptions(newOptions, true);
17384 : 193 : break;
17385 : 71 : case RELKIND_INDEX:
17386 : : case RELKIND_PARTITIONED_INDEX:
17387 : 71 : (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
17388 : 57 : break;
17389 : 0 : case RELKIND_TOASTVALUE:
17390 : : /* fall through to error -- shouldn't ever get here */
17391 : : default:
17392 [ # # ]: 0 : ereport(ERROR,
17393 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17394 : : errmsg("cannot set options for relation \"%s\"",
17395 : : RelationGetRelationName(rel)),
17396 : : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
17397 : : break;
17398 : : }
17399 : :
17400 : : /* Special-case validation of view options */
17401 [ + + ]: 641 : if (rel->rd_rel->relkind == RELKIND_VIEW)
17402 : : {
17403 : 193 : Query *view_query = get_view_query(rel);
17404 : 193 : List *view_options = untransformRelOptions(newOptions);
17405 : : ListCell *cell;
17406 : 193 : bool check_option = false;
17407 : :
17408 [ + + + + : 261 : foreach(cell, view_options)
+ + ]
17409 : : {
17410 : 68 : DefElem *defel = (DefElem *) lfirst(cell);
17411 : :
17412 [ + + ]: 68 : if (strcmp(defel->defname, "check_option") == 0)
17413 : 16 : check_option = true;
17414 : : }
17415 : :
17416 : : /*
17417 : : * If the check option is specified, look to see if the view is
17418 : : * actually auto-updatable or not.
17419 : : */
17420 [ + + ]: 193 : if (check_option)
17421 : : {
17422 : : const char *view_updatable_error =
17423 : 16 : view_query_is_auto_updatable(view_query, true);
17424 : :
17425 [ - + ]: 16 : if (view_updatable_error)
17426 [ # # ]: 0 : ereport(ERROR,
17427 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17428 : : errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
17429 : : errhint("%s", _(view_updatable_error))));
17430 : : }
17431 : : }
17432 : :
17433 : : /*
17434 : : * All we need do here is update the pg_class row; the new options will be
17435 : : * propagated into relcaches during post-commit cache inval.
17436 : : */
17437 : 641 : memset(repl_val, 0, sizeof(repl_val));
17438 : 641 : memset(repl_null, false, sizeof(repl_null));
17439 : 641 : memset(repl_repl, false, sizeof(repl_repl));
17440 : :
17441 [ + + ]: 641 : if (newOptions != (Datum) 0)
17442 : 427 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17443 : : else
17444 : 214 : repl_null[Anum_pg_class_reloptions - 1] = true;
17445 : :
17446 : 641 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17447 : :
17448 : 641 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17449 : : repl_val, repl_null, repl_repl);
17450 : :
17451 : 641 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17452 : 641 : UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
17453 : :
17454 [ - + ]: 641 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17455 : :
17456 : 641 : heap_freetuple(newtuple);
17457 : :
17458 : 641 : ReleaseSysCache(tuple);
17459 : :
17460 : : /* repeat the whole exercise for the toast table, if there's one */
17461 [ + + ]: 641 : if (OidIsValid(rel->rd_rel->reltoastrelid))
17462 : : {
17463 : : Relation toastrel;
17464 : 222 : Oid toastid = rel->rd_rel->reltoastrelid;
17465 : :
17466 : 222 : toastrel = table_open(toastid, lockmode);
17467 : :
17468 : : /* Fetch heap tuple */
17469 : 222 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
17470 [ - + ]: 222 : if (!HeapTupleIsValid(tuple))
17471 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", toastid);
17472 : :
17473 [ - + ]: 222 : if (operation == AT_ReplaceRelOptions)
17474 : : {
17475 : : /*
17476 : : * If we're supposed to replace the reloptions list, we just
17477 : : * pretend there were none before.
17478 : : */
17479 : 0 : datum = (Datum) 0;
17480 : : }
17481 : : else
17482 : : {
17483 : : bool isnull;
17484 : :
17485 : : /* Get the old reloptions */
17486 : 222 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
17487 : : &isnull);
17488 [ + + ]: 222 : if (isnull)
17489 : 198 : datum = (Datum) 0;
17490 : : }
17491 : :
17492 : 222 : newOptions = transformRelOptions(datum, defList, "toast", validnsps,
17493 : : false, operation == AT_ResetRelOptions);
17494 : :
17495 : 222 : (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
17496 : :
17497 : 222 : memset(repl_val, 0, sizeof(repl_val));
17498 : 222 : memset(repl_null, false, sizeof(repl_null));
17499 : 222 : memset(repl_repl, false, sizeof(repl_repl));
17500 : :
17501 [ + + ]: 222 : if (newOptions != (Datum) 0)
17502 : 28 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17503 : : else
17504 : 194 : repl_null[Anum_pg_class_reloptions - 1] = true;
17505 : :
17506 : 222 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17507 : :
17508 : 222 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17509 : : repl_val, repl_null, repl_repl);
17510 : :
17511 : 222 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17512 : :
17513 [ - + ]: 222 : InvokeObjectPostAlterHookArg(RelationRelationId,
17514 : : RelationGetRelid(toastrel), 0,
17515 : : InvalidOid, true);
17516 : :
17517 : 222 : heap_freetuple(newtuple);
17518 : :
17519 : 222 : ReleaseSysCache(tuple);
17520 : :
17521 : 222 : table_close(toastrel, NoLock);
17522 : : }
17523 : :
17524 : 641 : table_close(pgclass, RowExclusiveLock);
17525 : : }
17526 : :
17527 : : /*
17528 : : * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
17529 : : * rewriting to be done, so we just want to copy the data as fast as possible.
17530 : : */
17531 : : static void
17532 : 132 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
17533 : : {
17534 : : Relation rel;
17535 : : Oid reltoastrelid;
17536 : : RelFileNumber newrelfilenumber;
17537 : : RelFileLocator newrlocator;
17538 : 132 : List *reltoastidxids = NIL;
17539 : : ListCell *lc;
17540 : :
17541 : : /*
17542 : : * Need lock here in case we are recursing to toast table or index
17543 : : */
17544 : 132 : rel = relation_open(tableOid, lockmode);
17545 : :
17546 : : /* Check first if relation can be moved to new tablespace */
17547 [ + + ]: 132 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17548 : : {
17549 [ - + ]: 5 : InvokeObjectPostAlterHook(RelationRelationId,
17550 : : RelationGetRelid(rel), 0);
17551 : 5 : relation_close(rel, NoLock);
17552 : 5 : return;
17553 : : }
17554 : :
17555 : 127 : reltoastrelid = rel->rd_rel->reltoastrelid;
17556 : : /* Fetch the list of indexes on toast relation if necessary */
17557 [ + + ]: 127 : if (OidIsValid(reltoastrelid))
17558 : : {
17559 : 17 : Relation toastRel = relation_open(reltoastrelid, lockmode);
17560 : :
17561 : 17 : reltoastidxids = RelationGetIndexList(toastRel);
17562 : 17 : relation_close(toastRel, lockmode);
17563 : : }
17564 : :
17565 : : /*
17566 : : * Relfilenumbers are not unique in databases across tablespaces, so we
17567 : : * need to allocate a new one in the new tablespace.
17568 : : */
17569 : 127 : newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
17570 : 127 : rel->rd_rel->relpersistence);
17571 : :
17572 : : /* Open old and new relation */
17573 : 127 : newrlocator = rel->rd_locator;
17574 : 127 : newrlocator.relNumber = newrelfilenumber;
17575 : 127 : newrlocator.spcOid = newTableSpace;
17576 : :
17577 : : /* hand off to AM to actually create new rel storage and copy the data */
17578 [ + + ]: 127 : if (rel->rd_rel->relkind == RELKIND_INDEX)
17579 : : {
17580 : 45 : index_copy_data(rel, newrlocator);
17581 : : }
17582 : : else
17583 : : {
17584 : : Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
17585 : 82 : table_relation_copy_data(rel, &newrlocator);
17586 : : }
17587 : :
17588 : : /*
17589 : : * Update the pg_class row.
17590 : : *
17591 : : * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
17592 : : * executed on pg_class or its indexes (the above copy wouldn't contain
17593 : : * the updated pg_class entry), but that's forbidden with
17594 : : * CheckRelationTableSpaceMove().
17595 : : */
17596 : 127 : SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
17597 : :
17598 [ - + ]: 127 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17599 : :
17600 : 127 : RelationAssumeNewRelfilelocator(rel);
17601 : :
17602 : 127 : relation_close(rel, NoLock);
17603 : :
17604 : : /* Make sure the reltablespace change is visible */
17605 : 127 : CommandCounterIncrement();
17606 : :
17607 : : /* Move associated toast relation and/or indexes, too */
17608 [ + + ]: 127 : if (OidIsValid(reltoastrelid))
17609 : 17 : ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
17610 [ + + + + : 144 : foreach(lc, reltoastidxids)
+ + ]
17611 : 17 : ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
17612 : :
17613 : : /* Clean up */
17614 : 127 : list_free(reltoastidxids);
17615 : : }
17616 : :
17617 : : /*
17618 : : * Special handling of ALTER TABLE SET TABLESPACE for relations with no
17619 : : * storage that have an interest in preserving tablespace.
17620 : : *
17621 : : * Since these have no storage the tablespace can be updated with a simple
17622 : : * metadata only operation to update the tablespace.
17623 : : */
17624 : : static void
17625 : 24 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
17626 : : {
17627 : : /*
17628 : : * Shouldn't be called on relations having storage; these are processed in
17629 : : * phase 3.
17630 : : */
17631 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17632 : :
17633 : : /* check if relation can be moved to its new tablespace */
17634 [ - + ]: 24 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17635 : : {
17636 [ # # ]: 0 : InvokeObjectPostAlterHook(RelationRelationId,
17637 : : RelationGetRelid(rel),
17638 : : 0);
17639 : 0 : return;
17640 : : }
17641 : :
17642 : : /* Update can be done, so change reltablespace */
17643 : 20 : SetRelationTableSpace(rel, newTableSpace, InvalidOid);
17644 : :
17645 [ - + ]: 20 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17646 : :
17647 : : /* Make sure the reltablespace change is visible */
17648 : 20 : CommandCounterIncrement();
17649 : : }
17650 : :
17651 : : /*
17652 : : * Alter Table ALL ... SET TABLESPACE
17653 : : *
17654 : : * Allows a user to move all objects of some type in a given tablespace in the
17655 : : * current database to another tablespace. Objects can be chosen based on the
17656 : : * owner of the object also, to allow users to move only their objects.
17657 : : * The user must have CREATE rights on the new tablespace, as usual. The main
17658 : : * permissions handling is done by the lower-level table move function.
17659 : : *
17660 : : * All to-be-moved objects are locked first. If NOWAIT is specified and the
17661 : : * lock can't be acquired then we ereport(ERROR).
17662 : : */
17663 : : Oid
17664 : 21 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
17665 : : {
17666 : 21 : List *relations = NIL;
17667 : : ListCell *l;
17668 : : ScanKeyData key[1];
17669 : : Relation rel;
17670 : : TableScanDesc scan;
17671 : : HeapTuple tuple;
17672 : : Oid orig_tablespaceoid;
17673 : : Oid new_tablespaceoid;
17674 : 21 : List *role_oids = roleSpecsToIds(stmt->roles);
17675 : :
17676 : : /* Ensure we were not asked to move something we can't */
17677 [ + + + + ]: 21 : if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17678 [ - + ]: 8 : stmt->objtype != OBJECT_MATVIEW)
17679 [ # # ]: 0 : ereport(ERROR,
17680 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17681 : : errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17682 : :
17683 : : /* Get the orig and new tablespace OIDs */
17684 : 21 : orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17685 : 21 : new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17686 : :
17687 : : /* Can't move shared relations in to or out of pg_global */
17688 : : /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17689 [ + - - + ]: 21 : if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
17690 : : new_tablespaceoid == GLOBALTABLESPACE_OID)
17691 [ # # ]: 0 : ereport(ERROR,
17692 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17693 : : errmsg("cannot move relations in to or out of pg_global tablespace")));
17694 : :
17695 : : /*
17696 : : * Must have CREATE rights on the new tablespace, unless it is the
17697 : : * database default tablespace (which all users implicitly have CREATE
17698 : : * rights on).
17699 : : */
17700 [ + - + + ]: 21 : if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
17701 : : {
17702 : : AclResult aclresult;
17703 : :
17704 : 1 : aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
17705 : : ACL_CREATE);
17706 [ - + ]: 1 : if (aclresult != ACLCHECK_OK)
17707 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
17708 : 0 : get_tablespace_name(new_tablespaceoid));
17709 : : }
17710 : :
17711 : : /*
17712 : : * Now that the checks are done, check if we should set either to
17713 : : * InvalidOid because it is our database's default tablespace.
17714 : : */
17715 [ + + ]: 21 : if (orig_tablespaceoid == MyDatabaseTableSpace)
17716 : 1 : orig_tablespaceoid = InvalidOid;
17717 : :
17718 [ + + ]: 21 : if (new_tablespaceoid == MyDatabaseTableSpace)
17719 : 20 : new_tablespaceoid = InvalidOid;
17720 : :
17721 : : /* no-op */
17722 [ - + ]: 21 : if (orig_tablespaceoid == new_tablespaceoid)
17723 : 0 : return new_tablespaceoid;
17724 : :
17725 : : /*
17726 : : * Walk the list of objects in the tablespace and move them. This will
17727 : : * only find objects in our database, of course.
17728 : : */
17729 : 21 : ScanKeyInit(&key[0],
17730 : : Anum_pg_class_reltablespace,
17731 : : BTEqualStrategyNumber, F_OIDEQ,
17732 : : ObjectIdGetDatum(orig_tablespaceoid));
17733 : :
17734 : 21 : rel = table_open(RelationRelationId, AccessShareLock);
17735 : 21 : scan = table_beginscan_catalog(rel, 1, key);
17736 [ + + ]: 470 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17737 : : {
17738 : 449 : Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
17739 : 449 : Oid relOid = relForm->oid;
17740 : :
17741 : : /*
17742 : : * Do not move objects in pg_catalog as part of this, if an admin
17743 : : * really wishes to do so, they can issue the individual ALTER
17744 : : * commands directly.
17745 : : *
17746 : : * Also, explicitly avoid any shared tables, temp tables, TOAST (TOAST
17747 : : * will be moved with the main table).
17748 : : *
17749 : : * Conflict log tables are system-managed for logical replication and
17750 : : * cannot be altered directly, so skip them as well; otherwise a
17751 : : * single such table in the source tablespace would abort the whole
17752 : : * bulk move.
17753 : : */
17754 [ + + ]: 449 : if (IsCatalogNamespace(relForm->relnamespace) ||
17755 [ + - + - ]: 410 : relForm->relisshared ||
17756 [ + + ]: 410 : isAnyTempNamespace(relForm->relnamespace) ||
17757 [ + + ]: 344 : IsToastNamespace(relForm->relnamespace) ||
17758 : 139 : IsConflictLogTableNamespace(relForm->relnamespace))
17759 : 311 : continue;
17760 : :
17761 : : /* Only move the object type requested */
17762 [ + + ]: 138 : if ((stmt->objtype == OBJECT_TABLE &&
17763 [ + + ]: 110 : relForm->relkind != RELKIND_RELATION &&
17764 [ - + ]: 89 : relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17765 [ + + ]: 49 : (stmt->objtype == OBJECT_INDEX &&
17766 [ + + ]: 24 : relForm->relkind != RELKIND_INDEX &&
17767 [ - + ]: 4 : relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17768 [ + + ]: 45 : (stmt->objtype == OBJECT_MATVIEW &&
17769 [ - + ]: 4 : relForm->relkind != RELKIND_MATVIEW))
17770 : 93 : continue;
17771 : :
17772 : : /* Check if we are only moving objects owned by certain roles */
17773 [ - + - - ]: 45 : if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17774 : 0 : continue;
17775 : :
17776 : : /*
17777 : : * Handle permissions-checking here since we are locking the tables
17778 : : * and also to avoid doing a bunch of work only to fail part-way. Note
17779 : : * that permissions will also be checked by AlterTableInternal().
17780 : : *
17781 : : * Caller must be considered an owner on the table to move it.
17782 : : */
17783 [ - + ]: 45 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17784 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
17785 : 0 : NameStr(relForm->relname));
17786 : :
17787 [ - + ]: 45 : if (stmt->nowait &&
17788 [ # # ]: 0 : !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
17789 [ # # ]: 0 : ereport(ERROR,
17790 : : (errcode(ERRCODE_OBJECT_IN_USE),
17791 : : errmsg("aborting because lock on relation \"%s.%s\" is not available",
17792 : : get_namespace_name(relForm->relnamespace),
17793 : : NameStr(relForm->relname))));
17794 : : else
17795 : 45 : LockRelationOid(relOid, AccessExclusiveLock);
17796 : :
17797 : : /* Add to our list of objects to move */
17798 : 45 : relations = lappend_oid(relations, relOid);
17799 : : }
17800 : :
17801 : 21 : table_endscan(scan);
17802 : 21 : table_close(rel, AccessShareLock);
17803 : :
17804 [ + + ]: 21 : if (relations == NIL)
17805 [ + - + - ]: 8 : ereport(NOTICE,
17806 : : (errcode(ERRCODE_NO_DATA_FOUND),
17807 : : errmsg("no matching relations in tablespace \"%s\" found",
17808 : : orig_tablespaceoid == InvalidOid ? "(database default)" :
17809 : : get_tablespace_name(orig_tablespaceoid))));
17810 : :
17811 : : /* Everything is locked, loop through and move all of the relations. */
17812 [ + + + + : 66 : foreach(l, relations)
+ + ]
17813 : : {
17814 : 45 : List *cmds = NIL;
17815 : 45 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
17816 : :
17817 : 45 : cmd->subtype = AT_SetTableSpace;
17818 : 45 : cmd->name = stmt->new_tablespacename;
17819 : :
17820 : 45 : cmds = lappend(cmds, cmd);
17821 : :
17822 : 45 : EventTriggerAlterTableStart((Node *) stmt);
17823 : : /* OID is set by AlterTableInternal */
17824 : 45 : AlterTableInternal(lfirst_oid(l), cmds, false);
17825 : 45 : EventTriggerAlterTableEnd();
17826 : : }
17827 : :
17828 : 21 : return new_tablespaceoid;
17829 : : }
17830 : :
17831 : : static void
17832 : 45 : index_copy_data(Relation rel, RelFileLocator newrlocator)
17833 : : {
17834 : : SMgrRelation dstrel;
17835 : :
17836 : : /*
17837 : : * Since we copy the file directly without looking at the shared buffers,
17838 : : * we'd better first flush out any pages of the source relation that are
17839 : : * in shared buffers. We assume no new changes will be made while we are
17840 : : * holding exclusive lock on the rel.
17841 : : */
17842 : 45 : FlushRelationBuffers(rel);
17843 : :
17844 : : /*
17845 : : * Create and copy all forks of the relation, and schedule unlinking of
17846 : : * old physical files.
17847 : : *
17848 : : * NOTE: any conflict in relfilenumber value will be caught in
17849 : : * RelationCreateStorage().
17850 : : */
17851 : 45 : dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
17852 : :
17853 : : /* copy main fork */
17854 : 45 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
17855 : 45 : rel->rd_rel->relpersistence);
17856 : :
17857 : : /* copy those extra forks that exist */
17858 : 45 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
17859 [ + + ]: 180 : forkNum <= MAX_FORKNUM; forkNum++)
17860 : : {
17861 [ - + ]: 135 : if (smgrexists(RelationGetSmgr(rel), forkNum))
17862 : : {
17863 : 0 : smgrcreate(dstrel, forkNum, false);
17864 : :
17865 : : /*
17866 : : * WAL log creation if the relation is persistent, or this is the
17867 : : * init fork of an unlogged relation.
17868 : : */
17869 [ # # ]: 0 : if (RelationIsPermanent(rel) ||
17870 [ # # # # ]: 0 : (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
17871 : : forkNum == INIT_FORKNUM))
17872 : 0 : log_smgrcreate(&newrlocator, forkNum);
17873 : 0 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
17874 : 0 : rel->rd_rel->relpersistence);
17875 : : }
17876 : : }
17877 : :
17878 : : /* drop old relation, and close new one */
17879 : 45 : RelationDropStorage(rel);
17880 : 45 : smgrclose(dstrel);
17881 : 45 : }
17882 : :
17883 : : /*
17884 : : * ALTER TABLE ENABLE/DISABLE TRIGGER
17885 : : *
17886 : : * We just pass this off to trigger.c.
17887 : : */
17888 : : static void
17889 : 191 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
17890 : : char fires_when, bool skip_system, bool recurse,
17891 : : LOCKMODE lockmode)
17892 : : {
17893 : 191 : EnableDisableTrigger(rel, trigname, InvalidOid,
17894 : : fires_when, skip_system, recurse,
17895 : : lockmode);
17896 : :
17897 [ + + ]: 191 : InvokeObjectPostAlterHook(RelationRelationId,
17898 : : RelationGetRelid(rel), 0);
17899 : 191 : }
17900 : :
17901 : : /*
17902 : : * ALTER TABLE ENABLE/DISABLE RULE
17903 : : *
17904 : : * We just pass this off to rewriteDefine.c.
17905 : : */
17906 : : static void
17907 : 29 : ATExecEnableDisableRule(Relation rel, const char *rulename,
17908 : : char fires_when, LOCKMODE lockmode)
17909 : : {
17910 : 29 : EnableDisableRule(rel, rulename, fires_when);
17911 : :
17912 [ + + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
17913 : : RelationGetRelid(rel), 0);
17914 : 29 : }
17915 : :
17916 : : /*
17917 : : * Preparation phase of [NO] INHERIT
17918 : : *
17919 : : * Check the relation defined as a child.
17920 : : */
17921 : : static void
17922 : 366 : ATPrepChangeInherit(Relation child_rel)
17923 : : {
17924 [ + + ]: 366 : if (child_rel->rd_rel->reloftype)
17925 [ + - ]: 8 : ereport(ERROR,
17926 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17927 : : errmsg("cannot change inheritance of typed table")));
17928 : :
17929 [ + + ]: 358 : if (child_rel->rd_rel->relispartition)
17930 [ + - ]: 12 : ereport(ERROR,
17931 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17932 : : errmsg("cannot change inheritance of a partition")));
17933 : 346 : }
17934 : :
17935 : : /*
17936 : : * ALTER TABLE INHERIT
17937 : : *
17938 : : * Return the address of the new parent relation.
17939 : : */
17940 : : static ObjectAddress
17941 : 285 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
17942 : : {
17943 : : Relation parent_rel;
17944 : : List *children;
17945 : : ObjectAddress address;
17946 : : const char *trigger_name;
17947 : :
17948 : : /*
17949 : : * A self-exclusive lock is needed here. See the similar case in
17950 : : * MergeAttributes() for a full explanation.
17951 : : */
17952 : 285 : parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
17953 : :
17954 : : /*
17955 : : * Must be owner of both parent and child -- child was checked by
17956 : : * ATSimplePermissions call in ATPrepCmd
17957 : : */
17958 : 285 : ATSimplePermissions(AT_AddInherit, parent_rel,
17959 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
17960 : :
17961 : : /* Permanent rels cannot inherit from temporary ones */
17962 [ + + ]: 285 : if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17963 [ - + ]: 4 : child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
17964 [ # # ]: 0 : ereport(ERROR,
17965 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17966 : : errmsg("cannot inherit from temporary relation \"%s\"",
17967 : : RelationGetRelationName(parent_rel))));
17968 : :
17969 : : /* If parent rel is temp, it must belong to this session */
17970 [ + + - + ]: 285 : if (RELATION_IS_OTHER_TEMP(parent_rel))
17971 [ # # ]: 0 : ereport(ERROR,
17972 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17973 : : errmsg("cannot inherit from temporary relation of another session")));
17974 : :
17975 : : /* Ditto for the child */
17976 [ + + - + ]: 285 : if (RELATION_IS_OTHER_TEMP(child_rel))
17977 [ # # ]: 0 : ereport(ERROR,
17978 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17979 : : errmsg("cannot inherit to temporary relation of another session")));
17980 : :
17981 : : /* Prevent partitioned tables from becoming inheritance parents */
17982 [ + + ]: 285 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17983 [ + - ]: 4 : ereport(ERROR,
17984 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17985 : : errmsg("cannot inherit from partitioned table \"%s\"",
17986 : : parent->relname)));
17987 : :
17988 : : /* Likewise for partitions */
17989 [ + + ]: 281 : if (parent_rel->rd_rel->relispartition)
17990 [ + - ]: 4 : ereport(ERROR,
17991 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17992 : : errmsg("cannot inherit from a partition")));
17993 : :
17994 : : /*
17995 : : * Prevent circularity by seeing if proposed parent inherits from child.
17996 : : * (In particular, this disallows making a rel inherit from itself.)
17997 : : *
17998 : : * This is not completely bulletproof because of race conditions: in
17999 : : * multi-level inheritance trees, someone else could concurrently be
18000 : : * making another inheritance link that closes the loop but does not join
18001 : : * either of the rels we have locked. Preventing that seems to require
18002 : : * exclusive locks on the entire inheritance tree, which is a cure worse
18003 : : * than the disease. find_all_inheritors() will cope with circularity
18004 : : * anyway, so don't sweat it too much.
18005 : : *
18006 : : * We use weakest lock we can on child's children, namely AccessShareLock.
18007 : : */
18008 : 277 : children = find_all_inheritors(RelationGetRelid(child_rel),
18009 : : AccessShareLock, NULL);
18010 : :
18011 [ + + ]: 277 : if (list_member_oid(children, RelationGetRelid(parent_rel)))
18012 [ + - ]: 8 : ereport(ERROR,
18013 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18014 : : errmsg("circular inheritance not allowed"),
18015 : : errdetail("\"%s\" is already a child of \"%s\".",
18016 : : parent->relname,
18017 : : RelationGetRelationName(child_rel))));
18018 : :
18019 : : /*
18020 : : * If child_rel has row-level triggers with transition tables, we
18021 : : * currently don't allow it to become an inheritance child. See also
18022 : : * prohibitions in ATExecAttachPartition() and CreateTrigger().
18023 : : */
18024 : 269 : trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
18025 [ + + ]: 269 : if (trigger_name != NULL)
18026 [ + - ]: 4 : ereport(ERROR,
18027 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18028 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
18029 : : trigger_name, RelationGetRelationName(child_rel)),
18030 : : errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
18031 : :
18032 : : /* OK to create inheritance */
18033 : 265 : CreateInheritance(child_rel, parent_rel, false);
18034 : :
18035 : 205 : ObjectAddressSet(address, RelationRelationId,
18036 : : RelationGetRelid(parent_rel));
18037 : :
18038 : : /* keep our lock on the parent relation until commit */
18039 : 205 : table_close(parent_rel, NoLock);
18040 : :
18041 : 205 : return address;
18042 : : }
18043 : :
18044 : : /*
18045 : : * CreateInheritance
18046 : : * Catalog manipulation portion of creating inheritance between a child
18047 : : * table and a parent table.
18048 : : *
18049 : : * This verifies that all the columns and check constraints of the parent
18050 : : * appear in the child and that they have the same data types and expressions.
18051 : : *
18052 : : * Common to ATExecAddInherit() and ATExecAttachPartition().
18053 : : */
18054 : : static void
18055 : 1690 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
18056 : : {
18057 : : Relation catalogRelation;
18058 : : SysScanDesc scan;
18059 : : ScanKeyData key;
18060 : : HeapTuple inheritsTuple;
18061 : : int32 inhseqno;
18062 : :
18063 : : /* Note: get RowExclusiveLock because we will write pg_inherits below. */
18064 : 1690 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18065 : :
18066 : : /*
18067 : : * Check for duplicates in the list of parents, and determine the highest
18068 : : * inhseqno already present; we'll use the next one for the new parent.
18069 : : * Also, if proposed child is a partition, it cannot already be
18070 : : * inheriting.
18071 : : *
18072 : : * Note: we do not reject the case where the child already inherits from
18073 : : * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
18074 : : */
18075 : 1690 : ScanKeyInit(&key,
18076 : : Anum_pg_inherits_inhrelid,
18077 : : BTEqualStrategyNumber, F_OIDEQ,
18078 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18079 : 1690 : scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
18080 : : true, NULL, 1, &key);
18081 : :
18082 : : /* inhseqno sequences start at 1 */
18083 : 1690 : inhseqno = 0;
18084 [ + + ]: 1741 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18085 : : {
18086 : 55 : Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18087 : :
18088 [ + + ]: 55 : if (inh->inhparent == RelationGetRelid(parent_rel))
18089 [ + - ]: 4 : ereport(ERROR,
18090 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18091 : : errmsg("relation \"%s\" would be inherited from more than once",
18092 : : RelationGetRelationName(parent_rel))));
18093 : :
18094 [ + - ]: 51 : if (inh->inhseqno > inhseqno)
18095 : 51 : inhseqno = inh->inhseqno;
18096 : : }
18097 : 1686 : systable_endscan(scan);
18098 : :
18099 : : /* Match up the columns and bump attinhcount as needed */
18100 : 1686 : MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
18101 : :
18102 : : /* Match up the constraints and bump coninhcount as needed */
18103 : 1598 : MergeConstraintsIntoExisting(child_rel, parent_rel);
18104 : :
18105 : : /*
18106 : : * OK, it looks valid. Make the catalog entries that show inheritance.
18107 : : */
18108 : 1558 : StoreCatalogInheritance1(RelationGetRelid(child_rel),
18109 : : RelationGetRelid(parent_rel),
18110 : : inhseqno + 1,
18111 : : catalogRelation,
18112 : 1558 : parent_rel->rd_rel->relkind ==
18113 : : RELKIND_PARTITIONED_TABLE);
18114 : :
18115 : : /* Now we're done with pg_inherits */
18116 : 1558 : table_close(catalogRelation, RowExclusiveLock);
18117 : 1558 : }
18118 : :
18119 : : /*
18120 : : * Obtain the source-text form of the constraint expression for a check
18121 : : * constraint, given its pg_constraint tuple
18122 : : */
18123 : : static char *
18124 : 464 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
18125 : : {
18126 : : Form_pg_constraint con;
18127 : : bool isnull;
18128 : : Datum attr;
18129 : : Datum expr;
18130 : :
18131 : 464 : con = (Form_pg_constraint) GETSTRUCT(contup);
18132 : 464 : attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
18133 [ - + ]: 464 : if (isnull)
18134 [ # # ]: 0 : elog(ERROR, "null conbin for constraint %u", con->oid);
18135 : :
18136 : 464 : expr = DirectFunctionCall2(pg_get_expr, attr,
18137 : : ObjectIdGetDatum(con->conrelid));
18138 : 464 : return TextDatumGetCString(expr);
18139 : : }
18140 : :
18141 : : /*
18142 : : * Determine whether two check constraints are functionally equivalent
18143 : : *
18144 : : * The test we apply is to see whether they reverse-compile to the same
18145 : : * source string. This insulates us from issues like whether attributes
18146 : : * have the same physical column numbers in parent and child relations.
18147 : : *
18148 : : * Note that we ignore enforceability as there are cases where constraints
18149 : : * with differing enforceability are allowed.
18150 : : */
18151 : : static bool
18152 : 232 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
18153 : : {
18154 : 232 : Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
18155 : 232 : Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
18156 : :
18157 [ + - ]: 232 : if (acon->condeferrable != bcon->condeferrable ||
18158 [ + - ]: 232 : acon->condeferred != bcon->condeferred ||
18159 [ + + ]: 232 : strcmp(decompile_conbin(a, tupleDesc),
18160 : 232 : decompile_conbin(b, tupleDesc)) != 0)
18161 : 4 : return false;
18162 : : else
18163 : 228 : return true;
18164 : : }
18165 : :
18166 : : /*
18167 : : * Check columns in child table match up with columns in parent, and increment
18168 : : * their attinhcount.
18169 : : *
18170 : : * Called by CreateInheritance
18171 : : *
18172 : : * Currently all parent columns must be found in child. Missing columns are an
18173 : : * error. One day we might consider creating new columns like CREATE TABLE
18174 : : * does. However, that is widely unpopular --- in the common use case of
18175 : : * partitioned tables it's a foot-gun.
18176 : : *
18177 : : * The data type must match exactly. If the parent column is NOT NULL then
18178 : : * the child must be as well. Defaults are not compared, however.
18179 : : */
18180 : : static void
18181 : 1686 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
18182 : : {
18183 : : Relation attrrel;
18184 : : TupleDesc parent_desc;
18185 : :
18186 : 1686 : attrrel = table_open(AttributeRelationId, RowExclusiveLock);
18187 : 1686 : parent_desc = RelationGetDescr(parent_rel);
18188 : :
18189 [ + + ]: 5353 : for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
18190 : : {
18191 : 3755 : Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
18192 : 3755 : char *parent_attname = NameStr(parent_att->attname);
18193 : : HeapTuple tuple;
18194 : :
18195 : : /* Ignore dropped columns in the parent. */
18196 [ + + ]: 3755 : if (parent_att->attisdropped)
18197 : 180 : continue;
18198 : :
18199 : : /* Find same column in child (matching on column name). */
18200 : 3575 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
18201 [ + + ]: 3575 : if (HeapTupleIsValid(tuple))
18202 : : {
18203 : 3567 : Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
18204 : :
18205 [ + + ]: 3567 : if (parent_att->atttypid != child_att->atttypid ||
18206 [ + + ]: 3563 : parent_att->atttypmod != child_att->atttypmod)
18207 [ + - ]: 8 : ereport(ERROR,
18208 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18209 : : errmsg("child table \"%s\" has different type for column \"%s\"",
18210 : : RelationGetRelationName(child_rel), parent_attname)));
18211 : :
18212 [ + + ]: 3559 : if (parent_att->attcollation != child_att->attcollation)
18213 [ + - ]: 4 : ereport(ERROR,
18214 : : (errcode(ERRCODE_COLLATION_MISMATCH),
18215 : : errmsg("child table \"%s\" has different collation for column \"%s\"",
18216 : : RelationGetRelationName(child_rel), parent_attname)));
18217 : :
18218 : : /*
18219 : : * If the parent has a not-null constraint that's not NO INHERIT,
18220 : : * make sure the child has one too.
18221 : : *
18222 : : * Other constraints are checked elsewhere.
18223 : : */
18224 [ + + + + ]: 3555 : if (parent_att->attnotnull && !child_att->attnotnull)
18225 : : {
18226 : : HeapTuple contup;
18227 : :
18228 : 32 : contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
18229 : 32 : parent_att->attnum);
18230 [ + - ]: 32 : if (HeapTupleIsValid(contup) &&
18231 [ + + ]: 32 : !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
18232 [ + - ]: 20 : ereport(ERROR,
18233 : : errcode(ERRCODE_DATATYPE_MISMATCH),
18234 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18235 : : parent_attname, RelationGetRelationName(child_rel)));
18236 : : }
18237 : :
18238 : : /*
18239 : : * Child column must be generated if and only if parent column is.
18240 : : */
18241 [ + + + + ]: 3535 : if (parent_att->attgenerated && !child_att->attgenerated)
18242 [ + - ]: 24 : ereport(ERROR,
18243 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18244 : : errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
18245 [ + + + + ]: 3511 : if (child_att->attgenerated && !parent_att->attgenerated)
18246 [ + - ]: 16 : ereport(ERROR,
18247 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18248 : : errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
18249 : :
18250 [ + + + - : 3495 : if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
+ + ]
18251 [ + - + + : 8 : ereport(ERROR,
+ + ]
18252 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18253 : : errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
18254 : : errdetail("Parent column is %s, child column is %s.",
18255 : : parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
18256 : : child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
18257 : :
18258 : : /*
18259 : : * Regular inheritance children are independent enough not to
18260 : : * inherit identity columns. But partitions are integral part of
18261 : : * a partitioned table and inherit identity column.
18262 : : */
18263 [ + + ]: 3487 : if (ispartition)
18264 : 3038 : child_att->attidentity = parent_att->attidentity;
18265 : :
18266 : : /*
18267 : : * OK, bump the child column's inheritance count. (If we fail
18268 : : * later on, this change will just roll back.)
18269 : : */
18270 [ - + ]: 3487 : if (pg_add_s16_overflow(child_att->attinhcount, 1,
18271 : : &child_att->attinhcount))
18272 [ # # ]: 0 : ereport(ERROR,
18273 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18274 : : errmsg("too many inheritance parents"));
18275 : :
18276 : : /*
18277 : : * In case of partitions, we must enforce that value of attislocal
18278 : : * is same in all partitions. (Note: there are only inherited
18279 : : * attributes in partitions)
18280 : : */
18281 [ + + ]: 3487 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18282 : : {
18283 : : Assert(child_att->attinhcount == 1);
18284 : 3038 : child_att->attislocal = false;
18285 : : }
18286 : :
18287 : 3487 : CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
18288 : 3487 : heap_freetuple(tuple);
18289 : : }
18290 : : else
18291 : : {
18292 [ + - ]: 8 : ereport(ERROR,
18293 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18294 : : errmsg("child table is missing column \"%s\"", parent_attname)));
18295 : : }
18296 : : }
18297 : :
18298 : 1598 : table_close(attrrel, RowExclusiveLock);
18299 : 1598 : }
18300 : :
18301 : : /*
18302 : : * Check constraints in child table match up with constraints in parent,
18303 : : * and increment their coninhcount.
18304 : : *
18305 : : * Constraints that are marked ONLY in the parent are ignored.
18306 : : *
18307 : : * Called by CreateInheritance
18308 : : *
18309 : : * Currently all constraints in parent must be present in the child. One day we
18310 : : * may consider adding new constraints like CREATE TABLE does.
18311 : : *
18312 : : * XXX This is O(N^2) which may be an issue with tables with hundreds of
18313 : : * constraints. As long as tables have more like 10 constraints it shouldn't be
18314 : : * a problem though. Even 100 constraints ought not be the end of the world.
18315 : : *
18316 : : * XXX See MergeWithExistingConstraint too if you change this code.
18317 : : */
18318 : : static void
18319 : 1598 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
18320 : : {
18321 : : Relation constraintrel;
18322 : : SysScanDesc parent_scan;
18323 : : ScanKeyData parent_key;
18324 : : HeapTuple parent_tuple;
18325 : 1598 : Oid parent_relid = RelationGetRelid(parent_rel);
18326 : : AttrMap *attmap;
18327 : :
18328 : 1598 : constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
18329 : :
18330 : : /* Outer loop scans through the parent's constraint definitions */
18331 : 1598 : ScanKeyInit(&parent_key,
18332 : : Anum_pg_constraint_conrelid,
18333 : : BTEqualStrategyNumber, F_OIDEQ,
18334 : : ObjectIdGetDatum(parent_relid));
18335 : 1598 : parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
18336 : : true, NULL, 1, &parent_key);
18337 : :
18338 : 1598 : attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
18339 : : RelationGetDescr(child_rel),
18340 : : true);
18341 : :
18342 [ + + ]: 2873 : while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
18343 : : {
18344 : 1315 : Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
18345 : : SysScanDesc child_scan;
18346 : : ScanKeyData child_key;
18347 : : HeapTuple child_tuple;
18348 : : AttrNumber parent_attno;
18349 : 1315 : bool found = false;
18350 : :
18351 [ + + ]: 1315 : if (parent_con->contype != CONSTRAINT_CHECK &&
18352 [ + + ]: 1207 : parent_con->contype != CONSTRAINT_NOTNULL)
18353 : 650 : continue;
18354 : :
18355 : : /* if the parent's constraint is marked NO INHERIT, it's not inherited */
18356 [ + + ]: 697 : if (parent_con->connoinherit)
18357 : 32 : continue;
18358 : :
18359 [ + + ]: 665 : if (parent_con->contype == CONSTRAINT_NOTNULL)
18360 : 573 : parent_attno = extractNotNullColumn(parent_tuple);
18361 : : else
18362 : 92 : parent_attno = InvalidAttrNumber;
18363 : :
18364 : : /* Search for a child constraint matching this one */
18365 : 665 : ScanKeyInit(&child_key,
18366 : : Anum_pg_constraint_conrelid,
18367 : : BTEqualStrategyNumber, F_OIDEQ,
18368 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18369 : 665 : child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
18370 : : true, NULL, 1, &child_key);
18371 : :
18372 [ + + ]: 1052 : while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
18373 : : {
18374 : 1036 : Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
18375 : : HeapTuple child_copy;
18376 : :
18377 [ + + ]: 1036 : if (child_con->contype != parent_con->contype)
18378 : 186 : continue;
18379 : :
18380 : : /*
18381 : : * CHECK constraint are matched by constraint name, NOT NULL ones
18382 : : * by attribute number.
18383 : : */
18384 [ + + ]: 850 : if (child_con->contype == CONSTRAINT_CHECK)
18385 : : {
18386 : 122 : if (strcmp(NameStr(parent_con->conname),
18387 [ + + ]: 99 : NameStr(child_con->conname)) != 0)
18388 : 23 : continue;
18389 : : }
18390 [ + - ]: 751 : else if (child_con->contype == CONSTRAINT_NOTNULL)
18391 : : {
18392 : : Form_pg_attribute parent_attr;
18393 : : Form_pg_attribute child_attr;
18394 : : AttrNumber child_attno;
18395 : :
18396 : 751 : parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
18397 : 751 : child_attno = extractNotNullColumn(child_tuple);
18398 [ + + ]: 751 : if (parent_attno != attmap->attnums[child_attno - 1])
18399 : 178 : continue;
18400 : :
18401 : 573 : child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
18402 : : /* there shouldn't be constraints on dropped columns */
18403 [ + - - + ]: 573 : if (parent_attr->attisdropped || child_attr->attisdropped)
18404 [ # # ]: 0 : elog(ERROR, "found not-null constraint on dropped columns");
18405 : : }
18406 : :
18407 [ + + ]: 649 : if (child_con->contype == CONSTRAINT_CHECK &&
18408 [ + + ]: 76 : !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
18409 [ + - ]: 4 : ereport(ERROR,
18410 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18411 : : errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
18412 : : RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
18413 : :
18414 : : /*
18415 : : * If the child constraint is "no inherit" then cannot merge
18416 : : */
18417 [ + + ]: 645 : if (child_con->connoinherit)
18418 [ + - ]: 8 : ereport(ERROR,
18419 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18420 : : errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
18421 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18422 : :
18423 : : /*
18424 : : * If the child constraint is "not valid" then cannot merge with a
18425 : : * valid parent constraint
18426 : : */
18427 [ + + + + ]: 637 : if (parent_con->convalidated && child_con->conenforced &&
18428 [ + + ]: 593 : !child_con->convalidated)
18429 [ + - ]: 8 : ereport(ERROR,
18430 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18431 : : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
18432 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18433 : :
18434 : : /*
18435 : : * A NOT ENFORCED child constraint cannot be merged with an
18436 : : * ENFORCED parent constraint. However, the reverse is allowed,
18437 : : * where the child constraint is ENFORCED.
18438 : : */
18439 [ + + + + ]: 629 : if (parent_con->conenforced && !child_con->conenforced)
18440 [ + - ]: 4 : ereport(ERROR,
18441 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18442 : : errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
18443 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18444 : :
18445 : : /*
18446 : : * OK, bump the child constraint's inheritance count. (If we fail
18447 : : * later on, this change will just roll back.)
18448 : : */
18449 : 625 : child_copy = heap_copytuple(child_tuple);
18450 : 625 : child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
18451 : :
18452 [ - + ]: 625 : if (pg_add_s16_overflow(child_con->coninhcount, 1,
18453 : : &child_con->coninhcount))
18454 [ # # ]: 0 : ereport(ERROR,
18455 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18456 : : errmsg("too many inheritance parents"));
18457 : :
18458 : : /*
18459 : : * In case of partitions, an inherited constraint must be
18460 : : * inherited only once since it cannot have multiple parents and
18461 : : * it is never considered local.
18462 : : */
18463 [ + + ]: 625 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18464 : : {
18465 : : Assert(child_con->coninhcount == 1);
18466 : 526 : child_con->conislocal = false;
18467 : : }
18468 : :
18469 : 625 : CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
18470 : 625 : heap_freetuple(child_copy);
18471 : :
18472 : 625 : found = true;
18473 : 625 : break;
18474 : : }
18475 : :
18476 : 641 : systable_endscan(child_scan);
18477 : :
18478 [ + + ]: 641 : if (!found)
18479 : : {
18480 [ - + ]: 16 : if (parent_con->contype == CONSTRAINT_NOTNULL)
18481 [ # # ]: 0 : ereport(ERROR,
18482 : : errcode(ERRCODE_DATATYPE_MISMATCH),
18483 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18484 : : get_attname(parent_relid,
18485 : : extractNotNullColumn(parent_tuple),
18486 : : false),
18487 : : RelationGetRelationName(child_rel)));
18488 : :
18489 [ + - ]: 16 : ereport(ERROR,
18490 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18491 : : errmsg("child table is missing constraint \"%s\"",
18492 : : NameStr(parent_con->conname))));
18493 : : }
18494 : : }
18495 : :
18496 : 1558 : systable_endscan(parent_scan);
18497 : 1558 : table_close(constraintrel, RowExclusiveLock);
18498 : 1558 : }
18499 : :
18500 : : /*
18501 : : * ALTER TABLE NO INHERIT
18502 : : *
18503 : : * Return value is the address of the relation that is no longer parent.
18504 : : */
18505 : : static ObjectAddress
18506 : 61 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
18507 : : {
18508 : : ObjectAddress address;
18509 : : Relation parent_rel;
18510 : :
18511 : : /*
18512 : : * AccessShareLock on the parent is probably enough, seeing that DROP
18513 : : * TABLE doesn't lock parent tables at all. We need some lock since we'll
18514 : : * be inspecting the parent's schema.
18515 : : */
18516 : 61 : parent_rel = table_openrv(parent, AccessShareLock);
18517 : :
18518 : : /*
18519 : : * We don't bother to check ownership of the parent table --- ownership of
18520 : : * the child is presumed enough rights.
18521 : : */
18522 : :
18523 : : /* Off to RemoveInheritance() where most of the work happens */
18524 : 61 : RemoveInheritance(rel, parent_rel, false);
18525 : :
18526 : 57 : ObjectAddressSet(address, RelationRelationId,
18527 : : RelationGetRelid(parent_rel));
18528 : :
18529 : : /* keep our lock on the parent relation until commit */
18530 : 57 : table_close(parent_rel, NoLock);
18531 : :
18532 : 57 : return address;
18533 : : }
18534 : :
18535 : : /*
18536 : : * MarkInheritDetached
18537 : : *
18538 : : * Set inhdetachpending for a partition, for ATExecDetachPartition
18539 : : * in concurrent mode. While at it, verify that no other partition is
18540 : : * already pending detach.
18541 : : */
18542 : : static void
18543 : 76 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
18544 : : {
18545 : : Relation catalogRelation;
18546 : : SysScanDesc scan;
18547 : : ScanKeyData key;
18548 : : HeapTuple inheritsTuple;
18549 : 76 : bool found = false;
18550 : :
18551 : : Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18552 : :
18553 : : /*
18554 : : * Find pg_inherits entries by inhparent. (We need to scan them all in
18555 : : * order to verify that no other partition is pending detach.)
18556 : : */
18557 : 76 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18558 : 76 : ScanKeyInit(&key,
18559 : : Anum_pg_inherits_inhparent,
18560 : : BTEqualStrategyNumber, F_OIDEQ,
18561 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18562 : 76 : scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
18563 : : true, NULL, 1, &key);
18564 : :
18565 [ + + ]: 298 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18566 : : {
18567 : : Form_pg_inherits inhForm;
18568 : :
18569 : 147 : inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18570 [ + + ]: 147 : if (inhForm->inhdetachpending)
18571 [ + - ]: 1 : ereport(ERROR,
18572 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
18573 : : errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
18574 : : get_rel_name(inhForm->inhrelid),
18575 : : get_namespace_name(parent_rel->rd_rel->relnamespace),
18576 : : RelationGetRelationName(parent_rel)),
18577 : : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
18578 : :
18579 [ + + ]: 146 : if (inhForm->inhrelid == RelationGetRelid(child_rel))
18580 : : {
18581 : : HeapTuple newtup;
18582 : :
18583 : 75 : newtup = heap_copytuple(inheritsTuple);
18584 : 75 : ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
18585 : :
18586 : 75 : CatalogTupleUpdate(catalogRelation,
18587 : 75 : &inheritsTuple->t_self,
18588 : : newtup);
18589 : 75 : found = true;
18590 : 75 : heap_freetuple(newtup);
18591 : : /* keep looking, to ensure we catch others pending detach */
18592 : : }
18593 : : }
18594 : :
18595 : : /* Done */
18596 : 75 : systable_endscan(scan);
18597 : 75 : table_close(catalogRelation, RowExclusiveLock);
18598 : :
18599 [ - + ]: 75 : if (!found)
18600 [ # # ]: 0 : ereport(ERROR,
18601 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18602 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18603 : : RelationGetRelationName(child_rel),
18604 : : RelationGetRelationName(parent_rel))));
18605 : 75 : }
18606 : :
18607 : : /*
18608 : : * RemoveInheritance
18609 : : *
18610 : : * Drop a parent from the child's parents. This just adjusts the attinhcount
18611 : : * and attislocal of the columns and removes the pg_inherit and pg_depend
18612 : : * entries. expect_detached is passed down to DeleteInheritsTuple, q.v..
18613 : : *
18614 : : * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
18615 : : * up attislocal stays true, which means if a child is ever removed from a
18616 : : * parent then its columns will never be automatically dropped which may
18617 : : * surprise. But at least we'll never surprise by dropping columns someone
18618 : : * isn't expecting to be dropped which would actually mean data loss.
18619 : : *
18620 : : * coninhcount and conislocal for inherited constraints are adjusted in
18621 : : * exactly the same way.
18622 : : *
18623 : : * Common to ATExecDropInherit() and ATExecDetachPartition().
18624 : : */
18625 : : static void
18626 : 385 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
18627 : : {
18628 : : Relation catalogRelation;
18629 : : SysScanDesc scan;
18630 : : ScanKeyData key[3];
18631 : : HeapTuple attributeTuple,
18632 : : constraintTuple;
18633 : : AttrMap *attmap;
18634 : : List *connames;
18635 : : List *nncolumns;
18636 : : bool found;
18637 : : bool is_partitioning;
18638 : :
18639 : 385 : is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18640 : :
18641 : 385 : found = DeleteInheritsTuple(RelationGetRelid(child_rel),
18642 : : RelationGetRelid(parent_rel),
18643 : : expect_detached,
18644 : 385 : RelationGetRelationName(child_rel));
18645 [ + + ]: 385 : if (!found)
18646 : : {
18647 [ + + ]: 16 : if (is_partitioning)
18648 [ + - ]: 12 : ereport(ERROR,
18649 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18650 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18651 : : RelationGetRelationName(child_rel),
18652 : : RelationGetRelationName(parent_rel))));
18653 : : else
18654 [ + - ]: 4 : ereport(ERROR,
18655 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18656 : : errmsg("relation \"%s\" is not a parent of relation \"%s\"",
18657 : : RelationGetRelationName(parent_rel),
18658 : : RelationGetRelationName(child_rel))));
18659 : : }
18660 : :
18661 : : /*
18662 : : * Search through child columns looking for ones matching parent rel
18663 : : */
18664 : 369 : catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
18665 : 369 : ScanKeyInit(&key[0],
18666 : : Anum_pg_attribute_attrelid,
18667 : : BTEqualStrategyNumber, F_OIDEQ,
18668 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18669 : 369 : scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
18670 : : true, NULL, 1, key);
18671 [ + + ]: 3308 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
18672 : : {
18673 : 2939 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
18674 : :
18675 : : /* Ignore if dropped or not inherited */
18676 [ + + ]: 2939 : if (att->attisdropped)
18677 : 4 : continue;
18678 [ + + ]: 2935 : if (att->attinhcount <= 0)
18679 : 2234 : continue;
18680 : :
18681 [ + + ]: 701 : if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
18682 : 701 : NameStr(att->attname)))
18683 : : {
18684 : : /* Decrement inhcount and possibly set islocal to true */
18685 : 665 : HeapTuple copyTuple = heap_copytuple(attributeTuple);
18686 : 665 : Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
18687 : :
18688 : 665 : copy_att->attinhcount--;
18689 [ + + ]: 665 : if (copy_att->attinhcount == 0)
18690 : 645 : copy_att->attislocal = true;
18691 : :
18692 : 665 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18693 : 665 : heap_freetuple(copyTuple);
18694 : : }
18695 : : }
18696 : 369 : systable_endscan(scan);
18697 : 369 : table_close(catalogRelation, RowExclusiveLock);
18698 : :
18699 : : /*
18700 : : * Likewise, find inherited check and not-null constraints and disinherit
18701 : : * them. To do this, we first need a list of the names of the parent's
18702 : : * check constraints. (We cheat a bit by only checking for name matches,
18703 : : * assuming that the expressions will match.)
18704 : : *
18705 : : * For NOT NULL columns, we store column numbers to match, mapping them in
18706 : : * to the child rel's attribute numbers.
18707 : : */
18708 : 369 : attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
18709 : : RelationGetDescr(parent_rel),
18710 : : false);
18711 : :
18712 : 369 : catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
18713 : 369 : ScanKeyInit(&key[0],
18714 : : Anum_pg_constraint_conrelid,
18715 : : BTEqualStrategyNumber, F_OIDEQ,
18716 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18717 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18718 : : true, NULL, 1, key);
18719 : :
18720 : 369 : connames = NIL;
18721 : 369 : nncolumns = NIL;
18722 : :
18723 [ + + ]: 794 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18724 : : {
18725 : 425 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18726 : :
18727 [ + + ]: 425 : if (con->connoinherit)
18728 : 68 : continue;
18729 : :
18730 [ + + ]: 357 : if (con->contype == CONSTRAINT_CHECK)
18731 : 8 : connames = lappend(connames, pstrdup(NameStr(con->conname)));
18732 [ + + ]: 357 : if (con->contype == CONSTRAINT_NOTNULL)
18733 : : {
18734 : 133 : AttrNumber parent_attno = extractNotNullColumn(constraintTuple);
18735 : :
18736 : 133 : nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
18737 : : }
18738 : : }
18739 : :
18740 : 369 : systable_endscan(scan);
18741 : :
18742 : : /* Now scan the child's constraints to find matches */
18743 : 369 : ScanKeyInit(&key[0],
18744 : : Anum_pg_constraint_conrelid,
18745 : : BTEqualStrategyNumber, F_OIDEQ,
18746 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18747 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18748 : : true, NULL, 1, key);
18749 : :
18750 [ + + ]: 790 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18751 : : {
18752 : 421 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18753 : 421 : bool match = false;
18754 : :
18755 : : /*
18756 : : * Match CHECK constraints by name, not-null constraints by column
18757 : : * number, and ignore all others.
18758 : : */
18759 [ + + ]: 421 : if (con->contype == CONSTRAINT_CHECK)
18760 : : {
18761 [ + + + + : 92 : foreach_ptr(char, chkname, connames)
+ + ]
18762 : : {
18763 [ + - ]: 12 : if (con->contype == CONSTRAINT_CHECK &&
18764 [ + + ]: 12 : strcmp(NameStr(con->conname), chkname) == 0)
18765 : : {
18766 : 8 : match = true;
18767 : 8 : connames = foreach_delete_current(connames, chkname);
18768 : 8 : break;
18769 : : }
18770 : : }
18771 : : }
18772 [ + + ]: 377 : else if (con->contype == CONSTRAINT_NOTNULL)
18773 : : {
18774 : 173 : AttrNumber child_attno = extractNotNullColumn(constraintTuple);
18775 : :
18776 [ + + + + : 350 : foreach_int(prevattno, nncolumns)
+ + ]
18777 : : {
18778 [ + + ]: 137 : if (prevattno == child_attno)
18779 : : {
18780 : 133 : match = true;
18781 : 133 : nncolumns = foreach_delete_current(nncolumns, prevattno);
18782 : 133 : break;
18783 : : }
18784 : : }
18785 : : }
18786 : : else
18787 : 204 : continue;
18788 : :
18789 [ + + ]: 217 : if (match)
18790 : : {
18791 : : /* Decrement inhcount and possibly set islocal to true */
18792 : 141 : HeapTuple copyTuple = heap_copytuple(constraintTuple);
18793 : 141 : Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
18794 : :
18795 [ - + ]: 141 : if (copy_con->coninhcount <= 0) /* shouldn't happen */
18796 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
18797 : : RelationGetRelid(child_rel), NameStr(copy_con->conname));
18798 : :
18799 : 141 : copy_con->coninhcount--;
18800 [ + + ]: 141 : if (copy_con->coninhcount == 0)
18801 : 129 : copy_con->conislocal = true;
18802 : :
18803 : 141 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18804 : 141 : heap_freetuple(copyTuple);
18805 : : }
18806 : : }
18807 : :
18808 : : /* We should have matched all constraints */
18809 [ + - - + ]: 369 : if (connames != NIL || nncolumns != NIL)
18810 [ # # ]: 0 : elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
18811 : : list_length(connames) + list_length(nncolumns),
18812 : : RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
18813 : :
18814 : 369 : systable_endscan(scan);
18815 : 369 : table_close(catalogRelation, RowExclusiveLock);
18816 : :
18817 [ + + ]: 369 : drop_parent_dependency(RelationGetRelid(child_rel),
18818 : : RelationRelationId,
18819 : : RelationGetRelid(parent_rel),
18820 : : child_dependency_type(is_partitioning));
18821 : :
18822 : : /*
18823 : : * Post alter hook of this inherits. Since object_access_hook doesn't take
18824 : : * multiple object identifiers, we relay oid of parent relation using
18825 : : * auxiliary_id argument.
18826 : : */
18827 [ - + ]: 369 : InvokeObjectPostAlterHookArg(InheritsRelationId,
18828 : : RelationGetRelid(child_rel), 0,
18829 : : RelationGetRelid(parent_rel), false);
18830 : 369 : }
18831 : :
18832 : : /*
18833 : : * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
18834 : : * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
18835 : : * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
18836 : : * be TypeRelationId). There's no convenient way to do this, so go trawling
18837 : : * through pg_depend.
18838 : : */
18839 : : static void
18840 : 377 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
18841 : : DependencyType deptype)
18842 : : {
18843 : : Relation catalogRelation;
18844 : : SysScanDesc scan;
18845 : : ScanKeyData key[3];
18846 : : HeapTuple depTuple;
18847 : :
18848 : 377 : catalogRelation = table_open(DependRelationId, RowExclusiveLock);
18849 : :
18850 : 377 : ScanKeyInit(&key[0],
18851 : : Anum_pg_depend_classid,
18852 : : BTEqualStrategyNumber, F_OIDEQ,
18853 : : ObjectIdGetDatum(RelationRelationId));
18854 : 377 : ScanKeyInit(&key[1],
18855 : : Anum_pg_depend_objid,
18856 : : BTEqualStrategyNumber, F_OIDEQ,
18857 : : ObjectIdGetDatum(relid));
18858 : 377 : ScanKeyInit(&key[2],
18859 : : Anum_pg_depend_objsubid,
18860 : : BTEqualStrategyNumber, F_INT4EQ,
18861 : : Int32GetDatum(0));
18862 : :
18863 : 377 : scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
18864 : : NULL, 3, key);
18865 : :
18866 [ + + ]: 1172 : while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
18867 : : {
18868 : 795 : Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
18869 : :
18870 [ + + ]: 795 : if (dep->refclassid == refclassid &&
18871 [ + + ]: 405 : dep->refobjid == refobjid &&
18872 [ + - ]: 377 : dep->refobjsubid == 0 &&
18873 [ + - ]: 377 : dep->deptype == deptype)
18874 : 377 : CatalogTupleDelete(catalogRelation, &depTuple->t_self);
18875 : : }
18876 : :
18877 : 377 : systable_endscan(scan);
18878 : 377 : table_close(catalogRelation, RowExclusiveLock);
18879 : 377 : }
18880 : :
18881 : : /*
18882 : : * ALTER TABLE OF
18883 : : *
18884 : : * Attach a table to a composite type, as though it had been created with CREATE
18885 : : * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
18886 : : * subject table must not have inheritance parents. These restrictions ensure
18887 : : * that you cannot create a configuration impossible with CREATE TABLE OF alone.
18888 : : *
18889 : : * The address of the type is returned.
18890 : : */
18891 : : static ObjectAddress
18892 : 50 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
18893 : : {
18894 : 50 : Oid relid = RelationGetRelid(rel);
18895 : : Type typetuple;
18896 : : Form_pg_type typeform;
18897 : : Oid typeid;
18898 : : Relation inheritsRelation,
18899 : : relationRelation;
18900 : : SysScanDesc scan;
18901 : : ScanKeyData key;
18902 : : AttrNumber table_attno,
18903 : : type_attno;
18904 : : TupleDesc typeTupleDesc,
18905 : : tableTupleDesc;
18906 : : ObjectAddress tableobj,
18907 : : typeobj;
18908 : : HeapTuple classtuple;
18909 : : AclResult aclresult;
18910 : :
18911 : : /* Validate the type. */
18912 : 50 : typetuple = typenameType(NULL, ofTypename, NULL);
18913 : 50 : check_of_type(typetuple);
18914 : 50 : typeform = (Form_pg_type) GETSTRUCT(typetuple);
18915 : 50 : typeid = typeform->oid;
18916 : :
18917 : 50 : aclresult = object_aclcheck(TypeRelationId, typeid, GetUserId(), ACL_USAGE);
18918 [ + + ]: 50 : if (aclresult != ACLCHECK_OK)
18919 : 4 : aclcheck_error_type(aclresult, typeid);
18920 : :
18921 : : /* Fail if the table has any inheritance parents. */
18922 : 46 : inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
18923 : 46 : ScanKeyInit(&key,
18924 : : Anum_pg_inherits_inhrelid,
18925 : : BTEqualStrategyNumber, F_OIDEQ,
18926 : : ObjectIdGetDatum(relid));
18927 : 46 : scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
18928 : : true, NULL, 1, &key);
18929 [ + + ]: 46 : if (HeapTupleIsValid(systable_getnext(scan)))
18930 [ + - ]: 4 : ereport(ERROR,
18931 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18932 : : errmsg("typed tables cannot inherit")));
18933 : 42 : systable_endscan(scan);
18934 : 42 : table_close(inheritsRelation, AccessShareLock);
18935 : :
18936 : : /*
18937 : : * Check the tuple descriptors for compatibility. Unlike inheritance, we
18938 : : * require that the order also match. However, attnotnull need not match.
18939 : : */
18940 : 42 : typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
18941 : 42 : tableTupleDesc = RelationGetDescr(rel);
18942 : 42 : table_attno = 1;
18943 [ + + ]: 133 : for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
18944 : : {
18945 : : Form_pg_attribute type_attr,
18946 : : table_attr;
18947 : : const char *type_attname,
18948 : : *table_attname;
18949 : :
18950 : : /* Get the next non-dropped type attribute. */
18951 : 107 : type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
18952 [ + + ]: 107 : if (type_attr->attisdropped)
18953 : 29 : continue;
18954 : 78 : type_attname = NameStr(type_attr->attname);
18955 : :
18956 : : /* Get the next non-dropped table attribute. */
18957 : : do
18958 : : {
18959 [ + + ]: 86 : if (table_attno > tableTupleDesc->natts)
18960 [ + - ]: 4 : ereport(ERROR,
18961 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18962 : : errmsg("table is missing column \"%s\"",
18963 : : type_attname)));
18964 : 82 : table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
18965 : 82 : table_attno++;
18966 [ + + ]: 82 : } while (table_attr->attisdropped);
18967 : 74 : table_attname = NameStr(table_attr->attname);
18968 : :
18969 : : /* Compare name. */
18970 [ + + ]: 74 : if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
18971 [ + - ]: 4 : ereport(ERROR,
18972 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18973 : : errmsg("table has column \"%s\" where type requires \"%s\"",
18974 : : table_attname, type_attname)));
18975 : :
18976 : : /* Compare type. */
18977 [ + + ]: 70 : if (table_attr->atttypid != type_attr->atttypid ||
18978 [ + + ]: 66 : table_attr->atttypmod != type_attr->atttypmod ||
18979 [ - + ]: 62 : table_attr->attcollation != type_attr->attcollation)
18980 [ + - ]: 8 : ereport(ERROR,
18981 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18982 : : errmsg("table \"%s\" has different type for column \"%s\"",
18983 : : RelationGetRelationName(rel), type_attname)));
18984 : : }
18985 [ + - ]: 26 : ReleaseTupleDesc(typeTupleDesc);
18986 : :
18987 : : /* Any remaining columns at the end of the table had better be dropped. */
18988 [ + + ]: 26 : for (; table_attno <= tableTupleDesc->natts; table_attno++)
18989 : : {
18990 : 4 : Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
18991 : : table_attno - 1);
18992 : :
18993 [ + - ]: 4 : if (!table_attr->attisdropped)
18994 [ + - ]: 4 : ereport(ERROR,
18995 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18996 : : errmsg("table has extra column \"%s\"",
18997 : : NameStr(table_attr->attname))));
18998 : : }
18999 : :
19000 : : /* If the table was already typed, drop the existing dependency. */
19001 [ + + ]: 22 : if (rel->rd_rel->reloftype)
19002 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
19003 : : DEPENDENCY_NORMAL);
19004 : :
19005 : : /* Record a dependency on the new type. */
19006 : 22 : tableobj.classId = RelationRelationId;
19007 : 22 : tableobj.objectId = relid;
19008 : 22 : tableobj.objectSubId = 0;
19009 : 22 : typeobj.classId = TypeRelationId;
19010 : 22 : typeobj.objectId = typeid;
19011 : 22 : typeobj.objectSubId = 0;
19012 : 22 : recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
19013 : :
19014 : : /* Update pg_class.reloftype */
19015 : 22 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19016 : 22 : classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19017 [ - + ]: 22 : if (!HeapTupleIsValid(classtuple))
19018 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19019 : 22 : ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
19020 : 22 : CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
19021 : :
19022 [ - + ]: 22 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19023 : :
19024 : 22 : heap_freetuple(classtuple);
19025 : 22 : table_close(relationRelation, RowExclusiveLock);
19026 : :
19027 : 22 : ReleaseSysCache(typetuple);
19028 : :
19029 : 22 : return typeobj;
19030 : : }
19031 : :
19032 : : /*
19033 : : * ALTER TABLE NOT OF
19034 : : *
19035 : : * Detach a typed table from its originating type. Just clear reloftype and
19036 : : * remove the dependency.
19037 : : */
19038 : : static void
19039 : 4 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
19040 : : {
19041 : 4 : Oid relid = RelationGetRelid(rel);
19042 : : Relation relationRelation;
19043 : : HeapTuple tuple;
19044 : :
19045 [ - + ]: 4 : if (!OidIsValid(rel->rd_rel->reloftype))
19046 [ # # ]: 0 : ereport(ERROR,
19047 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19048 : : errmsg("\"%s\" is not a typed table",
19049 : : RelationGetRelationName(rel))));
19050 : :
19051 : : /*
19052 : : * We don't bother to check ownership of the type --- ownership of the
19053 : : * table is presumed enough rights. No lock required on the type, either.
19054 : : */
19055 : :
19056 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
19057 : : DEPENDENCY_NORMAL);
19058 : :
19059 : : /* Clear pg_class.reloftype */
19060 : 4 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19061 : 4 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19062 [ - + ]: 4 : if (!HeapTupleIsValid(tuple))
19063 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19064 : 4 : ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
19065 : 4 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
19066 : :
19067 [ - + ]: 4 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19068 : :
19069 : 4 : heap_freetuple(tuple);
19070 : 4 : table_close(relationRelation, RowExclusiveLock);
19071 : 4 : }
19072 : :
19073 : : /*
19074 : : * relation_mark_replica_identity: Update a table's replica identity
19075 : : *
19076 : : * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
19077 : : * index. Otherwise, it must be InvalidOid.
19078 : : *
19079 : : * Caller had better hold an exclusive lock on the relation, as the results
19080 : : * of running two of these concurrently wouldn't be pretty.
19081 : : */
19082 : : static void
19083 : 297 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
19084 : : bool is_internal)
19085 : : {
19086 : : Relation pg_index;
19087 : : Relation pg_class;
19088 : : HeapTuple pg_class_tuple;
19089 : : HeapTuple pg_index_tuple;
19090 : : Form_pg_class pg_class_form;
19091 : : Form_pg_index pg_index_form;
19092 : : ListCell *index;
19093 : :
19094 : : /*
19095 : : * Check whether relreplident has changed, and update it if so.
19096 : : */
19097 : 297 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19098 : 297 : pg_class_tuple = SearchSysCacheCopy1(RELOID,
19099 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19100 [ - + ]: 297 : if (!HeapTupleIsValid(pg_class_tuple))
19101 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation \"%s\"",
19102 : : RelationGetRelationName(rel));
19103 : 297 : pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
19104 [ + + ]: 297 : if (pg_class_form->relreplident != ri_type)
19105 : : {
19106 : 263 : pg_class_form->relreplident = ri_type;
19107 : 263 : CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
19108 : : }
19109 : 297 : table_close(pg_class, RowExclusiveLock);
19110 : 297 : heap_freetuple(pg_class_tuple);
19111 : :
19112 : : /*
19113 : : * Update the per-index indisreplident flags correctly.
19114 : : */
19115 : 297 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
19116 [ + + + + : 779 : foreach(index, RelationGetIndexList(rel))
+ + ]
19117 : : {
19118 : 482 : Oid thisIndexOid = lfirst_oid(index);
19119 : 482 : bool dirty = false;
19120 : :
19121 : 482 : pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
19122 : : ObjectIdGetDatum(thisIndexOid));
19123 [ - + ]: 482 : if (!HeapTupleIsValid(pg_index_tuple))
19124 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
19125 : 482 : pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
19126 : :
19127 [ + + ]: 482 : if (thisIndexOid == indexOid)
19128 : : {
19129 : : /* Set the bit if not already set. */
19130 [ + + ]: 162 : if (!pg_index_form->indisreplident)
19131 : : {
19132 : 150 : dirty = true;
19133 : 150 : pg_index_form->indisreplident = true;
19134 : : }
19135 : : }
19136 : : else
19137 : : {
19138 : : /* Unset the bit if set. */
19139 [ + + ]: 320 : if (pg_index_form->indisreplident)
19140 : : {
19141 : 34 : dirty = true;
19142 : 34 : pg_index_form->indisreplident = false;
19143 : : }
19144 : : }
19145 : :
19146 [ + + ]: 482 : if (dirty)
19147 : : {
19148 : 184 : CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
19149 [ - + ]: 184 : InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
19150 : : InvalidOid, is_internal);
19151 : :
19152 : : /*
19153 : : * Invalidate the relcache for the table, so that after we commit
19154 : : * all sessions will refresh the table's replica identity index
19155 : : * before attempting any UPDATE or DELETE on the table. (If we
19156 : : * changed the table's pg_class row above, then a relcache inval
19157 : : * is already queued due to that; but we might not have.)
19158 : : */
19159 : 184 : CacheInvalidateRelcache(rel);
19160 : : }
19161 : 482 : heap_freetuple(pg_index_tuple);
19162 : : }
19163 : :
19164 : 297 : table_close(pg_index, RowExclusiveLock);
19165 : 297 : }
19166 : :
19167 : : /*
19168 : : * ALTER TABLE <name> REPLICA IDENTITY ...
19169 : : */
19170 : : static void
19171 : 333 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
19172 : : {
19173 : : Oid indexOid;
19174 : : Relation indexRel;
19175 : : int key;
19176 : :
19177 [ + + ]: 333 : if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
19178 : : {
19179 : 5 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19180 : 5 : return;
19181 : : }
19182 [ + + ]: 328 : else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
19183 : : {
19184 : 100 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19185 : 100 : return;
19186 : : }
19187 [ + + ]: 228 : else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
19188 : : {
19189 : 30 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19190 : 30 : return;
19191 : : }
19192 [ - + ]: 198 : else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
19193 : : {
19194 : : /* fallthrough */ ;
19195 : : }
19196 : : else
19197 [ # # ]: 0 : elog(ERROR, "unexpected identity type %u", stmt->identity_type);
19198 : :
19199 : : /* Check that the index exists */
19200 : 198 : indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
19201 [ - + ]: 198 : if (!OidIsValid(indexOid))
19202 [ # # ]: 0 : ereport(ERROR,
19203 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
19204 : : errmsg("index \"%s\" for table \"%s\" does not exist",
19205 : : stmt->name, RelationGetRelationName(rel))));
19206 : :
19207 : 198 : indexRel = index_open(indexOid, ShareLock);
19208 : :
19209 : : /* Check that the index is on the relation we're altering. */
19210 [ + - ]: 198 : if (indexRel->rd_index == NULL ||
19211 [ + + ]: 198 : indexRel->rd_index->indrelid != RelationGetRelid(rel))
19212 [ + - ]: 4 : ereport(ERROR,
19213 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19214 : : errmsg("\"%s\" is not an index for table \"%s\"",
19215 : : RelationGetRelationName(indexRel),
19216 : : RelationGetRelationName(rel))));
19217 : :
19218 : : /*
19219 : : * The AM must support uniqueness, and the index must in fact be unique.
19220 : : * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
19221 : : * exclusion), we can use that too.
19222 : : */
19223 [ + + ]: 194 : if ((!indexRel->rd_indam->amcanunique ||
19224 [ + + ]: 180 : !indexRel->rd_index->indisunique) &&
19225 [ + + - + ]: 18 : !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
19226 [ + - ]: 8 : ereport(ERROR,
19227 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19228 : : errmsg("cannot use non-unique index \"%s\" as replica identity",
19229 : : RelationGetRelationName(indexRel))));
19230 : : /* Deferred indexes are not guaranteed to be always unique. */
19231 [ + + ]: 186 : if (!indexRel->rd_index->indimmediate)
19232 [ + - ]: 8 : ereport(ERROR,
19233 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19234 : : errmsg("cannot use non-immediate index \"%s\" as replica identity",
19235 : : RelationGetRelationName(indexRel))));
19236 : : /* Expression indexes aren't supported. */
19237 [ + + ]: 178 : if (RelationGetIndexExpressions(indexRel) != NIL)
19238 [ + - ]: 4 : ereport(ERROR,
19239 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19240 : : errmsg("cannot use expression index \"%s\" as replica identity",
19241 : : RelationGetRelationName(indexRel))));
19242 : : /* Predicate indexes aren't supported. */
19243 [ + + ]: 174 : if (RelationGetIndexPredicate(indexRel) != NIL)
19244 [ + - ]: 4 : ereport(ERROR,
19245 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19246 : : errmsg("cannot use partial index \"%s\" as replica identity",
19247 : : RelationGetRelationName(indexRel))));
19248 : :
19249 : : /* Check index for nullable columns. */
19250 [ + + ]: 377 : for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
19251 : : {
19252 : 215 : int16 attno = indexRel->rd_index->indkey.values[key];
19253 : : Form_pg_attribute attr;
19254 : : HeapTuple contup;
19255 : : Form_pg_constraint conForm;
19256 : :
19257 : : /*
19258 : : * Reject any other system columns. (Going forward, we'll disallow
19259 : : * indexes containing such columns in the first place, but they might
19260 : : * exist in older branches.)
19261 : : */
19262 [ - + ]: 215 : if (attno <= 0)
19263 [ # # ]: 0 : ereport(ERROR,
19264 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
19265 : : errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
19266 : : RelationGetRelationName(indexRel), attno)));
19267 : :
19268 : 215 : attr = TupleDescAttr(rel->rd_att, attno - 1);
19269 [ + + ]: 215 : if (!attr->attnotnull)
19270 [ + - ]: 4 : ereport(ERROR,
19271 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19272 : : errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
19273 : : RelationGetRelationName(indexRel),
19274 : : NameStr(attr->attname))));
19275 : :
19276 : : /*
19277 : : * Verify that the not-null constraint for the column is valid.
19278 : : */
19279 : 211 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel), attno);
19280 [ - + ]: 211 : if (!HeapTupleIsValid(contup))
19281 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
19282 : : NameStr(attr->attname), RelationGetRelationName(rel));
19283 : 211 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
19284 [ + + ]: 211 : if (!conForm->convalidated)
19285 [ + - ]: 4 : ereport(ERROR,
19286 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19287 : : errmsg("cannot use index \"%s\" as replica identity",
19288 : : RelationGetRelationName(indexRel)),
19289 : : /*- translator: third %s is a constraint characteristic such as NOT VALID */
19290 : : errdetail("The constraint \"%s\" on column \"%s\" is marked %s.",
19291 : : NameStr(conForm->conname), NameStr(attr->attname), "NOT VALID"),
19292 : : errhint("You might need to validate it using %s.",
19293 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
19294 : 207 : heap_freetuple(contup);
19295 : : }
19296 : :
19297 : : /* This index is suitable for use as a replica identity. Mark it. */
19298 : 162 : relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
19299 : :
19300 : 162 : index_close(indexRel, NoLock);
19301 : : }
19302 : :
19303 : : /*
19304 : : * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
19305 : : */
19306 : : static void
19307 : 256 : ATExecSetRowSecurity(Relation rel, bool rls)
19308 : : {
19309 : : Relation pg_class;
19310 : : Oid relid;
19311 : : HeapTuple tuple;
19312 : :
19313 : 256 : relid = RelationGetRelid(rel);
19314 : :
19315 : : /* Pull the record for this relation and update it */
19316 : 256 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19317 : :
19318 : 256 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19319 : :
19320 [ - + ]: 256 : if (!HeapTupleIsValid(tuple))
19321 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19322 : :
19323 : 256 : ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
19324 : 256 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
19325 : :
19326 [ + + ]: 256 : InvokeObjectPostAlterHook(RelationRelationId,
19327 : : RelationGetRelid(rel), 0);
19328 : :
19329 : 256 : table_close(pg_class, RowExclusiveLock);
19330 : 256 : heap_freetuple(tuple);
19331 : 256 : }
19332 : :
19333 : : /*
19334 : : * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
19335 : : */
19336 : : static void
19337 : 85 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
19338 : : {
19339 : : Relation pg_class;
19340 : : Oid relid;
19341 : : HeapTuple tuple;
19342 : :
19343 : 85 : relid = RelationGetRelid(rel);
19344 : :
19345 : 85 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19346 : :
19347 : 85 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19348 : :
19349 [ - + ]: 85 : if (!HeapTupleIsValid(tuple))
19350 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19351 : :
19352 : 85 : ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
19353 : 85 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
19354 : :
19355 [ + + ]: 85 : InvokeObjectPostAlterHook(RelationRelationId,
19356 : : RelationGetRelid(rel), 0);
19357 : :
19358 : 85 : table_close(pg_class, RowExclusiveLock);
19359 : 85 : heap_freetuple(tuple);
19360 : 85 : }
19361 : :
19362 : : /*
19363 : : * ALTER FOREIGN TABLE <name> OPTIONS (...)
19364 : : */
19365 : : static void
19366 : 34 : ATExecGenericOptions(Relation rel, List *options)
19367 : : {
19368 : : Relation ftrel;
19369 : : ForeignServer *server;
19370 : : ForeignDataWrapper *fdw;
19371 : : HeapTuple tuple;
19372 : : bool isnull;
19373 : : Datum repl_val[Natts_pg_foreign_table];
19374 : : bool repl_null[Natts_pg_foreign_table];
19375 : : bool repl_repl[Natts_pg_foreign_table];
19376 : : Datum datum;
19377 : : Form_pg_foreign_table tableform;
19378 : :
19379 [ - + ]: 34 : if (options == NIL)
19380 : 0 : return;
19381 : :
19382 : 34 : ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
19383 : :
19384 : 34 : tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
19385 : : ObjectIdGetDatum(rel->rd_id));
19386 [ - + ]: 34 : if (!HeapTupleIsValid(tuple))
19387 [ # # ]: 0 : ereport(ERROR,
19388 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
19389 : : errmsg("foreign table \"%s\" does not exist",
19390 : : RelationGetRelationName(rel))));
19391 : 34 : tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
19392 : 34 : server = GetForeignServer(tableform->ftserver);
19393 : 34 : fdw = GetForeignDataWrapper(server->fdwid);
19394 : :
19395 : 34 : memset(repl_val, 0, sizeof(repl_val));
19396 : 34 : memset(repl_null, false, sizeof(repl_null));
19397 : 34 : memset(repl_repl, false, sizeof(repl_repl));
19398 : :
19399 : : /* Extract the current options */
19400 : 34 : datum = SysCacheGetAttr(FOREIGNTABLEREL,
19401 : : tuple,
19402 : : Anum_pg_foreign_table_ftoptions,
19403 : : &isnull);
19404 [ + + ]: 34 : if (isnull)
19405 : 2 : datum = PointerGetDatum(NULL);
19406 : :
19407 : : /* Transform the options */
19408 : 34 : datum = transformGenericOptions(ForeignTableRelationId,
19409 : : datum,
19410 : : options,
19411 : : fdw->fdwvalidator);
19412 : :
19413 [ + - ]: 33 : if (DatumGetPointer(datum) != NULL)
19414 : 33 : repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
19415 : : else
19416 : 0 : repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
19417 : :
19418 : 33 : repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
19419 : :
19420 : : /* Everything looks good - update the tuple */
19421 : :
19422 : 33 : tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
19423 : : repl_val, repl_null, repl_repl);
19424 : :
19425 : 33 : CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
19426 : :
19427 : : /*
19428 : : * Invalidate relcache so that all sessions will refresh any cached plans
19429 : : * that might depend on the old options.
19430 : : */
19431 : 33 : CacheInvalidateRelcache(rel);
19432 : :
19433 [ - + ]: 33 : InvokeObjectPostAlterHook(ForeignTableRelationId,
19434 : : RelationGetRelid(rel), 0);
19435 : :
19436 : 33 : table_close(ftrel, RowExclusiveLock);
19437 : :
19438 : 33 : heap_freetuple(tuple);
19439 : : }
19440 : :
19441 : : /*
19442 : : * ALTER TABLE ALTER COLUMN SET COMPRESSION
19443 : : *
19444 : : * Return value is the address of the modified column
19445 : : */
19446 : : static ObjectAddress
19447 : 49 : ATExecSetCompression(Relation rel,
19448 : : const char *column,
19449 : : Node *newValue,
19450 : : LOCKMODE lockmode)
19451 : : {
19452 : : Relation attrel;
19453 : : HeapTuple tuple;
19454 : : Form_pg_attribute atttableform;
19455 : : AttrNumber attnum;
19456 : : char *compression;
19457 : : char cmethod;
19458 : : ObjectAddress address;
19459 : :
19460 : 49 : compression = strVal(newValue);
19461 : :
19462 : 49 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
19463 : :
19464 : : /* copy the cache entry so we can scribble on it below */
19465 : 49 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
19466 [ - + ]: 49 : if (!HeapTupleIsValid(tuple))
19467 [ # # ]: 0 : ereport(ERROR,
19468 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
19469 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
19470 : : column, RelationGetRelationName(rel))));
19471 : :
19472 : : /* prevent them from altering a system attribute */
19473 : 49 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
19474 : 49 : attnum = atttableform->attnum;
19475 [ - + ]: 49 : if (attnum <= 0)
19476 [ # # ]: 0 : ereport(ERROR,
19477 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19478 : : errmsg("cannot alter system column \"%s\"", column)));
19479 : :
19480 : : /*
19481 : : * Check that column type is compressible, then get the attribute
19482 : : * compression method code
19483 : : */
19484 : 49 : cmethod = GetAttributeCompression(atttableform->atttypid, compression);
19485 : :
19486 : : /* update pg_attribute entry */
19487 : 45 : atttableform->attcompression = cmethod;
19488 : 45 : CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
19489 : :
19490 [ - + ]: 45 : InvokeObjectPostAlterHook(RelationRelationId,
19491 : : RelationGetRelid(rel),
19492 : : attnum);
19493 : :
19494 : : /*
19495 : : * Apply the change to indexes as well (only for simple index columns,
19496 : : * matching behavior of index.c ConstructTupleDescriptor()).
19497 : : */
19498 : 45 : SetIndexStorageProperties(rel, attrel, attnum,
19499 : : false, 0,
19500 : : true, cmethod,
19501 : : lockmode);
19502 : :
19503 : 45 : heap_freetuple(tuple);
19504 : :
19505 : 45 : table_close(attrel, RowExclusiveLock);
19506 : :
19507 : : /* make changes visible */
19508 : 45 : CommandCounterIncrement();
19509 : :
19510 : 45 : ObjectAddressSubSet(address, RelationRelationId,
19511 : : RelationGetRelid(rel), attnum);
19512 : 45 : return address;
19513 : : }
19514 : :
19515 : :
19516 : : /*
19517 : : * Preparation phase for SET LOGGED/UNLOGGED
19518 : : *
19519 : : * This verifies that we're not trying to change a temp table. Also,
19520 : : * existing foreign key constraints are checked to avoid ending up with
19521 : : * permanent tables referencing unlogged tables.
19522 : : */
19523 : : static void
19524 : 71 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
19525 : : {
19526 : : Relation pg_constraint;
19527 : : HeapTuple tuple;
19528 : : SysScanDesc scan;
19529 : : ScanKeyData skey[1];
19530 : :
19531 : : /*
19532 : : * Disallow changing status for a temp table. Also verify whether we can
19533 : : * get away with doing nothing; in such cases we don't need to run the
19534 : : * checks below, either.
19535 : : */
19536 [ - + + - ]: 71 : switch (rel->rd_rel->relpersistence)
19537 : : {
19538 : 0 : case RELPERSISTENCE_TEMP:
19539 [ # # ]: 0 : ereport(ERROR,
19540 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19541 : : errmsg("cannot change logged status of table \"%s\" because it is temporary",
19542 : : RelationGetRelationName(rel)),
19543 : : errtable(rel)));
19544 : : break;
19545 : 41 : case RELPERSISTENCE_PERMANENT:
19546 [ + + ]: 41 : if (toLogged)
19547 : : /* nothing to do */
19548 : 8 : return;
19549 : 37 : break;
19550 : 30 : case RELPERSISTENCE_UNLOGGED:
19551 [ + + ]: 30 : if (!toLogged)
19552 : : /* nothing to do */
19553 : 4 : return;
19554 : 26 : break;
19555 : : }
19556 : :
19557 : : /*
19558 : : * UNLOGGED tables can neither be published nor be named in a
19559 : : * publication's EXCEPT clause, so reject the change if the table is
19560 : : * referenced by any publication.
19561 : : */
19562 [ + + + + ]: 63 : if (!toLogged && RelationHasPublication(RelationGetRelid(rel)))
19563 [ + - ]: 4 : ereport(ERROR,
19564 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19565 : : errmsg("cannot change table \"%s\" to unlogged because it is referenced by a publication",
19566 : : RelationGetRelationName(rel)),
19567 : : errdetail("Unlogged relations cannot be published or excluded via an EXCEPT clause."),
19568 : : errhint("Drop the table from the publication, or remove it from the publication's EXCEPT clause, first.")));
19569 : :
19570 : : /*
19571 : : * Check existing foreign key constraints to preserve the invariant that
19572 : : * permanent tables cannot reference unlogged ones. Self-referencing
19573 : : * foreign keys can safely be ignored.
19574 : : */
19575 : 59 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
19576 : :
19577 : : /*
19578 : : * Scan conrelid if changing to permanent, else confrelid. This also
19579 : : * determines whether a useful index exists.
19580 : : */
19581 [ + + ]: 59 : ScanKeyInit(&skey[0],
19582 : : toLogged ? Anum_pg_constraint_conrelid :
19583 : : Anum_pg_constraint_confrelid,
19584 : : BTEqualStrategyNumber, F_OIDEQ,
19585 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19586 [ + + ]: 59 : scan = systable_beginscan(pg_constraint,
19587 : : toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
19588 : : true, NULL, 1, skey);
19589 : :
19590 [ + + ]: 95 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
19591 : : {
19592 : 44 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
19593 : :
19594 [ + + ]: 44 : if (con->contype == CONSTRAINT_FOREIGN)
19595 : : {
19596 : : Oid foreignrelid;
19597 : : Relation foreignrel;
19598 : :
19599 : : /* the opposite end of what we used as scankey */
19600 [ + + ]: 20 : foreignrelid = toLogged ? con->confrelid : con->conrelid;
19601 : :
19602 : : /* ignore if self-referencing */
19603 [ + + ]: 20 : if (RelationGetRelid(rel) == foreignrelid)
19604 : 8 : continue;
19605 : :
19606 : 12 : foreignrel = relation_open(foreignrelid, AccessShareLock);
19607 : :
19608 [ + + ]: 12 : if (toLogged)
19609 : : {
19610 [ + - ]: 4 : if (!RelationIsPermanent(foreignrel))
19611 [ + - ]: 4 : ereport(ERROR,
19612 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19613 : : errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
19614 : : RelationGetRelationName(rel),
19615 : : RelationGetRelationName(foreignrel)),
19616 : : errtableconstraint(rel, NameStr(con->conname))));
19617 : : }
19618 : : else
19619 : : {
19620 [ + + ]: 8 : if (RelationIsPermanent(foreignrel))
19621 [ + - ]: 4 : ereport(ERROR,
19622 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19623 : : errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
19624 : : RelationGetRelationName(rel),
19625 : : RelationGetRelationName(foreignrel)),
19626 : : errtableconstraint(rel, NameStr(con->conname))));
19627 : : }
19628 : :
19629 : 4 : relation_close(foreignrel, AccessShareLock);
19630 : : }
19631 : : }
19632 : :
19633 : 51 : systable_endscan(scan);
19634 : :
19635 : 51 : table_close(pg_constraint, AccessShareLock);
19636 : :
19637 : : /* force rewrite if necessary; see comment in ATRewriteTables */
19638 : 51 : tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
19639 [ + + ]: 51 : if (toLogged)
19640 : 22 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
19641 : : else
19642 : 29 : tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
19643 : 51 : tab->chgPersistence = true;
19644 : : }
19645 : :
19646 : : /*
19647 : : * Execute ALTER TABLE SET SCHEMA
19648 : : */
19649 : : ObjectAddress
19650 : 76 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
19651 : : {
19652 : : Relation rel;
19653 : : Oid relid;
19654 : : Oid oldNspOid;
19655 : : Oid nspOid;
19656 : : RangeVar *newrv;
19657 : : ObjectAddresses *objsMoved;
19658 : : ObjectAddress myself;
19659 : :
19660 : 76 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
19661 : 76 : stmt->missing_ok ? RVR_MISSING_OK : 0,
19662 : : RangeVarCallbackForAlterRelation,
19663 : : stmt);
19664 : :
19665 [ + + ]: 71 : if (!OidIsValid(relid))
19666 : : {
19667 [ + - ]: 8 : ereport(NOTICE,
19668 : : (errmsg("relation \"%s\" does not exist, skipping",
19669 : : stmt->relation->relname)));
19670 : 8 : return InvalidObjectAddress;
19671 : : }
19672 : :
19673 : 63 : rel = relation_open(relid, NoLock);
19674 : :
19675 : 63 : oldNspOid = RelationGetNamespace(rel);
19676 : :
19677 : : /* If it's an owned sequence, disallow moving it by itself. */
19678 [ + + ]: 63 : if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19679 : : {
19680 : : Oid tableId;
19681 : : int32 colId;
19682 : :
19683 [ + + - + ]: 6 : if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19684 : 1 : sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
19685 [ + - ]: 4 : ereport(ERROR,
19686 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19687 : : errmsg("cannot move an owned sequence into another schema"),
19688 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
19689 : : RelationGetRelationName(rel),
19690 : : get_rel_name(tableId))));
19691 : : }
19692 : :
19693 : : /* Get and lock schema OID and check its permissions. */
19694 : 59 : newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19695 : 59 : nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
19696 : :
19697 : : /* common checks on switching namespaces */
19698 : 55 : CheckSetNamespace(oldNspOid, nspOid);
19699 : :
19700 : 55 : objsMoved = new_object_addresses();
19701 : 55 : AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
19702 : 55 : free_object_addresses(objsMoved);
19703 : :
19704 : 55 : ObjectAddressSet(myself, RelationRelationId, relid);
19705 : :
19706 [ + - ]: 55 : if (oldschema)
19707 : 55 : *oldschema = oldNspOid;
19708 : :
19709 : : /* close rel, but keep lock until commit */
19710 : 55 : relation_close(rel, NoLock);
19711 : :
19712 : 55 : return myself;
19713 : : }
19714 : :
19715 : : /*
19716 : : * The guts of relocating a table or materialized view to another namespace:
19717 : : * besides moving the relation itself, its dependent objects are relocated to
19718 : : * the new schema.
19719 : : */
19720 : : void
19721 : 56 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
19722 : : ObjectAddresses *objsMoved)
19723 : : {
19724 : : Relation classRel;
19725 : :
19726 : : Assert(objsMoved != NULL);
19727 : :
19728 : : /* OK, modify the pg_class row and pg_depend entry */
19729 : 56 : classRel = table_open(RelationRelationId, RowExclusiveLock);
19730 : :
19731 : 56 : AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
19732 : : nspOid, true, objsMoved);
19733 : :
19734 : : /* Fix the table's row type too, if it has one */
19735 [ + + ]: 56 : if (OidIsValid(rel->rd_rel->reltype))
19736 : 55 : AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
19737 : : false, /* isImplicitArray */
19738 : : false, /* ignoreDependent */
19739 : : false, /* errorOnTableType */
19740 : : objsMoved);
19741 : :
19742 : : /* Fix other dependent stuff */
19743 : 56 : AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
19744 : 56 : AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
19745 : : objsMoved, AccessExclusiveLock);
19746 : 56 : AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
19747 : : false, objsMoved);
19748 : :
19749 : 56 : table_close(classRel, RowExclusiveLock);
19750 : 56 : }
19751 : :
19752 : : /*
19753 : : * The guts of relocating a relation to another namespace: fix the pg_class
19754 : : * entry, and the pg_depend entry if any. Caller must already have
19755 : : * opened and write-locked pg_class.
19756 : : */
19757 : : void
19758 : 123 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
19759 : : Oid oldNspOid, Oid newNspOid,
19760 : : bool hasDependEntry,
19761 : : ObjectAddresses *objsMoved)
19762 : : {
19763 : : HeapTuple classTup;
19764 : : Form_pg_class classForm;
19765 : : ObjectAddress thisobj;
19766 : 123 : bool already_done = false;
19767 : :
19768 : : /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19769 : 123 : classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
19770 [ - + ]: 123 : if (!HeapTupleIsValid(classTup))
19771 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
19772 : 123 : classForm = (Form_pg_class) GETSTRUCT(classTup);
19773 : :
19774 : : Assert(classForm->relnamespace == oldNspOid);
19775 : :
19776 : 123 : thisobj.classId = RelationRelationId;
19777 : 123 : thisobj.objectId = relOid;
19778 : 123 : thisobj.objectSubId = 0;
19779 : :
19780 : : /*
19781 : : * If the object has already been moved, don't move it again. If it's
19782 : : * already in the right place, don't move it, but still fire the object
19783 : : * access hook.
19784 : : */
19785 : 123 : already_done = object_address_present(&thisobj, objsMoved);
19786 [ + - + + ]: 123 : if (!already_done && oldNspOid != newNspOid)
19787 : 95 : {
19788 : 95 : ItemPointerData otid = classTup->t_self;
19789 : :
19790 : : /* check for duplicate name (more friendly than unique-index failure) */
19791 [ - + ]: 95 : if (get_relname_relid(NameStr(classForm->relname),
19792 : : newNspOid) != InvalidOid)
19793 [ # # ]: 0 : ereport(ERROR,
19794 : : (errcode(ERRCODE_DUPLICATE_TABLE),
19795 : : errmsg("relation \"%s\" already exists in schema \"%s\"",
19796 : : NameStr(classForm->relname),
19797 : : get_namespace_name(newNspOid))));
19798 : :
19799 : : /* classTup is a copy, so OK to scribble on */
19800 : 95 : classForm->relnamespace = newNspOid;
19801 : :
19802 : 95 : CatalogTupleUpdate(classRel, &otid, classTup);
19803 : 95 : UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19804 : :
19805 : :
19806 : : /* Update dependency on schema if caller said so */
19807 [ + + - + ]: 163 : if (hasDependEntry &&
19808 : 68 : changeDependencyFor(RelationRelationId,
19809 : : relOid,
19810 : : NamespaceRelationId,
19811 : : oldNspOid,
19812 : : newNspOid) != 1)
19813 [ # # ]: 0 : elog(ERROR, "could not change schema dependency for relation \"%s\"",
19814 : : NameStr(classForm->relname));
19815 : : }
19816 : : else
19817 : 28 : UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19818 [ + - ]: 123 : if (!already_done)
19819 : : {
19820 : 123 : add_exact_object_address(&thisobj, objsMoved);
19821 : :
19822 [ - + ]: 123 : InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19823 : : }
19824 : :
19825 : 123 : heap_freetuple(classTup);
19826 : 123 : }
19827 : :
19828 : : /*
19829 : : * Move all indexes for the specified relation to another namespace.
19830 : : *
19831 : : * Note: we assume adequate permission checking was done by the caller,
19832 : : * and that the caller has a suitable lock on the owning relation.
19833 : : */
19834 : : static void
19835 : 56 : AlterIndexNamespaces(Relation classRel, Relation rel,
19836 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
19837 : : {
19838 : : List *indexList;
19839 : : ListCell *l;
19840 : :
19841 : 56 : indexList = RelationGetIndexList(rel);
19842 : :
19843 [ + + + + : 86 : foreach(l, indexList)
+ + ]
19844 : : {
19845 : 30 : Oid indexOid = lfirst_oid(l);
19846 : : ObjectAddress thisobj;
19847 : :
19848 : 30 : thisobj.classId = RelationRelationId;
19849 : 30 : thisobj.objectId = indexOid;
19850 : 30 : thisobj.objectSubId = 0;
19851 : :
19852 : : /*
19853 : : * Note: currently, the index will not have its own dependency on the
19854 : : * namespace, so we don't need to do changeDependencyFor(). There's no
19855 : : * row type in pg_type, either.
19856 : : *
19857 : : * XXX this objsMoved test may be pointless -- surely we have a single
19858 : : * dependency link from a relation to each index?
19859 : : */
19860 [ + - ]: 30 : if (!object_address_present(&thisobj, objsMoved))
19861 : : {
19862 : 30 : AlterRelationNamespaceInternal(classRel, indexOid,
19863 : : oldNspOid, newNspOid,
19864 : : false, objsMoved);
19865 : 30 : add_exact_object_address(&thisobj, objsMoved);
19866 : : }
19867 : : }
19868 : :
19869 : 56 : list_free(indexList);
19870 : 56 : }
19871 : :
19872 : : /*
19873 : : * Move all identity and SERIAL-column sequences of the specified relation to another
19874 : : * namespace.
19875 : : *
19876 : : * Note: we assume adequate permission checking was done by the caller,
19877 : : * and that the caller has a suitable lock on the owning relation.
19878 : : */
19879 : : static void
19880 : 56 : AlterSeqNamespaces(Relation classRel, Relation rel,
19881 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
19882 : : LOCKMODE lockmode)
19883 : : {
19884 : : Relation depRel;
19885 : : SysScanDesc scan;
19886 : : ScanKeyData key[2];
19887 : : HeapTuple tup;
19888 : :
19889 : : /*
19890 : : * SERIAL sequences are those having an auto dependency on one of the
19891 : : * table's columns (we don't care *which* column, exactly).
19892 : : */
19893 : 56 : depRel = table_open(DependRelationId, AccessShareLock);
19894 : :
19895 : 56 : ScanKeyInit(&key[0],
19896 : : Anum_pg_depend_refclassid,
19897 : : BTEqualStrategyNumber, F_OIDEQ,
19898 : : ObjectIdGetDatum(RelationRelationId));
19899 : 56 : ScanKeyInit(&key[1],
19900 : : Anum_pg_depend_refobjid,
19901 : : BTEqualStrategyNumber, F_OIDEQ,
19902 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19903 : : /* we leave refobjsubid unspecified */
19904 : :
19905 : 56 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
19906 : : NULL, 2, key);
19907 : :
19908 [ + + ]: 405 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
19909 : : {
19910 : 349 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
19911 : : Relation seqRel;
19912 : :
19913 : : /* skip dependencies other than auto dependencies on columns */
19914 [ + + ]: 349 : if (depForm->refobjsubid == 0 ||
19915 [ + + ]: 252 : depForm->classid != RelationRelationId ||
19916 [ + - ]: 28 : depForm->objsubid != 0 ||
19917 [ - + - - ]: 28 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
19918 : 321 : continue;
19919 : :
19920 : : /* Use relation_open just in case it's an index */
19921 : 28 : seqRel = relation_open(depForm->objid, lockmode);
19922 : :
19923 : : /* skip non-sequence relations */
19924 [ - + ]: 28 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
19925 : : {
19926 : : /* No need to keep the lock */
19927 : 0 : relation_close(seqRel, lockmode);
19928 : 0 : continue;
19929 : : }
19930 : :
19931 : : /* Fix the pg_class and pg_depend entries */
19932 : 28 : AlterRelationNamespaceInternal(classRel, depForm->objid,
19933 : : oldNspOid, newNspOid,
19934 : : true, objsMoved);
19935 : :
19936 : : /*
19937 : : * Sequences used to have entries in pg_type, but no longer do. If we
19938 : : * ever re-instate that, we'll need to move the pg_type entry to the
19939 : : * new namespace, too (using AlterTypeNamespaceInternal).
19940 : : */
19941 : : Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
19942 : :
19943 : : /* Now we can close it. Keep the lock till end of transaction. */
19944 : 28 : relation_close(seqRel, NoLock);
19945 : : }
19946 : :
19947 : 56 : systable_endscan(scan);
19948 : :
19949 : 56 : relation_close(depRel, AccessShareLock);
19950 : 56 : }
19951 : :
19952 : :
19953 : : /*
19954 : : * This code supports
19955 : : * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
19956 : : *
19957 : : * Because we only support this for TEMP tables, it's sufficient to remember
19958 : : * the state in a backend-local data structure.
19959 : : */
19960 : :
19961 : : /*
19962 : : * Register a newly-created relation's ON COMMIT action.
19963 : : */
19964 : : void
19965 : 116 : register_on_commit_action(Oid relid, OnCommitAction action)
19966 : : {
19967 : : OnCommitItem *oc;
19968 : : MemoryContext oldcxt;
19969 : :
19970 : : /*
19971 : : * We needn't bother registering the relation unless there is an ON COMMIT
19972 : : * action we need to take.
19973 : : */
19974 [ + - + + ]: 116 : if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19975 : 16 : return;
19976 : :
19977 : 100 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
19978 : :
19979 : 100 : oc = palloc_object(OnCommitItem);
19980 : 100 : oc->relid = relid;
19981 : 100 : oc->oncommit = action;
19982 : 100 : oc->creating_subid = GetCurrentSubTransactionId();
19983 : 100 : oc->deleting_subid = InvalidSubTransactionId;
19984 : :
19985 : : /*
19986 : : * We use lcons() here so that ON COMMIT actions are processed in reverse
19987 : : * order of registration. That might not be essential but it seems
19988 : : * reasonable.
19989 : : */
19990 : 100 : on_commits = lcons(oc, on_commits);
19991 : :
19992 : 100 : MemoryContextSwitchTo(oldcxt);
19993 : : }
19994 : :
19995 : : /*
19996 : : * Unregister any ON COMMIT action when a relation is deleted.
19997 : : *
19998 : : * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
19999 : : */
20000 : : void
20001 : 32438 : remove_on_commit_action(Oid relid)
20002 : : {
20003 : : ListCell *l;
20004 : :
20005 [ + + + + : 32535 : foreach(l, on_commits)
+ + ]
20006 : : {
20007 : 189 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20008 : :
20009 [ + + ]: 189 : if (oc->relid == relid)
20010 : : {
20011 : 92 : oc->deleting_subid = GetCurrentSubTransactionId();
20012 : 92 : break;
20013 : : }
20014 : : }
20015 : 32438 : }
20016 : :
20017 : : /*
20018 : : * Perform ON COMMIT actions.
20019 : : *
20020 : : * This is invoked just before actually committing, since it's possible
20021 : : * to encounter errors.
20022 : : */
20023 : : void
20024 : 617251 : PreCommit_on_commit_actions(void)
20025 : : {
20026 : : ListCell *l;
20027 : 617251 : List *oids_to_truncate = NIL;
20028 : 617251 : List *oids_to_drop = NIL;
20029 : :
20030 [ + + + + : 617798 : foreach(l, on_commits)
+ + ]
20031 : : {
20032 : 547 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20033 : :
20034 : : /* Ignore entry if already dropped in this xact */
20035 [ + + ]: 547 : if (oc->deleting_subid != InvalidSubTransactionId)
20036 : 49 : continue;
20037 : :
20038 [ - + + - ]: 498 : switch (oc->oncommit)
20039 : : {
20040 : 0 : case ONCOMMIT_NOOP:
20041 : : case ONCOMMIT_PRESERVE_ROWS:
20042 : : /* Do nothing (there shouldn't be such entries, actually) */
20043 : 0 : break;
20044 : 463 : case ONCOMMIT_DELETE_ROWS:
20045 : :
20046 : : /*
20047 : : * If this transaction hasn't accessed any temporary
20048 : : * relations, we can skip truncating ON COMMIT DELETE ROWS
20049 : : * tables, as they must still be empty.
20050 : : */
20051 [ + + ]: 463 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
20052 : 298 : oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
20053 : 463 : break;
20054 : 35 : case ONCOMMIT_DROP:
20055 : 35 : oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
20056 : 35 : break;
20057 : : }
20058 : : }
20059 : :
20060 : : /*
20061 : : * Truncate relations before dropping so that all dependencies between
20062 : : * relations are removed after they are worked on. Doing it like this
20063 : : * might be a waste as it is possible that a relation being truncated will
20064 : : * be dropped anyway due to its parent being dropped, but this makes the
20065 : : * code more robust because of not having to re-check that the relation
20066 : : * exists at truncation time.
20067 : : */
20068 [ + + ]: 617251 : if (oids_to_truncate != NIL)
20069 : 254 : heap_truncate(oids_to_truncate);
20070 : :
20071 [ + + ]: 617247 : if (oids_to_drop != NIL)
20072 : : {
20073 : 31 : ObjectAddresses *targetObjects = new_object_addresses();
20074 : :
20075 [ + - + + : 66 : foreach(l, oids_to_drop)
+ + ]
20076 : : {
20077 : : ObjectAddress object;
20078 : :
20079 : 35 : object.classId = RelationRelationId;
20080 : 35 : object.objectId = lfirst_oid(l);
20081 : 35 : object.objectSubId = 0;
20082 : :
20083 : : Assert(!object_address_present(&object, targetObjects));
20084 : :
20085 : 35 : add_exact_object_address(&object, targetObjects);
20086 : : }
20087 : :
20088 : : /*
20089 : : * Object deletion might involve toast table access (to clean up
20090 : : * toasted catalog entries), so ensure we have a valid snapshot.
20091 : : */
20092 : 31 : PushActiveSnapshot(GetTransactionSnapshot());
20093 : :
20094 : : /*
20095 : : * Since this is an automatic drop, rather than one directly initiated
20096 : : * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
20097 : : */
20098 : 31 : performMultipleDeletions(targetObjects, DROP_CASCADE,
20099 : : PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
20100 : :
20101 : 31 : PopActiveSnapshot();
20102 : :
20103 : : #ifdef USE_ASSERT_CHECKING
20104 : :
20105 : : /*
20106 : : * Note that table deletion will call remove_on_commit_action, so the
20107 : : * entry should get marked as deleted.
20108 : : */
20109 : : foreach(l, on_commits)
20110 : : {
20111 : : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20112 : :
20113 : : if (oc->oncommit != ONCOMMIT_DROP)
20114 : : continue;
20115 : :
20116 : : Assert(oc->deleting_subid != InvalidSubTransactionId);
20117 : : }
20118 : : #endif
20119 : : }
20120 : 617247 : }
20121 : :
20122 : : /*
20123 : : * Post-commit or post-abort cleanup for ON COMMIT management.
20124 : : *
20125 : : * All we do here is remove no-longer-needed OnCommitItem entries.
20126 : : *
20127 : : * During commit, remove entries that were deleted during this transaction;
20128 : : * during abort, remove those created during this transaction.
20129 : : */
20130 : : void
20131 : 653076 : AtEOXact_on_commit_actions(bool isCommit)
20132 : : {
20133 : : ListCell *cur_item;
20134 : :
20135 [ + + + + : 653643 : foreach(cur_item, on_commits)
+ + ]
20136 : : {
20137 : 567 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20138 : :
20139 [ + + + + ]: 635 : if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
20140 : 68 : oc->creating_subid != InvalidSubTransactionId)
20141 : : {
20142 : : /* cur_item must be removed */
20143 : 100 : on_commits = foreach_delete_current(on_commits, cur_item);
20144 : 100 : pfree(oc);
20145 : : }
20146 : : else
20147 : : {
20148 : : /* cur_item must be preserved */
20149 : 467 : oc->creating_subid = InvalidSubTransactionId;
20150 : 467 : oc->deleting_subid = InvalidSubTransactionId;
20151 : : }
20152 : : }
20153 : 653076 : }
20154 : :
20155 : : /*
20156 : : * Post-subcommit or post-subabort cleanup for ON COMMIT management.
20157 : : *
20158 : : * During subabort, we can immediately remove entries created during this
20159 : : * subtransaction. During subcommit, just relabel entries marked during
20160 : : * this subtransaction as being the parent's responsibility.
20161 : : */
20162 : : void
20163 : 22915 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
20164 : : SubTransactionId parentSubid)
20165 : : {
20166 : : ListCell *cur_item;
20167 : :
20168 [ - + - - : 22915 : foreach(cur_item, on_commits)
- + ]
20169 : : {
20170 : 0 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20171 : :
20172 [ # # # # ]: 0 : if (!isCommit && oc->creating_subid == mySubid)
20173 : : {
20174 : : /* cur_item must be removed */
20175 : 0 : on_commits = foreach_delete_current(on_commits, cur_item);
20176 : 0 : pfree(oc);
20177 : : }
20178 : : else
20179 : : {
20180 : : /* cur_item must be preserved */
20181 [ # # ]: 0 : if (oc->creating_subid == mySubid)
20182 : 0 : oc->creating_subid = parentSubid;
20183 [ # # ]: 0 : if (oc->deleting_subid == mySubid)
20184 [ # # ]: 0 : oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
20185 : : }
20186 : : }
20187 : 22915 : }
20188 : :
20189 : : /*
20190 : : * This is intended as a callback for RangeVarGetRelidExtended(). It allows
20191 : : * the relation to be locked only if (1) it's a plain or partitioned table,
20192 : : * materialized view, or TOAST table and (2) the current user is the owner (or
20193 : : * the superuser) or has been granted MAINTAIN. This meets the
20194 : : * permission-checking needs of CLUSTER, REPACK, REINDEX TABLE, and REFRESH
20195 : : * MATERIALIZED VIEW; we expose it here so that it can be used by all.
20196 : : */
20197 : : void
20198 : 743 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
20199 : : Oid relId, Oid oldRelId, void *arg)
20200 : : {
20201 : : char relkind;
20202 : : AclResult aclresult;
20203 : :
20204 : : /* Nothing to do if the relation was not found. */
20205 [ + + ]: 743 : if (!OidIsValid(relId))
20206 : 4 : return;
20207 : :
20208 : : /*
20209 : : * If the relation does exist, check whether it's an index. But note that
20210 : : * the relation might have been dropped between the time we did the name
20211 : : * lookup and now. In that case, there's nothing to do.
20212 : : */
20213 : 739 : relkind = get_rel_relkind(relId);
20214 [ - + ]: 739 : if (!relkind)
20215 : 0 : return;
20216 [ + + + + : 739 : if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
+ + ]
20217 [ + + ]: 102 : relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
20218 [ + - ]: 18 : ereport(ERROR,
20219 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20220 : : errmsg("\"%s\" is not a table or materialized view", relation->relname)));
20221 : :
20222 : : /* Check permissions */
20223 : 721 : aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
20224 [ + + ]: 721 : if (aclresult != ACLCHECK_OK)
20225 : 20 : aclcheck_error(aclresult,
20226 : 20 : get_relkind_objtype(get_rel_relkind(relId)),
20227 : 20 : relation->relname);
20228 : : }
20229 : :
20230 : : /*
20231 : : * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
20232 : : */
20233 : : static void
20234 : 1439 : RangeVarCallbackForTruncate(const RangeVar *relation,
20235 : : Oid relId, Oid oldRelId, void *arg)
20236 : : {
20237 : : HeapTuple tuple;
20238 : :
20239 : : /* Nothing to do if the relation was not found. */
20240 [ - + ]: 1439 : if (!OidIsValid(relId))
20241 : 0 : return;
20242 : :
20243 : 1439 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20244 [ - + ]: 1439 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20245 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20246 : :
20247 : 1439 : truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
20248 : 1436 : truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
20249 : :
20250 : 1416 : ReleaseSysCache(tuple);
20251 : : }
20252 : :
20253 : : /*
20254 : : * Callback for RangeVarGetRelidExtended(). Checks that the current user is
20255 : : * the owner of the relation, or superuser.
20256 : : */
20257 : : void
20258 : 10490 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
20259 : : Oid relId, Oid oldRelId, void *arg)
20260 : : {
20261 : : HeapTuple tuple;
20262 : :
20263 : : /* Nothing to do if the relation was not found. */
20264 [ + + ]: 10490 : if (!OidIsValid(relId))
20265 : 4 : return;
20266 : :
20267 : 10486 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20268 [ - + ]: 10486 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20269 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20270 : :
20271 [ + + ]: 10486 : if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
20272 : 4 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
20273 : 4 : relation->relname);
20274 : :
20275 : : /*
20276 : : * Conflict log tables are used internally for logical replication
20277 : : * conflict logging and should not be modified directly, as it could
20278 : : * disrupt conflict logging.
20279 : : */
20280 [ + + ]: 10482 : if (IsConflictLogTableClass((Form_pg_class) GETSTRUCT(tuple)))
20281 [ + - ]: 4 : ereport(ERROR,
20282 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20283 : : errmsg("cannot change conflict log table \"%s\"",
20284 : : relation->relname),
20285 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
20286 : :
20287 [ + + + + ]: 20896 : if (!allowSystemTableMods &&
20288 : 10418 : IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
20289 [ + - ]: 1 : ereport(ERROR,
20290 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
20291 : : errmsg("permission denied: \"%s\" is a system catalog",
20292 : : relation->relname)));
20293 : :
20294 : 10477 : ReleaseSysCache(tuple);
20295 : : }
20296 : :
20297 : : /*
20298 : : * Common RangeVarGetRelid callback for rename, set schema, and alter table
20299 : : * processing.
20300 : : */
20301 : : static void
20302 : 22087 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
20303 : : void *arg)
20304 : : {
20305 : 22087 : Node *stmt = (Node *) arg;
20306 : : ObjectType reltype;
20307 : : HeapTuple tuple;
20308 : : Form_pg_class classform;
20309 : : AclResult aclresult;
20310 : : char relkind;
20311 : :
20312 : 22087 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
20313 [ + + ]: 22087 : if (!HeapTupleIsValid(tuple))
20314 : 165 : return; /* concurrently dropped */
20315 : 21922 : classform = (Form_pg_class) GETSTRUCT(tuple);
20316 : 21922 : relkind = classform->relkind;
20317 : :
20318 : : /* Must own relation. */
20319 [ + + ]: 21922 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
20320 : 40 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
20321 : :
20322 : : /*
20323 : : * Conflict log tables are used internally for logical replication
20324 : : * conflict logging and should not be altered directly, as it could
20325 : : * disrupt conflict logging.
20326 : : */
20327 [ + + ]: 21882 : if (IsConflictLogTableClass(classform))
20328 [ + - ]: 13 : ereport(ERROR,
20329 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20330 : : errmsg("cannot alter conflict log table \"%s\"",
20331 : : rv->relname),
20332 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
20333 : :
20334 : : /* No system table modifications unless explicitly allowed. */
20335 [ + + + + ]: 21869 : if (!allowSystemTableMods && IsSystemClass(relid, classform))
20336 [ + - ]: 18 : ereport(ERROR,
20337 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
20338 : : errmsg("permission denied: \"%s\" is a system catalog",
20339 : : rv->relname)));
20340 : :
20341 : : /*
20342 : : * Extract the specified relation type from the statement parse tree.
20343 : : *
20344 : : * Also, for ALTER .. RENAME, check permissions: the user must (still)
20345 : : * have CREATE rights on the containing namespace.
20346 : : */
20347 [ + + ]: 21851 : if (IsA(stmt, RenameStmt))
20348 : : {
20349 : 283 : aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
20350 : : GetUserId(), ACL_CREATE);
20351 [ - + ]: 283 : if (aclresult != ACLCHECK_OK)
20352 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
20353 : 0 : get_namespace_name(classform->relnamespace));
20354 : 283 : reltype = ((RenameStmt *) stmt)->renameType;
20355 : : }
20356 [ + + ]: 21568 : else if (IsA(stmt, AlterObjectSchemaStmt))
20357 : 64 : reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
20358 : :
20359 [ + - ]: 21504 : else if (IsA(stmt, AlterTableStmt))
20360 : 21504 : reltype = ((AlterTableStmt *) stmt)->objtype;
20361 : : else
20362 : : {
20363 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
20364 : : reltype = OBJECT_TABLE; /* placate compiler */
20365 : : }
20366 : :
20367 : : /*
20368 : : * For compatibility with prior releases, we allow ALTER TABLE to be used
20369 : : * with most other types of relations (but not composite types). We allow
20370 : : * similar flexibility for ALTER INDEX in the case of RENAME, but not
20371 : : * otherwise. Otherwise, the user must select the correct form of the
20372 : : * command for the relation at issue.
20373 : : */
20374 [ + + - + ]: 21851 : if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
20375 [ # # ]: 0 : ereport(ERROR,
20376 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20377 : : errmsg("\"%s\" is not a sequence", rv->relname)));
20378 : :
20379 [ + + - + ]: 21851 : if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
20380 [ # # ]: 0 : ereport(ERROR,
20381 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20382 : : errmsg("\"%s\" is not a view", rv->relname)));
20383 : :
20384 [ + + - + ]: 21851 : if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
20385 [ # # ]: 0 : ereport(ERROR,
20386 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20387 : : errmsg("\"%s\" is not a materialized view", rv->relname)));
20388 : :
20389 [ + + - + ]: 21851 : if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
20390 [ # # ]: 0 : ereport(ERROR,
20391 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20392 : : errmsg("\"%s\" is not a foreign table", rv->relname)));
20393 : :
20394 [ + + - + ]: 21851 : if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
20395 [ # # ]: 0 : ereport(ERROR,
20396 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20397 : : errmsg("\"%s\" is not a composite type", rv->relname)));
20398 : :
20399 [ + + + + : 21851 : if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
+ + ]
20400 : : relkind != RELKIND_PARTITIONED_INDEX
20401 [ + + ]: 24 : && !IsA(stmt, RenameStmt))
20402 [ + - ]: 4 : ereport(ERROR,
20403 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20404 : : errmsg("\"%s\" is not an index", rv->relname)));
20405 : :
20406 : : /*
20407 : : * Don't allow ALTER TABLE on composite types. We want people to use ALTER
20408 : : * TYPE for that.
20409 : : */
20410 [ + + - + ]: 21847 : if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
20411 [ # # ]: 0 : ereport(ERROR,
20412 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20413 : : errmsg("\"%s\" is a composite type", rv->relname),
20414 : : /* translator: %s is an SQL ALTER command */
20415 : : errhint("Use %s instead.",
20416 : : "ALTER TYPE")));
20417 : :
20418 : : /*
20419 : : * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
20420 : : * to a different schema, such as indexes and TOAST tables.
20421 : : */
20422 [ + + ]: 21847 : if (IsA(stmt, AlterObjectSchemaStmt))
20423 : : {
20424 [ + - - + ]: 64 : if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
20425 [ # # ]: 0 : ereport(ERROR,
20426 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20427 : : errmsg("cannot change schema of index \"%s\"",
20428 : : rv->relname),
20429 : : errhint("Change the schema of the table instead.")));
20430 [ - + ]: 64 : else if (relkind == RELKIND_COMPOSITE_TYPE)
20431 [ # # ]: 0 : ereport(ERROR,
20432 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20433 : : errmsg("cannot change schema of composite type \"%s\"",
20434 : : rv->relname),
20435 : : /* translator: %s is an SQL ALTER command */
20436 : : errhint("Use %s instead.",
20437 : : "ALTER TYPE")));
20438 [ - + ]: 64 : else if (relkind == RELKIND_TOASTVALUE)
20439 [ # # ]: 0 : ereport(ERROR,
20440 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20441 : : errmsg("cannot change schema of TOAST table \"%s\"",
20442 : : rv->relname),
20443 : : errhint("Change the schema of the table instead.")));
20444 : : }
20445 : :
20446 : 21847 : ReleaseSysCache(tuple);
20447 : : }
20448 : :
20449 : : /*
20450 : : * Transform any expressions present in the partition key
20451 : : *
20452 : : * Returns a transformed PartitionSpec.
20453 : : */
20454 : : static PartitionSpec *
20455 : 3400 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
20456 : : {
20457 : : PartitionSpec *newspec;
20458 : : ParseState *pstate;
20459 : : ParseNamespaceItem *nsitem;
20460 : : ListCell *l;
20461 : :
20462 : 3400 : newspec = makeNode(PartitionSpec);
20463 : :
20464 : 3400 : newspec->strategy = partspec->strategy;
20465 : 3400 : newspec->partParams = NIL;
20466 : 3400 : newspec->location = partspec->location;
20467 : :
20468 : : /* Check valid number of columns for strategy */
20469 [ + + + + ]: 5005 : if (partspec->strategy == PARTITION_STRATEGY_LIST &&
20470 : 1605 : list_length(partspec->partParams) != 1)
20471 [ + - ]: 4 : ereport(ERROR,
20472 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20473 : : errmsg("cannot use \"list\" partition strategy with more than one column")));
20474 : :
20475 : : /*
20476 : : * Create a dummy ParseState and insert the target relation as its sole
20477 : : * rangetable entry. We need a ParseState for transformExpr.
20478 : : */
20479 : 3396 : pstate = make_parsestate(NULL);
20480 : 3396 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
20481 : : NULL, false, true);
20482 : 3396 : addNSItemToQuery(pstate, nsitem, true, true, true);
20483 : :
20484 : : /* take care of any partition expressions */
20485 [ + - + + : 7094 : foreach(l, partspec->partParams)
+ + ]
20486 : : {
20487 : 3714 : PartitionElem *pelem = lfirst_node(PartitionElem, l);
20488 : :
20489 [ + + ]: 3714 : if (pelem->expr)
20490 : : {
20491 : : /* Copy, to avoid scribbling on the input */
20492 : 232 : pelem = copyObject(pelem);
20493 : :
20494 : : /* Now do parse transformation of the expression */
20495 : 232 : pelem->expr = transformExpr(pstate, pelem->expr,
20496 : : EXPR_KIND_PARTITION_EXPRESSION);
20497 : :
20498 : : /* we have to fix its collations too */
20499 : 216 : assign_expr_collations(pstate, pelem->expr);
20500 : : }
20501 : :
20502 : 3698 : newspec->partParams = lappend(newspec->partParams, pelem);
20503 : : }
20504 : :
20505 : 3380 : return newspec;
20506 : : }
20507 : :
20508 : : /*
20509 : : * Compute per-partition-column information from a list of PartitionElems.
20510 : : * Expressions in the PartitionElems must be parse-analyzed already.
20511 : : */
20512 : : static void
20513 : 3380 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
20514 : : List **partexprs, Oid *partopclass, Oid *partcollation,
20515 : : PartitionStrategy strategy)
20516 : : {
20517 : : int attn;
20518 : : ListCell *lc;
20519 : : Oid am_oid;
20520 : :
20521 : 3380 : attn = 0;
20522 [ + - + + : 6990 : foreach(lc, partParams)
+ + ]
20523 : : {
20524 : 3698 : PartitionElem *pelem = lfirst_node(PartitionElem, lc);
20525 : : Oid atttype;
20526 : : Oid attcollation;
20527 : :
20528 [ + + ]: 3698 : if (pelem->name != NULL)
20529 : : {
20530 : : /* Simple attribute reference */
20531 : : HeapTuple atttuple;
20532 : : Form_pg_attribute attform;
20533 : :
20534 : 3482 : atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
20535 : 3482 : pelem->name);
20536 [ + + ]: 3482 : if (!HeapTupleIsValid(atttuple))
20537 [ + - ]: 8 : ereport(ERROR,
20538 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
20539 : : errmsg("column \"%s\" named in partition key does not exist",
20540 : : pelem->name),
20541 : : parser_errposition(pstate, pelem->location)));
20542 : 3474 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
20543 : :
20544 [ + + ]: 3474 : if (attform->attnum <= 0)
20545 [ + - ]: 4 : ereport(ERROR,
20546 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20547 : : errmsg("cannot use system column \"%s\" in partition key",
20548 : : pelem->name),
20549 : : parser_errposition(pstate, pelem->location)));
20550 : :
20551 : : /*
20552 : : * Stored generated columns cannot work: They are computed after
20553 : : * BEFORE triggers, but partition routing is done before all
20554 : : * triggers. Maybe virtual generated columns could be made to
20555 : : * work, but then they would need to be handled as an expression
20556 : : * below.
20557 : : */
20558 [ + + ]: 3470 : if (attform->attgenerated)
20559 [ + - ]: 8 : ereport(ERROR,
20560 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20561 : : errmsg("cannot use generated column in partition key"),
20562 : : errdetail("Column \"%s\" is a generated column.",
20563 : : pelem->name),
20564 : : parser_errposition(pstate, pelem->location)));
20565 : :
20566 : 3462 : partattrs[attn] = attform->attnum;
20567 : 3462 : atttype = attform->atttypid;
20568 : 3462 : attcollation = attform->attcollation;
20569 : 3462 : ReleaseSysCache(atttuple);
20570 : : }
20571 : : else
20572 : : {
20573 : : /* Expression */
20574 : 216 : Node *expr = pelem->expr;
20575 : : char partattname[16];
20576 : 216 : Bitmapset *expr_attrs = NULL;
20577 : : int i;
20578 : :
20579 : : Assert(expr != NULL);
20580 : 216 : atttype = exprType(expr);
20581 : 216 : attcollation = exprCollation(expr);
20582 : :
20583 : : /*
20584 : : * The expression must be of a storable type (e.g., not RECORD).
20585 : : * The test is the same as for whether a table column is of a safe
20586 : : * type (which is why we needn't check for the non-expression
20587 : : * case).
20588 : : */
20589 : 216 : snprintf(partattname, sizeof(partattname), "%d", attn + 1);
20590 : 216 : CheckAttributeType(partattname,
20591 : : atttype, attcollation,
20592 : : NIL, CHKATYPE_IS_PARTKEY);
20593 : :
20594 : : /*
20595 : : * Strip any top-level COLLATE clause. This ensures that we treat
20596 : : * "x COLLATE y" and "(x COLLATE y)" alike.
20597 : : */
20598 [ - + ]: 208 : while (IsA(expr, CollateExpr))
20599 : 0 : expr = (Node *) ((CollateExpr *) expr)->arg;
20600 : :
20601 : : /*
20602 : : * Examine all the columns in the partition key expression. When
20603 : : * the whole-row reference is present, examine all the columns of
20604 : : * the partitioned table.
20605 : : */
20606 : 208 : pull_varattnos(expr, 1, &expr_attrs);
20607 [ + + ]: 208 : if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, expr_attrs))
20608 : : {
20609 : 40 : expr_attrs = bms_add_range(expr_attrs,
20610 : : 1 - FirstLowInvalidHeapAttributeNumber,
20611 : 20 : RelationGetNumberOfAttributes(rel) - FirstLowInvalidHeapAttributeNumber);
20612 : 20 : expr_attrs = bms_del_member(expr_attrs, 0 - FirstLowInvalidHeapAttributeNumber);
20613 : : }
20614 : :
20615 : 208 : i = -1;
20616 [ + + ]: 457 : while ((i = bms_next_member(expr_attrs, i)) >= 0)
20617 : : {
20618 : 281 : AttrNumber attno = i + FirstLowInvalidHeapAttributeNumber;
20619 : :
20620 : : Assert(attno != 0);
20621 : :
20622 : : /*
20623 : : * Cannot allow system column references, since that would
20624 : : * make partition routing impossible: their values won't be
20625 : : * known yet when we need to do that.
20626 : : */
20627 [ - + ]: 281 : if (attno < 0)
20628 [ # # ]: 0 : ereport(ERROR,
20629 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20630 : : errmsg("partition key expressions cannot contain system column references")));
20631 : :
20632 : : /*
20633 : : * Stored generated columns cannot work: They are computed
20634 : : * after BEFORE triggers, but partition routing is done before
20635 : : * all triggers. Virtual generated columns could probably
20636 : : * work, but it would require more work elsewhere (for example
20637 : : * SET EXPRESSION would need to check whether the column is
20638 : : * used in partition keys). Seems safer to prohibit for now.
20639 : : */
20640 [ + + ]: 281 : if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
20641 [ + - ]: 32 : ereport(ERROR,
20642 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20643 : : errmsg("cannot use generated column in partition key"),
20644 : : errdetail("Column \"%s\" is a generated column.",
20645 : : get_attname(RelationGetRelid(rel), attno, false)),
20646 : : parser_errposition(pstate, pelem->location)));
20647 : : }
20648 : :
20649 [ + + ]: 176 : if (IsA(expr, Var) &&
20650 [ + + ]: 8 : ((Var *) expr)->varattno > 0)
20651 : : {
20652 : :
20653 : : /*
20654 : : * User wrote "(column)" or "(column COLLATE something)".
20655 : : * Treat it like simple attribute anyway.
20656 : : */
20657 : 4 : partattrs[attn] = ((Var *) expr)->varattno;
20658 : : }
20659 : : else
20660 : : {
20661 : 172 : partattrs[attn] = 0; /* marks the column as expression */
20662 : 172 : *partexprs = lappend(*partexprs, expr);
20663 : :
20664 : : /*
20665 : : * transformPartitionSpec() should have already rejected
20666 : : * subqueries, aggregates, window functions, and SRFs, based
20667 : : * on the EXPR_KIND_ for partition expressions.
20668 : : */
20669 : :
20670 : : /*
20671 : : * Preprocess the expression before checking for mutability.
20672 : : * This is essential for the reasons described in
20673 : : * contain_mutable_functions_after_planning. However, we call
20674 : : * expression_planner for ourselves rather than using that
20675 : : * function, because if constant-folding reduces the
20676 : : * expression to a constant, we'd like to know that so we can
20677 : : * complain below.
20678 : : *
20679 : : * Like contain_mutable_functions_after_planning, assume that
20680 : : * expression_planner won't scribble on its input, so this
20681 : : * won't affect the partexprs entry we saved above.
20682 : : */
20683 : 172 : expr = (Node *) expression_planner((Expr *) expr);
20684 : :
20685 : : /*
20686 : : * Partition expressions cannot contain mutable functions,
20687 : : * because a given row must always map to the same partition
20688 : : * as long as there is no change in the partition boundary
20689 : : * structure.
20690 : : */
20691 [ + + ]: 172 : if (contain_mutable_functions(expr))
20692 [ + - ]: 4 : ereport(ERROR,
20693 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20694 : : errmsg("functions in partition key expression must be marked IMMUTABLE")));
20695 : :
20696 : : /*
20697 : : * While it is not exactly *wrong* for a partition expression
20698 : : * to be a constant, it seems better to reject such keys.
20699 : : */
20700 [ + + ]: 168 : if (IsA(expr, Const))
20701 [ + - ]: 8 : ereport(ERROR,
20702 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20703 : : errmsg("cannot use constant expression as partition key")));
20704 : : }
20705 : : }
20706 : :
20707 : : /*
20708 : : * Apply collation override if any
20709 : : */
20710 [ + + ]: 3626 : if (pelem->collation)
20711 : 36 : attcollation = get_collation_oid(pelem->collation, false);
20712 : :
20713 : : /*
20714 : : * Check we have a collation iff it's a collatable type. The only
20715 : : * expected failures here are (1) COLLATE applied to a noncollatable
20716 : : * type, or (2) partition expression had an unresolved collation. But
20717 : : * we might as well code this to be a complete consistency check.
20718 : : */
20719 [ + + ]: 3626 : if (type_is_collatable(atttype))
20720 : : {
20721 [ - + ]: 397 : if (!OidIsValid(attcollation))
20722 [ # # ]: 0 : ereport(ERROR,
20723 : : (errcode(ERRCODE_INDETERMINATE_COLLATION),
20724 : : errmsg("could not determine which collation to use for partition expression"),
20725 : : errhint("Use the COLLATE clause to set the collation explicitly.")));
20726 : : }
20727 : : else
20728 : : {
20729 [ - + ]: 3229 : if (OidIsValid(attcollation))
20730 [ # # ]: 0 : ereport(ERROR,
20731 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
20732 : : errmsg("collations are not supported by type %s",
20733 : : format_type_be(atttype))));
20734 : : }
20735 : :
20736 : 3626 : partcollation[attn] = attcollation;
20737 : :
20738 : : /*
20739 : : * Identify the appropriate operator class. For list and range
20740 : : * partitioning, we use a btree operator class; hash partitioning uses
20741 : : * a hash operator class.
20742 : : */
20743 [ + + ]: 3626 : if (strategy == PARTITION_STRATEGY_HASH)
20744 : 207 : am_oid = HASH_AM_OID;
20745 : : else
20746 : 3419 : am_oid = BTREE_AM_OID;
20747 : :
20748 [ + + ]: 3626 : if (!pelem->opclass)
20749 : : {
20750 : 3526 : partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
20751 : :
20752 [ + + ]: 3526 : if (!OidIsValid(partopclass[attn]))
20753 : : {
20754 [ - + ]: 8 : if (strategy == PARTITION_STRATEGY_HASH)
20755 [ # # ]: 0 : ereport(ERROR,
20756 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
20757 : : errmsg("data type %s has no default operator class for access method \"%s\"",
20758 : : format_type_be(atttype), "hash"),
20759 : : errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
20760 : : else
20761 [ + - ]: 8 : ereport(ERROR,
20762 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
20763 : : errmsg("data type %s has no default operator class for access method \"%s\"",
20764 : : format_type_be(atttype), "btree"),
20765 : : errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
20766 : : }
20767 : : }
20768 : : else
20769 [ + + ]: 100 : partopclass[attn] = ResolveOpClass(pelem->opclass,
20770 : : atttype,
20771 : : am_oid == HASH_AM_OID ? "hash" : "btree",
20772 : : am_oid);
20773 : :
20774 : 3610 : attn++;
20775 : : }
20776 : 3292 : }
20777 : :
20778 : : /*
20779 : : * PartConstraintImpliedByRelConstraint
20780 : : * Do scanrel's existing constraints imply the partition constraint?
20781 : : *
20782 : : * "Existing constraints" include its check constraints and column-level
20783 : : * not-null constraints. partConstraint describes the partition constraint,
20784 : : * in implicit-AND form.
20785 : : */
20786 : : bool
20787 : 1979 : PartConstraintImpliedByRelConstraint(Relation scanrel,
20788 : : List *partConstraint)
20789 : : {
20790 : 1979 : List *existConstraint = NIL;
20791 : 1979 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20792 : : int i;
20793 : :
20794 [ + + + + ]: 1979 : if (constr && constr->has_not_null)
20795 : : {
20796 : 500 : int natts = scanrel->rd_att->natts;
20797 : :
20798 [ + + ]: 1662 : for (i = 1; i <= natts; i++)
20799 : : {
20800 : 1162 : CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20801 : :
20802 : : /* invalid not-null constraint must be ignored here */
20803 [ + + + - ]: 1162 : if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20804 : : {
20805 : 695 : Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
20806 : 695 : NullTest *ntest = makeNode(NullTest);
20807 : :
20808 : 695 : ntest->arg = (Expr *) makeVar(1,
20809 : : i,
20810 : : wholeatt->atttypid,
20811 : : wholeatt->atttypmod,
20812 : : wholeatt->attcollation,
20813 : : 0);
20814 : 695 : ntest->nulltesttype = IS_NOT_NULL;
20815 : :
20816 : : /*
20817 : : * argisrow=false is correct even for a composite column,
20818 : : * because attnotnull does not represent a SQL-spec IS NOT
20819 : : * NULL test in such a case, just IS DISTINCT FROM NULL.
20820 : : */
20821 : 695 : ntest->argisrow = false;
20822 : 695 : ntest->location = -1;
20823 : 695 : existConstraint = lappend(existConstraint, ntest);
20824 : : }
20825 : : }
20826 : : }
20827 : :
20828 : 1979 : return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20829 : : }
20830 : :
20831 : : /*
20832 : : * ConstraintImpliedByRelConstraint
20833 : : * Do scanrel's existing constraints imply the given constraint?
20834 : : *
20835 : : * testConstraint is the constraint to validate. provenConstraint is a
20836 : : * caller-provided list of conditions which this function may assume
20837 : : * to be true. Both provenConstraint and testConstraint must be in
20838 : : * implicit-AND form, must only contain immutable clauses, and must
20839 : : * contain only Vars with varno = 1.
20840 : : */
20841 : : bool
20842 : 2823 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
20843 : : {
20844 : 2823 : List *existConstraint = list_copy(provenConstraint);
20845 : 2823 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20846 : : int num_check,
20847 : : i;
20848 : :
20849 [ + + ]: 2823 : num_check = (constr != NULL) ? constr->num_check : 0;
20850 [ + + ]: 3159 : for (i = 0; i < num_check; i++)
20851 : : {
20852 : : Node *cexpr;
20853 : :
20854 : : /*
20855 : : * If this constraint hasn't been fully validated yet, we must ignore
20856 : : * it here.
20857 : : */
20858 [ + + ]: 336 : if (!constr->check[i].ccvalid)
20859 : 12 : continue;
20860 : :
20861 : : /*
20862 : : * NOT ENFORCED constraints are always marked as invalid, which should
20863 : : * have been ignored.
20864 : : */
20865 : : Assert(constr->check[i].ccenforced);
20866 : :
20867 : 324 : cexpr = stringToNode(constr->check[i].ccbin);
20868 : :
20869 : : /*
20870 : : * Run each expression through const-simplification and
20871 : : * canonicalization. It is necessary, because we will be comparing it
20872 : : * to similarly-processed partition constraint expressions, and may
20873 : : * fail to detect valid matches without this.
20874 : : */
20875 : 324 : cexpr = eval_const_expressions(NULL, cexpr);
20876 : 324 : cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
20877 : :
20878 : 324 : existConstraint = list_concat(existConstraint,
20879 : 324 : make_ands_implicit((Expr *) cexpr));
20880 : : }
20881 : :
20882 : : /*
20883 : : * Try to make the proof. Since we are comparing CHECK constraints, we
20884 : : * need to use weak implication, i.e., we assume existConstraint is
20885 : : * not-false and try to prove the same for testConstraint.
20886 : : *
20887 : : * Note that predicate_implied_by assumes its first argument is known
20888 : : * immutable. That should always be true for both NOT NULL and partition
20889 : : * constraints, so we don't test it here.
20890 : : */
20891 : 2823 : return predicate_implied_by(testConstraint, existConstraint, true);
20892 : : }
20893 : :
20894 : : /*
20895 : : * QueuePartitionConstraintValidation
20896 : : *
20897 : : * Add an entry to wqueue to have the given partition constraint validated by
20898 : : * Phase 3, for the given relation, and all its children.
20899 : : *
20900 : : * We first verify whether the given constraint is implied by pre-existing
20901 : : * relation constraints; if it is, there's no need to scan the table to
20902 : : * validate, so don't queue in that case.
20903 : : */
20904 : : static void
20905 : 1638 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
20906 : : List *partConstraint,
20907 : : bool validate_default)
20908 : : {
20909 : : /*
20910 : : * Based on the table's existing constraints, determine whether or not we
20911 : : * may skip scanning the table.
20912 : : */
20913 [ + + ]: 1638 : if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
20914 : : {
20915 [ + + ]: 55 : if (!validate_default)
20916 [ + + ]: 41 : ereport(DEBUG1,
20917 : : (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
20918 : : RelationGetRelationName(scanrel))));
20919 : : else
20920 [ + + ]: 14 : ereport(DEBUG1,
20921 : : (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
20922 : : RelationGetRelationName(scanrel))));
20923 : 55 : return;
20924 : : }
20925 : :
20926 : : /*
20927 : : * Constraints proved insufficient. For plain relations, queue a
20928 : : * validation item now; for partitioned tables, recurse to process each
20929 : : * partition.
20930 : : */
20931 [ + + ]: 1583 : if (scanrel->rd_rel->relkind == RELKIND_RELATION)
20932 : : {
20933 : : AlteredTableInfo *tab;
20934 : :
20935 : : /* Grab a work queue entry. */
20936 : 1320 : tab = ATGetQueueEntry(wqueue, scanrel);
20937 : : Assert(tab->partition_constraint == NULL);
20938 : 1320 : tab->partition_constraint = (Expr *) linitial(partConstraint);
20939 : 1320 : tab->validate_default = validate_default;
20940 : : }
20941 [ + + ]: 263 : else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20942 : : {
20943 : 232 : PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
20944 : : int i;
20945 : :
20946 [ + + ]: 488 : for (i = 0; i < partdesc->nparts; i++)
20947 : : {
20948 : : Relation part_rel;
20949 : : List *thisPartConstraint;
20950 : :
20951 : : /*
20952 : : * This is the minimum lock we need to prevent deadlocks.
20953 : : */
20954 : 256 : part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
20955 : :
20956 : : /*
20957 : : * Adjust the constraint for scanrel so that it matches this
20958 : : * partition's attribute numbers.
20959 : : */
20960 : : thisPartConstraint =
20961 : 256 : map_partition_varattnos(partConstraint, 1,
20962 : : part_rel, scanrel);
20963 : :
20964 : 256 : QueuePartitionConstraintValidation(wqueue, part_rel,
20965 : : thisPartConstraint,
20966 : : validate_default);
20967 : 256 : table_close(part_rel, NoLock); /* keep lock till commit */
20968 : : }
20969 : : }
20970 : : }
20971 : :
20972 : : /*
20973 : : * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
20974 : : *
20975 : : * Return the address of the newly attached partition.
20976 : : */
20977 : : static ObjectAddress
20978 : 1533 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
20979 : : AlterTableUtilityContext *context)
20980 : : {
20981 : : Relation attachrel,
20982 : : catalog;
20983 : : List *attachrel_children;
20984 : : List *partConstraint;
20985 : : SysScanDesc scan;
20986 : : ScanKeyData skey;
20987 : : AttrNumber attno;
20988 : : int natts;
20989 : : TupleDesc tupleDesc;
20990 : : ObjectAddress address;
20991 : : const char *trigger_name;
20992 : : Oid defaultPartOid;
20993 : : List *partBoundConstraint;
20994 : 1533 : List *exceptpuboids = NIL;
20995 : 1533 : ParseState *pstate = make_parsestate(NULL);
20996 : :
20997 : 1533 : pstate->p_sourcetext = context->queryString;
20998 : :
20999 : : /*
21000 : : * We must lock the default partition if one exists, because attaching a
21001 : : * new partition will change its partition constraint.
21002 : : */
21003 : : defaultPartOid =
21004 : 1533 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
21005 [ + + ]: 1533 : if (OidIsValid(defaultPartOid))
21006 : 117 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
21007 : :
21008 : 1533 : attachrel = table_openrv(cmd->name, AccessExclusiveLock);
21009 : :
21010 : : /*
21011 : : * XXX I think it'd be a good idea to grab locks on all tables referenced
21012 : : * by FKs at this point also.
21013 : : */
21014 : :
21015 : : /*
21016 : : * Must be owner of both parent and source table -- parent was checked by
21017 : : * ATSimplePermissions call in ATPrepCmd
21018 : : */
21019 : 1529 : ATSimplePermissions(AT_AttachPartition, attachrel,
21020 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
21021 : :
21022 : : /* A partition can only have one parent */
21023 [ + + ]: 1525 : if (attachrel->rd_rel->relispartition)
21024 [ + - ]: 4 : ereport(ERROR,
21025 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21026 : : errmsg("\"%s\" is already a partition",
21027 : : RelationGetRelationName(attachrel))));
21028 : :
21029 [ + + ]: 1521 : if (OidIsValid(attachrel->rd_rel->reloftype))
21030 [ + - ]: 4 : ereport(ERROR,
21031 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21032 : : errmsg("cannot attach a typed table as partition")));
21033 : :
21034 : : /*
21035 : : * Disallow attaching a partition if the table is referenced in a
21036 : : * publication EXCEPT clause. Changing the partition hierarchy could alter
21037 : : * the effective publication membership.
21038 : : */
21039 : 1517 : exceptpuboids = GetRelationExcludedPublications(RelationGetRelid(attachrel));
21040 [ + + ]: 1517 : if (exceptpuboids != NIL)
21041 : : {
21042 : 4 : bool first = true;
21043 : : StringInfoData pubnames;
21044 : :
21045 : 4 : initStringInfo(&pubnames);
21046 : :
21047 [ + - + + : 12 : foreach_oid(pubid, exceptpuboids)
+ + ]
21048 : : {
21049 : 4 : char *pubname = get_publication_name(pubid, false);
21050 : :
21051 [ + - ]: 4 : if (first)
21052 : 4 : appendStringInfo(&pubnames, _("\"%s\""), pubname);
21053 : : else
21054 : 0 : appendStringInfo(&pubnames, _(", \"%s\""), pubname);
21055 : 4 : first = false;
21056 : : }
21057 : :
21058 [ + - ]: 4 : ereport(ERROR,
21059 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21060 : : errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause",
21061 : : "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause",
21062 : : list_length(exceptpuboids),
21063 : : RelationGetRelationName(attachrel),
21064 : : pubnames.data),
21065 : : errdetail("The publication EXCEPT clause cannot contain tables that are partitions."),
21066 : : errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES."));
21067 : : }
21068 : :
21069 : 1513 : list_free(exceptpuboids);
21070 : :
21071 : : /*
21072 : : * Table being attached should not already be part of inheritance; either
21073 : : * as a child table...
21074 : : */
21075 : 1513 : catalog = table_open(InheritsRelationId, AccessShareLock);
21076 : 1513 : ScanKeyInit(&skey,
21077 : : Anum_pg_inherits_inhrelid,
21078 : : BTEqualStrategyNumber, F_OIDEQ,
21079 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21080 : 1513 : scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
21081 : : NULL, 1, &skey);
21082 [ + + ]: 1513 : if (HeapTupleIsValid(systable_getnext(scan)))
21083 [ + - ]: 4 : ereport(ERROR,
21084 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21085 : : errmsg("cannot attach inheritance child as partition")));
21086 : 1509 : systable_endscan(scan);
21087 : :
21088 : : /* ...or as a parent table (except the case when it is partitioned) */
21089 : 1509 : ScanKeyInit(&skey,
21090 : : Anum_pg_inherits_inhparent,
21091 : : BTEqualStrategyNumber, F_OIDEQ,
21092 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21093 : 1509 : scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
21094 : : 1, &skey);
21095 [ + + ]: 1509 : if (HeapTupleIsValid(systable_getnext(scan)) &&
21096 [ + + ]: 172 : attachrel->rd_rel->relkind == RELKIND_RELATION)
21097 [ + - ]: 4 : ereport(ERROR,
21098 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21099 : : errmsg("cannot attach inheritance parent as partition")));
21100 : 1505 : systable_endscan(scan);
21101 : 1505 : table_close(catalog, AccessShareLock);
21102 : :
21103 : : /*
21104 : : * Prevent circularity by seeing if rel is a partition of attachrel. (In
21105 : : * particular, this disallows making a rel a partition of itself.)
21106 : : *
21107 : : * We do that by checking if rel is a member of the list of attachrel's
21108 : : * partitions provided the latter is partitioned at all. We want to avoid
21109 : : * having to construct this list again, so we request the strongest lock
21110 : : * on all partitions. We need the strongest lock, because we may decide
21111 : : * to scan them if we find out that the table being attached (or its leaf
21112 : : * partitions) may contain rows that violate the partition constraint. If
21113 : : * the table has a constraint that would prevent such rows, which by
21114 : : * definition is present in all the partitions, we need not scan the
21115 : : * table, nor its partitions. But we cannot risk a deadlock by taking a
21116 : : * weaker lock now and the stronger one only when needed.
21117 : : */
21118 : 1505 : attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
21119 : : AccessExclusiveLock, NULL);
21120 [ + + ]: 1505 : if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
21121 [ + - ]: 8 : ereport(ERROR,
21122 : : (errcode(ERRCODE_DUPLICATE_TABLE),
21123 : : errmsg("circular inheritance not allowed"),
21124 : : errdetail("\"%s\" is already a child of \"%s\".",
21125 : : RelationGetRelationName(rel),
21126 : : RelationGetRelationName(attachrel))));
21127 : :
21128 : : /* If the parent is permanent, so must be all of its partitions. */
21129 [ + + ]: 1497 : if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
21130 [ + + ]: 1469 : attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
21131 [ + - ]: 4 : ereport(ERROR,
21132 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21133 : : errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
21134 : : RelationGetRelationName(rel))));
21135 : :
21136 : : /* Temp parent cannot have a partition that is itself not a temp */
21137 [ + + ]: 1493 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
21138 [ + + ]: 28 : attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
21139 [ + - ]: 12 : ereport(ERROR,
21140 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21141 : : errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
21142 : : RelationGetRelationName(rel))));
21143 : :
21144 : : /* If the parent is temp, it must belong to this session */
21145 [ + + - + ]: 1481 : if (RELATION_IS_OTHER_TEMP(rel))
21146 [ # # ]: 0 : ereport(ERROR,
21147 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21148 : : errmsg("cannot attach as partition of temporary relation of another session")));
21149 : :
21150 : : /* Ditto for the partition */
21151 [ + + - + ]: 1481 : if (RELATION_IS_OTHER_TEMP(attachrel))
21152 [ # # ]: 0 : ereport(ERROR,
21153 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21154 : : errmsg("cannot attach temporary relation of another session as partition")));
21155 : :
21156 : : /*
21157 : : * Check if attachrel has any identity columns or any columns that aren't
21158 : : * in the parent.
21159 : : */
21160 : 1481 : tupleDesc = RelationGetDescr(attachrel);
21161 : 1481 : natts = tupleDesc->natts;
21162 [ + + ]: 5051 : for (attno = 1; attno <= natts; attno++)
21163 : : {
21164 : 3598 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
21165 : 3598 : char *attributeName = NameStr(attribute->attname);
21166 : :
21167 : : /* Ignore dropped */
21168 [ + + ]: 3598 : if (attribute->attisdropped)
21169 : 368 : continue;
21170 : :
21171 [ + + ]: 3230 : if (attribute->attidentity)
21172 [ + - ]: 16 : ereport(ERROR,
21173 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21174 : : errmsg("table \"%s\" being attached contains an identity column \"%s\"",
21175 : : RelationGetRelationName(attachrel), attributeName),
21176 : : errdetail("The new partition may not contain an identity column."));
21177 : :
21178 : : /* Try to find the column in parent (matching on column name) */
21179 [ + + ]: 3214 : if (!SearchSysCacheExists2(ATTNAME,
21180 : : ObjectIdGetDatum(RelationGetRelid(rel)),
21181 : : CStringGetDatum(attributeName)))
21182 [ + - ]: 12 : ereport(ERROR,
21183 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
21184 : : errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
21185 : : RelationGetRelationName(attachrel), attributeName,
21186 : : RelationGetRelationName(rel)),
21187 : : errdetail("The new partition may contain only the columns present in parent.")));
21188 : : }
21189 : :
21190 : : /*
21191 : : * If child_rel has row-level triggers with transition tables, we
21192 : : * currently don't allow it to become a partition. See also prohibitions
21193 : : * in ATExecAddInherit() and CreateTrigger().
21194 : : */
21195 : 1453 : trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
21196 [ + + ]: 1453 : if (trigger_name != NULL)
21197 [ + - ]: 4 : ereport(ERROR,
21198 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
21199 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
21200 : : trigger_name, RelationGetRelationName(attachrel)),
21201 : : errdetail("ROW triggers with transition tables are not supported on partitions.")));
21202 : :
21203 : : /*
21204 : : * Check that the new partition's bound is valid and does not overlap any
21205 : : * of existing partitions of the parent - note that it does not return on
21206 : : * error.
21207 : : */
21208 : 1449 : check_new_partition_bound(RelationGetRelationName(attachrel), rel,
21209 : : cmd->bound, pstate);
21210 : :
21211 : : /* OK to create inheritance. Rest of the checks performed there */
21212 : 1425 : CreateInheritance(attachrel, rel, true);
21213 : :
21214 : : /* Update the pg_class entry. */
21215 : 1353 : StorePartitionBound(attachrel, rel, cmd->bound);
21216 : :
21217 : : /* Ensure there exists a correct set of indexes in the partition. */
21218 : 1353 : AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
21219 : :
21220 : : /* and triggers */
21221 : 1333 : CloneRowTriggersToPartition(rel, attachrel);
21222 : :
21223 : : /*
21224 : : * Clone foreign key constraints. Callee is responsible for setting up
21225 : : * for phase 3 constraint verification.
21226 : : */
21227 : 1329 : CloneForeignKeyConstraints(wqueue, rel, attachrel);
21228 : :
21229 : : /*
21230 : : * Generate partition constraint from the partition bound specification.
21231 : : * If the parent itself is a partition, make sure to include its
21232 : : * constraint as well.
21233 : : */
21234 : 1317 : partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
21235 : :
21236 : : /*
21237 : : * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
21238 : : * since it's needed later to construct the constraint expression for
21239 : : * validating against the default partition, if any.
21240 : : */
21241 : 1317 : partConstraint = list_concat_copy(partBoundConstraint,
21242 : 1317 : RelationGetPartitionQual(rel));
21243 : :
21244 : : /* Skip validation if there are no constraints to validate. */
21245 [ + + ]: 1317 : if (partConstraint)
21246 : : {
21247 : : /*
21248 : : * Run the partition quals through const-simplification similar to
21249 : : * check constraints. We skip canonicalize_qual, though, because
21250 : : * partition quals should be in canonical form already.
21251 : : */
21252 : : partConstraint =
21253 : 1289 : (List *) eval_const_expressions(NULL,
21254 : : (Node *) partConstraint);
21255 : :
21256 : : /* XXX this sure looks wrong */
21257 : 1289 : partConstraint = list_make1(make_ands_explicit(partConstraint));
21258 : :
21259 : : /*
21260 : : * Adjust the generated constraint to match this partition's attribute
21261 : : * numbers.
21262 : : */
21263 : 1289 : partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
21264 : : rel);
21265 : :
21266 : : /* Validate partition constraints against the table being attached. */
21267 : 1289 : QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
21268 : : false);
21269 : : }
21270 : :
21271 : : /*
21272 : : * If we're attaching a partition other than the default partition and a
21273 : : * default one exists, then that partition's partition constraint changes,
21274 : : * so add an entry to the work queue to validate it, too. (We must not do
21275 : : * this when the partition being attached is the default one; we already
21276 : : * did it above!)
21277 : : */
21278 [ + + ]: 1317 : if (OidIsValid(defaultPartOid))
21279 : : {
21280 : : Relation defaultrel;
21281 : : List *defPartConstraint;
21282 : :
21283 : : Assert(!cmd->bound->is_default);
21284 : :
21285 : : /* we already hold a lock on the default partition */
21286 : 93 : defaultrel = table_open(defaultPartOid, NoLock);
21287 : : defPartConstraint =
21288 : 93 : get_proposed_default_constraint(partBoundConstraint);
21289 : :
21290 : : /*
21291 : : * Map the Vars in the constraint expression from rel's attnos to
21292 : : * defaultrel's.
21293 : : */
21294 : : defPartConstraint =
21295 : 93 : map_partition_varattnos(defPartConstraint,
21296 : : 1, defaultrel, rel);
21297 : 93 : QueuePartitionConstraintValidation(wqueue, defaultrel,
21298 : : defPartConstraint, true);
21299 : :
21300 : : /* keep our lock until commit. */
21301 : 93 : table_close(defaultrel, NoLock);
21302 : : }
21303 : :
21304 : 1317 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
21305 : :
21306 : : /*
21307 : : * If the partition we just attached is partitioned itself, invalidate
21308 : : * relcache for all descendent partitions too to ensure that their
21309 : : * rd_partcheck expression trees are rebuilt; partitions already locked at
21310 : : * the beginning of this function.
21311 : : */
21312 [ + + ]: 1317 : if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21313 : : {
21314 : : ListCell *l;
21315 : :
21316 [ + - + + : 663 : foreach(l, attachrel_children)
+ + ]
21317 : : {
21318 : 446 : CacheInvalidateRelcacheByRelid(lfirst_oid(l));
21319 : : }
21320 : : }
21321 : :
21322 : : /* keep our lock until commit */
21323 : 1317 : table_close(attachrel, NoLock);
21324 : :
21325 : 1317 : return address;
21326 : : }
21327 : :
21328 : : /*
21329 : : * AttachPartitionEnsureIndexes
21330 : : * subroutine for ATExecAttachPartition to create/match indexes
21331 : : *
21332 : : * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
21333 : : * PARTITION: every partition must have an index attached to each index on the
21334 : : * partitioned table.
21335 : : */
21336 : : static void
21337 : 1353 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
21338 : : {
21339 : : List *idxes;
21340 : : List *attachRelIdxs;
21341 : : Relation *attachrelIdxRels;
21342 : : IndexInfo **attachInfos;
21343 : : ListCell *cell;
21344 : : MemoryContext cxt;
21345 : : MemoryContext oldcxt;
21346 : :
21347 : 1353 : cxt = AllocSetContextCreate(CurrentMemoryContext,
21348 : : "AttachPartitionEnsureIndexes",
21349 : : ALLOCSET_DEFAULT_SIZES);
21350 : 1353 : oldcxt = MemoryContextSwitchTo(cxt);
21351 : :
21352 : 1353 : idxes = RelationGetIndexList(rel);
21353 : 1353 : attachRelIdxs = RelationGetIndexList(attachrel);
21354 : 1353 : attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
21355 : 1353 : attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
21356 : :
21357 : : /* Build arrays of all existing indexes and their IndexInfos */
21358 [ + + + + : 2959 : foreach_oid(cldIdxId, attachRelIdxs)
+ + ]
21359 : : {
21360 : 253 : int i = foreach_current_index(cldIdxId);
21361 : :
21362 : 253 : attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
21363 : 253 : attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
21364 : : }
21365 : :
21366 : : /*
21367 : : * If we're attaching a foreign table, we must fail if any of the indexes
21368 : : * is a constraint index; otherwise, there's nothing to do here. Do this
21369 : : * before starting work, to avoid wasting the effort of building a few
21370 : : * non-unique indexes before coming across a unique one.
21371 : : */
21372 [ + + ]: 1353 : if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
21373 : : {
21374 [ + + + + : 55 : foreach(cell, idxes)
+ + ]
21375 : : {
21376 : 24 : Oid idx = lfirst_oid(cell);
21377 : 24 : Relation idxRel = index_open(idx, AccessShareLock);
21378 : :
21379 [ + + ]: 24 : if (idxRel->rd_index->indisunique ||
21380 [ - + ]: 16 : idxRel->rd_index->indisprimary)
21381 [ + - ]: 8 : ereport(ERROR,
21382 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21383 : : errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
21384 : : RelationGetRelationName(attachrel),
21385 : : RelationGetRelationName(rel)),
21386 : : errdetail("Partitioned table \"%s\" contains unique indexes.",
21387 : : RelationGetRelationName(rel))));
21388 : 16 : index_close(idxRel, AccessShareLock);
21389 : : }
21390 : :
21391 : 31 : goto out;
21392 : : }
21393 : :
21394 : : /*
21395 : : * For each index on the partitioned table, find a matching one in the
21396 : : * partition-to-be; if one is not found, create one.
21397 : : */
21398 [ + + + + : 1595 : foreach(cell, idxes)
+ + ]
21399 : : {
21400 : 293 : Oid idx = lfirst_oid(cell);
21401 : 293 : Relation idxRel = index_open(idx, AccessShareLock);
21402 : : IndexInfo *info;
21403 : : AttrMap *attmap;
21404 : 293 : bool found = false;
21405 : : Oid constraintOid;
21406 : :
21407 : : /*
21408 : : * Ignore indexes in the partitioned table other than partitioned
21409 : : * indexes.
21410 : : */
21411 [ - + ]: 293 : if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
21412 : : {
21413 : 0 : index_close(idxRel, AccessShareLock);
21414 : 0 : continue;
21415 : : }
21416 : :
21417 : : /* construct an indexinfo to compare existing indexes against */
21418 : 293 : info = BuildIndexInfo(idxRel);
21419 : 293 : attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
21420 : : RelationGetDescr(rel),
21421 : : false);
21422 : 293 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
21423 : :
21424 : : /*
21425 : : * Scan the list of existing indexes in the partition-to-be, and mark
21426 : : * the first matching, valid, unattached one we find, if any, as
21427 : : * partition of the parent index. If we find one, we're done.
21428 : : */
21429 [ + + ]: 333 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21430 : : {
21431 : 181 : Oid cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
21432 : 181 : Oid cldConstrOid = InvalidOid;
21433 : :
21434 : : /* does this index have a parent? if so, can't use it */
21435 [ + + ]: 181 : if (attachrelIdxRels[i]->rd_rel->relispartition)
21436 : 8 : continue;
21437 : :
21438 : : /* If this index is invalid, can't use it */
21439 [ + + ]: 173 : if (!attachrelIdxRels[i]->rd_index->indisvalid)
21440 : 4 : continue;
21441 : :
21442 [ + + ]: 169 : if (CompareIndexInfo(attachInfos[i], info,
21443 : 169 : attachrelIdxRels[i]->rd_indcollation,
21444 : 169 : idxRel->rd_indcollation,
21445 : 169 : attachrelIdxRels[i]->rd_opfamily,
21446 : 169 : idxRel->rd_opfamily,
21447 : : attmap))
21448 : : {
21449 : : /*
21450 : : * If this index is being created in the parent because of a
21451 : : * constraint, then the child needs to have a constraint also,
21452 : : * so look for one. If there is no such constraint, this
21453 : : * index is no good, so keep looking.
21454 : : */
21455 [ + + ]: 145 : if (OidIsValid(constraintOid))
21456 : : {
21457 : : cldConstrOid =
21458 : 80 : get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
21459 : : cldIdxId);
21460 : : /* no dice */
21461 [ + + ]: 80 : if (!OidIsValid(cldConstrOid))
21462 : 4 : continue;
21463 : :
21464 : : /* Ensure they're both the same type of constraint */
21465 [ - + ]: 152 : if (get_constraint_type(constraintOid) !=
21466 : 76 : get_constraint_type(cldConstrOid))
21467 : 0 : continue;
21468 : : }
21469 : :
21470 : : /* bingo. */
21471 : 141 : IndexSetParentIndex(attachrelIdxRels[i], idx);
21472 [ + + ]: 141 : if (OidIsValid(constraintOid))
21473 : 76 : ConstraintSetParentConstraint(cldConstrOid, constraintOid,
21474 : : RelationGetRelid(attachrel));
21475 : 141 : found = true;
21476 : :
21477 : 141 : CommandCounterIncrement();
21478 : 141 : break;
21479 : : }
21480 : : }
21481 : :
21482 : : /*
21483 : : * If no suitable index was found in the partition-to-be, create one
21484 : : * now. Note that if this is a PK, not-null constraints must already
21485 : : * exist.
21486 : : */
21487 [ + + ]: 293 : if (!found)
21488 : : {
21489 : : IndexStmt *stmt;
21490 : : Oid conOid;
21491 : :
21492 : 152 : stmt = generateClonedIndexStmt(NULL,
21493 : : idxRel, attmap,
21494 : : &conOid);
21495 : 152 : DefineIndex(NULL,
21496 : : RelationGetRelid(attachrel), stmt, InvalidOid,
21497 : : RelationGetRelid(idxRel),
21498 : : conOid,
21499 : : -1,
21500 : : true, false, false, false, false);
21501 : : }
21502 : :
21503 : 281 : index_close(idxRel, AccessShareLock);
21504 : : }
21505 : :
21506 : 1333 : out:
21507 : : /* Clean up. */
21508 [ + + ]: 1578 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21509 : 245 : index_close(attachrelIdxRels[i], AccessShareLock);
21510 : 1333 : MemoryContextSwitchTo(oldcxt);
21511 : 1333 : MemoryContextDelete(cxt);
21512 : 1333 : }
21513 : :
21514 : : /*
21515 : : * CloneRowTriggersToPartition
21516 : : * subroutine for ATExecAttachPartition/DefineRelation to create row
21517 : : * triggers on partitions
21518 : : */
21519 : : static void
21520 : 1565 : CloneRowTriggersToPartition(Relation parent, Relation partition)
21521 : : {
21522 : : Relation pg_trigger;
21523 : : ScanKeyData key;
21524 : : SysScanDesc scan;
21525 : : HeapTuple tuple;
21526 : : MemoryContext perTupCxt;
21527 : :
21528 : 1565 : ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
21529 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
21530 : 1565 : pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
21531 : 1565 : scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
21532 : : true, NULL, 1, &key);
21533 : :
21534 : 1565 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
21535 : : "clone trig", ALLOCSET_SMALL_SIZES);
21536 : :
21537 [ + + ]: 2622 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
21538 : : {
21539 : 1061 : Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
21540 : : CreateTrigStmt *trigStmt;
21541 : 1061 : Node *qual = NULL;
21542 : : Datum value;
21543 : : bool isnull;
21544 : 1061 : List *cols = NIL;
21545 : 1061 : List *trigargs = NIL;
21546 : : MemoryContext oldcxt;
21547 : :
21548 : : /*
21549 : : * Ignore statement-level triggers; those are not cloned.
21550 : : */
21551 [ + + ]: 1061 : if (!TRIGGER_FOR_ROW(trigForm->tgtype))
21552 : 958 : continue;
21553 : :
21554 : : /*
21555 : : * Don't clone internal triggers, because the constraint cloning code
21556 : : * will.
21557 : : */
21558 [ + + ]: 1049 : if (trigForm->tgisinternal)
21559 : 946 : continue;
21560 : :
21561 : : /*
21562 : : * Complain if we find an unexpected trigger type.
21563 : : */
21564 [ + + ]: 103 : if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
21565 [ - + ]: 91 : !TRIGGER_FOR_AFTER(trigForm->tgtype))
21566 [ # # ]: 0 : elog(ERROR, "unexpected trigger \"%s\" found",
21567 : : NameStr(trigForm->tgname));
21568 : :
21569 : : /* Use short-lived context for CREATE TRIGGER */
21570 : 103 : oldcxt = MemoryContextSwitchTo(perTupCxt);
21571 : :
21572 : : /*
21573 : : * If there is a WHEN clause, generate a 'cooked' version of it that's
21574 : : * appropriate for the partition.
21575 : : */
21576 : 103 : value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
21577 : : RelationGetDescr(pg_trigger), &isnull);
21578 [ + + ]: 103 : if (!isnull)
21579 : : {
21580 : 4 : qual = stringToNode(TextDatumGetCString(value));
21581 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
21582 : : partition, parent);
21583 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
21584 : : partition, parent);
21585 : : }
21586 : :
21587 : : /*
21588 : : * If there is a column list, transform it to a list of column names.
21589 : : * Note we don't need to map this list in any way ...
21590 : : */
21591 [ + + ]: 103 : if (trigForm->tgattr.dim1 > 0)
21592 : : {
21593 : : int i;
21594 : :
21595 [ + + ]: 8 : for (i = 0; i < trigForm->tgattr.dim1; i++)
21596 : : {
21597 : : Form_pg_attribute col;
21598 : :
21599 : 4 : col = TupleDescAttr(parent->rd_att,
21600 : 4 : trigForm->tgattr.values[i] - 1);
21601 : 4 : cols = lappend(cols,
21602 : 4 : makeString(pstrdup(NameStr(col->attname))));
21603 : : }
21604 : : }
21605 : :
21606 : : /* Reconstruct trigger arguments list. */
21607 [ + + ]: 103 : if (trigForm->tgnargs > 0)
21608 : : {
21609 : : char *p;
21610 : :
21611 : 8 : value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
21612 : : RelationGetDescr(pg_trigger), &isnull);
21613 [ - + ]: 8 : if (isnull)
21614 [ # # ]: 0 : elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
21615 : : NameStr(trigForm->tgname), RelationGetRelationName(partition));
21616 : :
21617 : 8 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
21618 : :
21619 [ + + ]: 24 : for (int i = 0; i < trigForm->tgnargs; i++)
21620 : : {
21621 : 16 : trigargs = lappend(trigargs, makeString(pstrdup(p)));
21622 : 16 : p += strlen(p) + 1;
21623 : : }
21624 : : }
21625 : :
21626 : 103 : trigStmt = makeNode(CreateTrigStmt);
21627 : 103 : trigStmt->replace = false;
21628 : 103 : trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
21629 : 103 : trigStmt->trigname = NameStr(trigForm->tgname);
21630 : 103 : trigStmt->relation = NULL;
21631 : 103 : trigStmt->funcname = NULL; /* passed separately */
21632 : 103 : trigStmt->args = trigargs;
21633 : 103 : trigStmt->row = true;
21634 : 103 : trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
21635 : 103 : trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
21636 : 103 : trigStmt->columns = cols;
21637 : 103 : trigStmt->whenClause = NULL; /* passed separately */
21638 : 103 : trigStmt->transitionRels = NIL; /* not supported at present */
21639 : 103 : trigStmt->deferrable = trigForm->tgdeferrable;
21640 : 103 : trigStmt->initdeferred = trigForm->tginitdeferred;
21641 : 103 : trigStmt->constrrel = NULL; /* passed separately */
21642 : :
21643 : 103 : CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
21644 : : trigForm->tgconstrrelid, InvalidOid, InvalidOid,
21645 : : trigForm->tgfoid, trigForm->oid, qual,
21646 : 103 : false, true, trigForm->tgenabled);
21647 : :
21648 : 99 : MemoryContextSwitchTo(oldcxt);
21649 : 99 : MemoryContextReset(perTupCxt);
21650 : : }
21651 : :
21652 : 1561 : MemoryContextDelete(perTupCxt);
21653 : :
21654 : 1561 : systable_endscan(scan);
21655 : 1561 : table_close(pg_trigger, RowExclusiveLock);
21656 : 1561 : }
21657 : :
21658 : : /*
21659 : : * ALTER TABLE DETACH PARTITION
21660 : : *
21661 : : * Return the address of the relation that is no longer a partition of rel.
21662 : : *
21663 : : * If concurrent mode is requested, we run in two transactions. A side-
21664 : : * effect is that this command cannot run in a multi-part ALTER TABLE.
21665 : : * Currently, that's enforced by the grammar.
21666 : : *
21667 : : * The strategy for concurrency is to first modify the partition's
21668 : : * pg_inherit catalog row to make it visible to everyone that the
21669 : : * partition is detached, lock the partition against writes, and commit
21670 : : * the transaction; anyone who requests the partition descriptor from
21671 : : * that point onwards has to ignore such a partition. In a second
21672 : : * transaction, we wait until all transactions that could have seen the
21673 : : * partition as attached are gone, then we remove the rest of partition
21674 : : * metadata (pg_inherits and pg_class.relpartbounds).
21675 : : */
21676 : : static ObjectAddress
21677 : 362 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
21678 : : RangeVar *name, bool concurrent)
21679 : : {
21680 : : Relation partRel;
21681 : : ObjectAddress address;
21682 : : Oid defaultPartOid;
21683 : :
21684 : : /*
21685 : : * We must lock the default partition, because detaching this partition
21686 : : * will change its partition constraint.
21687 : : */
21688 : : defaultPartOid =
21689 : 362 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
21690 [ + + ]: 362 : if (OidIsValid(defaultPartOid))
21691 : : {
21692 : : /*
21693 : : * Concurrent detaching when a default partition exists is not
21694 : : * supported. The main problem is that the default partition
21695 : : * constraint would change. And there's a definitional problem: what
21696 : : * should happen to the tuples that are being inserted that belong to
21697 : : * the partition being detached? Putting them on the partition being
21698 : : * detached would be wrong, since they'd become "lost" after the
21699 : : * detaching completes but we cannot put them in the default partition
21700 : : * either until we alter its partition constraint.
21701 : : *
21702 : : * I think we could solve this problem if we effected the constraint
21703 : : * change before committing the first transaction. But the lock would
21704 : : * have to remain AEL and it would cause concurrent query planning to
21705 : : * be blocked, so changing it that way would be even worse.
21706 : : */
21707 [ + + ]: 70 : if (concurrent)
21708 [ + - ]: 8 : ereport(ERROR,
21709 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21710 : : errmsg("cannot detach partitions concurrently when a default partition exists")));
21711 : 62 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
21712 : : }
21713 : :
21714 : : /*
21715 : : * In concurrent mode, the partition is locked with share-update-exclusive
21716 : : * in the first transaction. This allows concurrent transactions to be
21717 : : * doing DML to the partition.
21718 : : */
21719 [ + + ]: 354 : partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
21720 : : AccessExclusiveLock);
21721 : :
21722 : : /*
21723 : : * Check inheritance conditions and either delete the pg_inherits row (in
21724 : : * non-concurrent mode) or just set the inhdetachpending flag.
21725 : : */
21726 [ + + ]: 346 : if (!concurrent)
21727 : 270 : RemoveInheritance(partRel, rel, false);
21728 : : else
21729 : 76 : MarkInheritDetached(partRel, rel);
21730 : :
21731 : : /*
21732 : : * Ensure that foreign keys still hold after this detach. This keeps
21733 : : * locks on the referencing tables, which prevents concurrent transactions
21734 : : * from adding rows that we wouldn't see. For this to work in concurrent
21735 : : * mode, it is critical that the partition appears as no longer attached
21736 : : * for the RI queries as soon as the first transaction commits.
21737 : : */
21738 : 333 : ATDetachCheckNoForeignKeyRefs(partRel);
21739 : :
21740 : : /*
21741 : : * Concurrent mode has to work harder; first we add a new constraint to
21742 : : * the partition that matches the partition constraint. Then we close our
21743 : : * existing transaction, and in a new one wait for all processes to catch
21744 : : * up on the catalog updates we've done so far; at that point we can
21745 : : * complete the operation.
21746 : : */
21747 [ + + ]: 311 : if (concurrent)
21748 : : {
21749 : : Oid partrelid,
21750 : : parentrelid;
21751 : : LOCKTAG tag;
21752 : : char *parentrelname;
21753 : : char *partrelname;
21754 : :
21755 : : /*
21756 : : * We're almost done now; the only traces that remain are the
21757 : : * pg_inherits tuple and the partition's relpartbounds. Before we can
21758 : : * remove those, we need to wait until all transactions that know that
21759 : : * this is a partition are gone.
21760 : : */
21761 : :
21762 : : /*
21763 : : * Remember relation OIDs to re-acquire them later; and relation names
21764 : : * too, for error messages if something is dropped in between.
21765 : : */
21766 : 73 : partrelid = RelationGetRelid(partRel);
21767 : 73 : parentrelid = RelationGetRelid(rel);
21768 : 73 : parentrelname = MemoryContextStrdup(PortalContext,
21769 : 73 : RelationGetRelationName(rel));
21770 : 73 : partrelname = MemoryContextStrdup(PortalContext,
21771 : 73 : RelationGetRelationName(partRel));
21772 : :
21773 : : /* Invalidate relcache entries for the parent -- must be before close */
21774 : 73 : CacheInvalidateRelcache(rel);
21775 : :
21776 : 73 : table_close(partRel, NoLock);
21777 : 73 : table_close(rel, NoLock);
21778 : 73 : tab->rel = NULL;
21779 : :
21780 : : /* Make updated catalog entry visible */
21781 : 73 : PopActiveSnapshot();
21782 : 73 : CommitTransactionCommand();
21783 : :
21784 : 73 : StartTransactionCommand();
21785 : :
21786 : : /*
21787 : : * Now wait. This ensures that all queries that were planned
21788 : : * including the partition are finished before we remove the rest of
21789 : : * catalog entries. We don't need or indeed want to acquire this
21790 : : * lock, though -- that would block later queries.
21791 : : *
21792 : : * We don't need to concern ourselves with waiting for a lock on the
21793 : : * partition itself, since we will acquire AccessExclusiveLock below.
21794 : : */
21795 : 73 : SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
21796 : 73 : WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
21797 : :
21798 : : /*
21799 : : * Now acquire locks in both relations again. Note they may have been
21800 : : * removed in the meantime, so care is required.
21801 : : */
21802 : 47 : rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
21803 : 47 : partRel = try_relation_open(partrelid, AccessExclusiveLock);
21804 : :
21805 : : /* If the relations aren't there, something bad happened; bail out */
21806 [ - + ]: 47 : if (rel == NULL)
21807 : : {
21808 [ # # ]: 0 : if (partRel != NULL) /* shouldn't happen */
21809 [ # # ]: 0 : elog(WARNING, "dangling partition \"%s\" remains, can't fix",
21810 : : partrelname);
21811 [ # # ]: 0 : ereport(ERROR,
21812 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21813 : : errmsg("partitioned table \"%s\" was removed concurrently",
21814 : : parentrelname)));
21815 : : }
21816 [ - + ]: 47 : if (partRel == NULL)
21817 [ # # ]: 0 : ereport(ERROR,
21818 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21819 : : errmsg("partition \"%s\" was removed concurrently", partrelname)));
21820 : :
21821 : 47 : tab->rel = rel;
21822 : : }
21823 : :
21824 : : /*
21825 : : * Detaching the partition might involve TOAST table access, so ensure we
21826 : : * have a valid snapshot.
21827 : : */
21828 : 285 : PushActiveSnapshot(GetTransactionSnapshot());
21829 : :
21830 : : /* Do the final part of detaching */
21831 : 285 : DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
21832 : :
21833 : 284 : PopActiveSnapshot();
21834 : :
21835 : 284 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21836 : :
21837 : : /* keep our lock until commit */
21838 : 284 : table_close(partRel, NoLock);
21839 : :
21840 : 284 : return address;
21841 : : }
21842 : :
21843 : : /*
21844 : : * Second part of ALTER TABLE .. DETACH.
21845 : : *
21846 : : * This is separate so that it can be run independently when the second
21847 : : * transaction of the concurrent algorithm fails (crash or abort).
21848 : : */
21849 : : static void
21850 : 292 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
21851 : : Oid defaultPartOid)
21852 : : {
21853 : : Relation classRel;
21854 : : List *fks;
21855 : : ListCell *cell;
21856 : : List *indexes;
21857 : : Datum new_val[Natts_pg_class];
21858 : : bool new_null[Natts_pg_class],
21859 : : new_repl[Natts_pg_class];
21860 : : HeapTuple tuple,
21861 : : newtuple;
21862 : 292 : Relation trigrel = NULL;
21863 : 292 : List *fkoids = NIL;
21864 : :
21865 [ + + ]: 292 : if (concurrent)
21866 : : {
21867 : : /*
21868 : : * We can remove the pg_inherits row now. (In the non-concurrent case,
21869 : : * this was already done).
21870 : : */
21871 : 54 : RemoveInheritance(partRel, rel, true);
21872 : : }
21873 : :
21874 : : /* Drop any triggers that were cloned on creation/attach. */
21875 : 292 : DropClonedTriggersFromPartition(RelationGetRelid(partRel));
21876 : :
21877 : : /*
21878 : : * Detach any foreign keys that are inherited. This includes creating
21879 : : * additional action triggers.
21880 : : */
21881 : 292 : fks = copyObject(RelationGetFKeyList(partRel));
21882 [ + + ]: 292 : if (fks != NIL)
21883 : 56 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
21884 : :
21885 : : /*
21886 : : * It's possible that the partition being detached has a foreign key that
21887 : : * references a partitioned table. When that happens, there are multiple
21888 : : * pg_constraint rows for the partition: one points to the partitioned
21889 : : * table itself, while the others point to each of its partitions. Only
21890 : : * the topmost one is to be considered here; the child constraints must be
21891 : : * left alone, because conceptually those aren't coming from our parent
21892 : : * partitioned table, but from this partition itself.
21893 : : *
21894 : : * We implement this by collecting all the constraint OIDs in a first scan
21895 : : * of the FK array, and skipping in the loop below those constraints whose
21896 : : * parents are listed here.
21897 : : */
21898 [ + + + + : 696 : foreach_node(ForeignKeyCacheInfo, fk, fks)
+ + ]
21899 : 112 : fkoids = lappend_oid(fkoids, fk->conoid);
21900 : :
21901 [ + + + + : 404 : foreach(cell, fks)
+ + ]
21902 : : {
21903 : 112 : ForeignKeyCacheInfo *fk = lfirst(cell);
21904 : : HeapTuple contup;
21905 : : Form_pg_constraint conform;
21906 : :
21907 : 112 : contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
21908 [ - + ]: 112 : if (!HeapTupleIsValid(contup))
21909 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
21910 : 112 : conform = (Form_pg_constraint) GETSTRUCT(contup);
21911 : :
21912 : : /*
21913 : : * Consider only inherited foreign keys, and only if their parents
21914 : : * aren't in the list.
21915 : : */
21916 [ + - ]: 112 : if (conform->contype != CONSTRAINT_FOREIGN ||
21917 [ + + + + ]: 208 : !OidIsValid(conform->conparentid) ||
21918 : 96 : list_member_oid(fkoids, conform->conparentid))
21919 : : {
21920 : 44 : ReleaseSysCache(contup);
21921 : 44 : continue;
21922 : : }
21923 : :
21924 : : /*
21925 : : * The constraint on this table must be marked no longer a child of
21926 : : * the parent's constraint, as do its check triggers.
21927 : : */
21928 : 68 : ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
21929 : :
21930 : : /*
21931 : : * Also, look up the partition's "check" triggers corresponding to the
21932 : : * ENFORCED constraint being detached and detach them from the parent
21933 : : * triggers. NOT ENFORCED constraints do not have these triggers;
21934 : : * therefore, this step is not needed.
21935 : : */
21936 [ + - ]: 68 : if (fk->conenforced)
21937 : : {
21938 : : Oid insertTriggerOid,
21939 : : updateTriggerOid;
21940 : :
21941 : 68 : GetForeignKeyCheckTriggers(trigrel,
21942 : : fk->conoid, fk->confrelid, fk->conrelid,
21943 : : &insertTriggerOid, &updateTriggerOid);
21944 : : Assert(OidIsValid(insertTriggerOid));
21945 : 68 : TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
21946 : : RelationGetRelid(partRel));
21947 : : Assert(OidIsValid(updateTriggerOid));
21948 : 68 : TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
21949 : : RelationGetRelid(partRel));
21950 : : }
21951 : :
21952 : : /*
21953 : : * Lastly, create the action triggers on the referenced table, using
21954 : : * addFkRecurseReferenced, which requires some elaborate setup (so put
21955 : : * it in a separate block). While at it, if the table is partitioned,
21956 : : * that function will recurse to create the pg_constraint rows and
21957 : : * action triggers for each partition.
21958 : : *
21959 : : * Note there's no need to do addFkConstraint() here, because the
21960 : : * pg_constraint row already exists.
21961 : : */
21962 : : {
21963 : : Constraint *fkconstraint;
21964 : : int numfks;
21965 : : AttrNumber conkey[INDEX_MAX_KEYS];
21966 : : AttrNumber confkey[INDEX_MAX_KEYS];
21967 : : Oid conpfeqop[INDEX_MAX_KEYS];
21968 : : Oid conppeqop[INDEX_MAX_KEYS];
21969 : : Oid conffeqop[INDEX_MAX_KEYS];
21970 : : int numfkdelsetcols;
21971 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
21972 : : Relation refdRel;
21973 : :
21974 : 68 : DeconstructFkConstraintRow(contup,
21975 : : &numfks,
21976 : : conkey,
21977 : : confkey,
21978 : : conpfeqop,
21979 : : conppeqop,
21980 : : conffeqop,
21981 : : &numfkdelsetcols,
21982 : : confdelsetcols);
21983 : :
21984 : : /* Create a synthetic node we'll use throughout */
21985 : 68 : fkconstraint = makeNode(Constraint);
21986 : 68 : fkconstraint->contype = CONSTRAINT_FOREIGN;
21987 : 68 : fkconstraint->conname = pstrdup(NameStr(conform->conname));
21988 : 68 : fkconstraint->deferrable = conform->condeferrable;
21989 : 68 : fkconstraint->initdeferred = conform->condeferred;
21990 : 68 : fkconstraint->is_enforced = conform->conenforced;
21991 : 68 : fkconstraint->skip_validation = true;
21992 : 68 : fkconstraint->initially_valid = conform->convalidated;
21993 : : /* a few irrelevant fields omitted here */
21994 : 68 : fkconstraint->pktable = NULL;
21995 : 68 : fkconstraint->fk_attrs = NIL;
21996 : 68 : fkconstraint->pk_attrs = NIL;
21997 : 68 : fkconstraint->fk_matchtype = conform->confmatchtype;
21998 : 68 : fkconstraint->fk_upd_action = conform->confupdtype;
21999 : 68 : fkconstraint->fk_del_action = conform->confdeltype;
22000 : 68 : fkconstraint->fk_del_set_cols = NIL;
22001 : 68 : fkconstraint->old_conpfeqop = NIL;
22002 : 68 : fkconstraint->old_pktable_oid = InvalidOid;
22003 : 68 : fkconstraint->location = -1;
22004 : :
22005 : : /* set up colnames, used to generate the constraint name */
22006 [ + + ]: 168 : for (int i = 0; i < numfks; i++)
22007 : : {
22008 : : Form_pg_attribute att;
22009 : :
22010 : 100 : att = TupleDescAttr(RelationGetDescr(partRel),
22011 : 100 : conkey[i] - 1);
22012 : :
22013 : 100 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
22014 : 100 : makeString(NameStr(att->attname)));
22015 : : }
22016 : :
22017 : 68 : refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
22018 : :
22019 : 68 : addFkRecurseReferenced(fkconstraint, partRel,
22020 : : refdRel,
22021 : : conform->conindid,
22022 : : fk->conoid,
22023 : : numfks,
22024 : : confkey,
22025 : : conkey,
22026 : : conpfeqop,
22027 : : conppeqop,
22028 : : conffeqop,
22029 : : numfkdelsetcols,
22030 : : confdelsetcols,
22031 : : true,
22032 : : InvalidOid, InvalidOid,
22033 : 68 : conform->conperiod);
22034 : 68 : table_close(refdRel, NoLock); /* keep lock till end of xact */
22035 : : }
22036 : :
22037 : 68 : ReleaseSysCache(contup);
22038 : : }
22039 : 292 : list_free_deep(fks);
22040 [ + + ]: 292 : if (trigrel)
22041 : 56 : table_close(trigrel, RowExclusiveLock);
22042 : :
22043 : : /*
22044 : : * Any sub-constraints that are in the referenced-side of a larger
22045 : : * constraint have to be removed. This partition is no longer part of the
22046 : : * key space of the constraint.
22047 : : */
22048 [ + + + + : 327 : foreach(cell, GetParentedForeignKeyRefs(partRel))
+ + ]
22049 : : {
22050 : 36 : Oid constrOid = lfirst_oid(cell);
22051 : : ObjectAddress constraint;
22052 : :
22053 : 36 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22054 : 36 : deleteDependencyRecordsForClass(ConstraintRelationId,
22055 : : constrOid,
22056 : : ConstraintRelationId,
22057 : : DEPENDENCY_INTERNAL);
22058 : 36 : CommandCounterIncrement();
22059 : :
22060 : 36 : ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
22061 : 36 : performDeletion(&constraint, DROP_RESTRICT, 0);
22062 : : }
22063 : :
22064 : : /* Now we can detach indexes */
22065 : 291 : indexes = RelationGetIndexList(partRel);
22066 [ + + + + : 415 : foreach(cell, indexes)
+ + ]
22067 : : {
22068 : 124 : Oid idxid = lfirst_oid(cell);
22069 : : Oid parentidx;
22070 : : Relation idx;
22071 : : Oid constrOid;
22072 : : Oid parentConstrOid;
22073 : :
22074 [ + + ]: 124 : if (!has_superclass(idxid))
22075 : 8 : continue;
22076 : :
22077 : 116 : parentidx = get_partition_parent(idxid, false);
22078 : : Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
22079 : :
22080 : 116 : idx = index_open(idxid, AccessExclusiveLock);
22081 : 116 : IndexSetParentIndex(idx, InvalidOid);
22082 : :
22083 : : /*
22084 : : * If there's a constraint associated with the index, detach it too.
22085 : : * Careful: it is possible for a constraint index in a partition to be
22086 : : * the child of a non-constraint index, so verify whether the parent
22087 : : * index does actually have a constraint.
22088 : : */
22089 : 116 : constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
22090 : : idxid);
22091 : 116 : parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
22092 : : parentidx);
22093 [ + + + - ]: 116 : if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
22094 : 51 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22095 : :
22096 : 116 : index_close(idx, NoLock);
22097 : : }
22098 : :
22099 : : /* Update pg_class tuple */
22100 : 291 : classRel = table_open(RelationRelationId, RowExclusiveLock);
22101 : 291 : tuple = SearchSysCacheCopy1(RELOID,
22102 : : ObjectIdGetDatum(RelationGetRelid(partRel)));
22103 [ - + ]: 291 : if (!HeapTupleIsValid(tuple))
22104 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u",
22105 : : RelationGetRelid(partRel));
22106 : : Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
22107 : :
22108 : : /* Clear relpartbound and reset relispartition */
22109 : 291 : memset(new_val, 0, sizeof(new_val));
22110 : 291 : memset(new_null, false, sizeof(new_null));
22111 : 291 : memset(new_repl, false, sizeof(new_repl));
22112 : 291 : new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
22113 : 291 : new_null[Anum_pg_class_relpartbound - 1] = true;
22114 : 291 : new_repl[Anum_pg_class_relpartbound - 1] = true;
22115 : 291 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
22116 : : new_val, new_null, new_repl);
22117 : :
22118 : 291 : ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
22119 : 291 : CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
22120 : 291 : heap_freetuple(newtuple);
22121 : 291 : table_close(classRel, RowExclusiveLock);
22122 : :
22123 : : /*
22124 : : * Drop identity property from all identity columns of partition.
22125 : : */
22126 [ + + ]: 840 : for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
22127 : : {
22128 : 549 : Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
22129 : :
22130 [ + + + + ]: 549 : if (!attr->attisdropped && attr->attidentity)
22131 : 4 : ATExecDropIdentity(partRel, NameStr(attr->attname), false,
22132 : : AccessExclusiveLock, true, true);
22133 : : }
22134 : :
22135 [ + + ]: 291 : if (OidIsValid(defaultPartOid))
22136 : : {
22137 : : /*
22138 : : * If the relation being detached is the default partition itself,
22139 : : * remove it from the parent's pg_partitioned_table entry.
22140 : : *
22141 : : * If not, we must invalidate default partition's relcache entry, as
22142 : : * in StorePartitionBound: its partition constraint depends on every
22143 : : * other partition's partition constraint.
22144 : : */
22145 [ + + ]: 30 : if (RelationGetRelid(partRel) == defaultPartOid)
22146 : 1 : update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
22147 : : else
22148 : 29 : CacheInvalidateRelcacheByRelid(defaultPartOid);
22149 : : }
22150 : :
22151 : : /*
22152 : : * Invalidate the parent's relcache so that the partition is no longer
22153 : : * included in its partition descriptor.
22154 : : */
22155 : 291 : CacheInvalidateRelcache(rel);
22156 : :
22157 : : /*
22158 : : * If the partition we just detached is partitioned itself, invalidate
22159 : : * relcache for all descendent partitions too to ensure that their
22160 : : * rd_partcheck expression trees are rebuilt; must lock partitions before
22161 : : * doing so, using the same lockmode as what partRel has been locked with
22162 : : * by the caller.
22163 : : */
22164 [ + + ]: 291 : if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
22165 : : {
22166 : : List *children;
22167 : :
22168 : 41 : children = find_all_inheritors(RelationGetRelid(partRel),
22169 : : AccessExclusiveLock, NULL);
22170 [ + - + + : 135 : foreach(cell, children)
+ + ]
22171 : : {
22172 : 94 : CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
22173 : : }
22174 : : }
22175 : 291 : }
22176 : :
22177 : : /*
22178 : : * ALTER TABLE ... DETACH PARTITION ... FINALIZE
22179 : : *
22180 : : * To use when a DETACH PARTITION command previously did not run to
22181 : : * completion; this completes the detaching process.
22182 : : */
22183 : : static ObjectAddress
22184 : 7 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
22185 : : {
22186 : : Relation partRel;
22187 : : ObjectAddress address;
22188 : 7 : Snapshot snap = GetActiveSnapshot();
22189 : :
22190 : 7 : partRel = table_openrv(name, AccessExclusiveLock);
22191 : :
22192 : : /*
22193 : : * Wait until existing snapshots are gone. This is important if the
22194 : : * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
22195 : : * user could immediately run DETACH FINALIZE without actually waiting for
22196 : : * existing transactions. We must not complete the detach action until
22197 : : * all such queries are complete (otherwise we would present them with an
22198 : : * inconsistent view of catalogs).
22199 : : */
22200 : 7 : WaitForOlderSnapshots(snap->xmin, false);
22201 : :
22202 : 7 : DetachPartitionFinalize(rel, partRel, true, InvalidOid);
22203 : :
22204 : 7 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
22205 : :
22206 : 7 : table_close(partRel, NoLock);
22207 : :
22208 : 7 : return address;
22209 : : }
22210 : :
22211 : : /*
22212 : : * DropClonedTriggersFromPartition
22213 : : * subroutine for ATExecDetachPartition to remove any triggers that were
22214 : : * cloned to the partition when it was created-as-partition or attached.
22215 : : * This undoes what CloneRowTriggersToPartition did.
22216 : : */
22217 : : static void
22218 : 292 : DropClonedTriggersFromPartition(Oid partitionId)
22219 : : {
22220 : : ScanKeyData skey;
22221 : : SysScanDesc scan;
22222 : : HeapTuple trigtup;
22223 : : Relation tgrel;
22224 : : ObjectAddresses *objects;
22225 : :
22226 : 292 : objects = new_object_addresses();
22227 : :
22228 : : /*
22229 : : * Scan pg_trigger to search for all triggers on this rel.
22230 : : */
22231 : 292 : ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
22232 : : F_OIDEQ, ObjectIdGetDatum(partitionId));
22233 : 292 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
22234 : 292 : scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
22235 : : true, NULL, 1, &skey);
22236 [ + + ]: 556 : while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
22237 : : {
22238 : 264 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
22239 : : ObjectAddress trig;
22240 : :
22241 : : /* Ignore triggers that weren't cloned */
22242 [ + + ]: 264 : if (!OidIsValid(pg_trigger->tgparentid))
22243 : 252 : continue;
22244 : :
22245 : : /*
22246 : : * Ignore internal triggers that are implementation objects of foreign
22247 : : * keys, because these will be detached when the foreign keys
22248 : : * themselves are.
22249 : : */
22250 [ + + ]: 220 : if (OidIsValid(pg_trigger->tgconstrrelid))
22251 : 208 : continue;
22252 : :
22253 : : /*
22254 : : * This is ugly, but necessary: remove the dependency markings on the
22255 : : * trigger so that it can be removed.
22256 : : */
22257 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22258 : : TriggerRelationId,
22259 : : DEPENDENCY_PARTITION_PRI);
22260 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22261 : : RelationRelationId,
22262 : : DEPENDENCY_PARTITION_SEC);
22263 : :
22264 : : /* remember this trigger to remove it below */
22265 : 12 : ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
22266 : 12 : add_exact_object_address(&trig, objects);
22267 : : }
22268 : :
22269 : : /* make the dependency removal visible to the deletion below */
22270 : 292 : CommandCounterIncrement();
22271 : 292 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
22272 : :
22273 : : /* done */
22274 : 292 : free_object_addresses(objects);
22275 : 292 : systable_endscan(scan);
22276 : 292 : table_close(tgrel, RowExclusiveLock);
22277 : 292 : }
22278 : :
22279 : : /*
22280 : : * Before acquiring lock on an index, acquire the same lock on the owning
22281 : : * table.
22282 : : */
22283 : : struct AttachIndexCallbackState
22284 : : {
22285 : : Oid partitionOid;
22286 : : Oid parentTblOid;
22287 : : bool lockedParentTbl;
22288 : : };
22289 : :
22290 : : static void
22291 : 296 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
22292 : : void *arg)
22293 : : {
22294 : : struct AttachIndexCallbackState *state;
22295 : : Form_pg_class classform;
22296 : : HeapTuple tuple;
22297 : :
22298 : 296 : state = (struct AttachIndexCallbackState *) arg;
22299 : :
22300 [ + + ]: 296 : if (!state->lockedParentTbl)
22301 : : {
22302 : 286 : LockRelationOid(state->parentTblOid, AccessShareLock);
22303 : 286 : state->lockedParentTbl = true;
22304 : : }
22305 : :
22306 : : /*
22307 : : * If we previously locked some other heap, and the name we're looking up
22308 : : * no longer refers to an index on that relation, release the now-useless
22309 : : * lock. XXX maybe we should do *after* we verify whether the index does
22310 : : * not actually belong to the same relation ...
22311 : : */
22312 [ + + - + ]: 296 : if (relOid != oldRelOid && OidIsValid(state->partitionOid))
22313 : : {
22314 : 0 : UnlockRelationOid(state->partitionOid, AccessShareLock);
22315 : 0 : state->partitionOid = InvalidOid;
22316 : : }
22317 : :
22318 : : /* Didn't find a relation, so no need for locking or permission checks. */
22319 [ + + ]: 296 : if (!OidIsValid(relOid))
22320 : 4 : return;
22321 : :
22322 : 292 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
22323 [ - + ]: 292 : if (!HeapTupleIsValid(tuple))
22324 : 0 : return; /* concurrently dropped, so nothing to do */
22325 : 292 : classform = (Form_pg_class) GETSTRUCT(tuple);
22326 [ + + ]: 292 : if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
22327 [ + + ]: 226 : classform->relkind != RELKIND_INDEX)
22328 [ + - ]: 4 : ereport(ERROR,
22329 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22330 : : errmsg("\"%s\" is not an index", rv->relname)));
22331 : 288 : ReleaseSysCache(tuple);
22332 : :
22333 : : /*
22334 : : * Since we need only examine the heap's tupledesc, an access share lock
22335 : : * on it (preventing any DDL) is sufficient.
22336 : : */
22337 : 288 : state->partitionOid = IndexGetRelation(relOid, false);
22338 : 288 : LockRelationOid(state->partitionOid, AccessShareLock);
22339 : : }
22340 : :
22341 : : /*
22342 : : * ALTER INDEX i1 ATTACH PARTITION i2
22343 : : */
22344 : : static ObjectAddress
22345 : 286 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
22346 : : {
22347 : : Relation partIdx;
22348 : : Relation partTbl;
22349 : : Relation parentTbl;
22350 : : ObjectAddress address;
22351 : : Oid partIdxId;
22352 : : Oid currParent;
22353 : : struct AttachIndexCallbackState state;
22354 : :
22355 : : /*
22356 : : * We need to obtain lock on the index 'name' to modify it, but we also
22357 : : * need to read its owning table's tuple descriptor -- so we need to lock
22358 : : * both. To avoid deadlocks, obtain lock on the table before doing so on
22359 : : * the index. Furthermore, we need to examine the parent table of the
22360 : : * partition, so lock that one too.
22361 : : */
22362 : 286 : state.partitionOid = InvalidOid;
22363 : 286 : state.parentTblOid = parentIdx->rd_index->indrelid;
22364 : 286 : state.lockedParentTbl = false;
22365 : : partIdxId =
22366 : 286 : RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
22367 : : RangeVarCallbackForAttachIndex,
22368 : : &state);
22369 : : /* Not there? */
22370 [ - + ]: 278 : if (!OidIsValid(partIdxId))
22371 [ # # ]: 0 : ereport(ERROR,
22372 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
22373 : : errmsg("index \"%s\" does not exist", name->relname)));
22374 : :
22375 : : /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
22376 : 278 : partIdx = relation_open(partIdxId, AccessExclusiveLock);
22377 : :
22378 : : /* we already hold locks on both tables, so this is safe: */
22379 : 278 : parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
22380 : 278 : partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
22381 : :
22382 : 278 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
22383 : :
22384 : : /*
22385 : : * Check if the index is already attached to the correct parent,
22386 : : * ultimately attempting one round of validation if already the case.
22387 : : */
22388 : 556 : currParent = partIdx->rd_rel->relispartition ?
22389 [ + + ]: 278 : get_partition_parent(partIdxId, false) : InvalidOid;
22390 [ + + ]: 278 : if (currParent != RelationGetRelid(parentIdx))
22391 : : {
22392 : : IndexInfo *childInfo;
22393 : : IndexInfo *parentInfo;
22394 : : AttrMap *attmap;
22395 : : bool found;
22396 : : int i;
22397 : : PartitionDesc partDesc;
22398 : : Oid constraintOid,
22399 : 254 : cldConstrId = InvalidOid;
22400 : :
22401 : : /*
22402 : : * If this partition already has an index attached, refuse the
22403 : : * operation.
22404 : : */
22405 : 254 : refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
22406 : :
22407 [ - + ]: 250 : if (OidIsValid(currParent))
22408 [ # # ]: 0 : ereport(ERROR,
22409 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22410 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22411 : : RelationGetRelationName(partIdx),
22412 : : RelationGetRelationName(parentIdx)),
22413 : : errdetail("Index \"%s\" is already attached to another index.",
22414 : : RelationGetRelationName(partIdx))));
22415 : :
22416 : : /* Make sure it indexes a partition of the other index's table */
22417 : 250 : partDesc = RelationGetPartitionDesc(parentTbl, true);
22418 : 250 : found = false;
22419 [ + + ]: 379 : for (i = 0; i < partDesc->nparts; i++)
22420 : : {
22421 [ + + ]: 375 : if (partDesc->oids[i] == state.partitionOid)
22422 : : {
22423 : 246 : found = true;
22424 : 246 : break;
22425 : : }
22426 : : }
22427 [ + + ]: 250 : if (!found)
22428 [ + - ]: 4 : ereport(ERROR,
22429 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22430 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22431 : : RelationGetRelationName(partIdx),
22432 : : RelationGetRelationName(parentIdx)),
22433 : : errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
22434 : : RelationGetRelationName(partIdx),
22435 : : RelationGetRelationName(parentTbl))));
22436 : :
22437 : : /* Ensure the indexes are compatible */
22438 : 246 : childInfo = BuildIndexInfo(partIdx);
22439 : 246 : parentInfo = BuildIndexInfo(parentIdx);
22440 : 246 : attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
22441 : : RelationGetDescr(parentTbl),
22442 : : false);
22443 [ + + ]: 246 : if (!CompareIndexInfo(childInfo, parentInfo,
22444 : 246 : partIdx->rd_indcollation,
22445 : 246 : parentIdx->rd_indcollation,
22446 : 246 : partIdx->rd_opfamily,
22447 : 246 : parentIdx->rd_opfamily,
22448 : : attmap))
22449 [ + - ]: 32 : ereport(ERROR,
22450 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22451 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22452 : : RelationGetRelationName(partIdx),
22453 : : RelationGetRelationName(parentIdx)),
22454 : : errdetail("The index definitions do not match.")));
22455 : :
22456 : : /*
22457 : : * If there is a constraint in the parent, make sure there is one in
22458 : : * the child too.
22459 : : */
22460 : 214 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
22461 : : RelationGetRelid(parentIdx));
22462 : :
22463 [ + + ]: 214 : if (OidIsValid(constraintOid))
22464 : : {
22465 : 72 : cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
22466 : : partIdxId);
22467 [ + + ]: 72 : if (!OidIsValid(cldConstrId))
22468 [ + - ]: 4 : ereport(ERROR,
22469 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22470 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22471 : : RelationGetRelationName(partIdx),
22472 : : RelationGetRelationName(parentIdx)),
22473 : : errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
22474 : : RelationGetRelationName(parentIdx),
22475 : : RelationGetRelationName(parentTbl),
22476 : : RelationGetRelationName(partIdx))));
22477 : : }
22478 : :
22479 : : /*
22480 : : * If it's a primary key, make sure the columns in the partition are
22481 : : * NOT NULL.
22482 : : */
22483 [ + + ]: 210 : if (parentIdx->rd_index->indisprimary)
22484 : 51 : verifyPartitionIndexNotNull(childInfo, partTbl);
22485 : :
22486 : : /* All good -- do it */
22487 : 210 : IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
22488 [ + + ]: 210 : if (OidIsValid(constraintOid))
22489 : 68 : ConstraintSetParentConstraint(cldConstrId, constraintOid,
22490 : : RelationGetRelid(partTbl));
22491 : :
22492 : 210 : free_attrmap(attmap);
22493 : :
22494 : 210 : validatePartitionedIndex(parentIdx, parentTbl);
22495 : : }
22496 [ + + ]: 24 : else if (!parentIdx->rd_index->indisvalid)
22497 : : {
22498 : : /*
22499 : : * The index is attached, but the parent is still invalid; see if it
22500 : : * can be validated now.
22501 : : */
22502 : 12 : validatePartitionedIndex(parentIdx, parentTbl);
22503 : : }
22504 : :
22505 : 234 : relation_close(parentTbl, AccessShareLock);
22506 : : /* keep these locks till commit */
22507 : 234 : relation_close(partTbl, NoLock);
22508 : 234 : relation_close(partIdx, NoLock);
22509 : :
22510 : 234 : return address;
22511 : : }
22512 : :
22513 : : /*
22514 : : * Verify whether the given partition already contains an index attached
22515 : : * to the given partitioned index. If so, raise an error.
22516 : : */
22517 : : static void
22518 : 254 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
22519 : : {
22520 : : Oid existingIdx;
22521 : :
22522 : 254 : existingIdx = index_get_partition(partitionTbl,
22523 : : RelationGetRelid(parentIdx));
22524 [ + + ]: 254 : if (OidIsValid(existingIdx))
22525 [ + - ]: 4 : ereport(ERROR,
22526 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22527 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22528 : : RelationGetRelationName(partIdx),
22529 : : RelationGetRelationName(parentIdx)),
22530 : : errdetail("Another index \"%s\" is already attached for partition \"%s\".",
22531 : : get_rel_name(existingIdx),
22532 : : RelationGetRelationName(partitionTbl))));
22533 : 250 : }
22534 : :
22535 : : /*
22536 : : * Verify whether the set of attached partition indexes to a parent index on
22537 : : * a partitioned table is complete. If it is, mark the parent index valid.
22538 : : *
22539 : : * This should be called each time a partition index is attached.
22540 : : */
22541 : : static void
22542 : 254 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
22543 : : {
22544 : : Relation inheritsRel;
22545 : : SysScanDesc scan;
22546 : : ScanKeyData key;
22547 : 254 : int tuples = 0;
22548 : : HeapTuple inhTup;
22549 : 254 : bool updated = false;
22550 : :
22551 : : Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
22552 : :
22553 : : /*
22554 : : * Scan pg_inherits for this parent index. Count each valid index we find
22555 : : * (verifying the pg_index entry for each), and if we reach the total
22556 : : * amount we expect, we can mark this parent index as valid.
22557 : : */
22558 : 254 : inheritsRel = table_open(InheritsRelationId, AccessShareLock);
22559 : 254 : ScanKeyInit(&key, Anum_pg_inherits_inhparent,
22560 : : BTEqualStrategyNumber, F_OIDEQ,
22561 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22562 : 254 : scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
22563 : : NULL, 1, &key);
22564 [ + + ]: 647 : while ((inhTup = systable_getnext(scan)) != NULL)
22565 : : {
22566 : 393 : Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
22567 : : HeapTuple indTup;
22568 : : Form_pg_index indexForm;
22569 : :
22570 : 393 : indTup = SearchSysCache1(INDEXRELID,
22571 : : ObjectIdGetDatum(inhForm->inhrelid));
22572 [ - + ]: 393 : if (!HeapTupleIsValid(indTup))
22573 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
22574 : 393 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22575 [ + + ]: 393 : if (indexForm->indisvalid)
22576 : 327 : tuples += 1;
22577 : 393 : ReleaseSysCache(indTup);
22578 : : }
22579 : :
22580 : : /* Done with pg_inherits */
22581 : 254 : systable_endscan(scan);
22582 : 254 : table_close(inheritsRel, AccessShareLock);
22583 : :
22584 : : /*
22585 : : * If we found as many inherited indexes as the partitioned table has
22586 : : * partitions, we're good; update pg_index to set indisvalid.
22587 : : */
22588 [ + + ]: 254 : if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
22589 : : {
22590 : : Relation idxRel;
22591 : : HeapTuple indTup;
22592 : : Form_pg_index indexForm;
22593 : :
22594 : 121 : idxRel = table_open(IndexRelationId, RowExclusiveLock);
22595 : 121 : indTup = SearchSysCacheCopy1(INDEXRELID,
22596 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22597 [ - + ]: 121 : if (!HeapTupleIsValid(indTup))
22598 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u",
22599 : : RelationGetRelid(partedIdx));
22600 : 121 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22601 : :
22602 : 121 : indexForm->indisvalid = true;
22603 : 121 : updated = true;
22604 : :
22605 : 121 : CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
22606 : :
22607 : 121 : table_close(idxRel, RowExclusiveLock);
22608 : 121 : heap_freetuple(indTup);
22609 : : }
22610 : :
22611 : : /*
22612 : : * If this index is in turn a partition of a larger index, validating it
22613 : : * might cause the parent to become valid also. Try that.
22614 : : */
22615 [ + + + + ]: 254 : if (updated && partedIdx->rd_rel->relispartition)
22616 : : {
22617 : : Oid parentIdxId,
22618 : : parentTblId;
22619 : : Relation parentIdx,
22620 : : parentTbl;
22621 : :
22622 : : /* make sure we see the validation we just did */
22623 : 32 : CommandCounterIncrement();
22624 : :
22625 : 32 : parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
22626 : 32 : parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
22627 : 32 : parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
22628 : 32 : parentTbl = relation_open(parentTblId, AccessExclusiveLock);
22629 : : Assert(!parentIdx->rd_index->indisvalid);
22630 : :
22631 : 32 : validatePartitionedIndex(parentIdx, parentTbl);
22632 : :
22633 : 32 : relation_close(parentIdx, AccessExclusiveLock);
22634 : 32 : relation_close(parentTbl, AccessExclusiveLock);
22635 : : }
22636 : 254 : }
22637 : :
22638 : : /*
22639 : : * When attaching an index as a partition of a partitioned index which is a
22640 : : * primary key, verify that all the columns in the partition are marked NOT
22641 : : * NULL.
22642 : : */
22643 : : static void
22644 : 51 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
22645 : : {
22646 [ + + ]: 103 : for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
22647 : : {
22648 : 52 : Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
22649 : 52 : iinfo->ii_IndexAttrNumbers[i] - 1);
22650 : :
22651 [ - + ]: 52 : if (!att->attnotnull)
22652 [ # # ]: 0 : ereport(ERROR,
22653 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
22654 : : errmsg("invalid primary key definition"),
22655 : : errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
22656 : : NameStr(att->attname),
22657 : : RelationGetRelationName(partition)));
22658 : : }
22659 : 51 : }
22660 : :
22661 : : /*
22662 : : * Return an OID list of constraints that reference the given relation
22663 : : * that are marked as having a parent constraints.
22664 : : */
22665 : : static List *
22666 : 625 : GetParentedForeignKeyRefs(Relation partition)
22667 : : {
22668 : : Relation pg_constraint;
22669 : : HeapTuple tuple;
22670 : : SysScanDesc scan;
22671 : : ScanKeyData key[2];
22672 : 625 : List *constraints = NIL;
22673 : :
22674 : : /*
22675 : : * If no indexes, or no columns are referenceable by FKs, we can avoid the
22676 : : * scan.
22677 : : */
22678 [ + + + + ]: 896 : if (RelationGetIndexList(partition) == NIL ||
22679 : 271 : bms_is_empty(RelationGetIndexAttrBitmap(partition,
22680 : : INDEX_ATTR_BITMAP_KEY)))
22681 : 458 : return NIL;
22682 : :
22683 : : /* Search for constraints referencing this table */
22684 : 167 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
22685 : 167 : ScanKeyInit(&key[0],
22686 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
22687 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
22688 : 167 : ScanKeyInit(&key[1],
22689 : : Anum_pg_constraint_contype, BTEqualStrategyNumber,
22690 : : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
22691 : :
22692 : : /* XXX This is a seqscan, as we don't have a usable index */
22693 : 167 : scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
22694 [ + + ]: 268 : while ((tuple = systable_getnext(scan)) != NULL)
22695 : : {
22696 : 101 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22697 : :
22698 : : /*
22699 : : * We only need to process constraints that are part of larger ones.
22700 : : */
22701 [ - + ]: 101 : if (!OidIsValid(constrForm->conparentid))
22702 : 0 : continue;
22703 : :
22704 : 101 : constraints = lappend_oid(constraints, constrForm->oid);
22705 : : }
22706 : :
22707 : 167 : systable_endscan(scan);
22708 : 167 : table_close(pg_constraint, AccessShareLock);
22709 : :
22710 : 167 : return constraints;
22711 : : }
22712 : :
22713 : : /*
22714 : : * During DETACH PARTITION, verify that any foreign keys pointing to the
22715 : : * partitioned table would not become invalid. An error is raised if any
22716 : : * referenced values exist.
22717 : : */
22718 : : static void
22719 : 333 : ATDetachCheckNoForeignKeyRefs(Relation partition)
22720 : : {
22721 : : List *constraints;
22722 : : ListCell *cell;
22723 : :
22724 : 333 : constraints = GetParentedForeignKeyRefs(partition);
22725 : :
22726 [ + + + + : 376 : foreach(cell, constraints)
+ + ]
22727 : : {
22728 : 65 : Oid constrOid = lfirst_oid(cell);
22729 : : HeapTuple tuple;
22730 : : Form_pg_constraint constrForm;
22731 : : Relation rel;
22732 : 65 : Trigger trig = {0};
22733 : :
22734 : 65 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
22735 [ - + ]: 65 : if (!HeapTupleIsValid(tuple))
22736 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
22737 : 65 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22738 : :
22739 : : Assert(OidIsValid(constrForm->conparentid));
22740 : : Assert(constrForm->confrelid == RelationGetRelid(partition));
22741 : :
22742 : : /* prevent data changes into the referencing table until commit */
22743 : 65 : rel = table_open(constrForm->conrelid, ShareLock);
22744 : :
22745 : 65 : trig.tgoid = InvalidOid;
22746 : 65 : trig.tgname = NameStr(constrForm->conname);
22747 : 65 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
22748 : 65 : trig.tgisinternal = true;
22749 : 65 : trig.tgconstrrelid = RelationGetRelid(partition);
22750 : 65 : trig.tgconstrindid = constrForm->conindid;
22751 : 65 : trig.tgconstraint = constrForm->oid;
22752 : 65 : trig.tgdeferrable = false;
22753 : 65 : trig.tginitdeferred = false;
22754 : : /* we needn't fill in remaining fields */
22755 : :
22756 : 65 : RI_PartitionRemove_Check(&trig, rel, partition);
22757 : :
22758 : 43 : ReleaseSysCache(tuple);
22759 : :
22760 : 43 : table_close(rel, NoLock);
22761 : : }
22762 : 311 : }
22763 : :
22764 : : /*
22765 : : * resolve column compression specification to compression method.
22766 : : */
22767 : : static char
22768 : 165842 : GetAttributeCompression(Oid atttypid, const char *compression)
22769 : : {
22770 : : char cmethod;
22771 : :
22772 [ + + + + ]: 165842 : if (compression == NULL || strcmp(compression, "default") == 0)
22773 : 165721 : return InvalidCompressionMethod;
22774 : :
22775 : : /*
22776 : : * To specify a nondefault method, the column data type must be toastable.
22777 : : * Note this says nothing about whether the column's attstorage setting
22778 : : * permits compression; we intentionally allow attstorage and
22779 : : * attcompression to be independent. But with a non-toastable type,
22780 : : * attstorage could not be set to a value that would permit compression.
22781 : : *
22782 : : * We don't actually need to enforce this, since nothing bad would happen
22783 : : * if attcompression were non-default; it would never be consulted. But
22784 : : * it seems more user-friendly to complain about a certainly-useless
22785 : : * attempt to set the property.
22786 : : */
22787 [ + + ]: 121 : if (!TypeIsToastable(atttypid))
22788 [ + - ]: 4 : ereport(ERROR,
22789 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22790 : : errmsg("column data type %s does not support compression",
22791 : : format_type_be(atttypid))));
22792 : :
22793 : 117 : cmethod = CompressionNameToMethod(compression);
22794 [ + + ]: 117 : if (!CompressionMethodIsValid(cmethod))
22795 [ + - ]: 8 : ereport(ERROR,
22796 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22797 : : errmsg("invalid compression method \"%s\"", compression)));
22798 : :
22799 : 109 : return cmethod;
22800 : : }
22801 : :
22802 : : /*
22803 : : * resolve column storage specification
22804 : : */
22805 : : static char
22806 : 250 : GetAttributeStorage(Oid atttypid, const char *storagemode)
22807 : : {
22808 : 250 : char cstorage = 0;
22809 : :
22810 [ + + ]: 250 : if (pg_strcasecmp(storagemode, "plain") == 0)
22811 : 38 : cstorage = TYPSTORAGE_PLAIN;
22812 [ + + ]: 212 : else if (pg_strcasecmp(storagemode, "external") == 0)
22813 : 146 : cstorage = TYPSTORAGE_EXTERNAL;
22814 [ + + ]: 66 : else if (pg_strcasecmp(storagemode, "extended") == 0)
22815 : 41 : cstorage = TYPSTORAGE_EXTENDED;
22816 [ + + ]: 25 : else if (pg_strcasecmp(storagemode, "main") == 0)
22817 : 21 : cstorage = TYPSTORAGE_MAIN;
22818 [ + - ]: 4 : else if (pg_strcasecmp(storagemode, "default") == 0)
22819 : 4 : cstorage = get_typstorage(atttypid);
22820 : : else
22821 [ # # ]: 0 : ereport(ERROR,
22822 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22823 : : errmsg("invalid storage type \"%s\"",
22824 : : storagemode)));
22825 : :
22826 : : /*
22827 : : * safety check: do not allow toasted storage modes unless column datatype
22828 : : * is TOAST-aware.
22829 : : */
22830 [ + + + + ]: 250 : if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
22831 [ + - ]: 4 : ereport(ERROR,
22832 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22833 : : errmsg("column data type %s can only have storage PLAIN",
22834 : : format_type_be(atttypid))));
22835 : :
22836 : 246 : return cstorage;
22837 : : }
|